title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Construct DFA which interpreted as binary number is divisible by 2, 3, 4 - GeeksforGeeks | 28 Jun, 2020
Prerequisite: Finite Automata Introduction, Designing Finite AutomataProblem-1:Construct DFA, which accepts set of all strings over {0, 1} which interpreted as binary number is divisible by 2.
Explanation:Consider the following inputs,
{0, 01, 10, 11, 100, 101, 110........}
The state transition diagram of the language will be like:
In this DFA there are two states q0 and q1 and the input is strings of {0, 1} which is interpreted as binary number.The state q0 is final state and q1 is non-final state. State q0 will be representing all the numbers that are divisible by 2, that is {0, 10, 100, 110.....}.State q1 will be representing all the numbers that are not divisible by 2, that is {01, 11, 101, ......}.
def stateq0(n): #if length found 0 #print not accepted if (len(n)==0): print("string accepted") else: #if at index 0 #'0' found call #function stateq0 if(n[0]=='0'): stateq0(n[1:]) #else if '1' found #call function q1. elif (n[0]=='1'): stateq1(n[1:]) def stateq1(n): #if length found 0 #print not accepted if (len(n)==0): print("string not accepted") else: #if at index 0 #'0' found call #function stateq0 if(n[0]=='0'): stateq0(n[1:]) #else if '1' found #call function q1. elif (n[0]=='1'): stateq1(n[1:]) #take number from usern=int(input())#converting number to binaryn = bin(n).replace("0b", "") #call stateA#to check the inputstateq0(n)
INPUT: 5
OUTPUT: String Not Accepted
The above automata will accept set of all strings over {0, 1} which when interpreted as binary number is divisible by 2.Whenever the number is not divisible by 2 then it will go from state q0 to q1. When the number is divisible by 2, then it will go from state q1 to q0 or if it was initially in q0 then it will accept it.
Problem-2:Construct DFA, which accepts set of all strings over {0, 1} which interpreted as binary number is divisible by 3.
Explanation:Refer for solution: Binary string multiple of 3 using DFA.
Problem-3:Construct DFA, which accepts set of all strings over {0, 1} which interpreted as binary number is divisible by 4.
Explanation:Consider the following inputs,
{0, 01, 10, 11, 100, 101, 110........}
The state transition diagram of the language will be like:
Explanation:In this DFA there are three states q0, q1, q2, q3 and the input is strings of {0, 1} which is interpreted as binary number. The state q0 is final state and q1, q2, q3 are non-final state.
State q0 will be representing all the numbers that are divisible by 4, that is {0, 100, 1000.....}.
State q1 will be representing all the numbers that are not divisible by 4 and give remainder 1 when divided by 4, that is {01, 101,,......}.
State q2 will be representing all the numbers that are not divisible by 4 and give remainder 2 when divided by 4, that is {10, 110, ......}.
State q4 will be representing all the numbers that are not divisible by 4 and give remainder 3 when divided by 4, that is {11, 111, ......}.
The above automata will accept set of all strings over {0, 1} which when interpreted as binary number is divisible by 4.
State Whenever the number is not divisible by 4 and gives remainder of 1 then it will go to state q1.
State Whenever the number is not divisible by 4 and gives remainder of 2 then it will go to state q2.
State Whenever the number is not divisible by 4 and gives remainder of 3 then it will go to state q3.
State Whenever the number is divisible by 4, then it will go to state q0 or if it was initially in q0 then it will accept it.
def stateq0(n): #if length found 0 #print not accepted if (len(n)==0): print("string accepted") else: #if at index 0 #'0' found call #function stateq0 if(n[0]=='0'): stateq0(n[1:]) #else if '1' found #call function q1. elif (n[0]=='1'): stateq1(n[1:]) def stateq1(n): #if length found 0 #print not accepted if (len(n)==0): print("string not accepted") else: #if at index 0 #'0' found call #function stateq2 if(n[0]=='0'): stateq2(n[1:]) #else if '1' found #call function q3. elif (n[0]=='1'): stateq3(n[1:]) def stateq2(n): #if length found 0 #print not accepted if (len(n)==0): print("string not accepted") else: #if at index 0 #'0' found call #function stateq0 if(n[0]=='0'): stateq0(n[1:]) #else if '1' found #call function q1. elif (n[0]=='1'): stateq1(n[1:]) def stateq3(n): #if length found 0 #print not accepted if (len(n)==0): print("string not accepted") else: #if at index 0 #'0' found call #function stateq2 if(n[0]=='0'): stateq2(n[1:]) #else if '1' found #call function q3. elif (n[0]=='1'): stateq3(n[1:]) #take number from usern=int(input())#converting number to binaryn = bin(n).replace("0b", "") #call stateA#to check the inputstateq0(n)
_mridul_bhardwaj_
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Page Replacement Algorithms in Operating Systems
Differences between TCP and UDP
Cache Memory in Computer Organization
Introduction of Operating System - Set 1
Semaphores in Process Synchronization
Difference between DFA and NFA
Construct Pushdown Automata for given languages
Turing Machine in TOC
Introduction of Pushdown Automata
Difference between Mealy machine and Moore machine | [
{
"code": null,
"e": 26432,
"s": 26404,
"text": "\n28 Jun, 2020"
},
{
"code": null,
"e": 26625,
"s": 26432,
"text": "Prerequisite: Finite Automata Introduction, Designing Finite AutomataProblem-1:Construct DFA, which accepts set of all strings over {0, 1} which interpreted as binary number is divisible by 2."
},
{
"code": null,
"e": 26668,
"s": 26625,
"text": "Explanation:Consider the following inputs,"
},
{
"code": null,
"e": 26707,
"s": 26668,
"text": "{0, 01, 10, 11, 100, 101, 110........}"
},
{
"code": null,
"e": 26766,
"s": 26707,
"text": "The state transition diagram of the language will be like:"
},
{
"code": null,
"e": 27145,
"s": 26766,
"text": "In this DFA there are two states q0 and q1 and the input is strings of {0, 1} which is interpreted as binary number.The state q0 is final state and q1 is non-final state. State q0 will be representing all the numbers that are divisible by 2, that is {0, 10, 100, 110.....}.State q1 will be representing all the numbers that are not divisible by 2, that is {01, 11, 101, ......}."
},
{
"code": "def stateq0(n): #if length found 0 #print not accepted if (len(n)==0): print(\"string accepted\") else: #if at index 0 #'0' found call #function stateq0 if(n[0]=='0'): stateq0(n[1:]) #else if '1' found #call function q1. elif (n[0]=='1'): stateq1(n[1:]) def stateq1(n): #if length found 0 #print not accepted if (len(n)==0): print(\"string not accepted\") else: #if at index 0 #'0' found call #function stateq0 if(n[0]=='0'): stateq0(n[1:]) #else if '1' found #call function q1. elif (n[0]=='1'): stateq1(n[1:]) #take number from usern=int(input())#converting number to binaryn = bin(n).replace(\"0b\", \"\") #call stateA#to check the inputstateq0(n)",
"e": 28068,
"s": 27145,
"text": null
},
{
"code": null,
"e": 28106,
"s": 28068,
"text": "INPUT: 5\nOUTPUT: String Not Accepted\n"
},
{
"code": null,
"e": 28429,
"s": 28106,
"text": "The above automata will accept set of all strings over {0, 1} which when interpreted as binary number is divisible by 2.Whenever the number is not divisible by 2 then it will go from state q0 to q1. When the number is divisible by 2, then it will go from state q1 to q0 or if it was initially in q0 then it will accept it."
},
{
"code": null,
"e": 28553,
"s": 28429,
"text": "Problem-2:Construct DFA, which accepts set of all strings over {0, 1} which interpreted as binary number is divisible by 3."
},
{
"code": null,
"e": 28624,
"s": 28553,
"text": "Explanation:Refer for solution: Binary string multiple of 3 using DFA."
},
{
"code": null,
"e": 28748,
"s": 28624,
"text": "Problem-3:Construct DFA, which accepts set of all strings over {0, 1} which interpreted as binary number is divisible by 4."
},
{
"code": null,
"e": 28791,
"s": 28748,
"text": "Explanation:Consider the following inputs,"
},
{
"code": null,
"e": 28830,
"s": 28791,
"text": "{0, 01, 10, 11, 100, 101, 110........}"
},
{
"code": null,
"e": 28889,
"s": 28830,
"text": "The state transition diagram of the language will be like:"
},
{
"code": null,
"e": 29089,
"s": 28889,
"text": "Explanation:In this DFA there are three states q0, q1, q2, q3 and the input is strings of {0, 1} which is interpreted as binary number. The state q0 is final state and q1, q2, q3 are non-final state."
},
{
"code": null,
"e": 29189,
"s": 29089,
"text": "State q0 will be representing all the numbers that are divisible by 4, that is {0, 100, 1000.....}."
},
{
"code": null,
"e": 29330,
"s": 29189,
"text": "State q1 will be representing all the numbers that are not divisible by 4 and give remainder 1 when divided by 4, that is {01, 101,,......}."
},
{
"code": null,
"e": 29471,
"s": 29330,
"text": "State q2 will be representing all the numbers that are not divisible by 4 and give remainder 2 when divided by 4, that is {10, 110, ......}."
},
{
"code": null,
"e": 29612,
"s": 29471,
"text": "State q4 will be representing all the numbers that are not divisible by 4 and give remainder 3 when divided by 4, that is {11, 111, ......}."
},
{
"code": null,
"e": 29733,
"s": 29612,
"text": "The above automata will accept set of all strings over {0, 1} which when interpreted as binary number is divisible by 4."
},
{
"code": null,
"e": 29835,
"s": 29733,
"text": "State Whenever the number is not divisible by 4 and gives remainder of 1 then it will go to state q1."
},
{
"code": null,
"e": 29937,
"s": 29835,
"text": "State Whenever the number is not divisible by 4 and gives remainder of 2 then it will go to state q2."
},
{
"code": null,
"e": 30039,
"s": 29937,
"text": "State Whenever the number is not divisible by 4 and gives remainder of 3 then it will go to state q3."
},
{
"code": null,
"e": 30165,
"s": 30039,
"text": "State Whenever the number is divisible by 4, then it will go to state q0 or if it was initially in q0 then it will accept it."
},
{
"code": "def stateq0(n): #if length found 0 #print not accepted if (len(n)==0): print(\"string accepted\") else: #if at index 0 #'0' found call #function stateq0 if(n[0]=='0'): stateq0(n[1:]) #else if '1' found #call function q1. elif (n[0]=='1'): stateq1(n[1:]) def stateq1(n): #if length found 0 #print not accepted if (len(n)==0): print(\"string not accepted\") else: #if at index 0 #'0' found call #function stateq2 if(n[0]=='0'): stateq2(n[1:]) #else if '1' found #call function q3. elif (n[0]=='1'): stateq3(n[1:]) def stateq2(n): #if length found 0 #print not accepted if (len(n)==0): print(\"string not accepted\") else: #if at index 0 #'0' found call #function stateq0 if(n[0]=='0'): stateq0(n[1:]) #else if '1' found #call function q1. elif (n[0]=='1'): stateq1(n[1:]) def stateq3(n): #if length found 0 #print not accepted if (len(n)==0): print(\"string not accepted\") else: #if at index 0 #'0' found call #function stateq2 if(n[0]=='0'): stateq2(n[1:]) #else if '1' found #call function q3. elif (n[0]=='1'): stateq3(n[1:]) #take number from usern=int(input())#converting number to binaryn = bin(n).replace(\"0b\", \"\") #call stateA#to check the inputstateq0(n)",
"e": 31920,
"s": 30165,
"text": null
},
{
"code": null,
"e": 31938,
"s": 31920,
"text": "_mridul_bhardwaj_"
},
{
"code": null,
"e": 31946,
"s": 31938,
"text": "GATE CS"
},
{
"code": null,
"e": 31979,
"s": 31946,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 32077,
"s": 31979,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32126,
"s": 32077,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 32158,
"s": 32126,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 32196,
"s": 32158,
"text": "Cache Memory in Computer Organization"
},
{
"code": null,
"e": 32237,
"s": 32196,
"text": "Introduction of Operating System - Set 1"
},
{
"code": null,
"e": 32275,
"s": 32237,
"text": "Semaphores in Process Synchronization"
},
{
"code": null,
"e": 32306,
"s": 32275,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 32354,
"s": 32306,
"text": "Construct Pushdown Automata for given languages"
},
{
"code": null,
"e": 32376,
"s": 32354,
"text": "Turing Machine in TOC"
},
{
"code": null,
"e": 32410,
"s": 32376,
"text": "Introduction of Pushdown Automata"
}
]
|
How to Install FatRat Tool in Kali Linux? - GeeksforGeeks | 15 Feb, 2022
The FatRat is a free and open-source tool used as an exploiting tool. The FatRat tool adds malware with a payload and after that, the malware that you have developed can be executed on different types of operating systems such as android, windows, mac, Linux. The FatRat is a powerful tool that can bypass most of the Antivirus easily and can maintain the connection between attacker and victim. Fatrat Tool can help in generating backdoors, system exploitation, post-exploitation attacks, browser attacks, DLL files, FUD payloads against Linux, Mac OS X, Windows, and Android. We can create malware in different formats using FatRat so that it can be executed easily on the target operating system.
FatRat is used for exploitation.
FatRat is used to create malware
Fatrat is used to combine payload with malware.
Fatrat is used for creating Backdoors for Post Exploitation.
FatRat is used for browser attacks.
FatRat is used to get DDL files from Linux.
FatRat can create malware in different extensions.
FatRat is Free and Open Source
FatRat create payloads
FatRat can bypass most the antivirus.
FatRat can work with MSFvenom and Metasploit
FatRat can Generate payloads in Various formats.
FatRat generates Local or remote listener Generation.
FatRat can easily make Backdoor by category Operating System such as Linux, android etc.
Step 1: Open Your Kali Linux and move to the Desktop directory.
cd Desktop
Step 2: Now on desktop create a new Directory named fatrat.
mkdir fatrat
Step 3: Now move to fatrat directory.
cd fatrat
Step 4: Now you have to download the fatrat tool from GitHub to do that you have to clone it from GitHub. Just clone the tool using the following command.
git clone https://github.com/Screetsec/TheFatRat.git
Step 5: The TheFatRat tool has been downloaded into your Kali Linux now move to the directory where you have downloaded the tool and list out the content.
cd TheFatRat
ls
Step 6: Now you have to give the permission of execution to the setup.sh using the following command.
chmod +x setup.sh
Step 7: Now run the tool using the following command.
./setup.sh
We are Creating a Backdoor using msfvenom utility. So we have chosen Option 1.
2. Backdoors can be of various extensions like .elf,.bat,.php,.asp etc. So in this example, we are selection option 5 which is .php Backdoor.
In the below screenshot, you can see that our payload.php is ready and saved in a specific path. Now to perform an attack you can send this payload to the victim and ask him to execute it.
In the below Screenshot, you can see that we have displayed the contents or the coding of payload.php, in which LHOST and Port Number is specified.
We will Create Fud Backdoor using Fudwin 1.0. So we have selected Option 2 from the menu.
In the below Screenshot, you can see that there are 2 primary options.
Powerstager 0.2.5
Slow but Powerful
So we have selected option 1 which seems to be NEW.
In the below Screenshot, we have to specify the name of our payload and the Architecture of our Target System, so in this example we have selected 64Bit (XP64,Vista,7,8,10).
Now, we have to select the icon name in which payload will hide. So we have selected excel.ico.
We will be Creating a backdoor with Avoid Utility.
We are specifying backdoor name which is backdoor.exe
We have to select the strength or the size of the payload so in this example we have selected Normal payload stealth.
Selecting Payload Stealth
In the below Screenshot , you can see that our Payload is successfully created with the name backdoor.exe in the specified path.
We will create backdoor using PwnWinds Utility which is more powerful among others.
You can see that there is the various option of backdoor type, so in this example, we are creating a .bat extension payload which is a batch script in Windows Target.
Now, we are specifying the name for the payload and selecting the purpose of the payload. So in this case the payload is designed to give reverse tcp connection to the attacker.
You can see that, our payload is created and saved in the specified path.
We are Creating Trojan Package for Remote Access.
In the below Screenshot, we have specified the name of the Trojan and the path of the Debian package in which Trojan will be merged or hide. So in this case we have selected the google_chrome Debian package.
In the below Screenshot, we are specifying the purpose of the Trojan, so in this example, we have selected shell_reverse_tcp connection.
In the below Screenshot, you can see that our Trojan have integrated with the .deb package and stored in the specified path.
We will be using the SearchSploit option which consists of a list od databases of various payloads and backdoors for every type of target.
In the below Screenshot, Tool is asking us about our Target. So we have given Windows 10 as our target.
You can see that TheFatRat tool has returned us a number of payloads and backdoors for our Windows 10 Target.
We will be increasing the size of our payload to make it more stealth.
In the below Screenshot, we have selected the backdoor for which we need to increase the size. Also we need to select the size in mb or kb. So we have selected size in mb.
In the below Screenshot, we have selected the size in mb.
You can see that our backdoor.exe file size has been increased.
In the below Screenshot, we are checking the properties of backdoor.exe file for which we have increased size into mb.
sweetyty
gauravgandal
rkbhola5
sagar0719kumar
how-to-install
Kali-Linux
Linux-Tools
How To
Installation Guide
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS? | [
{
"code": null,
"e": 26307,
"s": 26279,
"text": "\n15 Feb, 2022"
},
{
"code": null,
"e": 27010,
"s": 26309,
"text": "The FatRat is a free and open-source tool used as an exploiting tool. The FatRat tool adds malware with a payload and after that, the malware that you have developed can be executed on different types of operating systems such as android, windows, mac, Linux. The FatRat is a powerful tool that can bypass most of the Antivirus easily and can maintain the connection between attacker and victim. Fatrat Tool can help in generating backdoors, system exploitation, post-exploitation attacks, browser attacks, DLL files, FUD payloads against Linux, Mac OS X, Windows, and Android. We can create malware in different formats using FatRat so that it can be executed easily on the target operating system. "
},
{
"code": null,
"e": 27045,
"s": 27012,
"text": "FatRat is used for exploitation."
},
{
"code": null,
"e": 27078,
"s": 27045,
"text": "FatRat is used to create malware"
},
{
"code": null,
"e": 27126,
"s": 27078,
"text": "Fatrat is used to combine payload with malware."
},
{
"code": null,
"e": 27187,
"s": 27126,
"text": "Fatrat is used for creating Backdoors for Post Exploitation."
},
{
"code": null,
"e": 27223,
"s": 27187,
"text": "FatRat is used for browser attacks."
},
{
"code": null,
"e": 27267,
"s": 27223,
"text": "FatRat is used to get DDL files from Linux."
},
{
"code": null,
"e": 27318,
"s": 27267,
"text": "FatRat can create malware in different extensions."
},
{
"code": null,
"e": 27349,
"s": 27318,
"text": "FatRat is Free and Open Source"
},
{
"code": null,
"e": 27372,
"s": 27349,
"text": "FatRat create payloads"
},
{
"code": null,
"e": 27410,
"s": 27372,
"text": "FatRat can bypass most the antivirus."
},
{
"code": null,
"e": 27455,
"s": 27410,
"text": "FatRat can work with MSFvenom and Metasploit"
},
{
"code": null,
"e": 27504,
"s": 27455,
"text": "FatRat can Generate payloads in Various formats."
},
{
"code": null,
"e": 27558,
"s": 27504,
"text": "FatRat generates Local or remote listener Generation."
},
{
"code": null,
"e": 27647,
"s": 27558,
"text": "FatRat can easily make Backdoor by category Operating System such as Linux, android etc."
},
{
"code": null,
"e": 27713,
"s": 27649,
"text": "Step 1: Open Your Kali Linux and move to the Desktop directory."
},
{
"code": null,
"e": 27727,
"s": 27715,
"text": "cd Desktop "
},
{
"code": null,
"e": 27789,
"s": 27729,
"text": "Step 2: Now on desktop create a new Directory named fatrat."
},
{
"code": null,
"e": 27804,
"s": 27791,
"text": "mkdir fatrat"
},
{
"code": null,
"e": 27844,
"s": 27806,
"text": "Step 3: Now move to fatrat directory."
},
{
"code": null,
"e": 27856,
"s": 27846,
"text": "cd fatrat"
},
{
"code": null,
"e": 28013,
"s": 27858,
"text": "Step 4: Now you have to download the fatrat tool from GitHub to do that you have to clone it from GitHub. Just clone the tool using the following command."
},
{
"code": null,
"e": 28068,
"s": 28015,
"text": "git clone https://github.com/Screetsec/TheFatRat.git"
},
{
"code": null,
"e": 28225,
"s": 28070,
"text": "Step 5: The TheFatRat tool has been downloaded into your Kali Linux now move to the directory where you have downloaded the tool and list out the content."
},
{
"code": null,
"e": 28243,
"s": 28227,
"text": "cd TheFatRat\nls"
},
{
"code": null,
"e": 28347,
"s": 28245,
"text": "Step 6: Now you have to give the permission of execution to the setup.sh using the following command."
},
{
"code": null,
"e": 28367,
"s": 28349,
"text": "chmod +x setup.sh"
},
{
"code": null,
"e": 28423,
"s": 28369,
"text": "Step 7: Now run the tool using the following command."
},
{
"code": null,
"e": 28436,
"s": 28425,
"text": "./setup.sh"
},
{
"code": null,
"e": 28517,
"s": 28438,
"text": "We are Creating a Backdoor using msfvenom utility. So we have chosen Option 1."
},
{
"code": null,
"e": 28663,
"s": 28521,
"text": "2. Backdoors can be of various extensions like .elf,.bat,.php,.asp etc. So in this example, we are selection option 5 which is .php Backdoor."
},
{
"code": null,
"e": 28856,
"s": 28667,
"text": "In the below screenshot, you can see that our payload.php is ready and saved in a specific path. Now to perform an attack you can send this payload to the victim and ask him to execute it."
},
{
"code": null,
"e": 29008,
"s": 28860,
"text": "In the below Screenshot, you can see that we have displayed the contents or the coding of payload.php, in which LHOST and Port Number is specified."
},
{
"code": null,
"e": 29102,
"s": 29012,
"text": "We will Create Fud Backdoor using Fudwin 1.0. So we have selected Option 2 from the menu."
},
{
"code": null,
"e": 29177,
"s": 29106,
"text": "In the below Screenshot, you can see that there are 2 primary options."
},
{
"code": null,
"e": 29199,
"s": 29181,
"text": "Powerstager 0.2.5"
},
{
"code": null,
"e": 29219,
"s": 29201,
"text": "Slow but Powerful"
},
{
"code": null,
"e": 29275,
"s": 29223,
"text": "So we have selected option 1 which seems to be NEW."
},
{
"code": null,
"e": 29453,
"s": 29279,
"text": "In the below Screenshot, we have to specify the name of our payload and the Architecture of our Target System, so in this example we have selected 64Bit (XP64,Vista,7,8,10)."
},
{
"code": null,
"e": 29553,
"s": 29457,
"text": "Now, we have to select the icon name in which payload will hide. So we have selected excel.ico."
},
{
"code": null,
"e": 29608,
"s": 29557,
"text": "We will be Creating a backdoor with Avoid Utility."
},
{
"code": null,
"e": 29666,
"s": 29612,
"text": "We are specifying backdoor name which is backdoor.exe"
},
{
"code": null,
"e": 29788,
"s": 29670,
"text": "We have to select the strength or the size of the payload so in this example we have selected Normal payload stealth."
},
{
"code": null,
"e": 29816,
"s": 29790,
"text": "Selecting Payload Stealth"
},
{
"code": null,
"e": 29947,
"s": 29818,
"text": "In the below Screenshot , you can see that our Payload is successfully created with the name backdoor.exe in the specified path."
},
{
"code": null,
"e": 30035,
"s": 29951,
"text": "We will create backdoor using PwnWinds Utility which is more powerful among others."
},
{
"code": null,
"e": 30206,
"s": 30039,
"text": "You can see that there is the various option of backdoor type, so in this example, we are creating a .bat extension payload which is a batch script in Windows Target."
},
{
"code": null,
"e": 30388,
"s": 30210,
"text": "Now, we are specifying the name for the payload and selecting the purpose of the payload. So in this case the payload is designed to give reverse tcp connection to the attacker."
},
{
"code": null,
"e": 30466,
"s": 30392,
"text": "You can see that, our payload is created and saved in the specified path."
},
{
"code": null,
"e": 30520,
"s": 30470,
"text": "We are Creating Trojan Package for Remote Access."
},
{
"code": null,
"e": 30732,
"s": 30524,
"text": "In the below Screenshot, we have specified the name of the Trojan and the path of the Debian package in which Trojan will be merged or hide. So in this case we have selected the google_chrome Debian package."
},
{
"code": null,
"e": 30873,
"s": 30736,
"text": "In the below Screenshot, we are specifying the purpose of the Trojan, so in this example, we have selected shell_reverse_tcp connection."
},
{
"code": null,
"e": 31002,
"s": 30877,
"text": "In the below Screenshot, you can see that our Trojan have integrated with the .deb package and stored in the specified path."
},
{
"code": null,
"e": 31145,
"s": 31006,
"text": "We will be using the SearchSploit option which consists of a list od databases of various payloads and backdoors for every type of target."
},
{
"code": null,
"e": 31253,
"s": 31149,
"text": "In the below Screenshot, Tool is asking us about our Target. So we have given Windows 10 as our target."
},
{
"code": null,
"e": 31367,
"s": 31257,
"text": "You can see that TheFatRat tool has returned us a number of payloads and backdoors for our Windows 10 Target."
},
{
"code": null,
"e": 31442,
"s": 31371,
"text": "We will be increasing the size of our payload to make it more stealth."
},
{
"code": null,
"e": 31618,
"s": 31446,
"text": "In the below Screenshot, we have selected the backdoor for which we need to increase the size. Also we need to select the size in mb or kb. So we have selected size in mb."
},
{
"code": null,
"e": 31680,
"s": 31622,
"text": "In the below Screenshot, we have selected the size in mb."
},
{
"code": null,
"e": 31748,
"s": 31684,
"text": "You can see that our backdoor.exe file size has been increased."
},
{
"code": null,
"e": 31871,
"s": 31752,
"text": "In the below Screenshot, we are checking the properties of backdoor.exe file for which we have increased size into mb."
},
{
"code": null,
"e": 31884,
"s": 31875,
"text": "sweetyty"
},
{
"code": null,
"e": 31897,
"s": 31884,
"text": "gauravgandal"
},
{
"code": null,
"e": 31906,
"s": 31897,
"text": "rkbhola5"
},
{
"code": null,
"e": 31921,
"s": 31906,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 31936,
"s": 31921,
"text": "how-to-install"
},
{
"code": null,
"e": 31947,
"s": 31936,
"text": "Kali-Linux"
},
{
"code": null,
"e": 31959,
"s": 31947,
"text": "Linux-Tools"
},
{
"code": null,
"e": 31966,
"s": 31959,
"text": "How To"
},
{
"code": null,
"e": 31985,
"s": 31966,
"text": "Installation Guide"
},
{
"code": null,
"e": 31996,
"s": 31985,
"text": "Linux-Unix"
},
{
"code": null,
"e": 32094,
"s": 31996,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32128,
"s": 32094,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 32186,
"s": 32128,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 32235,
"s": 32186,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 32282,
"s": 32235,
"text": "How to create a nested RecyclerView in Android"
},
{
"code": null,
"e": 32342,
"s": 32282,
"text": "How to Create and Setup Spring Boot Project in Eclipse IDE?"
},
{
"code": null,
"e": 32375,
"s": 32342,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32409,
"s": 32375,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 32444,
"s": 32409,
"text": "How to Install Pygame on Windows ?"
},
{
"code": null,
"e": 32502,
"s": 32444,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
}
]
|
How to add one polynomial to another using NumPy in Python? - GeeksforGeeks | 29 Aug, 2020
In this article, Let’s see how to add one polynomial to another. Two polynomials are given as input and the result is the addition of two polynomials.
The polynomial p(x) = C3 x2 + C2 x + C1 is represented in NumPy as : ( C1, C2, C3 ) { the coefficients (constants)}.
Let take two polynomials p(x) and q(x) then add these to get r(x) = p(x) + q(x) as a result of addition of two input polynomials.
If p(x) = A3 x2 + A2 x + A1
and
q(x) = B3 x2 + B2 x + B1
then result is
r(x) = p(x) + q(x)
i.e;
r(x) = (A3 + B3) x2 + (A2 + B2) x + (A1 + B1)
and output is
( (A1 + B1), (A2 + B2), (A3 + B3) )
Below is the implementation with some examples :
Example 1: simple_use
Python3
# importing packageimport numpy # define the polynomials# p(x) = 5(x**2) + (-2)x +5px = (5,-2,5) # q(x) = 2(x**2) + (-5)x +2qx = (2,-5,2) # add the polynomialsrx = numpy.polynomial.polynomial.polyadd(px,qx) # print the resultant polynomialprint(rx)
Output :
[ 7. -7. 7.]
Example 2: #add_with_decimals
Python3
# importing packageimport numpy # define the polynomials# p(x) = 2.2px = (0,0,2.2) # q(x) = 9.8(x**2) + 4qx = (9.8,0,4) # add the polynomialsrx = numpy.polynomial.polynomial.polyadd(px,qx) # print the resultant polynomialprint(rx)
Output :
[ 9.8 0. 6.2]
Example 3: eval_then_add
Python3
# importing packageimport numpy # define the polynomials# p(x) = (5/3)xpx = (0,5/3,0) # q(x) = (-7/4)(x**2) + (9/5)qx = (-7/4,0,9/5) # add the polynomialsrx = numpy.polynomial.polynomial.polyadd(px,qx) # print the resultant polynomialprint(rx)
Output :
[-1.75 1.66666667 1.8 ]
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python Classes and Objects | [
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 24363,
"s": 24212,
"text": "In this article, Let’s see how to add one polynomial to another. Two polynomials are given as input and the result is the addition of two polynomials."
},
{
"code": null,
"e": 24482,
"s": 24363,
"text": "The polynomial p(x) = C3 x2 + C2 x + C1 is represented in NumPy as : ( C1, C2, C3 ) { the coefficients (constants)}. "
},
{
"code": null,
"e": 24612,
"s": 24482,
"text": "Let take two polynomials p(x) and q(x) then add these to get r(x) = p(x) + q(x) as a result of addition of two input polynomials."
},
{
"code": null,
"e": 24813,
"s": 24612,
"text": "If p(x) = A3 x2 + A2 x + A1 \nand\nq(x) = B3 x2 + B2 x + B1 \n\nthen result is \nr(x) = p(x) + q(x) \ni.e;\nr(x) = (A3 + B3) x2 + (A2 + B2) x + (A1 + B1)\n \nand output is \n( (A1 + B1), (A2 + B2), (A3 + B3) )\n"
},
{
"code": null,
"e": 24862,
"s": 24813,
"text": "Below is the implementation with some examples :"
},
{
"code": null,
"e": 24884,
"s": 24862,
"text": "Example 1: simple_use"
},
{
"code": null,
"e": 24892,
"s": 24884,
"text": "Python3"
},
{
"code": "# importing packageimport numpy # define the polynomials# p(x) = 5(x**2) + (-2)x +5px = (5,-2,5) # q(x) = 2(x**2) + (-5)x +2qx = (2,-5,2) # add the polynomialsrx = numpy.polynomial.polynomial.polyadd(px,qx) # print the resultant polynomialprint(rx)",
"e": 25145,
"s": 24892,
"text": null
},
{
"code": null,
"e": 25154,
"s": 25145,
"text": "Output :"
},
{
"code": null,
"e": 25169,
"s": 25154,
"text": "[ 7. -7. 7.]\n"
},
{
"code": null,
"e": 25199,
"s": 25169,
"text": "Example 2: #add_with_decimals"
},
{
"code": null,
"e": 25207,
"s": 25199,
"text": "Python3"
},
{
"code": "# importing packageimport numpy # define the polynomials# p(x) = 2.2px = (0,0,2.2) # q(x) = 9.8(x**2) + 4qx = (9.8,0,4) # add the polynomialsrx = numpy.polynomial.polynomial.polyadd(px,qx) # print the resultant polynomialprint(rx)",
"e": 25442,
"s": 25207,
"text": null
},
{
"code": null,
"e": 25451,
"s": 25442,
"text": "Output :"
},
{
"code": null,
"e": 25469,
"s": 25451,
"text": "[ 9.8 0. 6.2]\n"
},
{
"code": null,
"e": 25494,
"s": 25469,
"text": "Example 3: eval_then_add"
},
{
"code": null,
"e": 25502,
"s": 25494,
"text": "Python3"
},
{
"code": "# importing packageimport numpy # define the polynomials# p(x) = (5/3)xpx = (0,5/3,0) # q(x) = (-7/4)(x**2) + (9/5)qx = (-7/4,0,9/5) # add the polynomialsrx = numpy.polynomial.polynomial.polyadd(px,qx) # print the resultant polynomialprint(rx)",
"e": 25750,
"s": 25502,
"text": null
},
{
"code": null,
"e": 25759,
"s": 25750,
"text": "Output :"
},
{
"code": null,
"e": 25798,
"s": 25759,
"text": "[-1.75 1.66666667 1.8 ]\n"
},
{
"code": null,
"e": 25833,
"s": 25798,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 25846,
"s": 25833,
"text": "Python-numpy"
},
{
"code": null,
"e": 25853,
"s": 25846,
"text": "Python"
},
{
"code": null,
"e": 25951,
"s": 25853,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25960,
"s": 25951,
"text": "Comments"
},
{
"code": null,
"e": 25973,
"s": 25960,
"text": "Old Comments"
},
{
"code": null,
"e": 26005,
"s": 25973,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26060,
"s": 26005,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26116,
"s": 26060,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26155,
"s": 26116,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26197,
"s": 26155,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26239,
"s": 26197,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26270,
"s": 26239,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26292,
"s": 26270,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26321,
"s": 26292,
"text": "Create a directory in Python"
}
]
|
Encrypt PDF using Java - GeeksforGeeks | 17 Jun, 2021
We can encrypt any PDF using Java by using the external library PDFBox. Inside PDFBox library 2 classes are available StandardProtectionPolicy and AccessPermission Class.
Encryption Approach:
By using the PDFBox library, you will see how you can encrypt the PDF file. Encryption is used when a user wants their own data or file in protected mode. Encryption is used as the inbuilt algorithm for encrypting the file which is simply needed credentials to access the file.
AccessPermission class is used to protect the PDF by assigning access permission to it. This class will restrict the user from performing different operations on the PDF. Example. Printing, copying, modifying, etc.
StandardProtectionPolicy class is used to apply a password to the PDF document.
Maven Dependency for PDFBox :
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.21</version>
</dependency>
1. Load the PDF Document:
Load the PDF file using load() static method (we can access it by using the class name) of class PDDocument. The load() method will accept the PDF file as a parameter.
File f = new File("path_of_PDFfile");
PDDocument pdd = PDDocument.load(f);
2. Create an instance of AccessPermission class :
AccessPermission ap = new AccessPermission();
3. Create an instance of StandardProtectionPolicy:
During the instantiation of StandardProtectionPolicy class pass owner password, user password, and object of AccessPermission class that is ‘ap’.
StandardProtectionPolicy stpp = new StandardProtectionPolicy("Owner_pass" , "user_pass" , ap);
Here we can use any password to encrypt the PDF file.
Example: Here consider the password “abcd” as a user and owner password.
StandardProtectionPolicy stpp = new StandardProtectionPolicy("abcd" , "abcd" , ap);
4. Set the length of Encryption Key:
Set the length of encryption key by using setEncryptionKeyLength() method of StandardProtectionPolicy class .
stpp.setEncryptionKeyLength(128);
5. Set Permission:
Set the permission to PDF using setPermission() method of StandardProtectionPolicy class. You have to pass the object of AccessPermissionclass as a parameter in setPermission() method.
stpp.setPermission(ap);
6. Protect the PDF file:
Protect the PDF file using the protect() method of PDDocument class. Here in this, we have to pass the object of StandardProtectionPolicy class as a parameter.
pdd.protect(stpp);
7. Save and close the Document:
Finally, save and close the document by using the save() and close() method of PDDocument class.
pdd.save("path_of_PDFfile"); // save the document
pdd.close(); // close the document
Java
import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.encryption.AccessPermission;import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;import java.io.File;import java.io.IOException; class PdfEncryption { public static void main(String[] args) throws IOException { // step 1. Loading the pdf file File f = new File("D:\\demo.pdf"); PDDocument pdd = PDDocument.load(f); // step 2.Creating instance of AccessPermission // class AccessPermission ap = new AccessPermission(); // step 3. Creating instance of // StandardProtectionPolicy StandardProtectionPolicy stpp = new StandardProtectionPolicy("abcd", "abcd", ap); // step 4. Setting the length of Encryption key stpp.setEncryptionKeyLength(128); // step 5. Setting the permission stpp.setPermissions(ap); // step 6. Protecting the PDF file pdd.protect(stpp); // step 7. Saving and closing the the PDF Document pdd.save("D:\\demo.pdf1"); pdd.close(); System.out.println("PDF Encrypted successfully..."); }}
Output:
Before Encryption :
Here, you will see you don’t need any password to access the file. Before Encryption, You can directly access the file without need any credentials. Let’s have a look.
After Encryption:
After Encryption, Your PDF file will be saved on a given location and will be saved in a protected mode that simply means you will need a password to access or to read the PDF file. Let’s have a look.
In these ways, you can easily protect your PDF Document using a password.
If you want to implement this program on Eclipse IDE then used the following steps given below.
Open Eclipse IDE.
Create a New Java Project for example PDFEncryption.
Now, Create a New Java Class like PdfEncryption.
Now, to add the dependencies add two .jar files that are using in the program.
Add PDFBox library from this link download .jar file and Add PDFBox 2.0.21.
Add Apache Commons Logging library from this link Apache Commons Logging 1.2.
You can check the given below screenshot for your reference.
ruhelaa48
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
Convert a String to Character array in Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 25111,
"s": 25083,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 25282,
"s": 25111,
"text": "We can encrypt any PDF using Java by using the external library PDFBox. Inside PDFBox library 2 classes are available StandardProtectionPolicy and AccessPermission Class."
},
{
"code": null,
"e": 25303,
"s": 25282,
"text": "Encryption Approach:"
},
{
"code": null,
"e": 25583,
"s": 25303,
"text": "By using the PDFBox library, you will see how you can encrypt the PDF file. Encryption is used when a user wants their own data or file in protected mode. Encryption is used as the inbuilt algorithm for encrypting the file which is simply needed credentials to access the file. "
},
{
"code": null,
"e": 25798,
"s": 25583,
"text": "AccessPermission class is used to protect the PDF by assigning access permission to it. This class will restrict the user from performing different operations on the PDF. Example. Printing, copying, modifying, etc."
},
{
"code": null,
"e": 25880,
"s": 25798,
"text": "StandardProtectionPolicy class is used to apply a password to the PDF document. "
},
{
"code": null,
"e": 25910,
"s": 25880,
"text": "Maven Dependency for PDFBox :"
},
{
"code": null,
"e": 26044,
"s": 25910,
"text": "<dependency>\n <groupId>org.apache.pdfbox</groupId>\n <artifactId>pdfbox</artifactId>\n <version>2.0.21</version>\n</dependency>"
},
{
"code": null,
"e": 26071,
"s": 26044,
"text": "1. Load the PDF Document: "
},
{
"code": null,
"e": 26240,
"s": 26071,
"text": "Load the PDF file using load() static method (we can access it by using the class name) of class PDDocument. The load() method will accept the PDF file as a parameter. "
},
{
"code": null,
"e": 26315,
"s": 26240,
"text": "File f = new File(\"path_of_PDFfile\");\nPDDocument pdd = PDDocument.load(f);"
},
{
"code": null,
"e": 26366,
"s": 26315,
"text": "2. Create an instance of AccessPermission class : "
},
{
"code": null,
"e": 26412,
"s": 26366,
"text": "AccessPermission ap = new AccessPermission();"
},
{
"code": null,
"e": 26464,
"s": 26412,
"text": "3. Create an instance of StandardProtectionPolicy: "
},
{
"code": null,
"e": 26611,
"s": 26464,
"text": "During the instantiation of StandardProtectionPolicy class pass owner password, user password, and object of AccessPermission class that is ‘ap’. "
},
{
"code": null,
"e": 26706,
"s": 26611,
"text": "StandardProtectionPolicy stpp = new StandardProtectionPolicy(\"Owner_pass\" , \"user_pass\" , ap);"
},
{
"code": null,
"e": 26761,
"s": 26706,
"text": " Here we can use any password to encrypt the PDF file."
},
{
"code": null,
"e": 26835,
"s": 26761,
"text": " Example: Here consider the password “abcd” as a user and owner password."
},
{
"code": null,
"e": 26920,
"s": 26835,
"text": "StandardProtectionPolicy stpp = new StandardProtectionPolicy(\"abcd\" , \"abcd\" , ap); "
},
{
"code": null,
"e": 26958,
"s": 26920,
"text": "4. Set the length of Encryption Key: "
},
{
"code": null,
"e": 27069,
"s": 26958,
"text": "Set the length of encryption key by using setEncryptionKeyLength() method of StandardProtectionPolicy class . "
},
{
"code": null,
"e": 27103,
"s": 27069,
"text": "stpp.setEncryptionKeyLength(128);"
},
{
"code": null,
"e": 27123,
"s": 27103,
"text": "5. Set Permission: "
},
{
"code": null,
"e": 27309,
"s": 27123,
"text": "Set the permission to PDF using setPermission() method of StandardProtectionPolicy class. You have to pass the object of AccessPermissionclass as a parameter in setPermission() method. "
},
{
"code": null,
"e": 27333,
"s": 27309,
"text": "stpp.setPermission(ap);"
},
{
"code": null,
"e": 27359,
"s": 27333,
"text": "6. Protect the PDF file: "
},
{
"code": null,
"e": 27521,
"s": 27359,
"text": "Protect the PDF file using the protect() method of PDDocument class. Here in this, we have to pass the object of StandardProtectionPolicy class as a parameter. "
},
{
"code": null,
"e": 27540,
"s": 27521,
"text": "pdd.protect(stpp);"
},
{
"code": null,
"e": 27573,
"s": 27540,
"text": "7. Save and close the Document: "
},
{
"code": null,
"e": 27671,
"s": 27573,
"text": "Finally, save and close the document by using the save() and close() method of PDDocument class. "
},
{
"code": null,
"e": 27787,
"s": 27671,
"text": "pdd.save(\"path_of_PDFfile\"); // save the document\npdd.close(); // close the document"
},
{
"code": null,
"e": 27792,
"s": 27787,
"text": "Java"
},
{
"code": "import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.encryption.AccessPermission;import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;import java.io.File;import java.io.IOException; class PdfEncryption { public static void main(String[] args) throws IOException { // step 1. Loading the pdf file File f = new File(\"D:\\\\demo.pdf\"); PDDocument pdd = PDDocument.load(f); // step 2.Creating instance of AccessPermission // class AccessPermission ap = new AccessPermission(); // step 3. Creating instance of // StandardProtectionPolicy StandardProtectionPolicy stpp = new StandardProtectionPolicy(\"abcd\", \"abcd\", ap); // step 4. Setting the length of Encryption key stpp.setEncryptionKeyLength(128); // step 5. Setting the permission stpp.setPermissions(ap); // step 6. Protecting the PDF file pdd.protect(stpp); // step 7. Saving and closing the the PDF Document pdd.save(\"D:\\\\demo.pdf1\"); pdd.close(); System.out.println(\"PDF Encrypted successfully...\"); }}",
"e": 28954,
"s": 27792,
"text": null
},
{
"code": null,
"e": 28966,
"s": 28958,
"text": "Output:"
},
{
"code": null,
"e": 28988,
"s": 28968,
"text": "Before Encryption :"
},
{
"code": null,
"e": 29159,
"s": 28990,
"text": "Here, you will see you don’t need any password to access the file. Before Encryption, You can directly access the file without need any credentials. Let’s have a look. "
},
{
"code": null,
"e": 29180,
"s": 29161,
"text": " After Encryption:"
},
{
"code": null,
"e": 29384,
"s": 29182,
"text": "After Encryption, Your PDF file will be saved on a given location and will be saved in a protected mode that simply means you will need a password to access or to read the PDF file. Let’s have a look. "
},
{
"code": null,
"e": 29463,
"s": 29388,
"text": "In these ways, you can easily protect your PDF Document using a password. "
},
{
"code": null,
"e": 29561,
"s": 29465,
"text": "If you want to implement this program on Eclipse IDE then used the following steps given below."
},
{
"code": null,
"e": 29581,
"s": 29563,
"text": "Open Eclipse IDE."
},
{
"code": null,
"e": 29634,
"s": 29581,
"text": "Create a New Java Project for example PDFEncryption."
},
{
"code": null,
"e": 29683,
"s": 29634,
"text": "Now, Create a New Java Class like PdfEncryption."
},
{
"code": null,
"e": 29762,
"s": 29683,
"text": "Now, to add the dependencies add two .jar files that are using in the program."
},
{
"code": null,
"e": 29838,
"s": 29762,
"text": "Add PDFBox library from this link download .jar file and Add PDFBox 2.0.21."
},
{
"code": null,
"e": 29916,
"s": 29838,
"text": "Add Apache Commons Logging library from this link Apache Commons Logging 1.2."
},
{
"code": null,
"e": 29979,
"s": 29918,
"text": "You can check the given below screenshot for your reference."
},
{
"code": null,
"e": 29993,
"s": 29983,
"text": "ruhelaa48"
},
{
"code": null,
"e": 29998,
"s": 29993,
"text": "Java"
},
{
"code": null,
"e": 30012,
"s": 29998,
"text": "Java Programs"
},
{
"code": null,
"e": 30017,
"s": 30012,
"text": "Java"
},
{
"code": null,
"e": 30115,
"s": 30017,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30124,
"s": 30115,
"text": "Comments"
},
{
"code": null,
"e": 30137,
"s": 30124,
"text": "Old Comments"
},
{
"code": null,
"e": 30188,
"s": 30137,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30218,
"s": 30188,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 30249,
"s": 30218,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 30268,
"s": 30249,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30300,
"s": 30268,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30344,
"s": 30300,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 30372,
"s": 30344,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 30398,
"s": 30372,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 30432,
"s": 30398,
"text": "Convert Double to Integer in Java"
}
]
|
Lowest Common Ancestor in a BST | Practice | GeeksforGeeks | Given a Binary Search Tree (with all values unique) and two node values. Find the Lowest Common Ancestors of the two nodes in the BST.
Example 1:
Input:
5
/ \
4 6
/ \
3 7
\
8
n1 = 7, n2 = 8
Output: 7
Example 2:
Input:
2
/ \
1 3
n1 = 1, n2 = 3
Output: 2
Your Task:
You don't need to read input or print anything. Your task is to complete the function LCA() which takes the root Node of the BST and two integer values n1 and n2 as inputs and returns the Lowest Common Ancestor of the Nodes with values n1 and n2 in the given BST.
Expected Time Complexity: O(Height of the BST).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 <= N <= 104
0
sikkusaurav1236 days ago
gud Q.
Node* LCA(Node *root, int n1, int n2){ //Your code here if(root==NULL) { return NULL; } if(root->data==n1 || root->data==n2) { return root; } Node* left=LCA(root->left,n1,n2); Node* right=LCA(root->right,n1,n2); if(left!=NULL && right!=NULL) { return root; } else if(left!=NULL && right==NULL) { return left; } else { return right; } }
0
adarshgupta4012 weeks ago
5 line Easy Java Code-
Node LCA(Node root, int p, int q)
{
if(root == null) return null;
int cur = root.data;
if(cur> p && cur> q) return LCA(root.left, p, q);
if(cur< p && cur< q) return LCA(root.right, p, q);
return root;
}
0
deepeshupadhyay853 weeks ago
Java Solution
class BST{ //Function to find the lowest common ancestor in a BST. Node LCA(Node node, int d1, int d2){ // code here. if (node == null) { return null; } if(d1<node.data && d2<node.data){ return LCA(node.left,d1,d2); }else if(d1>node.data && d2 > node.data){ return LCA(node.right,d1,d2); }else{ return node; } } }
+1
aryankhatana353 weeks ago
if(root==NULL){ return NULL; } if(root->data>n1 && root->data>n2){ return LCA(root->left,n1,n2); } if(root->data<n1 && root->data<n2){ return LCA(root->right,n1,n2); } return root;
0
aryankhatana353 weeks ago
while(root!=NULL){ if(root->data>n1 && root->data>n2) root=root->left; else if(root->data<n1 && root->data<n2 ) root=root->right; else{ return root; } }
+2
aryanar2018813 weeks ago
C++ Code
Node* LCA(Node *root, int n1, int n2){ Node *temp = root; while(true) { if(!temp) return NULL; if(n1==temp->data) return temp; else if(n2==temp->data) return temp; else if(temp->data>n1 && temp->data<n2) return temp; else if(temp->data<n1 && temp->data>n2) return temp; else if(temp->data>n1 && temp->data>n2) temp = temp->left; else if(temp->data<n1 && temp->data<n2) temp = temp->right; }}
0
kritikasinha2564 weeks ago
PYTHON
def LCA(root, n1, n2): l, r= min(n1, n2), max(n1,n2) while root is not None: if l <= root.data <= r: return root elif root.data >l and root.data>r: root = root.left else: root = root.right
+1
sfazal0001 month ago
node* LCA(node* root, int n1 ,int n2){ if(root == NULL) { return NULL; } if(n1 < root->data and n2 < root->data) { return LCA(root->left, n1 , n2); } else if(n1 > root->data and n2 > root ->data) { return LCA(root->right , n1 ,n2); } else { return root; }}
+2
adityasingh1091 month ago
Node* LCA(Node *root, int n1, int n2)
{
if(root == NULL)
return NULL;
if(root->data < n1 && root->data <n2)
return LCA(root->right, n1,n2);
if(root->data > n1 && root->data >n2)
return LCA(root->left, n1,n2);
return root;
}
0
detroix071 month ago
Node* LCA(Node *root, int n1, int n2){ if(root==NULL) return NULL; if(root->data==n1 or root->data==n2) return root; Node* left = LCA(root->left,n1,n2); Node* right = LCA(root->right,n1,n2); if(left!=NULL and right!=NULL) return root; else if (left==NULL) return r; else if(right==NULL) return l;}
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": 373,
"s": 238,
"text": "Given a Binary Search Tree (with all values unique) and two node values. Find the Lowest Common Ancestors of the two nodes in the BST."
},
{
"code": null,
"e": 384,
"s": 373,
"text": "Example 1:"
},
{
"code": null,
"e": 556,
"s": 384,
"text": "Input:\n 5\n / \\\n 4 6\n / \\\n 3 7\n \\\n 8\nn1 = 7, n2 = 8\nOutput: 7\n"
},
{
"code": null,
"e": 567,
"s": 556,
"text": "Example 2:"
},
{
"code": null,
"e": 626,
"s": 567,
"text": "Input:\n 2\n / \\\n 1 3\nn1 = 1, n2 = 3\nOutput: 2\n"
},
{
"code": null,
"e": 902,
"s": 626,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function LCA() which takes the root Node of the BST and two integer values n1 and n2 as inputs and returns the Lowest Common Ancestor of the Nodes with values n1 and n2 in the given BST. "
},
{
"code": null,
"e": 998,
"s": 902,
"text": "Expected Time Complexity: O(Height of the BST).\nExpected Auxiliary Space: O(Height of the BST)."
},
{
"code": null,
"e": 1025,
"s": 998,
"text": "Constraints:\n1 <= N <= 104"
},
{
"code": null,
"e": 1027,
"s": 1025,
"text": "0"
},
{
"code": null,
"e": 1052,
"s": 1027,
"text": "sikkusaurav1236 days ago"
},
{
"code": null,
"e": 1059,
"s": 1052,
"text": "gud Q."
},
{
"code": null,
"e": 1441,
"s": 1059,
"text": "Node* LCA(Node *root, int n1, int n2){ //Your code here if(root==NULL) { return NULL; } if(root->data==n1 || root->data==n2) { return root; } Node* left=LCA(root->left,n1,n2); Node* right=LCA(root->right,n1,n2); if(left!=NULL && right!=NULL) { return root; } else if(left!=NULL && right==NULL) { return left; } else { return right; } }"
},
{
"code": null,
"e": 1445,
"s": 1443,
"text": "0"
},
{
"code": null,
"e": 1471,
"s": 1445,
"text": "adarshgupta4012 weeks ago"
},
{
"code": null,
"e": 1494,
"s": 1471,
"text": "5 line Easy Java Code-"
},
{
"code": null,
"e": 1750,
"s": 1494,
"text": "Node LCA(Node root, int p, int q)\n\t{\n if(root == null) return null;\n int cur = root.data;\n if(cur> p && cur> q) return LCA(root.left, p, q);\n if(cur< p && cur< q) return LCA(root.right, p, q);\n return root; \n }"
},
{
"code": null,
"e": 1752,
"s": 1750,
"text": "0"
},
{
"code": null,
"e": 1781,
"s": 1752,
"text": "deepeshupadhyay853 weeks ago"
},
{
"code": null,
"e": 1796,
"s": 1781,
"text": "Java Solution "
},
{
"code": null,
"e": 2204,
"s": 1798,
"text": "class BST{ //Function to find the lowest common ancestor in a BST. Node LCA(Node node, int d1, int d2){ // code here. if (node == null) { return null; } if(d1<node.data && d2<node.data){ return LCA(node.left,d1,d2); }else if(d1>node.data && d2 > node.data){ return LCA(node.right,d1,d2); }else{ return node; } } } "
},
{
"code": null,
"e": 2207,
"s": 2204,
"text": "+1"
},
{
"code": null,
"e": 2233,
"s": 2207,
"text": "aryankhatana353 weeks ago"
},
{
"code": null,
"e": 2429,
"s": 2233,
"text": " if(root==NULL){ return NULL; } if(root->data>n1 && root->data>n2){ return LCA(root->left,n1,n2); } if(root->data<n1 && root->data<n2){ return LCA(root->right,n1,n2); } return root;"
},
{
"code": null,
"e": 2431,
"s": 2429,
"text": "0"
},
{
"code": null,
"e": 2457,
"s": 2431,
"text": "aryankhatana353 weeks ago"
},
{
"code": null,
"e": 2675,
"s": 2461,
"text": "while(root!=NULL){ if(root->data>n1 && root->data>n2) root=root->left; else if(root->data<n1 && root->data<n2 ) root=root->right; else{ return root; } }"
},
{
"code": null,
"e": 2678,
"s": 2675,
"text": "+2"
},
{
"code": null,
"e": 2703,
"s": 2678,
"text": "aryanar2018813 weeks ago"
},
{
"code": null,
"e": 2713,
"s": 2703,
"text": "C++ Code "
},
{
"code": null,
"e": 3155,
"s": 2713,
"text": "Node* LCA(Node *root, int n1, int n2){ Node *temp = root; while(true) { if(!temp) return NULL; if(n1==temp->data) return temp; else if(n2==temp->data) return temp; else if(temp->data>n1 && temp->data<n2) return temp; else if(temp->data<n1 && temp->data>n2) return temp; else if(temp->data>n1 && temp->data>n2) temp = temp->left; else if(temp->data<n1 && temp->data<n2) temp = temp->right; }}"
},
{
"code": null,
"e": 3157,
"s": 3155,
"text": "0"
},
{
"code": null,
"e": 3184,
"s": 3157,
"text": "kritikasinha2564 weeks ago"
},
{
"code": null,
"e": 3192,
"s": 3184,
"text": "PYTHON "
},
{
"code": null,
"e": 3436,
"s": 3192,
"text": "def LCA(root, n1, n2): l, r= min(n1, n2), max(n1,n2) while root is not None: if l <= root.data <= r: return root elif root.data >l and root.data>r: root = root.left else: root = root.right"
},
{
"code": null,
"e": 3439,
"s": 3436,
"text": "+1"
},
{
"code": null,
"e": 3460,
"s": 3439,
"text": "sfazal0001 month ago"
},
{
"code": null,
"e": 3795,
"s": 3460,
"text": "node* LCA(node* root, int n1 ,int n2){ if(root == NULL) { return NULL; } if(n1 < root->data and n2 < root->data) { return LCA(root->left, n1 , n2); } else if(n1 > root->data and n2 > root ->data) { return LCA(root->right , n1 ,n2); } else { return root; }} "
},
{
"code": null,
"e": 3798,
"s": 3795,
"text": "+2"
},
{
"code": null,
"e": 3824,
"s": 3798,
"text": "adityasingh1091 month ago"
},
{
"code": null,
"e": 4119,
"s": 3824,
"text": "Node* LCA(Node *root, int n1, int n2)\n{\n if(root == NULL)\n return NULL;\n \n if(root->data < n1 && root->data <n2)\n return LCA(root->right, n1,n2);\n \n if(root->data > n1 && root->data >n2)\n return LCA(root->left, n1,n2);\n \n return root; \n}"
},
{
"code": null,
"e": 4121,
"s": 4119,
"text": "0"
},
{
"code": null,
"e": 4142,
"s": 4121,
"text": "detroix071 month ago"
},
{
"code": null,
"e": 4448,
"s": 4142,
"text": "Node* LCA(Node *root, int n1, int n2){ if(root==NULL) return NULL; if(root->data==n1 or root->data==n2) return root; Node* left = LCA(root->left,n1,n2); Node* right = LCA(root->right,n1,n2); if(left!=NULL and right!=NULL) return root; else if (left==NULL) return r; else if(right==NULL) return l;} "
},
{
"code": null,
"e": 4594,
"s": 4448,
"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": 4630,
"s": 4594,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4640,
"s": 4630,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4650,
"s": 4640,
"text": "\nContest\n"
},
{
"code": null,
"e": 4713,
"s": 4650,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4861,
"s": 4713,
"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": 5069,
"s": 4861,
"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": 5175,
"s": 5069,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
p5.js | loop() Function - GeeksforGeeks | 17 Jan, 2020
The loop() function is used to call draw() function continuously. The loop() function can be stopped using noLoop() function.
Syntax:
loop()
Below example illustrates the loop() function in p5.js:
Example:
let l = 0; function setup() { // Create canvas of given size createCanvas(500, 300); // Set the background color background('green'); } function draw() { // Set the stroke color stroke('white'); l = l + 0.5; if (l > width) { l = 0; } // Function to draw the line line(l, 0, l, height); } function mousePressed() { noLoop();} function mouseReleased() { loop();}
Output:
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
JavaScript-p5.js
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
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
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": 43301,
"s": 43273,
"text": "\n17 Jan, 2020"
},
{
"code": null,
"e": 43427,
"s": 43301,
"text": "The loop() function is used to call draw() function continuously. The loop() function can be stopped using noLoop() function."
},
{
"code": null,
"e": 43435,
"s": 43427,
"text": "Syntax:"
},
{
"code": null,
"e": 43442,
"s": 43435,
"text": "loop()"
},
{
"code": null,
"e": 43498,
"s": 43442,
"text": "Below example illustrates the loop() function in p5.js:"
},
{
"code": null,
"e": 43507,
"s": 43498,
"text": "Example:"
},
{
"code": "let l = 0; function setup() { // Create canvas of given size createCanvas(500, 300); // Set the background color background('green'); } function draw() { // Set the stroke color stroke('white'); l = l + 0.5; if (l > width) { l = 0; } // Function to draw the line line(l, 0, l, height); } function mousePressed() { noLoop();} function mouseReleased() { loop();}",
"e": 43912,
"s": 43507,
"text": null
},
{
"code": null,
"e": 43920,
"s": 43912,
"text": "Output:"
},
{
"code": null,
"e": 44057,
"s": 43920,
"text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/"
},
{
"code": null,
"e": 44074,
"s": 44057,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 44085,
"s": 44074,
"text": "JavaScript"
},
{
"code": null,
"e": 44102,
"s": 44085,
"text": "Web Technologies"
},
{
"code": null,
"e": 44200,
"s": 44102,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44209,
"s": 44200,
"text": "Comments"
},
{
"code": null,
"e": 44222,
"s": 44209,
"text": "Old Comments"
},
{
"code": null,
"e": 44283,
"s": 44222,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 44328,
"s": 44283,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 44400,
"s": 44328,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 44469,
"s": 44400,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 44496,
"s": 44469,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 44552,
"s": 44496,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 44585,
"s": 44552,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 44647,
"s": 44585,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 44690,
"s": 44647,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
The intuition behind Shannon’s Entropy | by Aerin Kim | Towards Data Science | In Chapter 3.13 Information Theory of The Deep Learning Book by Ian Goodfellow, it says:
we define the self-information of an event X = x to be
I(x) = −log P (x)
Our definition of I(x) is therefore written in units of nats. One nat is the amount of information gained by observing an event of probability 1/e.
...
We can quantify the amount of uncertainty in an entire probability distribution using the Shannon entropy.
For anyone who wants to be fluent in Machine Learning, understanding Shannon’s entropy is crucial. Shannon’s Entropy leads to a function which is the bread and butter of an ML practitioner — the cross entropy that is heavily used as a loss function in classification and also the KL divergence which is widely used in variational inference.
Bits are either 0 or 1.
Therefore, with 1 bit, we can represent 2 different facts (aka information), either one or zero (or True or False). Let’s say you are a commander in World War II in 1945. Your telegrapher told you that if Nazis surrender, he will send you a ‘1’ and if they don’t, he will send you a ‘0’.
In 2018, you can send the exact same information on a smartphone typing
“The war is over” (instead of 1 bit, we use 8 bits * 15 characters = 120 bits)
“The war is not over” (8 bits * 19 characters = 152 bits)
So, we’re using more than 100 bits to send a message that could be reduced to just one bit.
Let’s say there are four possible war outcomes tomorrow instead of two. 1) Germany and Japan both surrender. 2) Germany surrenders but Japan doesn’t. 3) Japan surrenders but Germany doesn’t. 4) Both don’t surrender. Now your telegrapher would need 2 bits (00,01,10,11) to encode this message. In the same way, he would need only 8 bits even if there are 256 different scenarios.
A little more formally, the entropy of a variable is the “amount of information” contained in the variable. You can think of variable as news from the telegrapher. The news can be anything. It doesn’t have to be 4 states, 256 states, etc. In real life, news can be millions of different facts.
Now, back to our formula 3.49:
I(x) is the information content of X.
I(x) itself is a random variable. In our example, the possible outcomes of the War. Thus, H(x) is the expected value of every possible information.
Using the definition of expected value, the above equation can be re-written as
Wait... Why do we take the reciprocal of probability?
H(X) is the total amount of information in an entire probability distribution. This means 1/p(x) should be the information of each case (winning the war, losing the war, etc).
Lets say there is 50 50 chance that the Nazis would surrender (p = 1/2). Then, if your telegrapher tells you that they did surrender, you can eliminate the uncertainty of total 2 events (both surrender and not surrender), which is the reciprocal of p (=1/2).
When your events are all equally likely to happen and you know that one event just happened, you can eliminate the possibility of every other event (total 1/p events) happening. For example, let’s say there are 4 events and they are all equally likely to happen (p = 1/4). When one event happens, it says the other three events didn’t happen. Thus, we know what happened to total 4 events.
Let’s say there is a 75% chance that Nazis will surrender and a 25% chance that they won’t.
How much information does the event ‘surrender’ have?
log (1/0.75) = log(1.333) = 0.41 (log base 2 omitted going forward)
How much information does the event ‘not surrender’ have?
log (1/0.25) = log(4) = 2
As you see, the unlikely event has a higher entropy.
Here is the intuition on why information is the reciprocal of the probability.
The black dot is the news.
By knowing the black dot, we can eliminate 3 other white dots at the same time.
Total 4 dots (total information) burst.
Now, by knowing ONE black dot, how many TOTAL dots can we burst?
We can eliminate total 1 and 1/3 = 1.333 dots, which is the reciprocal of 3/4.
The total amount of dots you can burst = the information content in EACH news.
Thus, the information in EVERY possible news is 0.25 * log(4) + 0.75 * log(1.333)= 0.81 (Shannon’s entropy formula.)
Now we know where 1/p comes from. But why the log? Shannon thought that the information content of anything can be measured in bits. To write a number N in bits, we need to take a log base 2 of N.
If we have P(win) =1, the entropy is 0. It has 0 bits of uncertainty. (-log1 = 0)
Note that thermodynamic “entropy” and the “entropy” in information theory both capture increasing randomness.
Notice that in our example, with the “equally likely” messages, the entropy is higher (2 bits) than the “not equally likely” messages (0.81 bits). This is because there is less uncertainty in “not equally likely” messages. One event is more likely to come up than the other. This reduces the uncertainty.
For implementation addicts, here is the Python code.
See how the more the number of characters, the greater the uncertainty (entropy).
import math import randomdef H(sentence): """ Equation 3.49 (Shannon's Entropy) is implemented. """ entropy = 0 # There are 256 possible ASCII characters for character_i in range(256): Px = sentence.count(chr(character_i))/len(sentence) if Px > 0: entropy += - Px * math.log(Px, 2) return entropy# The telegrapher creates the "encoded message" with length 10000.# When he uses only 32 chars simple_message ="".join([chr(random.randint(0,32)) for i in range(10000)])# When he uses all 255 charscomplex_message ="".join([chr(random.randint(0,255)) for i in range(10000)])# Seeing is believing.In [20]: H(simple_message)Out[20]: 5.0426649536728 the In [21]: H(complex_message)Out[21]: 7.980385887737537# The entropy increases as the uncertainty of which character will be sent increases.
In the next post, I’ll explain how we extend Shannon’s Entropy to Cross Entropy and KL Divergence.
If you like my post, could you please clap? It gives me motivation to write more. :) | [
{
"code": null,
"e": 261,
"s": 172,
"text": "In Chapter 3.13 Information Theory of The Deep Learning Book by Ian Goodfellow, it says:"
},
{
"code": null,
"e": 316,
"s": 261,
"text": "we define the self-information of an event X = x to be"
},
{
"code": null,
"e": 334,
"s": 316,
"text": "I(x) = −log P (x)"
},
{
"code": null,
"e": 482,
"s": 334,
"text": "Our definition of I(x) is therefore written in units of nats. One nat is the amount of information gained by observing an event of probability 1/e."
},
{
"code": null,
"e": 486,
"s": 482,
"text": "..."
},
{
"code": null,
"e": 593,
"s": 486,
"text": "We can quantify the amount of uncertainty in an entire probability distribution using the Shannon entropy."
},
{
"code": null,
"e": 934,
"s": 593,
"text": "For anyone who wants to be fluent in Machine Learning, understanding Shannon’s entropy is crucial. Shannon’s Entropy leads to a function which is the bread and butter of an ML practitioner — the cross entropy that is heavily used as a loss function in classification and also the KL divergence which is widely used in variational inference."
},
{
"code": null,
"e": 958,
"s": 934,
"text": "Bits are either 0 or 1."
},
{
"code": null,
"e": 1246,
"s": 958,
"text": "Therefore, with 1 bit, we can represent 2 different facts (aka information), either one or zero (or True or False). Let’s say you are a commander in World War II in 1945. Your telegrapher told you that if Nazis surrender, he will send you a ‘1’ and if they don’t, he will send you a ‘0’."
},
{
"code": null,
"e": 1318,
"s": 1246,
"text": "In 2018, you can send the exact same information on a smartphone typing"
},
{
"code": null,
"e": 1397,
"s": 1318,
"text": "“The war is over” (instead of 1 bit, we use 8 bits * 15 characters = 120 bits)"
},
{
"code": null,
"e": 1455,
"s": 1397,
"text": "“The war is not over” (8 bits * 19 characters = 152 bits)"
},
{
"code": null,
"e": 1547,
"s": 1455,
"text": "So, we’re using more than 100 bits to send a message that could be reduced to just one bit."
},
{
"code": null,
"e": 1926,
"s": 1547,
"text": "Let’s say there are four possible war outcomes tomorrow instead of two. 1) Germany and Japan both surrender. 2) Germany surrenders but Japan doesn’t. 3) Japan surrenders but Germany doesn’t. 4) Both don’t surrender. Now your telegrapher would need 2 bits (00,01,10,11) to encode this message. In the same way, he would need only 8 bits even if there are 256 different scenarios."
},
{
"code": null,
"e": 2220,
"s": 1926,
"text": "A little more formally, the entropy of a variable is the “amount of information” contained in the variable. You can think of variable as news from the telegrapher. The news can be anything. It doesn’t have to be 4 states, 256 states, etc. In real life, news can be millions of different facts."
},
{
"code": null,
"e": 2251,
"s": 2220,
"text": "Now, back to our formula 3.49:"
},
{
"code": null,
"e": 2289,
"s": 2251,
"text": "I(x) is the information content of X."
},
{
"code": null,
"e": 2437,
"s": 2289,
"text": "I(x) itself is a random variable. In our example, the possible outcomes of the War. Thus, H(x) is the expected value of every possible information."
},
{
"code": null,
"e": 2517,
"s": 2437,
"text": "Using the definition of expected value, the above equation can be re-written as"
},
{
"code": null,
"e": 2571,
"s": 2517,
"text": "Wait... Why do we take the reciprocal of probability?"
},
{
"code": null,
"e": 2747,
"s": 2571,
"text": "H(X) is the total amount of information in an entire probability distribution. This means 1/p(x) should be the information of each case (winning the war, losing the war, etc)."
},
{
"code": null,
"e": 3006,
"s": 2747,
"text": "Lets say there is 50 50 chance that the Nazis would surrender (p = 1/2). Then, if your telegrapher tells you that they did surrender, you can eliminate the uncertainty of total 2 events (both surrender and not surrender), which is the reciprocal of p (=1/2)."
},
{
"code": null,
"e": 3396,
"s": 3006,
"text": "When your events are all equally likely to happen and you know that one event just happened, you can eliminate the possibility of every other event (total 1/p events) happening. For example, let’s say there are 4 events and they are all equally likely to happen (p = 1/4). When one event happens, it says the other three events didn’t happen. Thus, we know what happened to total 4 events."
},
{
"code": null,
"e": 3488,
"s": 3396,
"text": "Let’s say there is a 75% chance that Nazis will surrender and a 25% chance that they won’t."
},
{
"code": null,
"e": 3542,
"s": 3488,
"text": "How much information does the event ‘surrender’ have?"
},
{
"code": null,
"e": 3610,
"s": 3542,
"text": "log (1/0.75) = log(1.333) = 0.41 (log base 2 omitted going forward)"
},
{
"code": null,
"e": 3668,
"s": 3610,
"text": "How much information does the event ‘not surrender’ have?"
},
{
"code": null,
"e": 3694,
"s": 3668,
"text": "log (1/0.25) = log(4) = 2"
},
{
"code": null,
"e": 3747,
"s": 3694,
"text": "As you see, the unlikely event has a higher entropy."
},
{
"code": null,
"e": 3826,
"s": 3747,
"text": "Here is the intuition on why information is the reciprocal of the probability."
},
{
"code": null,
"e": 3853,
"s": 3826,
"text": "The black dot is the news."
},
{
"code": null,
"e": 3933,
"s": 3853,
"text": "By knowing the black dot, we can eliminate 3 other white dots at the same time."
},
{
"code": null,
"e": 3973,
"s": 3933,
"text": "Total 4 dots (total information) burst."
},
{
"code": null,
"e": 4038,
"s": 3973,
"text": "Now, by knowing ONE black dot, how many TOTAL dots can we burst?"
},
{
"code": null,
"e": 4117,
"s": 4038,
"text": "We can eliminate total 1 and 1/3 = 1.333 dots, which is the reciprocal of 3/4."
},
{
"code": null,
"e": 4196,
"s": 4117,
"text": "The total amount of dots you can burst = the information content in EACH news."
},
{
"code": null,
"e": 4313,
"s": 4196,
"text": "Thus, the information in EVERY possible news is 0.25 * log(4) + 0.75 * log(1.333)= 0.81 (Shannon’s entropy formula.)"
},
{
"code": null,
"e": 4510,
"s": 4313,
"text": "Now we know where 1/p comes from. But why the log? Shannon thought that the information content of anything can be measured in bits. To write a number N in bits, we need to take a log base 2 of N."
},
{
"code": null,
"e": 4592,
"s": 4510,
"text": "If we have P(win) =1, the entropy is 0. It has 0 bits of uncertainty. (-log1 = 0)"
},
{
"code": null,
"e": 4702,
"s": 4592,
"text": "Note that thermodynamic “entropy” and the “entropy” in information theory both capture increasing randomness."
},
{
"code": null,
"e": 5007,
"s": 4702,
"text": "Notice that in our example, with the “equally likely” messages, the entropy is higher (2 bits) than the “not equally likely” messages (0.81 bits). This is because there is less uncertainty in “not equally likely” messages. One event is more likely to come up than the other. This reduces the uncertainty."
},
{
"code": null,
"e": 5060,
"s": 5007,
"text": "For implementation addicts, here is the Python code."
},
{
"code": null,
"e": 5142,
"s": 5060,
"text": "See how the more the number of characters, the greater the uncertainty (entropy)."
},
{
"code": null,
"e": 5979,
"s": 5142,
"text": "import math import randomdef H(sentence): \"\"\" Equation 3.49 (Shannon's Entropy) is implemented. \"\"\" entropy = 0 # There are 256 possible ASCII characters for character_i in range(256): Px = sentence.count(chr(character_i))/len(sentence) if Px > 0: entropy += - Px * math.log(Px, 2) return entropy# The telegrapher creates the \"encoded message\" with length 10000.# When he uses only 32 chars simple_message =\"\".join([chr(random.randint(0,32)) for i in range(10000)])# When he uses all 255 charscomplex_message =\"\".join([chr(random.randint(0,255)) for i in range(10000)])# Seeing is believing.In [20]: H(simple_message)Out[20]: 5.0426649536728 the In [21]: H(complex_message)Out[21]: 7.980385887737537# The entropy increases as the uncertainty of which character will be sent increases."
},
{
"code": null,
"e": 6078,
"s": 5979,
"text": "In the next post, I’ll explain how we extend Shannon’s Entropy to Cross Entropy and KL Divergence."
}
]
|
Java Program to Print Downward Triangle Star Pattern - GeeksforGeeks | 17 Mar, 2021
Downward triangle star pattern means we want to print a triangle that is downward facing means base is upwards and by default, orientation is leftwards so the desired triangle to be printed should look like
* * * *
* * *
* *
*
Example
Java
// Java Program to Print Lower Star Triangle Pattern // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Nested 2 for loops for iteration over the matrix // Outer loop for rows int rows = 9; for (int a = rows - 1; a >= 0; a--) { // Inner loop for columns for (int b = 0; b <= a; b++) { // Prints star and space System.out.print("*" + " "); } // By now we are done with single row so new // line System.out.println(); } }}
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
java-basics
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23582,
"s": 23554,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 23789,
"s": 23582,
"text": "Downward triangle star pattern means we want to print a triangle that is downward facing means base is upwards and by default, orientation is leftwards so the desired triangle to be printed should look like"
},
{
"code": null,
"e": 23809,
"s": 23789,
"text": "* * * *\n* * *\n* *\n*"
},
{
"code": null,
"e": 23817,
"s": 23809,
"text": "Example"
},
{
"code": null,
"e": 23822,
"s": 23817,
"text": "Java"
},
{
"code": "// Java Program to Print Lower Star Triangle Pattern // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Nested 2 for loops for iteration over the matrix // Outer loop for rows int rows = 9; for (int a = rows - 1; a >= 0; a--) { // Inner loop for columns for (int b = 0; b <= a; b++) { // Prints star and space System.out.print(\"*\" + \" \"); } // By now we are done with single row so new // line System.out.println(); } }}",
"e": 24476,
"s": 23822,
"text": null
},
{
"code": null,
"e": 24576,
"s": 24476,
"text": "* * * * * * * * * \n* * * * * * * * \n* * * * * * * \n* * * * * * \n* * * * * \n* * * * \n* * * \n* * \n* \n"
},
{
"code": null,
"e": 24588,
"s": 24576,
"text": "java-basics"
},
{
"code": null,
"e": 24595,
"s": 24588,
"text": "Picked"
},
{
"code": null,
"e": 24600,
"s": 24595,
"text": "Java"
},
{
"code": null,
"e": 24614,
"s": 24600,
"text": "Java Programs"
},
{
"code": null,
"e": 24619,
"s": 24614,
"text": "Java"
},
{
"code": null,
"e": 24717,
"s": 24619,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24726,
"s": 24717,
"text": "Comments"
},
{
"code": null,
"e": 24739,
"s": 24726,
"text": "Old Comments"
},
{
"code": null,
"e": 24769,
"s": 24739,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 24784,
"s": 24769,
"text": "Stream In Java"
},
{
"code": null,
"e": 24805,
"s": 24784,
"text": "Constructors in Java"
},
{
"code": null,
"e": 24851,
"s": 24805,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 24870,
"s": 24851,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 24914,
"s": 24870,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 24940,
"s": 24914,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 24974,
"s": 24940,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 25021,
"s": 24974,
"text": "Implementing a Linked List in Java using Class"
}
]
|
How to create a hyperlink with a Label in Tkinter? | Tkinter Label widgets are generally used to display text or images. In this example, we will see how to add a hyperlink on a Label widget in an application.
In order to add a hyperlink, we can bind the label text with a button that makes it clickable. The open_new(url) method is used to define the function that opens a web browser to follow the link. The open_new(url) method is defined in the webbrowser module in Python which can be imported in the notebook using 'import webbrowser'.
#Import the required libraries
from tkinter import *
import webbrowser
#Create an instance of tkinter frame
win = Tk()
win.geometry("750x250")
#Define a callback function
def callback(url):
webbrowser.open_new_tab(url)
#Create a Label to display the link
link = Label(win, text="www.tutorialspoint.com",font=('Helveticabold', 15), fg="blue", cursor="hand2")
link.pack()
link.bind("<Button-1>", lambda e:
callback("http://www.tutorialspoint.com"))
win.mainloop()
Running the above code will display a Label text with a URL.
The displayed window will show a hyperlink which upon clicking will redirect the user to the website: www.tutorialspoint.com | [
{
"code": null,
"e": 1219,
"s": 1062,
"text": "Tkinter Label widgets are generally used to display text or images. In this example, we will see how to add a hyperlink on a Label widget in an application."
},
{
"code": null,
"e": 1551,
"s": 1219,
"text": "In order to add a hyperlink, we can bind the label text with a button that makes it clickable. The open_new(url) method is used to define the function that opens a web browser to follow the link. The open_new(url) method is defined in the webbrowser module in Python which can be imported in the notebook using 'import webbrowser'."
},
{
"code": null,
"e": 2020,
"s": 1551,
"text": "#Import the required libraries\nfrom tkinter import *\nimport webbrowser\n\n#Create an instance of tkinter frame\nwin = Tk()\nwin.geometry(\"750x250\")\n\n#Define a callback function\ndef callback(url):\n webbrowser.open_new_tab(url)\n\n#Create a Label to display the link\nlink = Label(win, text=\"www.tutorialspoint.com\",font=('Helveticabold', 15), fg=\"blue\", cursor=\"hand2\")\nlink.pack()\nlink.bind(\"<Button-1>\", lambda e:\ncallback(\"http://www.tutorialspoint.com\"))\n\nwin.mainloop()"
},
{
"code": null,
"e": 2081,
"s": 2020,
"text": "Running the above code will display a Label text with a URL."
},
{
"code": null,
"e": 2206,
"s": 2081,
"text": "The displayed window will show a hyperlink which upon clicking will redirect the user to the website: www.tutorialspoint.com"
}
]
|
Java & MySQL - Transactions | If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed to the database upon its completion.
That may be fine for simple applications, but there are three reasons why you may want to turn off the auto-commit and manage your own transactions −
To increase performance.
To increase performance.
To maintain the integrity of business processes.
To maintain the integrity of business processes.
To use distributed transactions.
To use distributed transactions.
Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction fails.
To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again.
For example, if you have a Connection object named conn, code the following to turn off auto-commit −
conn.setAutoCommit(false);
Once you are done with your changes and you want to commit the changes then call commit() method on connection object as follows −
conn.commit( );
Otherwise, to roll back updates to the database made using the Connection named conn, use the following code −
conn.rollback( );
The new JDBC 3.0 Savepoint interface gives you the additional transactional control.
When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a savepoint, you can use the rollback method to undo either all the changes or only the changes made after the savepoint.
The Connection object has two new methods that help you manage savepoints −
setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object.
setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object.
releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method.
releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method.
There is one rollback (String savepointName) method, which rolls back work to the specified savepoint.
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2833,
"s": 2686,
"text": "If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed to the database upon its completion."
},
{
"code": null,
"e": 2983,
"s": 2833,
"text": "That may be fine for simple applications, but there are three reasons why you may want to turn off the auto-commit and manage your own transactions −"
},
{
"code": null,
"e": 3008,
"s": 2983,
"text": "To increase performance."
},
{
"code": null,
"e": 3033,
"s": 3008,
"text": "To increase performance."
},
{
"code": null,
"e": 3082,
"s": 3033,
"text": "To maintain the integrity of business processes."
},
{
"code": null,
"e": 3131,
"s": 3082,
"text": "To maintain the integrity of business processes."
},
{
"code": null,
"e": 3164,
"s": 3131,
"text": "To use distributed transactions."
},
{
"code": null,
"e": 3197,
"s": 3164,
"text": "To use distributed transactions."
},
{
"code": null,
"e": 3423,
"s": 3197,
"text": "Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction fails."
},
{
"code": null,
"e": 3712,
"s": 3423,
"text": "To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again."
},
{
"code": null,
"e": 3814,
"s": 3712,
"text": "For example, if you have a Connection object named conn, code the following to turn off auto-commit −"
},
{
"code": null,
"e": 3842,
"s": 3814,
"text": "conn.setAutoCommit(false);\n"
},
{
"code": null,
"e": 3973,
"s": 3842,
"text": "Once you are done with your changes and you want to commit the changes then call commit() method on connection object as follows −"
},
{
"code": null,
"e": 3990,
"s": 3973,
"text": "conn.commit( );\n"
},
{
"code": null,
"e": 4101,
"s": 3990,
"text": "Otherwise, to roll back updates to the database made using the Connection named conn, use the following code −"
},
{
"code": null,
"e": 4120,
"s": 4101,
"text": "conn.rollback( );\n"
},
{
"code": null,
"e": 4205,
"s": 4120,
"text": "The new JDBC 3.0 Savepoint interface gives you the additional transactional control."
},
{
"code": null,
"e": 4434,
"s": 4205,
"text": "When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a savepoint, you can use the rollback method to undo either all the changes or only the changes made after the savepoint."
},
{
"code": null,
"e": 4510,
"s": 4434,
"text": "The Connection object has two new methods that help you manage savepoints −"
},
{
"code": null,
"e": 4608,
"s": 4510,
"text": "setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object."
},
{
"code": null,
"e": 4706,
"s": 4608,
"text": "setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object."
},
{
"code": null,
"e": 4905,
"s": 4706,
"text": "releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method."
},
{
"code": null,
"e": 5104,
"s": 4905,
"text": "releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method."
},
{
"code": null,
"e": 5207,
"s": 5104,
"text": "There is one rollback (String savepointName) method, which rolls back work to the specified savepoint."
},
{
"code": null,
"e": 5240,
"s": 5207,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5256,
"s": 5240,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5289,
"s": 5256,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5305,
"s": 5289,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5340,
"s": 5305,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5354,
"s": 5340,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5388,
"s": 5354,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5402,
"s": 5388,
"text": " Tushar Kale"
},
{
"code": null,
"e": 5439,
"s": 5402,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5454,
"s": 5439,
"text": " Monica Mittal"
},
{
"code": null,
"e": 5487,
"s": 5454,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5506,
"s": 5487,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5513,
"s": 5506,
"text": " Print"
},
{
"code": null,
"e": 5524,
"s": 5513,
"text": " Add Notes"
}
]
|
Check whether a node is a root node or not in JTree | To check whether a node is a root node or not, use the isRoot() method. This returns a boolean value. TRUE if the node is a root node, else FALSE is returned. For example, TRUE is returned since the following node is a root node −
node.isRoot()
Another example, FALSE is returned since the following node isn’t a root node −
node2.isRoot()
The following is an example to check whether a node is a root node or not −
package my;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class SwingDemo {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Demo");
DefaultMutableTreeNode node = new DefaultMutableTreeNode("Website");
DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Videos");
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Tutorials");
DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("QA");
DefaultMutableTreeNode node4 = new DefaultMutableTreeNode("Tools");
node.add(node1);
node.add(node2);
node.add(node3);
node.add(node4);
DefaultMutableTreeNode one = new DefaultMutableTreeNode("PHP Videos");
DefaultMutableTreeNode two = new DefaultMutableTreeNode("HTML5 Videos");
DefaultMutableTreeNode three = new DefaultMutableTreeNode("BlockchainVideos");
DefaultMutableTreeNode four = new DefaultMutableTreeNode("Java");
DefaultMutableTreeNode five = new DefaultMutableTreeNode("DBMS");
DefaultMutableTreeNode six = new DefaultMutableTreeNode("CSS");
DefaultMutableTreeNode seven = new DefaultMutableTreeNode("MongoDB");
DefaultMutableTreeNode eight = new DefaultMutableTreeNode("Python QA");
DefaultMutableTreeNode nine = new DefaultMutableTreeNode("jQuery QA");
DefaultMutableTreeNode ten = new DefaultMutableTreeNode("Photo Editing Tool");
node1.add(one);
node1.add(two);
node1.add(three);
node2.add(four);
node2.add(five);
node2.add(six);
node2.add(seven);
node3.add(eight);
node3.add(nine);
node4.add(ten);
JTree tree = new JTree(node);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
tree.putClientProperty("JTree.lineStyle", "Angled");
System.out.println("Number of children of node1 (Videos) = " +node1.getChildCount());
System.out.println("Number of children of node2 (Tutorials) = " +node2.getChildCount());
System.out.println("Number of children of node3 (QA) = " +node3.getChildCount());
System.out.println("Number of children of node4 (Tools) = " +node4.getChildCount());
System.out.println("Depth of Tree = " + node.getDepth());
System.out.println("Count of Tree Leaves(root node) = " +node.getLeafCount());
System.out.println("Count of Tree Leaves(node1) = " +node1.getLeafCount());
System.out.println("Count of Tree Leaves(node2) = " +node2.getLeafCount());
System.out.println("Count of Tree Leaves(node3) = " +node3.getLeafCount());
System.out.println("Count of Tree Leaves(node3) = " +node4.getLeafCount());
System.out.println("Is node the root node? = " + node.isRoot());
System.out.println("Is node1 the root node? = " + node1.isRoot());
System.out.println("Is node2 the root node? = " + node2.isRoot());
System.out.println("Is node3 the root node? = " + node3.isRoot());
System.out.println("Is node4 the root node? = " + node4.isRoot());
tree.setRowHeight(25);
frame.add(tree);
frame.setSize(600,450);
frame.setVisible(true);
}
}
Following is our JTree − | [
{
"code": null,
"e": 1293,
"s": 1062,
"text": "To check whether a node is a root node or not, use the isRoot() method. This returns a boolean value. TRUE if the node is a root node, else FALSE is returned. For example, TRUE is returned since the following node is a root node −"
},
{
"code": null,
"e": 1307,
"s": 1293,
"text": "node.isRoot()"
},
{
"code": null,
"e": 1387,
"s": 1307,
"text": "Another example, FALSE is returned since the following node isn’t a root node −"
},
{
"code": null,
"e": 1402,
"s": 1387,
"text": "node2.isRoot()"
},
{
"code": null,
"e": 1478,
"s": 1402,
"text": "The following is an example to check whether a node is a root node or not −"
},
{
"code": null,
"e": 4692,
"s": 1478,
"text": "package my;\nimport javax.swing.JFrame;\nimport javax.swing.JTree;\nimport javax.swing.tree.DefaultMutableTreeNode;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame frame = new JFrame(\"Demo\");\n DefaultMutableTreeNode node = new DefaultMutableTreeNode(\"Website\");\n DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(\"Videos\");\n DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(\"Tutorials\");\n DefaultMutableTreeNode node3 = new DefaultMutableTreeNode(\"QA\");\n DefaultMutableTreeNode node4 = new DefaultMutableTreeNode(\"Tools\");\n node.add(node1);\n node.add(node2);\n node.add(node3);\n node.add(node4);\n DefaultMutableTreeNode one = new DefaultMutableTreeNode(\"PHP Videos\");\n DefaultMutableTreeNode two = new DefaultMutableTreeNode(\"HTML5 Videos\");\n DefaultMutableTreeNode three = new DefaultMutableTreeNode(\"BlockchainVideos\");\n DefaultMutableTreeNode four = new DefaultMutableTreeNode(\"Java\");\n DefaultMutableTreeNode five = new DefaultMutableTreeNode(\"DBMS\");\n DefaultMutableTreeNode six = new DefaultMutableTreeNode(\"CSS\");\n DefaultMutableTreeNode seven = new DefaultMutableTreeNode(\"MongoDB\");\n DefaultMutableTreeNode eight = new DefaultMutableTreeNode(\"Python QA\");\n DefaultMutableTreeNode nine = new DefaultMutableTreeNode(\"jQuery QA\");\n DefaultMutableTreeNode ten = new DefaultMutableTreeNode(\"Photo Editing Tool\");\n node1.add(one);\n node1.add(two);\n node1.add(three);\n node2.add(four);\n node2.add(five);\n node2.add(six);\n node2.add(seven);\n node3.add(eight);\n node3.add(nine);\n node4.add(ten);\n JTree tree = new JTree(node);\n for (int i = 0; i < tree.getRowCount(); i++) {\n tree.expandRow(i);\n }\n tree.putClientProperty(\"JTree.lineStyle\", \"Angled\");\n System.out.println(\"Number of children of node1 (Videos) = \" +node1.getChildCount());\n System.out.println(\"Number of children of node2 (Tutorials) = \" +node2.getChildCount());\n System.out.println(\"Number of children of node3 (QA) = \" +node3.getChildCount());\n System.out.println(\"Number of children of node4 (Tools) = \" +node4.getChildCount());\n System.out.println(\"Depth of Tree = \" + node.getDepth());\n System.out.println(\"Count of Tree Leaves(root node) = \" +node.getLeafCount());\n System.out.println(\"Count of Tree Leaves(node1) = \" +node1.getLeafCount());\n System.out.println(\"Count of Tree Leaves(node2) = \" +node2.getLeafCount());\n System.out.println(\"Count of Tree Leaves(node3) = \" +node3.getLeafCount());\n System.out.println(\"Count of Tree Leaves(node3) = \" +node4.getLeafCount());\n System.out.println(\"Is node the root node? = \" + node.isRoot());\n System.out.println(\"Is node1 the root node? = \" + node1.isRoot());\n System.out.println(\"Is node2 the root node? = \" + node2.isRoot());\n System.out.println(\"Is node3 the root node? = \" + node3.isRoot());\n System.out.println(\"Is node4 the root node? = \" + node4.isRoot());\n tree.setRowHeight(25);\n frame.add(tree);\n frame.setSize(600,450);\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 4717,
"s": 4692,
"text": "Following is our JTree −"
}
]
|
How to replace an item from an array in JavaScript? - GeeksforGeeks | 26 Jul, 2021
An item can be replaced in an array using two approaches:
Method 1: Using splice() methodThe array type in JavaScript provides us with splice() method that helps us in order to replace the items of an existing array by removing and inserting new elements at the required/desired index.Approach:Initialize an array and then we applied the splice() method on it resulting the insertion of the element “February” at index 1 without removing any element.Apply another splice() method on the resulted array after the first splice(), in order to replace the element “June” which is at index 4 (in the output array of the first splice() method) by the element “May”.Syntax:Array.splice(start_index, delete_count, value1, value2, value3, ...)Note: Splice() method deletes zero or more elements of an array starting with including the start_index element and replaces those elements with zero or more elements specified in the argument list.Splice() method modifies the array directly dissimilar to the similarly named Slice() method.Example 1: Below are some examples to illustrates Splice() method:This example illustrate the simple use of splice method.<!DOCTYPE html><html> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <p>Click on the button to replace the array elements. </p> <button onclick="element_replace()"> Replace </button> <p>The Updated Array Elements:</p> <p id="result"></p> <script> function element_replace() { // Initializing the array var list = ["January", "March", "April", "June"]; // splicing the array elements using splice() method list.splice(1, 0, "February"); // expected output [January, February, March, April, June] // splicing the output elements after the first splicing list.splice(4, 1, "May"); document.getElementById( "result").innerHTML = list; } </script> </center></body> </html>Output after clicking the button:
The array type in JavaScript provides us with splice() method that helps us in order to replace the items of an existing array by removing and inserting new elements at the required/desired index.
Approach:
Initialize an array and then we applied the splice() method on it resulting the insertion of the element “February” at index 1 without removing any element.
Apply another splice() method on the resulted array after the first splice(), in order to replace the element “June” which is at index 4 (in the output array of the first splice() method) by the element “May”.
Syntax:
Array.splice(start_index, delete_count, value1, value2, value3, ...)
Note: Splice() method deletes zero or more elements of an array starting with including the start_index element and replaces those elements with zero or more elements specified in the argument list.Splice() method modifies the array directly dissimilar to the similarly named Slice() method.
Example 1: Below are some examples to illustrates Splice() method:This example illustrate the simple use of splice method.
<!DOCTYPE html><html> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <p>Click on the button to replace the array elements. </p> <button onclick="element_replace()"> Replace </button> <p>The Updated Array Elements:</p> <p id="result"></p> <script> function element_replace() { // Initializing the array var list = ["January", "March", "April", "June"]; // splicing the array elements using splice() method list.splice(1, 0, "February"); // expected output [January, February, March, April, June] // splicing the output elements after the first splicing list.splice(4, 1, "May"); document.getElementById( "result").innerHTML = list; } </script> </center></body> </html>
Output after clicking the button:
Method 2: Using array map() and filter() methods.The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. arr.filter() the function is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument function. With the help ofApproach:Initialize an array.Select the targetd index with the help of .map and .filter methods.Set the new value at targeted indexSyntax:ele[ele.map((x, i) => [i, x]).filter(x => x[1] == old_value)[0][0]] = new_valueExample 2:<!DOCTYPE html><html> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <p> Click on the button to replace the array elements. </p> <button onclick="element_replace()"> Replace </button> <p>The Updated Array Elements:</p> <p id="result"></p> <script> function element_replace() { var ele = Array(10, 20, 300, 40, 50); ele[ele.map((x, i) => [i, x]).filter( x => x[1] == 300)[0][0]] = 30 console.log(ele); } </script> </center></body> </html>Output:
The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. arr.filter() the function is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument function. With the help of
Approach:
Initialize an array.
Select the targetd index with the help of .map and .filter methods.
Set the new value at targeted index
Syntax:
ele[ele.map((x, i) => [i, x]).filter(x => x[1] == old_value)[0][0]] = new_value
Example 2:
<!DOCTYPE html><html> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <p> Click on the button to replace the array elements. </p> <button onclick="element_replace()"> Replace </button> <p>The Updated Array Elements:</p> <p id="result"></p> <script> function element_replace() { var ele = Array(10, 20, 300, 40, 50); ele[ele.map((x, i) => [i, x]).filter( x => x[1] == 300)[0][0]] = 30 console.log(ele); } </script> </center></body> </html>
Output:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
javascript-array
JavaScript-Misc
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
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
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": 24479,
"s": 24451,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 24537,
"s": 24479,
"text": "An item can be replaced in an array using two approaches:"
},
{
"code": null,
"e": 26664,
"s": 24537,
"text": "Method 1: Using splice() methodThe array type in JavaScript provides us with splice() method that helps us in order to replace the items of an existing array by removing and inserting new elements at the required/desired index.Approach:Initialize an array and then we applied the splice() method on it resulting the insertion of the element “February” at index 1 without removing any element.Apply another splice() method on the resulted array after the first splice(), in order to replace the element “June” which is at index 4 (in the output array of the first splice() method) by the element “May”.Syntax:Array.splice(start_index, delete_count, value1, value2, value3, ...)Note: Splice() method deletes zero or more elements of an array starting with including the start_index element and replaces those elements with zero or more elements specified in the argument list.Splice() method modifies the array directly dissimilar to the similarly named Slice() method.Example 1: Below are some examples to illustrates Splice() method:This example illustrate the simple use of splice method.<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <p>Click on the button to replace the array elements. </p> <button onclick=\"element_replace()\"> Replace </button> <p>The Updated Array Elements:</p> <p id=\"result\"></p> <script> function element_replace() { // Initializing the array var list = [\"January\", \"March\", \"April\", \"June\"]; // splicing the array elements using splice() method list.splice(1, 0, \"February\"); // expected output [January, February, March, April, June] // splicing the output elements after the first splicing list.splice(4, 1, \"May\"); document.getElementById( \"result\").innerHTML = list; } </script> </center></body> </html>Output after clicking the button:"
},
{
"code": null,
"e": 26861,
"s": 26664,
"text": "The array type in JavaScript provides us with splice() method that helps us in order to replace the items of an existing array by removing and inserting new elements at the required/desired index."
},
{
"code": null,
"e": 26871,
"s": 26861,
"text": "Approach:"
},
{
"code": null,
"e": 27028,
"s": 26871,
"text": "Initialize an array and then we applied the splice() method on it resulting the insertion of the element “February” at index 1 without removing any element."
},
{
"code": null,
"e": 27238,
"s": 27028,
"text": "Apply another splice() method on the resulted array after the first splice(), in order to replace the element “June” which is at index 4 (in the output array of the first splice() method) by the element “May”."
},
{
"code": null,
"e": 27246,
"s": 27238,
"text": "Syntax:"
},
{
"code": null,
"e": 27315,
"s": 27246,
"text": "Array.splice(start_index, delete_count, value1, value2, value3, ...)"
},
{
"code": null,
"e": 27607,
"s": 27315,
"text": "Note: Splice() method deletes zero or more elements of an array starting with including the start_index element and replaces those elements with zero or more elements specified in the argument list.Splice() method modifies the array directly dissimilar to the similarly named Slice() method."
},
{
"code": null,
"e": 27730,
"s": 27607,
"text": "Example 1: Below are some examples to illustrates Splice() method:This example illustrate the simple use of splice method."
},
{
"code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <p>Click on the button to replace the array elements. </p> <button onclick=\"element_replace()\"> Replace </button> <p>The Updated Array Elements:</p> <p id=\"result\"></p> <script> function element_replace() { // Initializing the array var list = [\"January\", \"March\", \"April\", \"June\"]; // splicing the array elements using splice() method list.splice(1, 0, \"February\"); // expected output [January, February, March, April, June] // splicing the output elements after the first splicing list.splice(4, 1, \"May\"); document.getElementById( \"result\").innerHTML = list; } </script> </center></body> </html>",
"e": 28735,
"s": 27730,
"text": null
},
{
"code": null,
"e": 28769,
"s": 28735,
"text": "Output after clicking the button:"
},
{
"code": null,
"e": 30039,
"s": 28769,
"text": "Method 2: Using array map() and filter() methods.The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. arr.filter() the function is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument function. With the help ofApproach:Initialize an array.Select the targetd index with the help of .map and .filter methods.Set the new value at targeted indexSyntax:ele[ele.map((x, i) => [i, x]).filter(x => x[1] == old_value)[0][0]] = new_valueExample 2:<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <p> Click on the button to replace the array elements. </p> <button onclick=\"element_replace()\"> Replace </button> <p>The Updated Array Elements:</p> <p id=\"result\"></p> <script> function element_replace() { var ele = Array(10, 20, 300, 40, 50); ele[ele.map((x, i) => [i, x]).filter( x => x[1] == 300)[0][0]] = 30 console.log(ele); } </script> </center></body> </html>Output:"
},
{
"code": null,
"e": 30366,
"s": 30039,
"text": "The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. arr.filter() the function is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument function. With the help of"
},
{
"code": null,
"e": 30376,
"s": 30366,
"text": "Approach:"
},
{
"code": null,
"e": 30397,
"s": 30376,
"text": "Initialize an array."
},
{
"code": null,
"e": 30465,
"s": 30397,
"text": "Select the targetd index with the help of .map and .filter methods."
},
{
"code": null,
"e": 30501,
"s": 30465,
"text": "Set the new value at targeted index"
},
{
"code": null,
"e": 30509,
"s": 30501,
"text": "Syntax:"
},
{
"code": null,
"e": 30589,
"s": 30509,
"text": "ele[ele.map((x, i) => [i, x]).filter(x => x[1] == old_value)[0][0]] = new_value"
},
{
"code": null,
"e": 30600,
"s": 30589,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <p> Click on the button to replace the array elements. </p> <button onclick=\"element_replace()\"> Replace </button> <p>The Updated Array Elements:</p> <p id=\"result\"></p> <script> function element_replace() { var ele = Array(10, 20, 300, 40, 50); ele[ele.map((x, i) => [i, x]).filter( x => x[1] == 300)[0][0]] = 30 console.log(ele); } </script> </center></body> </html>",
"e": 31261,
"s": 30600,
"text": null
},
{
"code": null,
"e": 31269,
"s": 31261,
"text": "Output:"
},
{
"code": null,
"e": 31488,
"s": 31269,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 31505,
"s": 31488,
"text": "javascript-array"
},
{
"code": null,
"e": 31521,
"s": 31505,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 31528,
"s": 31521,
"text": "Picked"
},
{
"code": null,
"e": 31539,
"s": 31528,
"text": "JavaScript"
},
{
"code": null,
"e": 31556,
"s": 31539,
"text": "Web Technologies"
},
{
"code": null,
"e": 31654,
"s": 31556,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31663,
"s": 31654,
"text": "Comments"
},
{
"code": null,
"e": 31676,
"s": 31663,
"text": "Old Comments"
},
{
"code": null,
"e": 31737,
"s": 31676,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31782,
"s": 31737,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31854,
"s": 31782,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 31906,
"s": 31854,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 31952,
"s": 31906,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 32008,
"s": 31952,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 32041,
"s": 32008,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32103,
"s": 32041,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 32146,
"s": 32103,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Maximum number of characters between any two same character in a string in C | We are given a string of alphabets. The array can have at least two occurrences of the same character. The task here is to find the maximum number of characters between any two occurrences of a character. If there is no repetition of any character then return -1.
Input − string str = “abcdba”
Output −Maximum number of characters between any two same character in a string − 4
Explanation − The repeating characters are ‘a’ and ‘b’ only with indexes −
1. 2‘a’ first index 0 last 5 , characters in between 5-0-1=4
2. ‘b’ first index 1 last 4 , characters in between 4-1-1=2
Maximum character in between repeating alphabets : 4
Input − string str = “AbcAaBcbC”
Output −Maximum number of characters between any two same character in a string − 5
Explanation − The repeating characters are ‘A’ , ‘b’ , ‘c’ only with indexes −
1. ‘A’ first index 0 last 3 , characters in between 3-0-1=2
2. ‘b’ first index 1 last 7 , characters in between 7-1-1=5
3. ‘c’ first index 2 last 6 , characters in between 6-2-1=3
Maximum character in between repeating alphabets : 5
Note − if the input string is “abcdefg” , there are no repeating characters so the function will return -1.
We take a character array having a string of characters as Str[]
We take a character array having a string of characters as Str[]
The function maxChars( char str[],int n) is used to calculate the maximum number of characters between any two repeating alphabets.
The function maxChars( char str[],int n) is used to calculate the maximum number of characters between any two repeating alphabets.
We initialize the variable maxC with -1.
We initialize the variable maxC with -1.
Inside for loop traverse the array of string from the beginning.
Inside for loop traverse the array of string from the beginning.
In nested for loop traverse the remaining characters and search for repetitions if any. ( if ( str[i] == str[j] ).
In nested for loop traverse the remaining characters and search for repetitions if any. ( if ( str[i] == str[j] ).
If it is true then calculate difference between characters by subtracting the indexes. ( temp=j-i-1)
If it is true then calculate difference between characters by subtracting the indexes. ( temp=j-i-1)
If this value is maximum found so far, then store it in maxC.
If this value is maximum found so far, then store it in maxC.
Return maxC after traversing the whole string.
Return maxC after traversing the whole string.
Live Demo
#include <stdio.h>
#include <stdio.h>
#include <math.h>
int maxChars(char str[],int n){
int size = n;
int maxC = -1;
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
if (str[i] == str[j]){
int temp=abs(j-i-1);
maxC = maxC>temp?maxC:temp;
}
return maxC;
}
// Driver code
int main(){
char Str[] = "AbcAaBcbC";
printf("Maximum number of characters between any two same character in a string :%d",
maxChars(Str,9) );
return 0;
}
If we run the above code it will generate the following output −
Maximum number of characters between any two same character in a string : 5 | [
{
"code": null,
"e": 1326,
"s": 1062,
"text": "We are given a string of alphabets. The array can have at least two occurrences of the same character. The task here is to find the maximum number of characters between any two occurrences of a character. If there is no repetition of any character then return -1."
},
{
"code": null,
"e": 1356,
"s": 1326,
"text": "Input − string str = “abcdba”"
},
{
"code": null,
"e": 1440,
"s": 1356,
"text": "Output −Maximum number of characters between any two same character in a string − 4"
},
{
"code": null,
"e": 1515,
"s": 1440,
"text": "Explanation − The repeating characters are ‘a’ and ‘b’ only with indexes −"
},
{
"code": null,
"e": 1692,
"s": 1515,
"text": "1. 2‘a’ first index 0 last 5 , characters in between 5-0-1=4\n2. ‘b’ first index 1 last 4 , characters in between 4-1-1=2\n Maximum character in between repeating alphabets : 4"
},
{
"code": null,
"e": 1725,
"s": 1692,
"text": "Input − string str = “AbcAaBcbC”"
},
{
"code": null,
"e": 1809,
"s": 1725,
"text": "Output −Maximum number of characters between any two same character in a string − 5"
},
{
"code": null,
"e": 1888,
"s": 1809,
"text": "Explanation − The repeating characters are ‘A’ , ‘b’ , ‘c’ only with indexes −"
},
{
"code": null,
"e": 2124,
"s": 1888,
"text": "1. ‘A’ first index 0 last 3 , characters in between 3-0-1=2\n2. ‘b’ first index 1 last 7 , characters in between 7-1-1=5\n3. ‘c’ first index 2 last 6 , characters in between 6-2-1=3\n Maximum character in between repeating alphabets : 5"
},
{
"code": null,
"e": 2232,
"s": 2124,
"text": "Note − if the input string is “abcdefg” , there are no repeating characters so the function will return -1."
},
{
"code": null,
"e": 2297,
"s": 2232,
"text": "We take a character array having a string of characters as Str[]"
},
{
"code": null,
"e": 2362,
"s": 2297,
"text": "We take a character array having a string of characters as Str[]"
},
{
"code": null,
"e": 2494,
"s": 2362,
"text": "The function maxChars( char str[],int n) is used to calculate the maximum number of characters between any two repeating alphabets."
},
{
"code": null,
"e": 2626,
"s": 2494,
"text": "The function maxChars( char str[],int n) is used to calculate the maximum number of characters between any two repeating alphabets."
},
{
"code": null,
"e": 2667,
"s": 2626,
"text": "We initialize the variable maxC with -1."
},
{
"code": null,
"e": 2708,
"s": 2667,
"text": "We initialize the variable maxC with -1."
},
{
"code": null,
"e": 2773,
"s": 2708,
"text": "Inside for loop traverse the array of string from the beginning."
},
{
"code": null,
"e": 2838,
"s": 2773,
"text": "Inside for loop traverse the array of string from the beginning."
},
{
"code": null,
"e": 2953,
"s": 2838,
"text": "In nested for loop traverse the remaining characters and search for repetitions if any. ( if ( str[i] == str[j] )."
},
{
"code": null,
"e": 3068,
"s": 2953,
"text": "In nested for loop traverse the remaining characters and search for repetitions if any. ( if ( str[i] == str[j] )."
},
{
"code": null,
"e": 3169,
"s": 3068,
"text": "If it is true then calculate difference between characters by subtracting the indexes. ( temp=j-i-1)"
},
{
"code": null,
"e": 3270,
"s": 3169,
"text": "If it is true then calculate difference between characters by subtracting the indexes. ( temp=j-i-1)"
},
{
"code": null,
"e": 3332,
"s": 3270,
"text": "If this value is maximum found so far, then store it in maxC."
},
{
"code": null,
"e": 3394,
"s": 3332,
"text": "If this value is maximum found so far, then store it in maxC."
},
{
"code": null,
"e": 3441,
"s": 3394,
"text": "Return maxC after traversing the whole string."
},
{
"code": null,
"e": 3488,
"s": 3441,
"text": "Return maxC after traversing the whole string."
},
{
"code": null,
"e": 3499,
"s": 3488,
"text": " Live Demo"
},
{
"code": null,
"e": 4011,
"s": 3499,
"text": "#include <stdio.h>\n#include <stdio.h>\n#include <math.h>\nint maxChars(char str[],int n){\n int size = n;\n int maxC = -1;\n for (int i = 0; i < n - 1; i++)\n for (int j = i + 1; j < n; j++)\n if (str[i] == str[j]){\n int temp=abs(j-i-1);\n maxC = maxC>temp?maxC:temp;\n }\n return maxC;\n}\n// Driver code\nint main(){\n char Str[] = \"AbcAaBcbC\";\n printf(\"Maximum number of characters between any two same character in a string :%d\",\n maxChars(Str,9) );\n return 0;\n}"
},
{
"code": null,
"e": 4076,
"s": 4011,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 4152,
"s": 4076,
"text": "Maximum number of characters between any two same character in a string : 5"
}
]
|
How to programmatically configure Chrome extension through Selenium WebDriver? | We can programmatically configure Chrome extension through Selenium webdriver. We can have multiple extensions of the Chrome browser while we manually open the browser and work on it.
However, while the Chrome browser is opened through Selenium webdriver, those extensions which are available to the local browser will not be present. To configure an extension, we have to obtain the .crx extension file of the extension.
Then we have to add that extension to the browser which is launched by
Selenium webdriver. To get all the extensions available to the browser enter
chrome://extensions on the browser.
To get add an extension for example: Momentum, visit the link −
https://chrome.google.com/webstore/category/extensions and enter Momentum in the search box. Once the search results are displayed, click on the relevant option.
After clicking on the Momentum extension, the details of the extension gets displayed. Copy the URL of the extension as highlighted in the below image.
Now, navigate to the link: https://chrome−extension−downloader.com/ and paste the URL we have copied within the Download extension field.
The .crx file of the extension gets downloaded to our system. We should then
save it in a desired location.
To add this extension to the Chrome browser, once it is launched by Selenium webdriver, we have to use the ChromeOptions class. We shall create an object of this class and apply addExtensions method on it.
The path of the .crx file of the extension that we want to add is passed as a parameter to that method. Then use the DesiredCapabilities class to set this browser capability.
We shall apply the setCapability method on the object of DesiredCapabilities and pass ChromeOptions.CAPABILITY and object of the ChromeOptions class as parameters to that method. Finally, the object of DesiredCapabilities is passed as a parameter to the webdriver object.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.io.File;
public class AddExtensns{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
//ChromeOptions object
ChromeOptions opt= new ChromeOptions();
//set path of .crx file of extension
opt.addExtensions(new File("C:\\Users\\Momentum_v0.92.2.crx"));
//DesiredCapabilities object
DesiredCapabilities c = DesiredCapabilities.chrome();
// set ChromeOptions capability
c.setCapability(ChromeOptions.CAPABILITY, opt);
// pass capability to driver
WebDriver driver = new ChromeDriver(c);
driver.get("https://www.tutorialspoint.com/index.htm");
}
} | [
{
"code": null,
"e": 1246,
"s": 1062,
"text": "We can programmatically configure Chrome extension through Selenium webdriver. We can have multiple extensions of the Chrome browser while we manually open the browser and work on it."
},
{
"code": null,
"e": 1484,
"s": 1246,
"text": "However, while the Chrome browser is opened through Selenium webdriver, those extensions which are available to the local browser will not be present. To configure an extension, we have to obtain the .crx extension file of the extension."
},
{
"code": null,
"e": 1632,
"s": 1484,
"text": "Then we have to add that extension to the browser which is launched by\nSelenium webdriver. To get all the extensions available to the browser enter"
},
{
"code": null,
"e": 1668,
"s": 1632,
"text": "chrome://extensions on the browser."
},
{
"code": null,
"e": 1732,
"s": 1668,
"text": "To get add an extension for example: Momentum, visit the link −"
},
{
"code": null,
"e": 1894,
"s": 1732,
"text": "https://chrome.google.com/webstore/category/extensions and enter Momentum in the search box. Once the search results are displayed, click on the relevant option."
},
{
"code": null,
"e": 2046,
"s": 1894,
"text": "After clicking on the Momentum extension, the details of the extension gets displayed. Copy the URL of the extension as highlighted in the below image."
},
{
"code": null,
"e": 2184,
"s": 2046,
"text": "Now, navigate to the link: https://chrome−extension−downloader.com/ and paste the URL we have copied within the Download extension field."
},
{
"code": null,
"e": 2292,
"s": 2184,
"text": "The .crx file of the extension gets downloaded to our system. We should then\nsave it in a desired location."
},
{
"code": null,
"e": 2498,
"s": 2292,
"text": "To add this extension to the Chrome browser, once it is launched by Selenium webdriver, we have to use the ChromeOptions class. We shall create an object of this class and apply addExtensions method on it."
},
{
"code": null,
"e": 2673,
"s": 2498,
"text": "The path of the .crx file of the extension that we want to add is passed as a parameter to that method. Then use the DesiredCapabilities class to set this browser capability."
},
{
"code": null,
"e": 2945,
"s": 2673,
"text": "We shall apply the setCapability method on the object of DesiredCapabilities and pass ChromeOptions.CAPABILITY and object of the ChromeOptions class as parameters to that method. Finally, the object of DesiredCapabilities is passed as a parameter to the webdriver object."
},
{
"code": null,
"e": 3956,
"s": 2945,
"text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.Capabilities;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.chrome.ChromeOptions;\nimport org.openqa.selenium.remote.CapabilityType;\nimport org.openqa.selenium.remote.DesiredCapabilities;\nimport java.io.File;\npublic class AddExtensns{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n //ChromeOptions object\n ChromeOptions opt= new ChromeOptions();\n //set path of .crx file of extension\n opt.addExtensions(new File(\"C:\\\\Users\\\\Momentum_v0.92.2.crx\"));\n //DesiredCapabilities object\n DesiredCapabilities c = DesiredCapabilities.chrome();\n // set ChromeOptions capability\n c.setCapability(ChromeOptions.CAPABILITY, opt);\n // pass capability to driver\n WebDriver driver = new ChromeDriver(c);\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n }\n}"
}
]
|
How to Test for Statistically Significant Relationships Between Categorical Variables with Chi Square | by Lisa Chen | Towards Data Science | A while back, I was analyzing market research data for a survey my company released to gauge customer sentiments towards a new product idea. Many of the variables were categorical (i.e. male, female, which of these features is most / least appealing) and after some initial research, I decided a chi-squared test for independence would be the best way to discern if there were certain segments of the population more or less likely to like a feature.
However, I noticed many of the tutorials for implementing post hoc testing were in SPSS or R, with almost no native packages in Python. This inspired me to put together a Python tutorial for chi square test for independence and post hoc testing to understand which categories are significant and relationship directionality (i.e. more or less likely to want a feature).
To demonstrate, I will be using the results of a survey where 8,415 Americans rated how comfortable they would be with getting on a domestic flight within the next month.
They survey results allowed me to slice by age and political affiliation, so my 2 research questions were:
Does age group impact attitudes towards flying (ATF)? If so, how?Does political affiliation impact attitudes towards flying (ATF)? If so, how?
Does age group impact attitudes towards flying (ATF)? If so, how?
Does political affiliation impact attitudes towards flying (ATF)? If so, how?
A short explanation of how the chi-squared test works is you first assume the null hypothesis, which is no relationship between variable A (i.e. age) and variable B (i.e. ATF). You calculate the expected value for each cell based on the distribution of your variables, and compare with the observed value. The assumption here is that any variance in observations is from distributions in the data, not any underlying relationship.
As an example, let’s calculate the expected value of respondents between 18–24 selecting “Very Comfortable.” 19.76% of all respondents were 18–24, and 12.77% of all respondents said they were very comfortable with flying soon.
Expected Value = 19.76% x 12.77% x 501 (all observations) = 12.64. So in this case, the observed value was almost spot on for the expected value.
The difference between the observed value and the expected value is used to calculate the chi-squared statistic, which — in conjunction with degrees of freedom, is used to determine if the difference between observed and expected is significant or due to sampling error. (More in depth detail on chi-square testing here).
I decided to tackle the relationship between age and ATF first. I pivoted my dataset to create a contingency table, which is the format accepted by the chi2_contingency SciPy method.
import pandas as pdimport numpy as npfrom scipy.stats import chi2_contingencyfrom scipy.stats import normimport math# Reading in my csv with age and attitudes towards flyingraw_df = pd.read_csv(“age_flying.csv”)# Pivoting the dataframe and assigning Age as the index, Status as the column headings, and percentage of respondents as the valuespivot_df = raw_df.pivot(index=’Age’, columns=’Status’, values=’Percentage’)
At this point, my dataframe looked like the following:
Nothing stood out to me as being particularly higher or lower than the expected value for the cell, but I decided to run the test just in case.
chi2, p, dof, ex = chi2_contingency(pivot_df, correction=False)print(chi2, '{:.10f}'.format(p))
My output was 14.885706463917337 0.5330249996, which means my p-value was 0.53 and I fail to reject the null hypothesis (H0: there is no relationship between age and attitude towards flying in the next month).
I moved on to my next research question to investigate if there is a relationship between political affiliation and ATF.
I ran the same process listed above, but the output of my chi-squared test this time was 79.59995957590428 0.0000000002. My p-value was significantly under the commonly accepted 0.05 alpha value, which means we’re in business!
At this point, all I know is that there is some sort of statistically significant relationship between political affiliation and ATF. Post hoc testing will enable me to understand which categories are contributing to this significance, and how.
My process is:
For each combination of political affiliation and ATF, calculate the adjusted standardized residuals between the observed values and the expected values. Standardized residuals is another name for z-scores. Adjustment means I adjust for different frequency counts between columns and rows.Calculate the p-values of the z-scores, which will tell me how probable the difference between the observed and expected value isApply a p-value correction to account for running multiple tests on the same dataset, which typically leads to Type 1 errors.
For each combination of political affiliation and ATF, calculate the adjusted standardized residuals between the observed values and the expected values. Standardized residuals is another name for z-scores. Adjustment means I adjust for different frequency counts between columns and rows.
Calculate the p-values of the z-scores, which will tell me how probable the difference between the observed and expected value is
Apply a p-value correction to account for running multiple tests on the same dataset, which typically leads to Type 1 errors.
The formula to calculate adjusted standardized residuals is as follows:
First, I turned the pivot table back into a regular dataframe. I did this because pivot tables have less functionality and I can’t access columns or rows by name.
observed_vals = pivot_df.reset_index(drop=True)observed_vals = observed_vals.rename_axis(None, axis=1)observed_vals.set_index([["Dem", "Ind", "Not_sure", "Other", "Rep"]], inplace=True)observed_vals = observed_vals.reset_index()observed_vals.rename(columns={"index": "Party"}, inplace=True)
Next, I created a new dataframe with the expected values. Luckily, the chi2_contingency method outputs an array of expected values.
expected_vals = pd.DataFrame(ex)expected_vals.set_index([["Dem", "Ind", "Not_sure", "Other", "Rep"]], inplace=True)expected_vals = expected_vals.reset_index()expected_vals.rename(columns={"index": "Party", 0: "SW_Comfortable", 1:"SW_Uncomfortable", 2:"V_Comfortable", 3:"V_Uncomfortable", 4:"dont_know"}, inplace=True)
Then, I created two tables for the row-wise totals and column-wise totals. These values are the n in the (1- RowMarginal/n) * (1 - ColumnMarginal/n) part of the equation.
# Creating a column-wise sum table, adding back the column with party namescol_sum = pd.DataFrame(observed_vals.sum(axis=1), columns=["count"])col_sum.insert(0, "Party", ["Dem", "Ind", "Not_sure", "Other", "Rep"], True)# Creating a row-wise sum tablerow_sum = pd.DataFrame(observed_vals.iloc[:,1:].sum(axis=0), columns=["count"]).reset_index()row_sum.rename(columns={"index":"Status"}, inplace=True)
At this point, I had all of the information I needed to start calculating adjusted standardized residuals (try saying that 10 times, fast). I wrote a script to iterate through every combination of political affiliation and ATF, and calculate the adjusted standardized residual and accompanying p-value.
I applied a Bonferroni Correction to the p-value, which lowered my p-value threshold to 0.002 to reject the null hypothesis (0.05 / 25 comparisons). P-value corrections are applied when multiple tests are done on the same dataset (25, in my case), which increases chances of false positives.
# Find all the unique political parties for pairwise comparisonparties = list(raw_df["Party"].unique())# Find all the unique attitudes towards flying for pairwise comparisonstatus = list(raw_df["Status"].unique())# Iterate through all combinations of parties and statusfor p in parties: for s in status: observed = float(observed_vals.loc[observed_vals.Party == p][s].values[0]) expected = float(expected_vals.loc[expected_vals.Party == p][s].values[0]) col_total = float(col_sum[col_sum["Party"] == p]["count"].values[0]) row_total = float(row_sum[row_sum["Status"] == s]["count"].values[0]) expected_row_prop = expected/row_total expected_col_prop = expected/col_total std_resid = (observed - expected) / (math.sqrt(expected * (1-expected_row_prop) * (1-expected_col_prop))) p_val = norm.sf(abs(std_resid)) if p_val < 0.05/25: print(p, s, std_resid, p_val)
All of you are probably cringing at the double for-loop, but whatever — it gets the job done, okay? I configured the script to only print relationships with a p-value less than the corrected p-value, and the following turned out to be statistically significant at p < 0.002:
In this article, I ran briefly through the process of conducting a chi-squared test for independence and post hoc test, focusing primarily on the technical implementation. However, I think understanding the theory behind the implementation is crucial for debugging and interpreting results, so I linked resources that I personally found helpful so you can review if necessary.
Let’s circle back to my two original research questions and see what conclusions we dug up:
Does age group impact attitudes towards flying (ATF)? If so, how? NoDoes political affiliation impact attitudes towards flying (ATF)? If so, how? Yes, and quite significantly so! Democrats are more likely to have a “Very Uncomfortable” ATF compared to the average, Republicans are more likely to have a “Very Comfortable” ATF compared to the average, people who are not sure of their political affiliation are less likely to have a “Very Uncomfortable” ATF, but more likely to put “Don’t know.”
Does age group impact attitudes towards flying (ATF)? If so, how? No
Does political affiliation impact attitudes towards flying (ATF)? If so, how? Yes, and quite significantly so! Democrats are more likely to have a “Very Uncomfortable” ATF compared to the average, Republicans are more likely to have a “Very Comfortable” ATF compared to the average, people who are not sure of their political affiliation are less likely to have a “Very Uncomfortable” ATF, but more likely to put “Don’t know.”
I found the last insight to be very interesting — people who do not have strong political affiliations are more likely to not have an opinion towards flying. One possible explanation could be respondents just breezed through questions and didn’t put much thought into their response, which led to selecting the most neutral answers (i.e. not sure, don’t know).
Another, more interesting explanation could be that people who are politically engaged are more likely to watch the news and regularly consume media about current events. Since many media outlets are focusing on COVID-19, people who stay up-to-date will be exposed to more debates between authority figures with strong opinions about pandemic best practices (i.e. public health and safety protocol, travel bans). Conversely, those without strong political affiliations may tune in less compared to their partisan peers, and therefore are exposed to less polarizing opinions on how best to handle travel.
At this point, however, that is purely conjecture on my part. Now it’s up to you guys to calculate the adjusted standardized residual for my hypothesis and let me know if I’m right 😉 | [
{
"code": null,
"e": 622,
"s": 171,
"text": "A while back, I was analyzing market research data for a survey my company released to gauge customer sentiments towards a new product idea. Many of the variables were categorical (i.e. male, female, which of these features is most / least appealing) and after some initial research, I decided a chi-squared test for independence would be the best way to discern if there were certain segments of the population more or less likely to like a feature."
},
{
"code": null,
"e": 992,
"s": 622,
"text": "However, I noticed many of the tutorials for implementing post hoc testing were in SPSS or R, with almost no native packages in Python. This inspired me to put together a Python tutorial for chi square test for independence and post hoc testing to understand which categories are significant and relationship directionality (i.e. more or less likely to want a feature)."
},
{
"code": null,
"e": 1163,
"s": 992,
"text": "To demonstrate, I will be using the results of a survey where 8,415 Americans rated how comfortable they would be with getting on a domestic flight within the next month."
},
{
"code": null,
"e": 1270,
"s": 1163,
"text": "They survey results allowed me to slice by age and political affiliation, so my 2 research questions were:"
},
{
"code": null,
"e": 1413,
"s": 1270,
"text": "Does age group impact attitudes towards flying (ATF)? If so, how?Does political affiliation impact attitudes towards flying (ATF)? If so, how?"
},
{
"code": null,
"e": 1479,
"s": 1413,
"text": "Does age group impact attitudes towards flying (ATF)? If so, how?"
},
{
"code": null,
"e": 1557,
"s": 1479,
"text": "Does political affiliation impact attitudes towards flying (ATF)? If so, how?"
},
{
"code": null,
"e": 1988,
"s": 1557,
"text": "A short explanation of how the chi-squared test works is you first assume the null hypothesis, which is no relationship between variable A (i.e. age) and variable B (i.e. ATF). You calculate the expected value for each cell based on the distribution of your variables, and compare with the observed value. The assumption here is that any variance in observations is from distributions in the data, not any underlying relationship."
},
{
"code": null,
"e": 2215,
"s": 1988,
"text": "As an example, let’s calculate the expected value of respondents between 18–24 selecting “Very Comfortable.” 19.76% of all respondents were 18–24, and 12.77% of all respondents said they were very comfortable with flying soon."
},
{
"code": null,
"e": 2361,
"s": 2215,
"text": "Expected Value = 19.76% x 12.77% x 501 (all observations) = 12.64. So in this case, the observed value was almost spot on for the expected value."
},
{
"code": null,
"e": 2683,
"s": 2361,
"text": "The difference between the observed value and the expected value is used to calculate the chi-squared statistic, which — in conjunction with degrees of freedom, is used to determine if the difference between observed and expected is significant or due to sampling error. (More in depth detail on chi-square testing here)."
},
{
"code": null,
"e": 2866,
"s": 2683,
"text": "I decided to tackle the relationship between age and ATF first. I pivoted my dataset to create a contingency table, which is the format accepted by the chi2_contingency SciPy method."
},
{
"code": null,
"e": 3284,
"s": 2866,
"text": "import pandas as pdimport numpy as npfrom scipy.stats import chi2_contingencyfrom scipy.stats import normimport math# Reading in my csv with age and attitudes towards flyingraw_df = pd.read_csv(“age_flying.csv”)# Pivoting the dataframe and assigning Age as the index, Status as the column headings, and percentage of respondents as the valuespivot_df = raw_df.pivot(index=’Age’, columns=’Status’, values=’Percentage’)"
},
{
"code": null,
"e": 3339,
"s": 3284,
"text": "At this point, my dataframe looked like the following:"
},
{
"code": null,
"e": 3483,
"s": 3339,
"text": "Nothing stood out to me as being particularly higher or lower than the expected value for the cell, but I decided to run the test just in case."
},
{
"code": null,
"e": 3579,
"s": 3483,
"text": "chi2, p, dof, ex = chi2_contingency(pivot_df, correction=False)print(chi2, '{:.10f}'.format(p))"
},
{
"code": null,
"e": 3789,
"s": 3579,
"text": "My output was 14.885706463917337 0.5330249996, which means my p-value was 0.53 and I fail to reject the null hypothesis (H0: there is no relationship between age and attitude towards flying in the next month)."
},
{
"code": null,
"e": 3910,
"s": 3789,
"text": "I moved on to my next research question to investigate if there is a relationship between political affiliation and ATF."
},
{
"code": null,
"e": 4137,
"s": 3910,
"text": "I ran the same process listed above, but the output of my chi-squared test this time was 79.59995957590428 0.0000000002. My p-value was significantly under the commonly accepted 0.05 alpha value, which means we’re in business!"
},
{
"code": null,
"e": 4382,
"s": 4137,
"text": "At this point, all I know is that there is some sort of statistically significant relationship between political affiliation and ATF. Post hoc testing will enable me to understand which categories are contributing to this significance, and how."
},
{
"code": null,
"e": 4397,
"s": 4382,
"text": "My process is:"
},
{
"code": null,
"e": 4941,
"s": 4397,
"text": "For each combination of political affiliation and ATF, calculate the adjusted standardized residuals between the observed values and the expected values. Standardized residuals is another name for z-scores. Adjustment means I adjust for different frequency counts between columns and rows.Calculate the p-values of the z-scores, which will tell me how probable the difference between the observed and expected value isApply a p-value correction to account for running multiple tests on the same dataset, which typically leads to Type 1 errors."
},
{
"code": null,
"e": 5231,
"s": 4941,
"text": "For each combination of political affiliation and ATF, calculate the adjusted standardized residuals between the observed values and the expected values. Standardized residuals is another name for z-scores. Adjustment means I adjust for different frequency counts between columns and rows."
},
{
"code": null,
"e": 5361,
"s": 5231,
"text": "Calculate the p-values of the z-scores, which will tell me how probable the difference between the observed and expected value is"
},
{
"code": null,
"e": 5487,
"s": 5361,
"text": "Apply a p-value correction to account for running multiple tests on the same dataset, which typically leads to Type 1 errors."
},
{
"code": null,
"e": 5559,
"s": 5487,
"text": "The formula to calculate adjusted standardized residuals is as follows:"
},
{
"code": null,
"e": 5722,
"s": 5559,
"text": "First, I turned the pivot table back into a regular dataframe. I did this because pivot tables have less functionality and I can’t access columns or rows by name."
},
{
"code": null,
"e": 6013,
"s": 5722,
"text": "observed_vals = pivot_df.reset_index(drop=True)observed_vals = observed_vals.rename_axis(None, axis=1)observed_vals.set_index([[\"Dem\", \"Ind\", \"Not_sure\", \"Other\", \"Rep\"]], inplace=True)observed_vals = observed_vals.reset_index()observed_vals.rename(columns={\"index\": \"Party\"}, inplace=True)"
},
{
"code": null,
"e": 6145,
"s": 6013,
"text": "Next, I created a new dataframe with the expected values. Luckily, the chi2_contingency method outputs an array of expected values."
},
{
"code": null,
"e": 6464,
"s": 6145,
"text": "expected_vals = pd.DataFrame(ex)expected_vals.set_index([[\"Dem\", \"Ind\", \"Not_sure\", \"Other\", \"Rep\"]], inplace=True)expected_vals = expected_vals.reset_index()expected_vals.rename(columns={\"index\": \"Party\", 0: \"SW_Comfortable\", 1:\"SW_Uncomfortable\", 2:\"V_Comfortable\", 3:\"V_Uncomfortable\", 4:\"dont_know\"}, inplace=True)"
},
{
"code": null,
"e": 6635,
"s": 6464,
"text": "Then, I created two tables for the row-wise totals and column-wise totals. These values are the n in the (1- RowMarginal/n) * (1 - ColumnMarginal/n) part of the equation."
},
{
"code": null,
"e": 7035,
"s": 6635,
"text": "# Creating a column-wise sum table, adding back the column with party namescol_sum = pd.DataFrame(observed_vals.sum(axis=1), columns=[\"count\"])col_sum.insert(0, \"Party\", [\"Dem\", \"Ind\", \"Not_sure\", \"Other\", \"Rep\"], True)# Creating a row-wise sum tablerow_sum = pd.DataFrame(observed_vals.iloc[:,1:].sum(axis=0), columns=[\"count\"]).reset_index()row_sum.rename(columns={\"index\":\"Status\"}, inplace=True)"
},
{
"code": null,
"e": 7338,
"s": 7035,
"text": "At this point, I had all of the information I needed to start calculating adjusted standardized residuals (try saying that 10 times, fast). I wrote a script to iterate through every combination of political affiliation and ATF, and calculate the adjusted standardized residual and accompanying p-value."
},
{
"code": null,
"e": 7630,
"s": 7338,
"text": "I applied a Bonferroni Correction to the p-value, which lowered my p-value threshold to 0.002 to reject the null hypothesis (0.05 / 25 comparisons). P-value corrections are applied when multiple tests are done on the same dataset (25, in my case), which increases chances of false positives."
},
{
"code": null,
"e": 8566,
"s": 7630,
"text": "# Find all the unique political parties for pairwise comparisonparties = list(raw_df[\"Party\"].unique())# Find all the unique attitudes towards flying for pairwise comparisonstatus = list(raw_df[\"Status\"].unique())# Iterate through all combinations of parties and statusfor p in parties: for s in status: observed = float(observed_vals.loc[observed_vals.Party == p][s].values[0]) expected = float(expected_vals.loc[expected_vals.Party == p][s].values[0]) col_total = float(col_sum[col_sum[\"Party\"] == p][\"count\"].values[0]) row_total = float(row_sum[row_sum[\"Status\"] == s][\"count\"].values[0]) expected_row_prop = expected/row_total expected_col_prop = expected/col_total std_resid = (observed - expected) / (math.sqrt(expected * (1-expected_row_prop) * (1-expected_col_prop))) p_val = norm.sf(abs(std_resid)) if p_val < 0.05/25: print(p, s, std_resid, p_val)"
},
{
"code": null,
"e": 8841,
"s": 8566,
"text": "All of you are probably cringing at the double for-loop, but whatever — it gets the job done, okay? I configured the script to only print relationships with a p-value less than the corrected p-value, and the following turned out to be statistically significant at p < 0.002:"
},
{
"code": null,
"e": 9218,
"s": 8841,
"text": "In this article, I ran briefly through the process of conducting a chi-squared test for independence and post hoc test, focusing primarily on the technical implementation. However, I think understanding the theory behind the implementation is crucial for debugging and interpreting results, so I linked resources that I personally found helpful so you can review if necessary."
},
{
"code": null,
"e": 9310,
"s": 9218,
"text": "Let’s circle back to my two original research questions and see what conclusions we dug up:"
},
{
"code": null,
"e": 9805,
"s": 9310,
"text": "Does age group impact attitudes towards flying (ATF)? If so, how? NoDoes political affiliation impact attitudes towards flying (ATF)? If so, how? Yes, and quite significantly so! Democrats are more likely to have a “Very Uncomfortable” ATF compared to the average, Republicans are more likely to have a “Very Comfortable” ATF compared to the average, people who are not sure of their political affiliation are less likely to have a “Very Uncomfortable” ATF, but more likely to put “Don’t know.”"
},
{
"code": null,
"e": 9874,
"s": 9805,
"text": "Does age group impact attitudes towards flying (ATF)? If so, how? No"
},
{
"code": null,
"e": 10301,
"s": 9874,
"text": "Does political affiliation impact attitudes towards flying (ATF)? If so, how? Yes, and quite significantly so! Democrats are more likely to have a “Very Uncomfortable” ATF compared to the average, Republicans are more likely to have a “Very Comfortable” ATF compared to the average, people who are not sure of their political affiliation are less likely to have a “Very Uncomfortable” ATF, but more likely to put “Don’t know.”"
},
{
"code": null,
"e": 10662,
"s": 10301,
"text": "I found the last insight to be very interesting — people who do not have strong political affiliations are more likely to not have an opinion towards flying. One possible explanation could be respondents just breezed through questions and didn’t put much thought into their response, which led to selecting the most neutral answers (i.e. not sure, don’t know)."
},
{
"code": null,
"e": 11266,
"s": 10662,
"text": "Another, more interesting explanation could be that people who are politically engaged are more likely to watch the news and regularly consume media about current events. Since many media outlets are focusing on COVID-19, people who stay up-to-date will be exposed to more debates between authority figures with strong opinions about pandemic best practices (i.e. public health and safety protocol, travel bans). Conversely, those without strong political affiliations may tune in less compared to their partisan peers, and therefore are exposed to less polarizing opinions on how best to handle travel."
}
]
|
Count words present in a string - GeeksforGeeks | 30 Jun, 2017
Given an array of words and a string, we need to count all words that are present in given string.
Examples:
Input : words[] = { "welcome", "to", "geeks", "portal"}
str = "geeksforgeeks is a computer science portal for geeks."
Output : 2
Two words "portal" and "geeks" is present in str.
Input : words[] = {"Save", "Water", "Save", "Yourself"}
str = "Save"
Output :1
Steps:
Extract each word from string.For each word, check if it is in word array(by creating set/map). If present, increment result.
Extract each word from string.
For each word, check if it is in word array(by creating set/map). If present, increment result.
Below is the Java implementation of above steps
// Java program to count number // of words present in a string import java.util.HashSet;import java.util.regex.Matcher;import java.util.regex.Pattern; public class Test { static int countOccurrence(String[] word, String str) { // counter int counter = 0; // for extracting words Pattern p = Pattern.compile("[a-zA-Z]+"); Matcher m = p.matcher(str); // HashSet for quick check whether // a word in str present in word[] or not HashSet<String> hs = new HashSet<String>(); for (String string : word) { hs.add(string); } while(m.find()) { if(hs.contains(m.group())) counter++; } return counter; } public static void main(String[] args) { String word[] = { "welcome", "to", "geeks", "portal"}; String str = "geeksforgeeks is a computer science portal for geeks."; System.out.println(countOccurrence(word,str)); } }
Output:
2
This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. 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.
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
Different methods to reverse a string in C/C++
Convert string to char array in C++
Array of Strings in C++ (5 Different Ways to Create)
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Reverse words in a given string
Check whether two strings are anagram of each other
Length of the longest substring without repeating characters
How to split a string in C/C++, Python and Java? | [
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n30 Jun, 2017"
},
{
"code": null,
"e": 24824,
"s": 24725,
"text": "Given an array of words and a string, we need to count all words that are present in given string."
},
{
"code": null,
"e": 24834,
"s": 24824,
"text": "Examples:"
},
{
"code": null,
"e": 25120,
"s": 24834,
"text": "Input : words[] = { \"welcome\", \"to\", \"geeks\", \"portal\"}\n str = \"geeksforgeeks is a computer science portal for geeks.\"\nOutput : 2\nTwo words \"portal\" and \"geeks\" is present in str.\n\n\nInput : words[] = {\"Save\", \"Water\", \"Save\", \"Yourself\"}\n str = \"Save\"\nOutput :1\n"
},
{
"code": null,
"e": 25127,
"s": 25120,
"text": "Steps:"
},
{
"code": null,
"e": 25253,
"s": 25127,
"text": "Extract each word from string.For each word, check if it is in word array(by creating set/map). If present, increment result."
},
{
"code": null,
"e": 25284,
"s": 25253,
"text": "Extract each word from string."
},
{
"code": null,
"e": 25380,
"s": 25284,
"text": "For each word, check if it is in word array(by creating set/map). If present, increment result."
},
{
"code": null,
"e": 25428,
"s": 25380,
"text": "Below is the Java implementation of above steps"
},
{
"code": "// Java program to count number // of words present in a string import java.util.HashSet;import java.util.regex.Matcher;import java.util.regex.Pattern; public class Test { static int countOccurrence(String[] word, String str) { // counter int counter = 0; // for extracting words Pattern p = Pattern.compile(\"[a-zA-Z]+\"); Matcher m = p.matcher(str); // HashSet for quick check whether // a word in str present in word[] or not HashSet<String> hs = new HashSet<String>(); for (String string : word) { hs.add(string); } while(m.find()) { if(hs.contains(m.group())) counter++; } return counter; } public static void main(String[] args) { String word[] = { \"welcome\", \"to\", \"geeks\", \"portal\"}; String str = \"geeksforgeeks is a computer science portal for geeks.\"; System.out.println(countOccurrence(word,str)); } }",
"e": 26515,
"s": 25428,
"text": null
},
{
"code": null,
"e": 26523,
"s": 26515,
"text": "Output:"
},
{
"code": null,
"e": 26526,
"s": 26523,
"text": "2\n"
},
{
"code": null,
"e": 26826,
"s": 26526,
"text": "This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 26951,
"s": 26826,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26959,
"s": 26951,
"text": "Strings"
},
{
"code": null,
"e": 26967,
"s": 26959,
"text": "Strings"
},
{
"code": null,
"e": 27065,
"s": 26967,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27074,
"s": 27065,
"text": "Comments"
},
{
"code": null,
"e": 27087,
"s": 27074,
"text": "Old Comments"
},
{
"code": null,
"e": 27144,
"s": 27087,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 27191,
"s": 27144,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 27227,
"s": 27191,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 27280,
"s": 27227,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 27318,
"s": 27280,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 27348,
"s": 27318,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 27380,
"s": 27348,
"text": "Reverse words in a given string"
},
{
"code": null,
"e": 27432,
"s": 27380,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 27493,
"s": 27432,
"text": "Length of the longest substring without repeating characters"
}
]
|
C++ Program to Perform Matrix Multiplication | A matrix is a rectangular array of numbers that is arranged in the form of rows and columns.
An example of a matrix is as follows.
A 3*2 matrix has 3 rows and 2 columns as shown below −
8 1
4 9
5 6
A program that performs matrix multiplication is as follows.
Live Demo
#include<iostream>
using namespace std;
int main() {
int product[10][10], r1=3, c1=3, r2=3, c2=3, i, j, k;
int a[3][3] = { {2, 4, 1} , {2, 3, 9} , {3, 1, 8} };
int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 4, 7} };
if (c1 != r2) {
cout<<"Column of first matrix should be equal to row of second matrix";
} else {
cout<<"The first matrix is:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c1; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
cout<<"The second matrix is:"<<endl;
for(i=0; i<r2; ++i) {
for(j=0; j<c2; ++j)
cout<<b[i][j]<<" ";
cout<<endl;
}
cout<<endl;
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j) {
product[i][j] = 0;
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k) {
product[i][j]+=a[i][k]*b[k][j];
}
cout<<"Product of the two matrices is:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c2; ++j)
cout<<product[i][j]<<" ";
cout<<endl;
}
}
return 0;
}
The first matrix is:
2 4 1
2 3 9
3 1 8
The second matrix is:
1 2 3
3 6 1
2 4 7
Product of the two matrices is:
16 32 17
29 58 72
22 44 66
In the above program, the two matrices a and b are initialized as follows −
int a[3][3] = { {2, 4, 1} , {2, 3, 9} , {3, 1, 8} };
int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 4, 7} };
If the number of columns in the first matrix are not equal to the number of rows in the second matrix then multiplication cannot be performed. In this case an error message is printed. It is given as follows.
if (c1 != r2) {
cout<<"Column of first matrix should be equal to row of second matrix";
}
Both the matrices a and b are displayed using a nested for loop. This is demonstrated by the following code snippet.
cout<<"The first matrix is:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c1; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
cout<<"The second matrix is:"<<endl;
for(i=0; i<r2; ++i) {
for(j=0; j<c2; ++j)
cout<<b[i][j]<<" ";
cout<<endl;
}
cout<<endl;
After this, the product[][] matrix is initialized to 0. Then a nested for loop is used to find the product of the 2 matrices a and b. This is demonstrated in the below code snippet.
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j) {
product[i][j] = 0;
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k) {
product[i][j]+=a[i][k]*b[k][j];
}
After the product is obtained, it is printed. This is shown as follows.
cout<<Product of the two matrices is:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c2; ++j)
cout<<product[i][j]<<" ";
cout<<endl;
} | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "A matrix is a rectangular array of numbers that is arranged in the form of rows and columns."
},
{
"code": null,
"e": 1193,
"s": 1155,
"text": "An example of a matrix is as follows."
},
{
"code": null,
"e": 1248,
"s": 1193,
"text": "A 3*2 matrix has 3 rows and 2 columns as shown below −"
},
{
"code": null,
"e": 1260,
"s": 1248,
"text": "8 1\n4 9\n5 6"
},
{
"code": null,
"e": 1321,
"s": 1260,
"text": "A program that performs matrix multiplication is as follows."
},
{
"code": null,
"e": 1332,
"s": 1321,
"text": " Live Demo"
},
{
"code": null,
"e": 2427,
"s": 1332,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int product[10][10], r1=3, c1=3, r2=3, c2=3, i, j, k;\n int a[3][3] = { {2, 4, 1} , {2, 3, 9} , {3, 1, 8} };\n int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 4, 7} };\n if (c1 != r2) {\n cout<<\"Column of first matrix should be equal to row of second matrix\";\n } else {\n cout<<\"The first matrix is:\"<<endl;\n for(i=0; i<r1; ++i) {\n for(j=0; j<c1; ++j)\n cout<<a[i][j]<<\" \";\n cout<<endl;\n }\n cout<<endl;\n cout<<\"The second matrix is:\"<<endl;\n for(i=0; i<r2; ++i) {\n for(j=0; j<c2; ++j)\n cout<<b[i][j]<<\" \";\n cout<<endl;\n }\n cout<<endl;\n for(i=0; i<r1; ++i)\n for(j=0; j<c2; ++j) {\n product[i][j] = 0;\n }\n for(i=0; i<r1; ++i)\n for(j=0; j<c2; ++j)\n for(k=0; k<c1; ++k) {\n product[i][j]+=a[i][k]*b[k][j];\n }\n cout<<\"Product of the two matrices is:\"<<endl;\n for(i=0; i<r1; ++i) {\n for(j=0; j<c2; ++j)\n cout<<product[i][j]<<\" \";\n cout<<endl;\n }\n }\n return 0;\n}"
},
{
"code": null,
"e": 2565,
"s": 2427,
"text": "The first matrix is:\n2 4 1\n2 3 9\n3 1 8\nThe second matrix is:\n1 2 3\n3 6 1\n2 4 7\nProduct of the two matrices is:\n16 32 17\n29 58 72\n22 44 66"
},
{
"code": null,
"e": 2641,
"s": 2565,
"text": "In the above program, the two matrices a and b are initialized as follows −"
},
{
"code": null,
"e": 2747,
"s": 2641,
"text": "int a[3][3] = { {2, 4, 1} , {2, 3, 9} , {3, 1, 8} };\nint b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 4, 7} };"
},
{
"code": null,
"e": 2956,
"s": 2747,
"text": "If the number of columns in the first matrix are not equal to the number of rows in the second matrix then multiplication cannot be performed. In this case an error message is printed. It is given as follows."
},
{
"code": null,
"e": 3049,
"s": 2956,
"text": "if (c1 != r2) {\n cout<<\"Column of first matrix should be equal to row of second matrix\";\n}"
},
{
"code": null,
"e": 3166,
"s": 3049,
"text": "Both the matrices a and b are displayed using a nested for loop. This is demonstrated by the following code snippet."
},
{
"code": null,
"e": 3433,
"s": 3166,
"text": "cout<<\"The first matrix is:\"<<endl;\nfor(i=0; i<r1; ++i) {\n for(j=0; j<c1; ++j)\n cout<<a[i][j]<<\" \";\n cout<<endl;\n}\ncout<<endl;\ncout<<\"The second matrix is:\"<<endl;\nfor(i=0; i<r2; ++i) {\n for(j=0; j<c2; ++j)\n cout<<b[i][j]<<\" \";\n cout<<endl;\n}\ncout<<endl;"
},
{
"code": null,
"e": 3615,
"s": 3433,
"text": "After this, the product[][] matrix is initialized to 0. Then a nested for loop is used to find the product of the 2 matrices a and b. This is demonstrated in the below code snippet."
},
{
"code": null,
"e": 3780,
"s": 3615,
"text": "for(i=0; i<r1; ++i)\nfor(j=0; j<c2; ++j) {\n product[i][j] = 0;\n}\nfor(i=0; i<r1; ++i)\nfor(j=0; j<c2; ++j)\nfor(k=0; k<c1; ++k) {\n product[i][j]+=a[i][k]*b[k][j];\n}"
},
{
"code": null,
"e": 3852,
"s": 3780,
"text": "After the product is obtained, it is printed. This is shown as follows."
},
{
"code": null,
"e": 3989,
"s": 3852,
"text": "cout<<Product of the two matrices is:\"<<endl;\nfor(i=0; i<r1; ++i) {\n for(j=0; j<c2; ++j)\n cout<<product[i][j]<<\" \";\n cout<<endl;\n}"
}
]
|
Construct a special tree from given preorder traversal - GeeksforGeeks | 18 Apr, 2022
Given an array ‘pre[]’ that represents Preorder traversal of a special binary tree where every node has either 0 or 2 children. One more array ‘preLN[]’ is given which has only two possible values ‘L’ and ‘N’. The value ‘L’ in ‘preLN[]’ indicates that the corresponding node in Binary Tree is a leaf node and value ‘N’ indicates that the corresponding node is a non-leaf node. Write a function to construct the tree from the given two arrays.
Example:
Input: pre[] = {10, 30, 20, 5, 15}, preLN[] = {‘N’, ‘N’, ‘L’, ‘L’, ‘L’}Output: Root of following tree
10
/ \
30 15
/ \
20 5
Approach: The first element in pre[] will always be root. So we can easily figure out the root. If the left subtree is empty, the right subtree must also be empty, and the preLN[] entry for root must be ‘L’. We can simply create a node and return it. If the left and right subtrees are not empty, then recursively call for left and right subtrees and link the returned nodes to root.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// A program to construct Binary Tree from preorder traversal#include<bits/stdc++.h> // A binary tree node structurestruct node{ int data; struct node *left; struct node *right;}; // Utility function to create a new Binary Tree nodestruct node* newNode (int data){ struct node *temp = new struct node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} // A recursive function to create a Binary Tree from given pre[]// preLN[] arrays. The function returns root of tree. index_ptr is used// to update index values in recursive calls. index must be initially// passed as 0 */struct node *constructTreeUtil(int pre[], char preLN[], int *index_ptr, int n){ int index = *index_ptr; // store the current value of index in pre[] // Base Case: All nodes are constructed if (index == n) return NULL; // Allocate memory for this node and increment index for // subsequent recursive calls struct node *temp = newNode ( pre[index] ); (*index_ptr)++; // If this is an internal node, construct left and right subtrees and link the subtrees if (preLN[index] == 'N') { temp->left = constructTreeUtil(pre, preLN, index_ptr, n); temp->right = constructTreeUtil(pre, preLN, index_ptr, n); } return temp;} // A wrapper over constructTreeUtil()struct node *constructTree(int pre[], char preLN[], int n){ // Initialize index as 0. Value of index is used in recursion to maintain // the current index in pre[] and preLN[] arrays. int index = 0; return constructTreeUtil (pre, preLN, &index, n);} // This function is used only for testingvoid printInorder (struct node* node){ if (node == NULL) return; // First recur on left child printInorder (node->left); // Print the data of node printf("%d ", node->data); // Now recur on right child printInorder (node->right);} // Driver codeint main(){ struct node *root = NULL; /* Constructing tree given in the above figure 10 / \ 30 15 / \ 20 5 */ int pre[] = {10, 30, 20, 5, 15}; char preLN[] = {'N', 'N', 'L', 'L', 'L'}; int n = sizeof(pre)/sizeof(pre[0]); // construct the above tree root = constructTree (pre, preLN, n); // Test the constructed tree printf("Inorder Traversal of the Constructed Binary Tree: \n"); printInorder (root); return 0;}
// Java program to construct a binary tree from preorder traversal // A Binary Tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class Index{ int index = 0;} class BinaryTree{ Node root; Index myindex = new Index(); /* A recursive function to create a Binary Tree from given pre[] preLN[] arrays. The function returns root of tree. index_ptr is used to update index values in recursive calls. index must be initially passed as 0 */ Node constructTreeUtil(int pre[], char preLN[], Index index_ptr, int n, Node temp) { // store the current value of index in pre[] int index = index_ptr.index; // Base Case: All nodes are constructed if (index == n) return null; // Allocate memory for this node and increment index for // subsequent recursive calls temp = new Node(pre[index]); (index_ptr.index)++; // If this is an internal node, construct left and right subtrees // and link the subtrees if (preLN[index] == 'N') { temp.left = constructTreeUtil(pre, preLN, index_ptr, n, temp.left); temp.right = constructTreeUtil(pre, preLN, index_ptr, n, temp.right); } return temp; } // A wrapper over constructTreeUtil() Node constructTree(int pre[], char preLN[], int n, Node node) { // Initialize index as 0. Value of index is used in recursion to // maintain the current index in pre[] and preLN[] arrays. int index = 0; return constructTreeUtil(pre, preLN, myindex, n, node); } /* This function is used only for testing */ void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.data + " "); /* now recur on right child */ printInorder(node.right); } // driver function to test the above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); int pre[] = new int[]{10, 30, 20, 5, 15}; char preLN[] = new char[]{'N', 'N', 'L', 'L', 'L'}; int n = pre.length; // construct the above tree Node mynode = tree.constructTree(pre, preLN, n, tree.root); // Test the constructed tree System.out.println("Following is Inorder Traversal of the" + "Constructed Binary Tree: "); tree.printInorder(mynode); }} // This code has been contributed by Mayank Jaiswal
# A program to construct Binary# Tree from preorder traversal # Utility function to create a# new Binary Tree nodeclass newNode: def __init__(self, data): self.data = data self.left = None self.right = None # A recursive function to create a# Binary Tree from given pre[] preLN[]# arrays. The function returns root of # tree. index_ptr is used to update# index values in recursive calls. index# must be initially passed as 0def constructTreeUtil(pre, preLN, index_ptr, n): index = index_ptr[0] # store the current value # of index in pre[] # Base Case: All nodes are constructed if index == n: return None # Allocate memory for this node and # increment index for subsequent # recursive calls temp = newNode(pre[index]) index_ptr[0] += 1 # If this is an internal node, construct left # and right subtrees and link the subtrees if preLN[index] == 'N': temp.left = constructTreeUtil(pre, preLN, index_ptr, n) temp.right = constructTreeUtil(pre, preLN, index_ptr, n) return temp # A wrapper over constructTreeUtil()def constructTree(pre, preLN, n): # Initialize index as 0. Value of index is # used in recursion to maintain the current # index in pre[] and preLN[] arrays. index = [0] return constructTreeUtil(pre, preLN, index, n) # This function is used only for testingdef printInorder (node): if node == None: return # first recur on left child printInorder (node.left) # then print the data of node print(node.data,end=" ") # now recur on right child printInorder (node.right) # Driver Codeif __name__ == '__main__': root = None # Constructing tree given in # the above figure # 10 # / \ # 30 15 # / \ # 20 5 pre = [10, 30, 20, 5, 15] preLN = ['N', 'N', 'L', 'L', 'L'] n = len(pre) # construct the above tree root = constructTree (pre, preLN, n) # Test the constructed tree print("Following is Inorder Traversal of", "the Constructed Binary Tree:") printInorder (root) # This code is contributed by PranchalK
// C# program to construct a binary// tree from preorder traversalusing System; // A Binary Tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class Index{ public int index = 0;} class GFG{public Node root;public Index myindex = new Index(); /* A recursive function to create aBinary Tree from given pre[] preLN[] arrays.The function returns root of tree. index_ptris used to update index values in recursivecalls. index must be initially passed as 0 */public virtual Node constructTreeUtil(int[] pre, char[] preLN, Index index_ptr, int n, Node temp){ // store the current value of index in pre[] int index = index_ptr.index; // Base Case: All nodes are constructed if (index == n) { return null; } // Allocate memory for this node // and increment index for // subsequent recursive calls temp = new Node(pre[index]); (index_ptr.index)++; // If this is an internal node, // construct left and right subtrees // and link the subtrees if (preLN[index] == 'N') { temp.left = constructTreeUtil(pre, preLN, index_ptr, n, temp.left); temp.right = constructTreeUtil(pre, preLN, index_ptr, n, temp.right); } return temp;} // A wrapper over constructTreeUtil()public virtual Node constructTree(int[] pre, char[] preLN, int n, Node node){ // Initialize index as 0. Value of // index is used in recursion to // maintain the current index in // pre[] and preLN[] arrays. int index = 0; return constructTreeUtil(pre, preLN, myindex, n, node);} /* This function is used only for testing */public virtual void printInorder(Node node){ if (node == null) { return; } /* first recur on left child */ printInorder(node.left); /* then print the data of node */ Console.Write(node.data + " "); /* now recur on right child */ printInorder(node.right);} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); int[] pre = new int[]{10, 30, 20, 5, 15}; char[] preLN = new char[]{'N', 'N', 'L', 'L', 'L'}; int n = pre.Length; // construct the above tree Node mynode = tree.constructTree(pre, preLN, n, tree.root); // Test the constructed tree Console.WriteLine("Following is Inorder Traversal of the" + "Constructed Binary Tree: "); tree.printInorder(mynode);}} // This code is contributed by Shrikant13
<script> // JavaScript program to construct a binary// tree from preorder traversal // A Binary Tree nodeclass Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} class Index{ constructor() { this.index = 0; }} var root = null;var myindex = new Index(); /* A recursive function to create aBinary Tree from given pre[] preLN[] arrays.The function returns root of tree. index_ptris used to update index values in recursivecalls. index must be initially passed as 0 */function constructTreeUtil(pre, preLN, index_ptr, n, temp){ // store the current value of index in pre[] var index = index_ptr.index; // Base Case: All nodes are constructed if (index == n) { return null; } // Allocate memory for this node // and increment index for // subsequent recursive calls temp = new Node(pre[index]); (index_ptr.index)++; // If this is an internal node, // construct left and right subtrees // and link the subtrees if (preLN[index] == 'N') { temp.left = constructTreeUtil(pre, preLN, index_ptr, n, temp.left); temp.right = constructTreeUtil(pre, preLN, index_ptr, n, temp.right); } return temp;} // A wrapper over constructTreeUtil()function constructTree(pre, preLN, n, node){ // Initialize index as 0. Value of // index is used in recursion to // maintain the current index in // pre[] and preLN[] arrays. var index = 0; return constructTreeUtil(pre, preLN, myindex, n, node);} /* This function is used only for testing */function printInorder( node){ if (node == null) { return; } /* first recur on left child */ printInorder(node.left); /* then print the data of node */ document.write(node.data + " "); /* now recur on right child */ printInorder(node.right);} // Driver Codevar pre = [10, 30, 20, 5, 15];var preLN = ['N', 'N', 'L', 'L', 'L'];var n = pre.length;// construct the above treevar mynode = constructTree(pre, preLN, n, root);// Test the constructed treedocument.write("Following is Inorder Traversal of the" + "Constructed Binary Tree:<br>");printInorder(mynode); </script>
Inorder Traversal of the Constructed Binary Tree:
20 30 5 10 15
Time Complexity: O(n)Auxiliary Space: O(n)
Method 2: Using Stack without recursion
Approach:
As the Pre-order Traversal is given so we first make a root and insert the first value into it.
Traverse the given pre-order traversal.Check the left of stack’s topIf it NULL then we add the present node on leftOtherwise, Add into right if right is NULL.If left and right both are not NULL, it means that the node have both left and right so we pop out the nodes until we won’t get any node whose left or right is NULL.If the present node is not a leaf node, push node into the stack.
Check the left of stack’s topIf it NULL then we add the present node on leftOtherwise, Add into right if right is NULL.
If it NULL then we add the present node on left
Otherwise, Add into right if right is NULL.
If left and right both are not NULL, it means that the node have both left and right so we pop out the nodes until we won’t get any node whose left or right is NULL.
If the present node is not a leaf node, push node into the stack.
Finally return the root of the constructed tree.
Below is the implementation of the above approach:
C++
// A program to construct Binary Tree from preorder// traversal#include <bits/stdc++.h>using namespace std; // A binary tree node structurestruct node { int data; struct node* left; struct node* right; node(int x) { data = x; left = right = NULL; }}; struct node* constructTree(int pre[], char preLN[], int n){ // Taking an empty Stack stack<node*> st; // Setting up root node node* root = new node(pre[0]); // Checking if root is not leaf node if (preLN[0] != 'L') st.push(root); // Iterating over the given node values for (int i = 1; i < n; i++) { node* temp = new node(pre[i]); // Checking if the left position is NULL or not if (!st.top()->left) { st.top()->left = temp; // Checking for leaf node if (preLN[i] != 'L') st.push(temp); } // Checking if the right position is NULL or not else if (!st.top()->right) { st.top()->right = temp; if (preLN[i] != 'L') // Checking for leaf node st.push(temp); } // If left and right of top node is already filles else { while (st.top()->left && st.top()->right) st.pop(); st.top()->right = temp; // Checking for leaf node if (preLN[i] != 'L') st.push(temp); } } // Returning the root of tree return root;} // This function is used only for testingvoid printInorder(struct node* node){ if (node == NULL) return; // First recur on left child printInorder(node->left); // Print the data of node printf("%d ", node->data); // Now recur on right child printInorder(node->right);} // Driver codeint main(){ struct node* root = NULL; /* Constructing tree given in the above figure 10 / \ 30 15 / \ 20 5 */ int pre[] = { 10, 30, 20, 5, 15 }; char preLN[] = { 'N', 'N', 'L', 'L', 'L' }; int n = sizeof(pre) / sizeof(pre[0]); // construct the above tree root = constructTree(pre, preLN, n); // Test the constructed tree printf("Inorder Traversal of the Constructed Binary Tree: \n"); printInorder(root); return 0;} // This code is contributed by shubhamrajput6156
Inorder Traversal of the Constructed Binary Tree:
20 30 5 10 15
Time Complexity: O(n)Auxiliary Space: O(n)
Construct the full k-ary tree from its preorder traversalPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above
shrikanth13
PranchalKatiyar
rutvik_56
vatsaljain316
shubhamrajput6156
Amazon
Traversal
Tree
Amazon
Traversal
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Binary Tree | Set 3 (Types of Binary Tree)
Decision Tree
Binary Tree | Set 2 (Properties)
A program to check if a binary tree is BST or not
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
Expression Tree
Binary Tree (Array implementation)
BFS vs DFS for Binary Tree | [
{
"code": null,
"e": 24972,
"s": 24944,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 25415,
"s": 24972,
"text": "Given an array ‘pre[]’ that represents Preorder traversal of a special binary tree where every node has either 0 or 2 children. One more array ‘preLN[]’ is given which has only two possible values ‘L’ and ‘N’. The value ‘L’ in ‘preLN[]’ indicates that the corresponding node in Binary Tree is a leaf node and value ‘N’ indicates that the corresponding node is a non-leaf node. Write a function to construct the tree from the given two arrays."
},
{
"code": null,
"e": 25425,
"s": 25415,
"text": "Example: "
},
{
"code": null,
"e": 25529,
"s": 25425,
"text": "Input: pre[] = {10, 30, 20, 5, 15}, preLN[] = {‘N’, ‘N’, ‘L’, ‘L’, ‘L’}Output: Root of following tree"
},
{
"code": null,
"e": 25542,
"s": 25529,
"text": " 10"
},
{
"code": null,
"e": 25556,
"s": 25542,
"text": " / \\"
},
{
"code": null,
"e": 25570,
"s": 25556,
"text": " 30 15"
},
{
"code": null,
"e": 25583,
"s": 25570,
"text": " / \\"
},
{
"code": null,
"e": 25595,
"s": 25583,
"text": " 20 5"
},
{
"code": null,
"e": 25981,
"s": 25595,
"text": "Approach: The first element in pre[] will always be root. So we can easily figure out the root. If the left subtree is empty, the right subtree must also be empty, and the preLN[] entry for root must be ‘L’. We can simply create a node and return it. If the left and right subtrees are not empty, then recursively call for left and right subtrees and link the returned nodes to root. "
},
{
"code": null,
"e": 26033,
"s": 25981,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26037,
"s": 26033,
"text": "C++"
},
{
"code": null,
"e": 26042,
"s": 26037,
"text": "Java"
},
{
"code": null,
"e": 26050,
"s": 26042,
"text": "Python3"
},
{
"code": null,
"e": 26053,
"s": 26050,
"text": "C#"
},
{
"code": null,
"e": 26064,
"s": 26053,
"text": "Javascript"
},
{
"code": "// A program to construct Binary Tree from preorder traversal#include<bits/stdc++.h> // A binary tree node structurestruct node{ int data; struct node *left; struct node *right;}; // Utility function to create a new Binary Tree nodestruct node* newNode (int data){ struct node *temp = new struct node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} // A recursive function to create a Binary Tree from given pre[]// preLN[] arrays. The function returns root of tree. index_ptr is used// to update index values in recursive calls. index must be initially// passed as 0 */struct node *constructTreeUtil(int pre[], char preLN[], int *index_ptr, int n){ int index = *index_ptr; // store the current value of index in pre[] // Base Case: All nodes are constructed if (index == n) return NULL; // Allocate memory for this node and increment index for // subsequent recursive calls struct node *temp = newNode ( pre[index] ); (*index_ptr)++; // If this is an internal node, construct left and right subtrees and link the subtrees if (preLN[index] == 'N') { temp->left = constructTreeUtil(pre, preLN, index_ptr, n); temp->right = constructTreeUtil(pre, preLN, index_ptr, n); } return temp;} // A wrapper over constructTreeUtil()struct node *constructTree(int pre[], char preLN[], int n){ // Initialize index as 0. Value of index is used in recursion to maintain // the current index in pre[] and preLN[] arrays. int index = 0; return constructTreeUtil (pre, preLN, &index, n);} // This function is used only for testingvoid printInorder (struct node* node){ if (node == NULL) return; // First recur on left child printInorder (node->left); // Print the data of node printf(\"%d \", node->data); // Now recur on right child printInorder (node->right);} // Driver codeint main(){ struct node *root = NULL; /* Constructing tree given in the above figure 10 / \\ 30 15 / \\ 20 5 */ int pre[] = {10, 30, 20, 5, 15}; char preLN[] = {'N', 'N', 'L', 'L', 'L'}; int n = sizeof(pre)/sizeof(pre[0]); // construct the above tree root = constructTree (pre, preLN, n); // Test the constructed tree printf(\"Inorder Traversal of the Constructed Binary Tree: \\n\"); printInorder (root); return 0;}",
"e": 28462,
"s": 26064,
"text": null
},
{
"code": "// Java program to construct a binary tree from preorder traversal // A Binary Tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class Index{ int index = 0;} class BinaryTree{ Node root; Index myindex = new Index(); /* A recursive function to create a Binary Tree from given pre[] preLN[] arrays. The function returns root of tree. index_ptr is used to update index values in recursive calls. index must be initially passed as 0 */ Node constructTreeUtil(int pre[], char preLN[], Index index_ptr, int n, Node temp) { // store the current value of index in pre[] int index = index_ptr.index; // Base Case: All nodes are constructed if (index == n) return null; // Allocate memory for this node and increment index for // subsequent recursive calls temp = new Node(pre[index]); (index_ptr.index)++; // If this is an internal node, construct left and right subtrees // and link the subtrees if (preLN[index] == 'N') { temp.left = constructTreeUtil(pre, preLN, index_ptr, n, temp.left); temp.right = constructTreeUtil(pre, preLN, index_ptr, n, temp.right); } return temp; } // A wrapper over constructTreeUtil() Node constructTree(int pre[], char preLN[], int n, Node node) { // Initialize index as 0. Value of index is used in recursion to // maintain the current index in pre[] and preLN[] arrays. int index = 0; return constructTreeUtil(pre, preLN, myindex, n, node); } /* This function is used only for testing */ void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.data + \" \"); /* now recur on right child */ printInorder(node.right); } // driver function to test the above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); int pre[] = new int[]{10, 30, 20, 5, 15}; char preLN[] = new char[]{'N', 'N', 'L', 'L', 'L'}; int n = pre.length; // construct the above tree Node mynode = tree.constructTree(pre, preLN, n, tree.root); // Test the constructed tree System.out.println(\"Following is Inorder Traversal of the\" + \"Constructed Binary Tree: \"); tree.printInorder(mynode); }} // This code has been contributed by Mayank Jaiswal",
"e": 31333,
"s": 28462,
"text": null
},
{
"code": "# A program to construct Binary# Tree from preorder traversal # Utility function to create a# new Binary Tree nodeclass newNode: def __init__(self, data): self.data = data self.left = None self.right = None # A recursive function to create a# Binary Tree from given pre[] preLN[]# arrays. The function returns root of # tree. index_ptr is used to update# index values in recursive calls. index# must be initially passed as 0def constructTreeUtil(pre, preLN, index_ptr, n): index = index_ptr[0] # store the current value # of index in pre[] # Base Case: All nodes are constructed if index == n: return None # Allocate memory for this node and # increment index for subsequent # recursive calls temp = newNode(pre[index]) index_ptr[0] += 1 # If this is an internal node, construct left # and right subtrees and link the subtrees if preLN[index] == 'N': temp.left = constructTreeUtil(pre, preLN, index_ptr, n) temp.right = constructTreeUtil(pre, preLN, index_ptr, n) return temp # A wrapper over constructTreeUtil()def constructTree(pre, preLN, n): # Initialize index as 0. Value of index is # used in recursion to maintain the current # index in pre[] and preLN[] arrays. index = [0] return constructTreeUtil(pre, preLN, index, n) # This function is used only for testingdef printInorder (node): if node == None: return # first recur on left child printInorder (node.left) # then print the data of node print(node.data,end=\" \") # now recur on right child printInorder (node.right) # Driver Codeif __name__ == '__main__': root = None # Constructing tree given in # the above figure # 10 # / \\ # 30 15 # / \\ # 20 5 pre = [10, 30, 20, 5, 15] preLN = ['N', 'N', 'L', 'L', 'L'] n = len(pre) # construct the above tree root = constructTree (pre, preLN, n) # Test the constructed tree print(\"Following is Inorder Traversal of\", \"the Constructed Binary Tree:\") printInorder (root) # This code is contributed by PranchalK",
"e": 33561,
"s": 31333,
"text": null
},
{
"code": "// C# program to construct a binary// tree from preorder traversalusing System; // A Binary Tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class Index{ public int index = 0;} class GFG{public Node root;public Index myindex = new Index(); /* A recursive function to create aBinary Tree from given pre[] preLN[] arrays.The function returns root of tree. index_ptris used to update index values in recursivecalls. index must be initially passed as 0 */public virtual Node constructTreeUtil(int[] pre, char[] preLN, Index index_ptr, int n, Node temp){ // store the current value of index in pre[] int index = index_ptr.index; // Base Case: All nodes are constructed if (index == n) { return null; } // Allocate memory for this node // and increment index for // subsequent recursive calls temp = new Node(pre[index]); (index_ptr.index)++; // If this is an internal node, // construct left and right subtrees // and link the subtrees if (preLN[index] == 'N') { temp.left = constructTreeUtil(pre, preLN, index_ptr, n, temp.left); temp.right = constructTreeUtil(pre, preLN, index_ptr, n, temp.right); } return temp;} // A wrapper over constructTreeUtil()public virtual Node constructTree(int[] pre, char[] preLN, int n, Node node){ // Initialize index as 0. Value of // index is used in recursion to // maintain the current index in // pre[] and preLN[] arrays. int index = 0; return constructTreeUtil(pre, preLN, myindex, n, node);} /* This function is used only for testing */public virtual void printInorder(Node node){ if (node == null) { return; } /* first recur on left child */ printInorder(node.left); /* then print the data of node */ Console.Write(node.data + \" \"); /* now recur on right child */ printInorder(node.right);} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); int[] pre = new int[]{10, 30, 20, 5, 15}; char[] preLN = new char[]{'N', 'N', 'L', 'L', 'L'}; int n = pre.Length; // construct the above tree Node mynode = tree.constructTree(pre, preLN, n, tree.root); // Test the constructed tree Console.WriteLine(\"Following is Inorder Traversal of the\" + \"Constructed Binary Tree: \"); tree.printInorder(mynode);}} // This code is contributed by Shrikant13",
"e": 36323,
"s": 33561,
"text": null
},
{
"code": "<script> // JavaScript program to construct a binary// tree from preorder traversal // A Binary Tree nodeclass Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} class Index{ constructor() { this.index = 0; }} var root = null;var myindex = new Index(); /* A recursive function to create aBinary Tree from given pre[] preLN[] arrays.The function returns root of tree. index_ptris used to update index values in recursivecalls. index must be initially passed as 0 */function constructTreeUtil(pre, preLN, index_ptr, n, temp){ // store the current value of index in pre[] var index = index_ptr.index; // Base Case: All nodes are constructed if (index == n) { return null; } // Allocate memory for this node // and increment index for // subsequent recursive calls temp = new Node(pre[index]); (index_ptr.index)++; // If this is an internal node, // construct left and right subtrees // and link the subtrees if (preLN[index] == 'N') { temp.left = constructTreeUtil(pre, preLN, index_ptr, n, temp.left); temp.right = constructTreeUtil(pre, preLN, index_ptr, n, temp.right); } return temp;} // A wrapper over constructTreeUtil()function constructTree(pre, preLN, n, node){ // Initialize index as 0. Value of // index is used in recursion to // maintain the current index in // pre[] and preLN[] arrays. var index = 0; return constructTreeUtil(pre, preLN, myindex, n, node);} /* This function is used only for testing */function printInorder( node){ if (node == null) { return; } /* first recur on left child */ printInorder(node.left); /* then print the data of node */ document.write(node.data + \" \"); /* now recur on right child */ printInorder(node.right);} // Driver Codevar pre = [10, 30, 20, 5, 15];var preLN = ['N', 'N', 'L', 'L', 'L'];var n = pre.length;// construct the above treevar mynode = constructTree(pre, preLN, n, root);// Test the constructed treedocument.write(\"Following is Inorder Traversal of the\" + \"Constructed Binary Tree:<br>\");printInorder(mynode); </script>",
"e": 38687,
"s": 36323,
"text": null
},
{
"code": null,
"e": 38753,
"s": 38687,
"text": "Inorder Traversal of the Constructed Binary Tree: \n20 30 5 10 15 "
},
{
"code": null,
"e": 38796,
"s": 38753,
"text": "Time Complexity: O(n)Auxiliary Space: O(n)"
},
{
"code": null,
"e": 38836,
"s": 38796,
"text": "Method 2: Using Stack without recursion"
},
{
"code": null,
"e": 38847,
"s": 38836,
"text": "Approach: "
},
{
"code": null,
"e": 38943,
"s": 38847,
"text": "As the Pre-order Traversal is given so we first make a root and insert the first value into it."
},
{
"code": null,
"e": 39333,
"s": 38943,
"text": "Traverse the given pre-order traversal.Check the left of stack’s topIf it NULL then we add the present node on leftOtherwise, Add into right if right is NULL.If left and right both are not NULL, it means that the node have both left and right so we pop out the nodes until we won’t get any node whose left or right is NULL.If the present node is not a leaf node, push node into the stack."
},
{
"code": null,
"e": 39454,
"s": 39333,
"text": "Check the left of stack’s topIf it NULL then we add the present node on leftOtherwise, Add into right if right is NULL."
},
{
"code": null,
"e": 39503,
"s": 39454,
"text": "If it NULL then we add the present node on left"
},
{
"code": null,
"e": 39547,
"s": 39503,
"text": "Otherwise, Add into right if right is NULL."
},
{
"code": null,
"e": 39713,
"s": 39547,
"text": "If left and right both are not NULL, it means that the node have both left and right so we pop out the nodes until we won’t get any node whose left or right is NULL."
},
{
"code": null,
"e": 39779,
"s": 39713,
"text": "If the present node is not a leaf node, push node into the stack."
},
{
"code": null,
"e": 39828,
"s": 39779,
"text": "Finally return the root of the constructed tree."
},
{
"code": null,
"e": 39880,
"s": 39828,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 39884,
"s": 39880,
"text": "C++"
},
{
"code": "// A program to construct Binary Tree from preorder// traversal#include <bits/stdc++.h>using namespace std; // A binary tree node structurestruct node { int data; struct node* left; struct node* right; node(int x) { data = x; left = right = NULL; }}; struct node* constructTree(int pre[], char preLN[], int n){ // Taking an empty Stack stack<node*> st; // Setting up root node node* root = new node(pre[0]); // Checking if root is not leaf node if (preLN[0] != 'L') st.push(root); // Iterating over the given node values for (int i = 1; i < n; i++) { node* temp = new node(pre[i]); // Checking if the left position is NULL or not if (!st.top()->left) { st.top()->left = temp; // Checking for leaf node if (preLN[i] != 'L') st.push(temp); } // Checking if the right position is NULL or not else if (!st.top()->right) { st.top()->right = temp; if (preLN[i] != 'L') // Checking for leaf node st.push(temp); } // If left and right of top node is already filles else { while (st.top()->left && st.top()->right) st.pop(); st.top()->right = temp; // Checking for leaf node if (preLN[i] != 'L') st.push(temp); } } // Returning the root of tree return root;} // This function is used only for testingvoid printInorder(struct node* node){ if (node == NULL) return; // First recur on left child printInorder(node->left); // Print the data of node printf(\"%d \", node->data); // Now recur on right child printInorder(node->right);} // Driver codeint main(){ struct node* root = NULL; /* Constructing tree given in the above figure 10 / \\ 30 15 / \\ 20 5 */ int pre[] = { 10, 30, 20, 5, 15 }; char preLN[] = { 'N', 'N', 'L', 'L', 'L' }; int n = sizeof(pre) / sizeof(pre[0]); // construct the above tree root = constructTree(pre, preLN, n); // Test the constructed tree printf(\"Inorder Traversal of the Constructed Binary Tree: \\n\"); printInorder(root); return 0;} // This code is contributed by shubhamrajput6156",
"e": 42216,
"s": 39884,
"text": null
},
{
"code": null,
"e": 42282,
"s": 42216,
"text": "Inorder Traversal of the Constructed Binary Tree: \n20 30 5 10 15 "
},
{
"code": null,
"e": 42325,
"s": 42282,
"text": "Time Complexity: O(n)Auxiliary Space: O(n)"
},
{
"code": null,
"e": 42506,
"s": 42325,
"text": "Construct the full k-ary tree from its preorder traversalPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 42518,
"s": 42506,
"text": "shrikanth13"
},
{
"code": null,
"e": 42534,
"s": 42518,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 42544,
"s": 42534,
"text": "rutvik_56"
},
{
"code": null,
"e": 42558,
"s": 42544,
"text": "vatsaljain316"
},
{
"code": null,
"e": 42576,
"s": 42558,
"text": "shubhamrajput6156"
},
{
"code": null,
"e": 42583,
"s": 42576,
"text": "Amazon"
},
{
"code": null,
"e": 42593,
"s": 42583,
"text": "Traversal"
},
{
"code": null,
"e": 42598,
"s": 42593,
"text": "Tree"
},
{
"code": null,
"e": 42605,
"s": 42598,
"text": "Amazon"
},
{
"code": null,
"e": 42615,
"s": 42605,
"text": "Traversal"
},
{
"code": null,
"e": 42620,
"s": 42615,
"text": "Tree"
},
{
"code": null,
"e": 42718,
"s": 42620,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42727,
"s": 42718,
"text": "Comments"
},
{
"code": null,
"e": 42740,
"s": 42727,
"text": "Old Comments"
},
{
"code": null,
"e": 42783,
"s": 42740,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 42797,
"s": 42783,
"text": "Decision Tree"
},
{
"code": null,
"e": 42830,
"s": 42797,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 42880,
"s": 42830,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 42963,
"s": 42880,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 42999,
"s": 42963,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 43047,
"s": 42999,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 43063,
"s": 43047,
"text": "Expression Tree"
},
{
"code": null,
"e": 43098,
"s": 43063,
"text": "Binary Tree (Array implementation)"
}
]
|
Controlling the Web with Python. An adventure in simple web automation | by Will Koehrsen | Towards Data Science | An adventure in simple web automation
Problem: Submitting class assignments requires navigating a maze of web pages so complex that several times I’ve turned an assignment in to the wrong place. Also, while this process only takes 1–2 minutes, it sometimes seems like an insurmountable barrier (like when I’ve finished an assignment way too late at night and I can barely remember my password).
Solution: Use Python to automatically submit completed assignments! Ideally, I would be able to save an assignment, type a few keys, and have my work uploaded in a matter of seconds. At first this sounded too good to be true, but then I discovered selenium, a tool which can be used with Python to navigate the web for you.
Anytime we find ourselves repeating tedious actions on the web with the same sequence of steps, this is a great chance to write a program to automate the process for us. With selenium and Python, we just need to write a script once, and which then we can run it as many times and save ourselves from repeating monotonous tasks (and in my case, eliminate the chance of submitting an assignment in the wrong place)!
Here, I’ll walk through the solution I developed to automatically (and correctly) submit my assignments. Along the way, we’ll cover the basics of using Python and selenium to programmatically control the web. While this program does work (I’m using it every day!) it’s pretty custom so you won’t be able to copy and paste the code for your application. Nonetheless, the general techniques here can be applied to a limitless number of situations. (If you want to see the complete code, it’s available on GitHub).
Before we can get to the fun part of automating the web, we need to figure out the general structure of our solution. Jumping right into programming without a plan is a great way to waste many hours in frustration. I want to write a program to submit completed course assignments to the correct location on Canvas (my university’s “learning management system”). Starting with the basics, I need a way to tell the program the name of the assignment to submit and the class. I went with a simple approach and created a folder to hold completed assignments with child folders for each class. In the child folders, I place the completed document named for the particular assignment. The program can figure out the name of the class from the folder, and the name of the assignment by the document title.
Here’s an example where the name of the class is EECS491 and the assignment is “Assignment 3 — Inference in Larger Graphical Models”.
The first part of the program is a loop to go through the folders to find the assignment and class, which we store in a Python tuple:
# os for file managementimport os# Build tuple of (class, file) to turn insubmission_dir = 'completed_assignments'dir_list = list(os.listdir(submission_dir))for directory in dir_list: file_list = list(os.listdir(os.path.join(submission_dir, directory))) if len(file_list) != 0: file_tup = (directory, file_list[0]) print(file_tup)('EECS491', 'Assignment 3 - Inference in Larger Graphical Models.txt')
This takes care of file management and the program now knows the program and the assignment to turn in. The next step is to use selenium to navigate to the correct webpage and upload the assignment.
To get started with selenium, we import the library and create a web driver, which is a browser that is controlled by our program. In this case, I’ll use Chrome as my browser and send the driver to the Canvas website where I submit assignments.
import selenium# Using Chrome to access webdriver = webdriver.Chrome()# Open the websitedriver.get('https://canvas.case.edu')
When we open the Canvas webpage, we are greeted with our first obstacle, a login box! To get past this, we will need to fill in an id and a password and click the login button.
Imagine the web driver as a person who has never seen a web page before: we need to tell it exactly where to click, what to type, and which buttons to press. There are a number of ways to tell our web driver what elements to find, all of which use selectors. A selector is a unique identifier for an element on a webpage. To find the selector for a specific element, say the CWRU ID box above, we need to inspect the webpage. In Chrome, this is done by pressing “ctrl + shift + i” or right clicking on any element and selecting “Inspect”. This brings up the Chrome developer tools, an extremely useful application which shows the HTML underlying any webpage.
To find a selector for the “CWRU ID” box, I right clicked in the box, hit “Inspect” and saw the following in developer tools. The highlighted line corresponds to the id box element (this line is called an HTML tag).
This HTML might look overwhelming, but we can ignore the majority of the information and focus on the id = "username" and name="username" parts. (these are known as attributes of the HTML tag).
To select the id box with our web driver, we can use either the id or name attribute we found in the developer tools. Web drivers in selenium have many different methods for selecting elements on a webpage and there are often multiple ways to select the exact same item:
# Select the id boxid_box = driver.find_element_by_name('username')# Equivalent Outcome! id_box = driver.find_element_by_id('username')
Our program now has access to the id_box and we can interact with it in various ways, such as typing in keys, or clicking (if we have selected a button).
# Send id informationid_box.send_keys('my_username')
We carry out the same process for the password box and login button, selecting each based on what we see in the Chrome developer tools. Then, we send information to the elements or click on them as needed.
# Find password boxpass_box = driver.find_element_by_name('password')# Send passwordpass_box.send_keys('my_password')# Find login buttonlogin_button = driver.find_element_by_name('submit')# Click loginlogin_button.click()
Once we are logged in, we are greeted by this slightly intimidating dashboard:
We again need to guide the program through the webpage by specifying exactly the elements to click on and the information to enter. In this case, I tell the program to select courses from the menu on the left, and then the class corresponding to the assignment I need to turn in:
# Find and click on list of coursescourses_button = driver.find_element_by_id('global_nav_courses_link')courses_button.click()# Get the name of the folderfolder = file_tup[0] # Class to select depends on folderif folder == 'EECS491': class_select = driver.find_element_by_link_text('Artificial Intelligence: Probabilistic Graphical Models (100/10039)')elif folder == 'EECS531': class_select = driver.find_element_by_link_text('Computer Vision (100/10040)')# Click on the specific classclass_select.click()
The program finds the correct class using the name of the folder we stored in the first step. In this case, I use the selection method find_element_by_link_text to find the specific class. The “link text” for an element is just another selector we can find by inspecting the page. :
This workflow may seem a little tedious, but remember, we only have to do it once when we write our program! After that, we can hit run as many times as we want and the program will navigate through all these pages for us.
We use the same ‘inspect page — select element — interact with element’ process to get through a couple more screens. Finally, we reach the assignment submission page:
At this point, I could see the finish line, but initially this screen perplexed me. I could click on the “Choose File” box pretty easily, but how was I supposed to select the actual file I need to upload? The answer turns out to be incredibly simple! We locate the Choose File box using a selector, and use the send_keys method to pass the exact path of the file (called file_location in the code below) to the box:
# Choose File buttonchoose_file = driver.find_element_by_name('attachments[0][uploaded_data]')# Complete path of the filefile_location = os.path.join(submission_dir, folder, file_name)# Send the file location to the buttonchoose_file.send_keys(file_location)
That’s it! By sending the exact path of the file to the button, we can skip the whole process of navigating through folders to find the right file. After sending the location, we are rewarded with the following screen showing that our file is uploaded and ready for submission.
Now, we select the “Submit Assignment” button, click, and our assignment is turned in!
# Locate submit button and clicksubmit_assignment = driver.find_element_by_id('submit_file_button')submit_assignent.click()
File management is always a critical step and I want to make sure I don’t re-submit or lose old assignments. I decided the best solution was to store a single file to be submitted in the completed_assignments folder at any one time and move files to asubmitted_assignments folder once they had been turned in. The final bit of code uses the os module to move the completed assignment by renaming it with the desired location:
# Location of files after submissionsubmitted_file_location = os.path.join(submitted_dir, submitted_file_name)# Rename essentially copies and pastes filesos.rename(file_location, submitted_file_location)
All of the proceeding code gets wrapped up in a single script, which I can run from the command line. To limit opportunities for mistakes, I only submit one assignment at a time, which isn’t a big deal given that it only takes about 5 seconds to run the program!
Here’s what it looks like when I start the program:
The program provides me with a chance to make sure this is the correct assignment before uploading. After the program has completed, I get the following output:
While the program is running, I can watch Python go to work for me:
The technique of automating the web with Python works great for many tasks, both general and in my field of data science. For example, we could use selenium to automatically download new data files every day (assuming the website doesn’t have an API). While it might seem like a lot of work to write the script initially, the benefit comes from the fact that we can have the computer repeat this sequence as many times as want in exactly the same manner. The program will never lose focus and wander off to Twitter. It will faithfully carry out the same exact series of steps with perfect consistency (which works great until the website changes).
I should mention you do want to be careful before you automate critical tasks. This example is relatively low-risk as I can always go back and re-submit assignments and I usually double-check the program’s handiwork. Websites change, and if you don’t change the program in response you might end up with a script that does something completely different than what you originally intended!
In terms of paying off, this program saves me about 30 seconds for every assignment and took 2 hours to write. So, if I use it to turn in 240 assignments, then I come out ahead on time! However, the payoff of this program is in designing a cool solution to a problem and learning a lot in the process. While my time might have been more effectively spent working on assignments rather than figuring out how to automatically turn them in, I thoroughly enjoyed this challenge. There are few things as satisfying as solving problems, and Python turns out to be a pretty good tool for doing exactly that.
As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will. | [
{
"code": null,
"e": 210,
"s": 172,
"text": "An adventure in simple web automation"
},
{
"code": null,
"e": 567,
"s": 210,
"text": "Problem: Submitting class assignments requires navigating a maze of web pages so complex that several times I’ve turned an assignment in to the wrong place. Also, while this process only takes 1–2 minutes, it sometimes seems like an insurmountable barrier (like when I’ve finished an assignment way too late at night and I can barely remember my password)."
},
{
"code": null,
"e": 891,
"s": 567,
"text": "Solution: Use Python to automatically submit completed assignments! Ideally, I would be able to save an assignment, type a few keys, and have my work uploaded in a matter of seconds. At first this sounded too good to be true, but then I discovered selenium, a tool which can be used with Python to navigate the web for you."
},
{
"code": null,
"e": 1305,
"s": 891,
"text": "Anytime we find ourselves repeating tedious actions on the web with the same sequence of steps, this is a great chance to write a program to automate the process for us. With selenium and Python, we just need to write a script once, and which then we can run it as many times and save ourselves from repeating monotonous tasks (and in my case, eliminate the chance of submitting an assignment in the wrong place)!"
},
{
"code": null,
"e": 1817,
"s": 1305,
"text": "Here, I’ll walk through the solution I developed to automatically (and correctly) submit my assignments. Along the way, we’ll cover the basics of using Python and selenium to programmatically control the web. While this program does work (I’m using it every day!) it’s pretty custom so you won’t be able to copy and paste the code for your application. Nonetheless, the general techniques here can be applied to a limitless number of situations. (If you want to see the complete code, it’s available on GitHub)."
},
{
"code": null,
"e": 2616,
"s": 1817,
"text": "Before we can get to the fun part of automating the web, we need to figure out the general structure of our solution. Jumping right into programming without a plan is a great way to waste many hours in frustration. I want to write a program to submit completed course assignments to the correct location on Canvas (my university’s “learning management system”). Starting with the basics, I need a way to tell the program the name of the assignment to submit and the class. I went with a simple approach and created a folder to hold completed assignments with child folders for each class. In the child folders, I place the completed document named for the particular assignment. The program can figure out the name of the class from the folder, and the name of the assignment by the document title."
},
{
"code": null,
"e": 2750,
"s": 2616,
"text": "Here’s an example where the name of the class is EECS491 and the assignment is “Assignment 3 — Inference in Larger Graphical Models”."
},
{
"code": null,
"e": 2884,
"s": 2750,
"text": "The first part of the program is a loop to go through the folders to find the assignment and class, which we store in a Python tuple:"
},
{
"code": null,
"e": 3301,
"s": 2884,
"text": "# os for file managementimport os# Build tuple of (class, file) to turn insubmission_dir = 'completed_assignments'dir_list = list(os.listdir(submission_dir))for directory in dir_list: file_list = list(os.listdir(os.path.join(submission_dir, directory))) if len(file_list) != 0: file_tup = (directory, file_list[0]) print(file_tup)('EECS491', 'Assignment 3 - Inference in Larger Graphical Models.txt')"
},
{
"code": null,
"e": 3500,
"s": 3301,
"text": "This takes care of file management and the program now knows the program and the assignment to turn in. The next step is to use selenium to navigate to the correct webpage and upload the assignment."
},
{
"code": null,
"e": 3745,
"s": 3500,
"text": "To get started with selenium, we import the library and create a web driver, which is a browser that is controlled by our program. In this case, I’ll use Chrome as my browser and send the driver to the Canvas website where I submit assignments."
},
{
"code": null,
"e": 3871,
"s": 3745,
"text": "import selenium# Using Chrome to access webdriver = webdriver.Chrome()# Open the websitedriver.get('https://canvas.case.edu')"
},
{
"code": null,
"e": 4048,
"s": 3871,
"text": "When we open the Canvas webpage, we are greeted with our first obstacle, a login box! To get past this, we will need to fill in an id and a password and click the login button."
},
{
"code": null,
"e": 4707,
"s": 4048,
"text": "Imagine the web driver as a person who has never seen a web page before: we need to tell it exactly where to click, what to type, and which buttons to press. There are a number of ways to tell our web driver what elements to find, all of which use selectors. A selector is a unique identifier for an element on a webpage. To find the selector for a specific element, say the CWRU ID box above, we need to inspect the webpage. In Chrome, this is done by pressing “ctrl + shift + i” or right clicking on any element and selecting “Inspect”. This brings up the Chrome developer tools, an extremely useful application which shows the HTML underlying any webpage."
},
{
"code": null,
"e": 4923,
"s": 4707,
"text": "To find a selector for the “CWRU ID” box, I right clicked in the box, hit “Inspect” and saw the following in developer tools. The highlighted line corresponds to the id box element (this line is called an HTML tag)."
},
{
"code": null,
"e": 5117,
"s": 4923,
"text": "This HTML might look overwhelming, but we can ignore the majority of the information and focus on the id = \"username\" and name=\"username\" parts. (these are known as attributes of the HTML tag)."
},
{
"code": null,
"e": 5388,
"s": 5117,
"text": "To select the id box with our web driver, we can use either the id or name attribute we found in the developer tools. Web drivers in selenium have many different methods for selecting elements on a webpage and there are often multiple ways to select the exact same item:"
},
{
"code": null,
"e": 5524,
"s": 5388,
"text": "# Select the id boxid_box = driver.find_element_by_name('username')# Equivalent Outcome! id_box = driver.find_element_by_id('username')"
},
{
"code": null,
"e": 5678,
"s": 5524,
"text": "Our program now has access to the id_box and we can interact with it in various ways, such as typing in keys, or clicking (if we have selected a button)."
},
{
"code": null,
"e": 5731,
"s": 5678,
"text": "# Send id informationid_box.send_keys('my_username')"
},
{
"code": null,
"e": 5937,
"s": 5731,
"text": "We carry out the same process for the password box and login button, selecting each based on what we see in the Chrome developer tools. Then, we send information to the elements or click on them as needed."
},
{
"code": null,
"e": 6159,
"s": 5937,
"text": "# Find password boxpass_box = driver.find_element_by_name('password')# Send passwordpass_box.send_keys('my_password')# Find login buttonlogin_button = driver.find_element_by_name('submit')# Click loginlogin_button.click()"
},
{
"code": null,
"e": 6238,
"s": 6159,
"text": "Once we are logged in, we are greeted by this slightly intimidating dashboard:"
},
{
"code": null,
"e": 6518,
"s": 6238,
"text": "We again need to guide the program through the webpage by specifying exactly the elements to click on and the information to enter. In this case, I tell the program to select courses from the menu on the left, and then the class corresponding to the assignment I need to turn in:"
},
{
"code": null,
"e": 7033,
"s": 6518,
"text": "# Find and click on list of coursescourses_button = driver.find_element_by_id('global_nav_courses_link')courses_button.click()# Get the name of the folderfolder = file_tup[0] # Class to select depends on folderif folder == 'EECS491': class_select = driver.find_element_by_link_text('Artificial Intelligence: Probabilistic Graphical Models (100/10039)')elif folder == 'EECS531': class_select = driver.find_element_by_link_text('Computer Vision (100/10040)')# Click on the specific classclass_select.click()"
},
{
"code": null,
"e": 7316,
"s": 7033,
"text": "The program finds the correct class using the name of the folder we stored in the first step. In this case, I use the selection method find_element_by_link_text to find the specific class. The “link text” for an element is just another selector we can find by inspecting the page. :"
},
{
"code": null,
"e": 7539,
"s": 7316,
"text": "This workflow may seem a little tedious, but remember, we only have to do it once when we write our program! After that, we can hit run as many times as we want and the program will navigate through all these pages for us."
},
{
"code": null,
"e": 7707,
"s": 7539,
"text": "We use the same ‘inspect page — select element — interact with element’ process to get through a couple more screens. Finally, we reach the assignment submission page:"
},
{
"code": null,
"e": 8123,
"s": 7707,
"text": "At this point, I could see the finish line, but initially this screen perplexed me. I could click on the “Choose File” box pretty easily, but how was I supposed to select the actual file I need to upload? The answer turns out to be incredibly simple! We locate the Choose File box using a selector, and use the send_keys method to pass the exact path of the file (called file_location in the code below) to the box:"
},
{
"code": null,
"e": 8382,
"s": 8123,
"text": "# Choose File buttonchoose_file = driver.find_element_by_name('attachments[0][uploaded_data]')# Complete path of the filefile_location = os.path.join(submission_dir, folder, file_name)# Send the file location to the buttonchoose_file.send_keys(file_location)"
},
{
"code": null,
"e": 8660,
"s": 8382,
"text": "That’s it! By sending the exact path of the file to the button, we can skip the whole process of navigating through folders to find the right file. After sending the location, we are rewarded with the following screen showing that our file is uploaded and ready for submission."
},
{
"code": null,
"e": 8747,
"s": 8660,
"text": "Now, we select the “Submit Assignment” button, click, and our assignment is turned in!"
},
{
"code": null,
"e": 8871,
"s": 8747,
"text": "# Locate submit button and clicksubmit_assignment = driver.find_element_by_id('submit_file_button')submit_assignent.click()"
},
{
"code": null,
"e": 9297,
"s": 8871,
"text": "File management is always a critical step and I want to make sure I don’t re-submit or lose old assignments. I decided the best solution was to store a single file to be submitted in the completed_assignments folder at any one time and move files to asubmitted_assignments folder once they had been turned in. The final bit of code uses the os module to move the completed assignment by renaming it with the desired location:"
},
{
"code": null,
"e": 9501,
"s": 9297,
"text": "# Location of files after submissionsubmitted_file_location = os.path.join(submitted_dir, submitted_file_name)# Rename essentially copies and pastes filesos.rename(file_location, submitted_file_location)"
},
{
"code": null,
"e": 9764,
"s": 9501,
"text": "All of the proceeding code gets wrapped up in a single script, which I can run from the command line. To limit opportunities for mistakes, I only submit one assignment at a time, which isn’t a big deal given that it only takes about 5 seconds to run the program!"
},
{
"code": null,
"e": 9816,
"s": 9764,
"text": "Here’s what it looks like when I start the program:"
},
{
"code": null,
"e": 9977,
"s": 9816,
"text": "The program provides me with a chance to make sure this is the correct assignment before uploading. After the program has completed, I get the following output:"
},
{
"code": null,
"e": 10045,
"s": 9977,
"text": "While the program is running, I can watch Python go to work for me:"
},
{
"code": null,
"e": 10693,
"s": 10045,
"text": "The technique of automating the web with Python works great for many tasks, both general and in my field of data science. For example, we could use selenium to automatically download new data files every day (assuming the website doesn’t have an API). While it might seem like a lot of work to write the script initially, the benefit comes from the fact that we can have the computer repeat this sequence as many times as want in exactly the same manner. The program will never lose focus and wander off to Twitter. It will faithfully carry out the same exact series of steps with perfect consistency (which works great until the website changes)."
},
{
"code": null,
"e": 11082,
"s": 10693,
"text": "I should mention you do want to be careful before you automate critical tasks. This example is relatively low-risk as I can always go back and re-submit assignments and I usually double-check the program’s handiwork. Websites change, and if you don’t change the program in response you might end up with a script that does something completely different than what you originally intended!"
},
{
"code": null,
"e": 11683,
"s": 11082,
"text": "In terms of paying off, this program saves me about 30 seconds for every assignment and took 2 hours to write. So, if I use it to turn in 240 assignments, then I come out ahead on time! However, the payoff of this program is in designing a cool solution to a problem and learning a lot in the process. While my time might have been more effectively spent working on assignments rather than figuring out how to automatically turn them in, I thoroughly enjoyed this challenge. There are few things as satisfying as solving problems, and Python turns out to be a pretty good tool for doing exactly that."
}
]
|
How to Change the Comparator to Return a Descending Order in Java TreeSet? - GeeksforGeeks | 17 Jan, 2022
Comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of two different classes. TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface. It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used.
Syntax: For the comparator is as follows:
public int compare(Object obj1, Object obj2):
Methods: Getting descending order in TreeSet by changing the comparator.
With user-defined classWithout user-defined class
With user-defined class
Without user-defined class
Method 1: With user-defined class
To change the comparator, a user-defined class is created that implements the Comparator interface more specifically descendingComparator for which pseudo code is as followed for clear understanding before implementing the same. descendingComparator() is passed as an argument in the TreeSet at the inst stance of creation to get the corresponding descending Order set.
Syntax: Passing descendingComparator()
Pseudo Code: TreeSet<String> set = new TreeSet<>(new descendingComparator());
Pseudo Code: Approach
class descendingComparator implements Comparator<String> {
public int compare(String i1, String i2) {
// compare using compareTo() method
return i2.compareTo(i1);
}
}
Example
Java
// Java Program to Change the Comparator to Return a// Descending Order in Java TreeSet // Importing all classes of// java.util packageimport java.util.*; // User0defined class (Helper class)// New class that implements comparator interfaceclass descendingComparator implements Comparator<Integer> { public int compare(Integer i1, Integer i2) { // compare using compareTo() method return i2.compareTo(i1); }} // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Create a TreeSet and pass descendingComparator() // as made in another class as parameter // to it to get Descending Order TreeSet<Integer> set = new TreeSet<>(new descendingComparator()); // Adding elements to Treeset // Custom inputs set.add(10); set.add(20); set.add(30); // Print Descending Ordered set in descending order // as above descendComparator() usage System.out.println("Descending Ordered set : " + set); }}
Method 2: Without user-defined class
Comparator to return a descending order in Java TreeSet at the time of the creation of TreeSet instead of making a new class.
Pseudo Code: Approach
TreeSet<Integer> set = new TreeSet<Integer>(new Comparator<Integer>()
{
public int compare(Integer i1,Integer i2)
{
// comparing using compareTo() method
return i2.compareTo(i1);
}
});
Example
Java
// Java Program to Change the Comparator// to Return Descending Order in Java TreeSet // Importing all classes of// java.util packageimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // implements comparator interface // to get Descending Order // Method 2: At the time of creation of TreeSet // Creating(defining) a TreeSet TreeSet<Integer> set = new TreeSet<Integer>( new Comparator<Integer>() { // Changing the comparator public int compare(Integer i1, Integer i2) { return i2.compareTo(i1); } }); // Add elements to above created TreeSet // Custom inputs set.add(10); set.add(20); set.add(30); // Print Descending Ordered TreeSet System.out.println("Descending Ordered Treeset : " + set); }}
Descending Ordered set : [30, 20, 10]
ruhelaa48
saurabh1990aror
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 24155,
"s": 23557,
"text": "Comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of two different classes. TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface. It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used. "
},
{
"code": null,
"e": 24197,
"s": 24155,
"text": "Syntax: For the comparator is as follows:"
},
{
"code": null,
"e": 24243,
"s": 24197,
"text": "public int compare(Object obj1, Object obj2):"
},
{
"code": null,
"e": 24316,
"s": 24243,
"text": "Methods: Getting descending order in TreeSet by changing the comparator."
},
{
"code": null,
"e": 24366,
"s": 24316,
"text": "With user-defined classWithout user-defined class"
},
{
"code": null,
"e": 24390,
"s": 24366,
"text": "With user-defined class"
},
{
"code": null,
"e": 24417,
"s": 24390,
"text": "Without user-defined class"
},
{
"code": null,
"e": 24451,
"s": 24417,
"text": "Method 1: With user-defined class"
},
{
"code": null,
"e": 24821,
"s": 24451,
"text": "To change the comparator, a user-defined class is created that implements the Comparator interface more specifically descendingComparator for which pseudo code is as followed for clear understanding before implementing the same. descendingComparator() is passed as an argument in the TreeSet at the inst stance of creation to get the corresponding descending Order set."
},
{
"code": null,
"e": 24860,
"s": 24821,
"text": "Syntax: Passing descendingComparator()"
},
{
"code": null,
"e": 24938,
"s": 24860,
"text": "Pseudo Code: TreeSet<String> set = new TreeSet<>(new descendingComparator());"
},
{
"code": null,
"e": 25139,
"s": 24938,
"text": "Pseudo Code: Approach\nclass descendingComparator implements Comparator<String> {\n\npublic int compare(String i1, String i2) {\n\n // compare using compareTo() method\n return i2.compareTo(i1);\n }\n}"
},
{
"code": null,
"e": 25147,
"s": 25139,
"text": "Example"
},
{
"code": null,
"e": 25152,
"s": 25147,
"text": "Java"
},
{
"code": "// Java Program to Change the Comparator to Return a// Descending Order in Java TreeSet // Importing all classes of// java.util packageimport java.util.*; // User0defined class (Helper class)// New class that implements comparator interfaceclass descendingComparator implements Comparator<Integer> { public int compare(Integer i1, Integer i2) { // compare using compareTo() method return i2.compareTo(i1); }} // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Create a TreeSet and pass descendingComparator() // as made in another class as parameter // to it to get Descending Order TreeSet<Integer> set = new TreeSet<>(new descendingComparator()); // Adding elements to Treeset // Custom inputs set.add(10); set.add(20); set.add(30); // Print Descending Ordered set in descending order // as above descendComparator() usage System.out.println(\"Descending Ordered set : \" + set); }}",
"e": 26243,
"s": 25152,
"text": null
},
{
"code": null,
"e": 26280,
"s": 26243,
"text": "Method 2: Without user-defined class"
},
{
"code": null,
"e": 26406,
"s": 26280,
"text": "Comparator to return a descending order in Java TreeSet at the time of the creation of TreeSet instead of making a new class."
},
{
"code": null,
"e": 26649,
"s": 26406,
"text": "Pseudo Code: Approach\n\nTreeSet<Integer> set = new TreeSet<Integer>(new Comparator<Integer>()\n{\n public int compare(Integer i1,Integer i2)\n {\n // comparing using compareTo() method\n return i2.compareTo(i1);\n }\n });"
},
{
"code": null,
"e": 26657,
"s": 26649,
"text": "Example"
},
{
"code": null,
"e": 26662,
"s": 26657,
"text": "Java"
},
{
"code": "// Java Program to Change the Comparator// to Return Descending Order in Java TreeSet // Importing all classes of// java.util packageimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // implements comparator interface // to get Descending Order // Method 2: At the time of creation of TreeSet // Creating(defining) a TreeSet TreeSet<Integer> set = new TreeSet<Integer>( new Comparator<Integer>() { // Changing the comparator public int compare(Integer i1, Integer i2) { return i2.compareTo(i1); } }); // Add elements to above created TreeSet // Custom inputs set.add(10); set.add(20); set.add(30); // Print Descending Ordered TreeSet System.out.println(\"Descending Ordered Treeset : \" + set); }}",
"e": 27666,
"s": 26662,
"text": null
},
{
"code": null,
"e": 27704,
"s": 27666,
"text": "Descending Ordered set : [30, 20, 10]"
},
{
"code": null,
"e": 27716,
"s": 27706,
"text": "ruhelaa48"
},
{
"code": null,
"e": 27732,
"s": 27716,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 27739,
"s": 27732,
"text": "Picked"
},
{
"code": null,
"e": 27744,
"s": 27739,
"text": "Java"
},
{
"code": null,
"e": 27758,
"s": 27744,
"text": "Java Programs"
},
{
"code": null,
"e": 27763,
"s": 27758,
"text": "Java"
},
{
"code": null,
"e": 27861,
"s": 27763,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27870,
"s": 27861,
"text": "Comments"
},
{
"code": null,
"e": 27883,
"s": 27870,
"text": "Old Comments"
},
{
"code": null,
"e": 27913,
"s": 27883,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27928,
"s": 27913,
"text": "Stream In Java"
},
{
"code": null,
"e": 27949,
"s": 27928,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27995,
"s": 27949,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28014,
"s": 27995,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28058,
"s": 28014,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 28084,
"s": 28058,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28118,
"s": 28084,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28165,
"s": 28118,
"text": "Implementing a Linked List in Java using Class"
}
]
|
How to Communicate Between Fragments in Android? - GeeksforGeeks | 17 Jan, 2022
Now a day most apps have so many features so for that they use multiple fragments in a single app and communication is one of the important parts of apps for sharing data from one fragment to another because two fragments can’t communicate directly. A Fragment represents a portion of any user interface. There can be a number of fragments within one activity. They have their own life cycle.
There are multiple ways in which we can communicate within apps:
We can communicate within fragments using the ViewModel.
We can also communicate between fragments using Interface.
In this article, we are going to explain communicating within between fragments using the Interface using Kotlin.
Step 1: Create a New Project in your android studio
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: Create two blank fragments
Navigate to your Project file where MainActivity.kt exists. Right-click on that folder and click on the new package and name it fragments. Now inside this newly created folder create two blank fragments and name them Fragment1 & Fragment2.
Step 3: Working with XML files
Navigate to the app > res > layout > fragment1.xml and add the below code to that file. Below is the code for the fragment1.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".fragments.Fragment1"> <!-- Text View for showing Fragment1 text --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Fragment 1" android:textSize="40sp" android:layout_centerHorizontal="true" android:gravity="center" android:layout_marginTop="20dp" android:textColor="@color/black"/> <!-- Edit Text for taking user input --> <EditText android:id="@+id/messageInput" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Enter text to Pass" android:layout_marginTop="200dp" android:gravity="center" android:layout_marginLeft="30dp" android:layout_marginRight="30dp" android:textSize="30sp"/> <!-- Button for submit user response --> <Button android:id="@+id/sendBtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/etText" android:text="Submit" android:backgroundTint="#0F9D58" android:textSize="20sp" android:textAllCaps="false" android:layout_marginLeft="30dp" android:layout_marginRight="30dp" android:layout_marginTop="20dp" /> </RelativeLayout>
Navigate to the app > res > layout > fragment2.xml and add the below code to that file. Below is the code for the fragment2.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".fragments.Fragment2"> <!-- Text View for showing Fragment2 text --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Fragment 2" android:textSize="40sp" android:layout_centerHorizontal="true" android:gravity="center" android:layout_marginTop="20dp" android:textColor="@color/black"/> <!-- Frame Layout which will replaced by data from Fragment1 --> <FrameLayout android:id="@+id/frameLayout" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/displayMessage" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Text" android:textSize="30sp" android:layout_centerHorizontal="true" android:gravity="center" android:layout_marginTop="300dp" android:textColor="@color/black"/> </FrameLayout> </RelativeLayout>
Step 4: Create Interface
Again navigate to your Project folder where MainActivity.kt exists and right-click on that folder -> new -> Kotlin class/file -> Interface them name it as Communicator.
Kotlin
package com.mrtechy.gfg interface Communicator { fun passData(ediTextInput:String)}
Step 5: Working With the MainActivity.kt
Kotlin
package com.mrtechy.gfg import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport com.mrtechy.gfg.fragments.Fragment1import com.mrtechy.gfg.fragments.Fragment2 class MainActivity : AppCompatActivity(), Communicator { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // created instance of Fragment1 val fragment1 = Fragment1() // Frame manager called to replace Fragment2 frame layout with Fragment1 data supportFragmentManager.beginTransaction().replace(R.id.frameLayout,fragment1).commit() } // Override function which we // have created in our interface override fun passData(ediTextInput: String) { val bundle = Bundle() bundle.putString("message", ediTextInput) val transaction = this.supportFragmentManager.beginTransaction() // Created instance of fragment2 val fragment2 = Fragment2() fragment2.arguments = bundle transaction.replace(R.id.frameLayout,fragment2) transaction.commit() }}
Step 6: Working With Fragment1 & Fragment file
Below is the code for the Fragment1.kt and Fragment2.kt files respectively.
Kotlin
Kotlin
package com.mrtechy.gfg.fragments import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.EditTextimport com.mrtechy.gfg.Communicatorimport com.mrtechy.gfg.R class Fragment1 : Fragment() { private lateinit var communicator: Communicator override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_1, container, false) communicator = activity as Communicator // there are button and edittext id which we have saved val button:Button = view.findViewById(R.id.sendBtn) val textMessage:EditText = view.findViewById(R.id.messageInput) // pass data to our interface while // button clicked using setOnClickListener button.setOnClickListener { communicator.passData(textMessage.text.toString()) } return view } }
package com.mrtechy.gfg.fragments import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.TextViewimport com.mrtechy.gfg.R class Fragment2 : Fragment() { // initialised a empty string variable var displayMessage:String? ="" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_2, container, false) val displayM:TextView = view.findViewById(R.id.displayMessage) // get text from interface and send // to textView present in Fragment2 displayMessage = arguments?.getString("message") displayM.text = displayMessage return view } }
Output:
Output
adnanirshad158
saurabh1990aror
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Change the Background Color After Clicking the Button in Android?
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
MVP (Model View Presenter) Architecture Pattern in Android with Example
Kotlin Setters and Getters | [
{
"code": null,
"e": 25036,
"s": 25008,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 25429,
"s": 25036,
"text": "Now a day most apps have so many features so for that they use multiple fragments in a single app and communication is one of the important parts of apps for sharing data from one fragment to another because two fragments can’t communicate directly. A Fragment represents a portion of any user interface. There can be a number of fragments within one activity. They have their own life cycle."
},
{
"code": null,
"e": 25494,
"s": 25429,
"text": "There are multiple ways in which we can communicate within apps:"
},
{
"code": null,
"e": 25551,
"s": 25494,
"text": "We can communicate within fragments using the ViewModel."
},
{
"code": null,
"e": 25610,
"s": 25551,
"text": "We can also communicate between fragments using Interface."
},
{
"code": null,
"e": 25724,
"s": 25610,
"text": "In this article, we are going to explain communicating within between fragments using the Interface using Kotlin."
},
{
"code": null,
"e": 25777,
"s": 25724,
"text": "Step 1: Create a New Project in your android studio "
},
{
"code": null,
"e": 25941,
"s": 25777,
"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": 25977,
"s": 25941,
"text": "Step 2: Create two blank fragments "
},
{
"code": null,
"e": 26217,
"s": 25977,
"text": "Navigate to your Project file where MainActivity.kt exists. Right-click on that folder and click on the new package and name it fragments. Now inside this newly created folder create two blank fragments and name them Fragment1 & Fragment2."
},
{
"code": null,
"e": 26248,
"s": 26217,
"text": "Step 3: Working with XML files"
},
{
"code": null,
"e": 26383,
"s": 26248,
"text": "Navigate to the app > res > layout > fragment1.xml and add the below code to that file. Below is the code for the fragment1.xml file. "
},
{
"code": null,
"e": 26387,
"s": 26383,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".fragments.Fragment1\"> <!-- Text View for showing Fragment1 text --> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Fragment 1\" android:textSize=\"40sp\" android:layout_centerHorizontal=\"true\" android:gravity=\"center\" android:layout_marginTop=\"20dp\" android:textColor=\"@color/black\"/> <!-- Edit Text for taking user input --> <EditText android:id=\"@+id/messageInput\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Enter text to Pass\" android:layout_marginTop=\"200dp\" android:gravity=\"center\" android:layout_marginLeft=\"30dp\" android:layout_marginRight=\"30dp\" android:textSize=\"30sp\"/> <!-- Button for submit user response --> <Button android:id=\"@+id/sendBtn\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/etText\" android:text=\"Submit\" android:backgroundTint=\"#0F9D58\" android:textSize=\"20sp\" android:textAllCaps=\"false\" android:layout_marginLeft=\"30dp\" android:layout_marginRight=\"30dp\" android:layout_marginTop=\"20dp\" /> </RelativeLayout>",
"e": 27953,
"s": 26387,
"text": null
},
{
"code": null,
"e": 28088,
"s": 27953,
"text": "Navigate to the app > res > layout > fragment2.xml and add the below code to that file. Below is the code for the fragment2.xml file. "
},
{
"code": null,
"e": 28092,
"s": 28088,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".fragments.Fragment2\"> <!-- Text View for showing Fragment2 text --> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Fragment 2\" android:textSize=\"40sp\" android:layout_centerHorizontal=\"true\" android:gravity=\"center\" android:layout_marginTop=\"20dp\" android:textColor=\"@color/black\"/> <!-- Frame Layout which will replaced by data from Fragment1 --> <FrameLayout android:id=\"@+id/frameLayout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <TextView android:id=\"@+id/displayMessage\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Text\" android:textSize=\"30sp\" android:layout_centerHorizontal=\"true\" android:gravity=\"center\" android:layout_marginTop=\"300dp\" android:textColor=\"@color/black\"/> </FrameLayout> </RelativeLayout>",
"e": 29397,
"s": 28092,
"text": null
},
{
"code": null,
"e": 29422,
"s": 29397,
"text": "Step 4: Create Interface"
},
{
"code": null,
"e": 29591,
"s": 29422,
"text": "Again navigate to your Project folder where MainActivity.kt exists and right-click on that folder -> new -> Kotlin class/file -> Interface them name it as Communicator."
},
{
"code": null,
"e": 29598,
"s": 29591,
"text": "Kotlin"
},
{
"code": "package com.mrtechy.gfg interface Communicator { fun passData(ediTextInput:String)}",
"e": 29685,
"s": 29598,
"text": null
},
{
"code": null,
"e": 29727,
"s": 29685,
"text": "Step 5: Working With the MainActivity.kt "
},
{
"code": null,
"e": 29734,
"s": 29727,
"text": "Kotlin"
},
{
"code": "package com.mrtechy.gfg import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport com.mrtechy.gfg.fragments.Fragment1import com.mrtechy.gfg.fragments.Fragment2 class MainActivity : AppCompatActivity(), Communicator { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // created instance of Fragment1 val fragment1 = Fragment1() // Frame manager called to replace Fragment2 frame layout with Fragment1 data supportFragmentManager.beginTransaction().replace(R.id.frameLayout,fragment1).commit() } // Override function which we // have created in our interface override fun passData(ediTextInput: String) { val bundle = Bundle() bundle.putString(\"message\", ediTextInput) val transaction = this.supportFragmentManager.beginTransaction() // Created instance of fragment2 val fragment2 = Fragment2() fragment2.arguments = bundle transaction.replace(R.id.frameLayout,fragment2) transaction.commit() }}",
"e": 30856,
"s": 29734,
"text": null
},
{
"code": null,
"e": 30903,
"s": 30856,
"text": "Step 6: Working With Fragment1 & Fragment file"
},
{
"code": null,
"e": 30980,
"s": 30903,
"text": "Below is the code for the Fragment1.kt and Fragment2.kt files respectively. "
},
{
"code": null,
"e": 30987,
"s": 30980,
"text": "Kotlin"
},
{
"code": null,
"e": 30994,
"s": 30987,
"text": "Kotlin"
},
{
"code": "package com.mrtechy.gfg.fragments import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.EditTextimport com.mrtechy.gfg.Communicatorimport com.mrtechy.gfg.R class Fragment1 : Fragment() { private lateinit var communicator: Communicator override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_1, container, false) communicator = activity as Communicator // there are button and edittext id which we have saved val button:Button = view.findViewById(R.id.sendBtn) val textMessage:EditText = view.findViewById(R.id.messageInput) // pass data to our interface while // button clicked using setOnClickListener button.setOnClickListener { communicator.passData(textMessage.text.toString()) } return view } }",
"e": 32117,
"s": 30994,
"text": null
},
{
"code": "package com.mrtechy.gfg.fragments import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.TextViewimport com.mrtechy.gfg.R class Fragment2 : Fragment() { // initialised a empty string variable var displayMessage:String? =\"\" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_2, container, false) val displayM:TextView = view.findViewById(R.id.displayMessage) // get text from interface and send // to textView present in Fragment2 displayMessage = arguments?.getString(\"message\") displayM.text = displayMessage return view } }",
"e": 33003,
"s": 32117,
"text": null
},
{
"code": null,
"e": 33011,
"s": 33003,
"text": "Output:"
},
{
"code": null,
"e": 33018,
"s": 33011,
"text": "Output"
},
{
"code": null,
"e": 33033,
"s": 33018,
"text": "adnanirshad158"
},
{
"code": null,
"e": 33049,
"s": 33033,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 33056,
"s": 33049,
"text": "Picked"
},
{
"code": null,
"e": 33064,
"s": 33056,
"text": "Android"
},
{
"code": null,
"e": 33071,
"s": 33064,
"text": "Kotlin"
},
{
"code": null,
"e": 33079,
"s": 33071,
"text": "Android"
},
{
"code": null,
"e": 33177,
"s": 33079,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33186,
"s": 33177,
"text": "Comments"
},
{
"code": null,
"e": 33199,
"s": 33186,
"text": "Old Comments"
},
{
"code": null,
"e": 33241,
"s": 33199,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 33279,
"s": 33241,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 33318,
"s": 33279,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 33368,
"s": 33318,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 33441,
"s": 33368,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 33460,
"s": 33441,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 33473,
"s": 33460,
"text": "Kotlin Array"
},
{
"code": null,
"e": 33515,
"s": 33473,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 33587,
"s": 33515,
"text": "MVP (Model View Presenter) Architecture Pattern in Android with Example"
}
]
|
Interactive COVID-19 report with RMarkdown, Plotly, Leaflet and Shiny | by Luis Chaves | Towards Data Science | This post is part 3 of a series of 4 publications. Refer to part 1 for an overview of the series, part 2 for an explanation of the data sources and minor data cleaning, part 3 for the creation of the visualisations, building the report and the deploy the document into ShinyApps.io and part 4 (soon to be ready) for automatic data update, compilation and publishing of the report. [Project repo]
Each article in the series is self-contained, meaning that you don’t need to read the whole series to make the most out of it.
· Goal ∘ Requirements· Data input· Plots ∘ Treemap Charts ∘ Line Charts ∘ Map Charts ∘ Enough plotting!· Making a Shiny RMarkdown Report ∘ Writing the report ∘ Uploading your document to the Cloud ∘ Publishing your app· Conclusion
In this tutorial, we will be learning how to make 7 kinds of charts to illustrate the progress of COVID19 across nations. We will then integrate these into an RMarkdown document and publish an interactive copy of it for free! — using RStudio premises.
Experience using R, dplyr and ggplot is useful but not essential. Across all my writing/coding I try to make the scripts as human-readable as possible.
First of all, today we will be using two datasets:
Daily count of confirmed COVID cases and COVID deaths by country (which we will call COVID events from here on). To get an idea of what this dataset looks like find the truncated table below:
Cumulative count of confirmed COVID cases and COVID deaths by country. Again find a truncated version of this table below:
Note: The tables above are truncated for visualisation purposes, the actual tables contain data from December, 31st 2019 onwards and for most countries/regions in the World.
I will walk you through the 7 charts we will be making. For every plot the process is the same:
Check the input format for the plotting functionManipulate the input data to get it in the right formatMake plot
Check the input format for the plotting function
Manipulate the input data to get it in the right format
Make plot
There may be some overlap in the data wrangling across plots but that is ok. My aim here is to show how each plot can be made on its own.
Treemap charts work great to represent hierarchies and the magnitude of each “child” element in its “parent”. Here we are plotting COVID events by country which can further be grouped by continent which can, in turn, be grouped as part of the world. Let’s see how to make the following plot with Plotly.
In our treemap, the size of each box will be proportional to the number of events at the latest date for each country, hence we will be using the cumulative table.
After going through the Plotly R Treemap documentation, two things become clear. First, we need all elements (countries, continents, world) in the treemap chart to have a corresponding value, as of now we only have data aggregated at the country level, we will need to aggregate this for each continent and to aggregate it globally. Second, we need a new column indicating the parent of each element: e.g. for Spain, Europe; for Europe, World, for World, nothing. Additionally, we will be calling each element labels as countries, continents and the “World” all need to be in the same column.
Below is the commented script to wrangle the data to the correct specifications:
Now that we have the data in the right format, making the plot is super easy:
The hoverinfo argument takes care of the data displayed when hovering over any particular element. The specification here is saying:
value show the value for the specific element (i.e. Number of deaths/cases).
percent parent : show what percentage of the parent value the current child value represents (e.g Number of deaths in Spains/Number of deaths in Europe).
percent root : show what percentage of the root value the current child value represents (e.g Number of deaths in Spains/Number of deaths in the World).
You can read more about further hovering options in the documentation section.
Finally, we wish to actually store these plots as RDS objects to load them when our Shiny app loads instead of having to compute them at runtime. For this we use the following code:
Note: You may find success simply saving the output of the plot_ly(...) function. When I first started working on this project I found that did not work. For me using the plotly_build() function fixed it.
Here we will be making classic line plots describing the number of events by country or continent over time. In this instance, we won’t be making plotly plots directly. Instead, we will be using ggplot2 and with use the ggplotly function to turn them into interactive plots. We will be making plots like the following:
First, let’s make our ggplot with the cumulative table:
If you’re not familiar with ggplot2, all these lines for a single plot may seem like a lot. While it may seem so, I believe this helps structure plots and also renders the code to be highly readable. Additionally, the group aesthetic (within the aes() function) is not often introduced in beginner ggplot tutorials. In our particular case, it is very important. If we were to not specify it, ggplot would think that the grouping variable for our line plot is continent and would make a very messy plot, see below for the comparison:
Ok now that we’ve made our ggplot, we can use ggplotly() to turn it into a plotly chart in one line. Moreover, given we have stored our ggplot as a variable we can modify it further, e.g. show the y-axis in log10 scale. Finally, we will pass the new plot through the plotly_build() function to be able to store it.
I made 6 other line plots from the cumulative dataset that you can see in the GitHub repository for this project (including curves for events by continent with and without log10 scale). The code for all these plots follows the same structure.
Again following the same principles and pretty much the same code I made another 6 plots like the one below from the daily dataset. The code for that is also available in the repository.
Believe it or not, I won’t be using the plotly map functions here. I have created maps with them before but I do not recommend using them. I’ve stumbled across a few bugs([1], [2]) and the plotly community has been very unresponsive. Hence here we will use Leaflet. Unlike Plotly, Leaflet is solely focused on maps, hence they make much much better tools to build maps.
Having been built by the RStudio team itself, the R Leaflet package has that R feeling to it and more especially a dplyr and ggplot feeling, where maps can be built by layers. Let’s jump to the code. I will present how to make a simple static map. Making one with a timeline is much more complicated hence I will devote a future stand-alone article to it.
First of all, we are going to need a GeoJSON file with the country boundaries. GeoJSON files are a standard used to store geographical boundaries (though many more exist such as shapefiles). I downloaded the countries GeoJSON file from datahub.io. Luckily country boundaries do not change much these days, hence we only need to download and process this file once. It is quite a beefy file for our usage (23MB), hence we will use a little trick to reduce its size. This will greatly improve the load time of our Shiny document (we are smart, we think ahead of time). The size of the file is so big because of all the details in the boundaries (e.g. the resolution of the coastlines). We can make use of the rmapshaper package and more broadly of the mapshaper tool to make our map more coarse and the file much smaller. Below is the script to do all of this from within R.
The world_geojson object contains two main elements of interest: data and polygons. At this stage, the data element contains only two columns, ISO code and the corresponding region name. The polygons element contains the necessary information to draw the polygons for each region. We are going to first merge the data element with the cumulative dataset. Next, we are going to manually remove the polygons for which no data is available in the cumulative dataset. This last step is necessary because the data and polygons are matched by position instead of by some sort of identifier, if we did not perform this last step, the US would appear in Europe, France in Africa or Asia and so forth.
Note: We are only plotting the latest available data for each region (lines 6–9)
Now, all we have to do is the plotting using leaflet . As I said previously, Leaflet in R supports being built in layers, using the magrittr pipe operator (%>%). First, we are going to define a suitable colour palette, I’ve chosen Blues which represent low values with a white-ish colour and uses more and more intense blues as values grow. Then we are going to initialize the main map with leaflet() just as we often do with ggplot() and add tiles, which is Leaflet jargon for the formatting of the map (colour of the sea, of the land... — explore different tiles in this demo).
Now, we are finally going to have a look at the data on top of the map. We are going to add in the polygons and colour them proportionately to the number of cases in each country as per the end of October.
Note, I’ve coloured the regions proportionately to their log10 number of cases as otherwise, the disparity is so big that the colour scale is useless. We have also used the ez_labels() function from the ezplot package, which turns large numbers into a readable format (e.g. 86453625 to 86.4M).
Finally, we are going to add a legend to our map and save the file so we can load it later.
After this, our map looks like the one below. It is also interactive, you can get more details by hovering over the map (though this does not work in Medium, it will work when we publish the document in the Shiny server).
Plotting is great but endless and also very context-dependent. Above I have shown how to make common and not so common plots to illustrate the COVID events over time but you could imagine countless more ways to do this!
RMarkdown documents (.Rmd) are super versatile files that allow you to write intuitive Markdown text and executable R code chunks, all in one place. They are similar to Jupyter Notebooks but are stored as plain text documents as opposed to JSON syntax. RMarkdown documents support a bunch of output formats including PDF, HTML, Word and beamer slides. They also natively support Latex and HTML which is powered by the document compiler pandoc. All RMarkdown documents start with a header like this one:
---title: "Title of my document"author: "<Name-of-Author"date: "<Today's date>"output: html_document---
If you are working from RStudio you can create an RMarkdown template by going File > New File > RMarkdown...
You can visualise the rendered document by clicking the Knit option and additionally you can have several output formats for a single .Rmd document (such as html_document, pdf_document, word_document). My preferred output format is html_document , it allows for interaction with Plotly and Leaflet objects as well as searchable tables. One thing HTML does not support is an actual user interface where the user modifies something on the front end which triggers a change in the backend and results in an updated front-end.
In the modern web, this is supported with JavaScript but as an R programmer, you may not want or have time to learn it, hence why we are going to use Shiny! This article is not a beginner Shiny tutorial but it will hopefully motivate you to get serious with learning Shiny. You can find beginner's material in RStudio’s site.
The magic with Shiny combined with RMarkdown is that you can simply add this line to your RMarkdown header and your document will work as a Shiny UI:
runtime: shiny
That’s it! Now let’s write our document.
We are going to first load all the plots we have previously made and then design the very basic UI.
Now that we have loaded the plots, we simply need to design the Shiny UI, which is composed of an input element and of rendering functions that react to the changes in the input.
An input block looks like this:
The first argument is the input ID which Shiny is going to use to refer to this input handler. Next is the label of this input handle (label) which will appear right above the handle in the document, then the possible choices (choices) and finally the default choice (selected). Other input handling functions exist, such as: fileInput(), dateInput(), sliderInput(), checkboxInput() and others.
Once, we got the input handling function ready, we just need a render*() function that handles the input, such as renderPlotly(), renderImage(), renderText() or others. As you can see below the layout and logic is super easy and intuitive:
I could stop here but I’ll give a last example to illustrate how a more complex logic can easily be handled with a few lines of code. If you are not interested, please skip to the last section where we finally deploy our Shiny document to the Cloud.
The line plots we made earlier offer a great example to build more complex logic. We can have a handle for the mode of the plots (Daily/cumulative), another for geography (Country/continent), another one for the event type (Deaths/Cases) and a final one to enable log10 scale when the continent geography is chosen:
Here we are going to take advantage of the fact that our plot names are standardised to make the logic more concise(see below).
Depending on the inputs, we are going to build a string corresponding to one of the plot names using the ifelse() function. The logic for the geography choice is even more special because if “Continent” is chosen we will create a checkbox to enable log10 scale. To do this we use what's called a conditional panel as seen in the next code chunk, additionally, we are going to wrap all of our input handlers inside an inputPanel() which will make them look very good and tidy:
This result in a tidy panel as shown below:
And below, it’s the logic to fetch the right plot based on the user’s selection of inputs:
I invite you once again to visit the live document in the cloud, as that will be the best way to understand what the UI experience is like. You can also find the source code for the .Rmd document in GitHub.
Setting up a shinyapps.io account
If you have made it this far, I hope you have gotten some useful knowledge out of this article. All that is left to do is to upload our document to the RStudio servers. If it’s the first time doing this you will need to create an account first.
Once that is set-up you need to add your Shiny credentials to your RStudio or R session. You can do this via RStudio or via the terminal:
Connect to Shiny via RStudio
Open to RStudio > Preferences on the top sidebar.
Go to Publishing, the panel should look like the one below
Then click on Connect... and click on ShinyApps.io. RStudio will guide you from there. You basically need to retrieve a token from your account in shinyapps.io and paste it in RStudio.
Connect to Shiny via the terminal
Log in to shinyapps.io
Click on Account > Tokens on the sidebar
Click on +Add Token, then Show
Finally, copy the code block that the shinyapps.io page is showing you which should look like:
rsconnect::setAccountInfo(name=<user-name>, token=<token>, secret=<SECRET>)
From RStudio
1 — Click on the blue publishing button as shown.
2 — A window like this one should open, you can give you ShinyApp whatever name you want, here that will be COVIDEDA. On the left, you can see the files and directories that will be uploaded to the server.
3 — Click on Publish
From the terminal
You can also upload the app from the terminal by using the following command:
From the moment your document (or app) is first published a folder called rsconnect/ will be created in your project directory. Every time you follow these steps again, you will be able to update your document! You can visit my report on this link: https://lucha6.shinyapps.io/COVIDEDA/
In this article, I have illustrated how to create an interactive report to explore COVID19 data. We have made some cool plots using ggplot , plotly and leaflet . We have also learnt how to deploy 100% interactive documents with the help of RMarkdown and Shiny. The next article will cover how to automate the process of updating the datasets, plots and deploy the document without us having to even turn on our computers! 😮🙃 | [
{
"code": null,
"e": 567,
"s": 171,
"text": "This post is part 3 of a series of 4 publications. Refer to part 1 for an overview of the series, part 2 for an explanation of the data sources and minor data cleaning, part 3 for the creation of the visualisations, building the report and the deploy the document into ShinyApps.io and part 4 (soon to be ready) for automatic data update, compilation and publishing of the report. [Project repo]"
},
{
"code": null,
"e": 694,
"s": 567,
"text": "Each article in the series is self-contained, meaning that you don’t need to read the whole series to make the most out of it."
},
{
"code": null,
"e": 925,
"s": 694,
"text": "· Goal ∘ Requirements· Data input· Plots ∘ Treemap Charts ∘ Line Charts ∘ Map Charts ∘ Enough plotting!· Making a Shiny RMarkdown Report ∘ Writing the report ∘ Uploading your document to the Cloud ∘ Publishing your app· Conclusion"
},
{
"code": null,
"e": 1177,
"s": 925,
"text": "In this tutorial, we will be learning how to make 7 kinds of charts to illustrate the progress of COVID19 across nations. We will then integrate these into an RMarkdown document and publish an interactive copy of it for free! — using RStudio premises."
},
{
"code": null,
"e": 1329,
"s": 1177,
"text": "Experience using R, dplyr and ggplot is useful but not essential. Across all my writing/coding I try to make the scripts as human-readable as possible."
},
{
"code": null,
"e": 1380,
"s": 1329,
"text": "First of all, today we will be using two datasets:"
},
{
"code": null,
"e": 1572,
"s": 1380,
"text": "Daily count of confirmed COVID cases and COVID deaths by country (which we will call COVID events from here on). To get an idea of what this dataset looks like find the truncated table below:"
},
{
"code": null,
"e": 1695,
"s": 1572,
"text": "Cumulative count of confirmed COVID cases and COVID deaths by country. Again find a truncated version of this table below:"
},
{
"code": null,
"e": 1869,
"s": 1695,
"text": "Note: The tables above are truncated for visualisation purposes, the actual tables contain data from December, 31st 2019 onwards and for most countries/regions in the World."
},
{
"code": null,
"e": 1965,
"s": 1869,
"text": "I will walk you through the 7 charts we will be making. For every plot the process is the same:"
},
{
"code": null,
"e": 2078,
"s": 1965,
"text": "Check the input format for the plotting functionManipulate the input data to get it in the right formatMake plot"
},
{
"code": null,
"e": 2127,
"s": 2078,
"text": "Check the input format for the plotting function"
},
{
"code": null,
"e": 2183,
"s": 2127,
"text": "Manipulate the input data to get it in the right format"
},
{
"code": null,
"e": 2193,
"s": 2183,
"text": "Make plot"
},
{
"code": null,
"e": 2331,
"s": 2193,
"text": "There may be some overlap in the data wrangling across plots but that is ok. My aim here is to show how each plot can be made on its own."
},
{
"code": null,
"e": 2635,
"s": 2331,
"text": "Treemap charts work great to represent hierarchies and the magnitude of each “child” element in its “parent”. Here we are plotting COVID events by country which can further be grouped by continent which can, in turn, be grouped as part of the world. Let’s see how to make the following plot with Plotly."
},
{
"code": null,
"e": 2799,
"s": 2635,
"text": "In our treemap, the size of each box will be proportional to the number of events at the latest date for each country, hence we will be using the cumulative table."
},
{
"code": null,
"e": 3392,
"s": 2799,
"text": "After going through the Plotly R Treemap documentation, two things become clear. First, we need all elements (countries, continents, world) in the treemap chart to have a corresponding value, as of now we only have data aggregated at the country level, we will need to aggregate this for each continent and to aggregate it globally. Second, we need a new column indicating the parent of each element: e.g. for Spain, Europe; for Europe, World, for World, nothing. Additionally, we will be calling each element labels as countries, continents and the “World” all need to be in the same column."
},
{
"code": null,
"e": 3473,
"s": 3392,
"text": "Below is the commented script to wrangle the data to the correct specifications:"
},
{
"code": null,
"e": 3551,
"s": 3473,
"text": "Now that we have the data in the right format, making the plot is super easy:"
},
{
"code": null,
"e": 3684,
"s": 3551,
"text": "The hoverinfo argument takes care of the data displayed when hovering over any particular element. The specification here is saying:"
},
{
"code": null,
"e": 3761,
"s": 3684,
"text": "value show the value for the specific element (i.e. Number of deaths/cases)."
},
{
"code": null,
"e": 3915,
"s": 3761,
"text": "percent parent : show what percentage of the parent value the current child value represents (e.g Number of deaths in Spains/Number of deaths in Europe)."
},
{
"code": null,
"e": 4068,
"s": 3915,
"text": "percent root : show what percentage of the root value the current child value represents (e.g Number of deaths in Spains/Number of deaths in the World)."
},
{
"code": null,
"e": 4147,
"s": 4068,
"text": "You can read more about further hovering options in the documentation section."
},
{
"code": null,
"e": 4329,
"s": 4147,
"text": "Finally, we wish to actually store these plots as RDS objects to load them when our Shiny app loads instead of having to compute them at runtime. For this we use the following code:"
},
{
"code": null,
"e": 4534,
"s": 4329,
"text": "Note: You may find success simply saving the output of the plot_ly(...) function. When I first started working on this project I found that did not work. For me using the plotly_build() function fixed it."
},
{
"code": null,
"e": 4853,
"s": 4534,
"text": "Here we will be making classic line plots describing the number of events by country or continent over time. In this instance, we won’t be making plotly plots directly. Instead, we will be using ggplot2 and with use the ggplotly function to turn them into interactive plots. We will be making plots like the following:"
},
{
"code": null,
"e": 4909,
"s": 4853,
"text": "First, let’s make our ggplot with the cumulative table:"
},
{
"code": null,
"e": 5442,
"s": 4909,
"text": "If you’re not familiar with ggplot2, all these lines for a single plot may seem like a lot. While it may seem so, I believe this helps structure plots and also renders the code to be highly readable. Additionally, the group aesthetic (within the aes() function) is not often introduced in beginner ggplot tutorials. In our particular case, it is very important. If we were to not specify it, ggplot would think that the grouping variable for our line plot is continent and would make a very messy plot, see below for the comparison:"
},
{
"code": null,
"e": 5757,
"s": 5442,
"text": "Ok now that we’ve made our ggplot, we can use ggplotly() to turn it into a plotly chart in one line. Moreover, given we have stored our ggplot as a variable we can modify it further, e.g. show the y-axis in log10 scale. Finally, we will pass the new plot through the plotly_build() function to be able to store it."
},
{
"code": null,
"e": 6000,
"s": 5757,
"text": "I made 6 other line plots from the cumulative dataset that you can see in the GitHub repository for this project (including curves for events by continent with and without log10 scale). The code for all these plots follows the same structure."
},
{
"code": null,
"e": 6187,
"s": 6000,
"text": "Again following the same principles and pretty much the same code I made another 6 plots like the one below from the daily dataset. The code for that is also available in the repository."
},
{
"code": null,
"e": 6557,
"s": 6187,
"text": "Believe it or not, I won’t be using the plotly map functions here. I have created maps with them before but I do not recommend using them. I’ve stumbled across a few bugs([1], [2]) and the plotly community has been very unresponsive. Hence here we will use Leaflet. Unlike Plotly, Leaflet is solely focused on maps, hence they make much much better tools to build maps."
},
{
"code": null,
"e": 6913,
"s": 6557,
"text": "Having been built by the RStudio team itself, the R Leaflet package has that R feeling to it and more especially a dplyr and ggplot feeling, where maps can be built by layers. Let’s jump to the code. I will present how to make a simple static map. Making one with a timeline is much more complicated hence I will devote a future stand-alone article to it."
},
{
"code": null,
"e": 7786,
"s": 6913,
"text": "First of all, we are going to need a GeoJSON file with the country boundaries. GeoJSON files are a standard used to store geographical boundaries (though many more exist such as shapefiles). I downloaded the countries GeoJSON file from datahub.io. Luckily country boundaries do not change much these days, hence we only need to download and process this file once. It is quite a beefy file for our usage (23MB), hence we will use a little trick to reduce its size. This will greatly improve the load time of our Shiny document (we are smart, we think ahead of time). The size of the file is so big because of all the details in the boundaries (e.g. the resolution of the coastlines). We can make use of the rmapshaper package and more broadly of the mapshaper tool to make our map more coarse and the file much smaller. Below is the script to do all of this from within R."
},
{
"code": null,
"e": 8479,
"s": 7786,
"text": "The world_geojson object contains two main elements of interest: data and polygons. At this stage, the data element contains only two columns, ISO code and the corresponding region name. The polygons element contains the necessary information to draw the polygons for each region. We are going to first merge the data element with the cumulative dataset. Next, we are going to manually remove the polygons for which no data is available in the cumulative dataset. This last step is necessary because the data and polygons are matched by position instead of by some sort of identifier, if we did not perform this last step, the US would appear in Europe, France in Africa or Asia and so forth."
},
{
"code": null,
"e": 8560,
"s": 8479,
"text": "Note: We are only plotting the latest available data for each region (lines 6–9)"
},
{
"code": null,
"e": 9140,
"s": 8560,
"text": "Now, all we have to do is the plotting using leaflet . As I said previously, Leaflet in R supports being built in layers, using the magrittr pipe operator (%>%). First, we are going to define a suitable colour palette, I’ve chosen Blues which represent low values with a white-ish colour and uses more and more intense blues as values grow. Then we are going to initialize the main map with leaflet() just as we often do with ggplot() and add tiles, which is Leaflet jargon for the formatting of the map (colour of the sea, of the land... — explore different tiles in this demo)."
},
{
"code": null,
"e": 9346,
"s": 9140,
"text": "Now, we are finally going to have a look at the data on top of the map. We are going to add in the polygons and colour them proportionately to the number of cases in each country as per the end of October."
},
{
"code": null,
"e": 9640,
"s": 9346,
"text": "Note, I’ve coloured the regions proportionately to their log10 number of cases as otherwise, the disparity is so big that the colour scale is useless. We have also used the ez_labels() function from the ezplot package, which turns large numbers into a readable format (e.g. 86453625 to 86.4M)."
},
{
"code": null,
"e": 9732,
"s": 9640,
"text": "Finally, we are going to add a legend to our map and save the file so we can load it later."
},
{
"code": null,
"e": 9954,
"s": 9732,
"text": "After this, our map looks like the one below. It is also interactive, you can get more details by hovering over the map (though this does not work in Medium, it will work when we publish the document in the Shiny server)."
},
{
"code": null,
"e": 10174,
"s": 9954,
"text": "Plotting is great but endless and also very context-dependent. Above I have shown how to make common and not so common plots to illustrate the COVID events over time but you could imagine countless more ways to do this!"
},
{
"code": null,
"e": 10677,
"s": 10174,
"text": "RMarkdown documents (.Rmd) are super versatile files that allow you to write intuitive Markdown text and executable R code chunks, all in one place. They are similar to Jupyter Notebooks but are stored as plain text documents as opposed to JSON syntax. RMarkdown documents support a bunch of output formats including PDF, HTML, Word and beamer slides. They also natively support Latex and HTML which is powered by the document compiler pandoc. All RMarkdown documents start with a header like this one:"
},
{
"code": null,
"e": 10781,
"s": 10677,
"text": "---title: \"Title of my document\"author: \"<Name-of-Author\"date: \"<Today's date>\"output: html_document---"
},
{
"code": null,
"e": 10890,
"s": 10781,
"text": "If you are working from RStudio you can create an RMarkdown template by going File > New File > RMarkdown..."
},
{
"code": null,
"e": 11413,
"s": 10890,
"text": "You can visualise the rendered document by clicking the Knit option and additionally you can have several output formats for a single .Rmd document (such as html_document, pdf_document, word_document). My preferred output format is html_document , it allows for interaction with Plotly and Leaflet objects as well as searchable tables. One thing HTML does not support is an actual user interface where the user modifies something on the front end which triggers a change in the backend and results in an updated front-end."
},
{
"code": null,
"e": 11739,
"s": 11413,
"text": "In the modern web, this is supported with JavaScript but as an R programmer, you may not want or have time to learn it, hence why we are going to use Shiny! This article is not a beginner Shiny tutorial but it will hopefully motivate you to get serious with learning Shiny. You can find beginner's material in RStudio’s site."
},
{
"code": null,
"e": 11889,
"s": 11739,
"text": "The magic with Shiny combined with RMarkdown is that you can simply add this line to your RMarkdown header and your document will work as a Shiny UI:"
},
{
"code": null,
"e": 11904,
"s": 11889,
"text": "runtime: shiny"
},
{
"code": null,
"e": 11945,
"s": 11904,
"text": "That’s it! Now let’s write our document."
},
{
"code": null,
"e": 12045,
"s": 11945,
"text": "We are going to first load all the plots we have previously made and then design the very basic UI."
},
{
"code": null,
"e": 12224,
"s": 12045,
"text": "Now that we have loaded the plots, we simply need to design the Shiny UI, which is composed of an input element and of rendering functions that react to the changes in the input."
},
{
"code": null,
"e": 12256,
"s": 12224,
"text": "An input block looks like this:"
},
{
"code": null,
"e": 12651,
"s": 12256,
"text": "The first argument is the input ID which Shiny is going to use to refer to this input handler. Next is the label of this input handle (label) which will appear right above the handle in the document, then the possible choices (choices) and finally the default choice (selected). Other input handling functions exist, such as: fileInput(), dateInput(), sliderInput(), checkboxInput() and others."
},
{
"code": null,
"e": 12891,
"s": 12651,
"text": "Once, we got the input handling function ready, we just need a render*() function that handles the input, such as renderPlotly(), renderImage(), renderText() or others. As you can see below the layout and logic is super easy and intuitive:"
},
{
"code": null,
"e": 13141,
"s": 12891,
"text": "I could stop here but I’ll give a last example to illustrate how a more complex logic can easily be handled with a few lines of code. If you are not interested, please skip to the last section where we finally deploy our Shiny document to the Cloud."
},
{
"code": null,
"e": 13457,
"s": 13141,
"text": "The line plots we made earlier offer a great example to build more complex logic. We can have a handle for the mode of the plots (Daily/cumulative), another for geography (Country/continent), another one for the event type (Deaths/Cases) and a final one to enable log10 scale when the continent geography is chosen:"
},
{
"code": null,
"e": 13585,
"s": 13457,
"text": "Here we are going to take advantage of the fact that our plot names are standardised to make the logic more concise(see below)."
},
{
"code": null,
"e": 14061,
"s": 13585,
"text": "Depending on the inputs, we are going to build a string corresponding to one of the plot names using the ifelse() function. The logic for the geography choice is even more special because if “Continent” is chosen we will create a checkbox to enable log10 scale. To do this we use what's called a conditional panel as seen in the next code chunk, additionally, we are going to wrap all of our input handlers inside an inputPanel() which will make them look very good and tidy:"
},
{
"code": null,
"e": 14105,
"s": 14061,
"text": "This result in a tidy panel as shown below:"
},
{
"code": null,
"e": 14196,
"s": 14105,
"text": "And below, it’s the logic to fetch the right plot based on the user’s selection of inputs:"
},
{
"code": null,
"e": 14403,
"s": 14196,
"text": "I invite you once again to visit the live document in the cloud, as that will be the best way to understand what the UI experience is like. You can also find the source code for the .Rmd document in GitHub."
},
{
"code": null,
"e": 14437,
"s": 14403,
"text": "Setting up a shinyapps.io account"
},
{
"code": null,
"e": 14682,
"s": 14437,
"text": "If you have made it this far, I hope you have gotten some useful knowledge out of this article. All that is left to do is to upload our document to the RStudio servers. If it’s the first time doing this you will need to create an account first."
},
{
"code": null,
"e": 14820,
"s": 14682,
"text": "Once that is set-up you need to add your Shiny credentials to your RStudio or R session. You can do this via RStudio or via the terminal:"
},
{
"code": null,
"e": 14849,
"s": 14820,
"text": "Connect to Shiny via RStudio"
},
{
"code": null,
"e": 14899,
"s": 14849,
"text": "Open to RStudio > Preferences on the top sidebar."
},
{
"code": null,
"e": 14958,
"s": 14899,
"text": "Go to Publishing, the panel should look like the one below"
},
{
"code": null,
"e": 15143,
"s": 14958,
"text": "Then click on Connect... and click on ShinyApps.io. RStudio will guide you from there. You basically need to retrieve a token from your account in shinyapps.io and paste it in RStudio."
},
{
"code": null,
"e": 15177,
"s": 15143,
"text": "Connect to Shiny via the terminal"
},
{
"code": null,
"e": 15200,
"s": 15177,
"text": "Log in to shinyapps.io"
},
{
"code": null,
"e": 15241,
"s": 15200,
"text": "Click on Account > Tokens on the sidebar"
},
{
"code": null,
"e": 15272,
"s": 15241,
"text": "Click on +Add Token, then Show"
},
{
"code": null,
"e": 15367,
"s": 15272,
"text": "Finally, copy the code block that the shinyapps.io page is showing you which should look like:"
},
{
"code": null,
"e": 15451,
"s": 15367,
"text": "rsconnect::setAccountInfo(name=<user-name>,\t\t\t token=<token>,\t\t\t secret=<SECRET>)"
},
{
"code": null,
"e": 15464,
"s": 15451,
"text": "From RStudio"
},
{
"code": null,
"e": 15514,
"s": 15464,
"text": "1 — Click on the blue publishing button as shown."
},
{
"code": null,
"e": 15720,
"s": 15514,
"text": "2 — A window like this one should open, you can give you ShinyApp whatever name you want, here that will be COVIDEDA. On the left, you can see the files and directories that will be uploaded to the server."
},
{
"code": null,
"e": 15741,
"s": 15720,
"text": "3 — Click on Publish"
},
{
"code": null,
"e": 15759,
"s": 15741,
"text": "From the terminal"
},
{
"code": null,
"e": 15837,
"s": 15759,
"text": "You can also upload the app from the terminal by using the following command:"
},
{
"code": null,
"e": 16124,
"s": 15837,
"text": "From the moment your document (or app) is first published a folder called rsconnect/ will be created in your project directory. Every time you follow these steps again, you will be able to update your document! You can visit my report on this link: https://lucha6.shinyapps.io/COVIDEDA/"
}
]
|
C library function - strncpy() | The C library function char *strncpy(char *dest, const char *src, size_t n) copies up to n characters from the string pointed to, by src to dest. In a case where the length of src is less than that of n, the remainder of dest will be padded with null bytes.
Following is the declaration for strncpy() function.
char *strncpy(char *dest, const char *src, size_t n)
dest − This is the pointer to the destination array where the content is to be copied.
dest − This is the pointer to the destination array where the content is to be copied.
src − This is the string to be copied.
src − This is the string to be copied.
n − The number of characters to be copied from source.
n − The number of characters to be copied from source.
This function returns the pointer to the copied string.
The following example shows the usage of strncpy() function. Here we have used function memset() to clear the memory location.
#include <stdio.h>
#include <string.h>
int main () {
char src[40];
char dest[12];
memset(dest, '\0', sizeof(dest));
strcpy(src, "This is tutorialspoint.com");
strncpy(dest, src, 10);
printf("Final copied string : %s\n", dest);
return(0);
}
Let us compile and run the above program that will produce the following result −
Final copied string : This is tu
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": 2265,
"s": 2007,
"text": "The C library function char *strncpy(char *dest, const char *src, size_t n) copies up to n characters from the string pointed to, by src to dest. In a case where the length of src is less than that of n, the remainder of dest will be padded with null bytes."
},
{
"code": null,
"e": 2318,
"s": 2265,
"text": "Following is the declaration for strncpy() function."
},
{
"code": null,
"e": 2371,
"s": 2318,
"text": "char *strncpy(char *dest, const char *src, size_t n)"
},
{
"code": null,
"e": 2458,
"s": 2371,
"text": "dest − This is the pointer to the destination array where the content is to be copied."
},
{
"code": null,
"e": 2545,
"s": 2458,
"text": "dest − This is the pointer to the destination array where the content is to be copied."
},
{
"code": null,
"e": 2584,
"s": 2545,
"text": "src − This is the string to be copied."
},
{
"code": null,
"e": 2623,
"s": 2584,
"text": "src − This is the string to be copied."
},
{
"code": null,
"e": 2678,
"s": 2623,
"text": "n − The number of characters to be copied from source."
},
{
"code": null,
"e": 2733,
"s": 2678,
"text": "n − The number of characters to be copied from source."
},
{
"code": null,
"e": 2789,
"s": 2733,
"text": "This function returns the pointer to the copied string."
},
{
"code": null,
"e": 2916,
"s": 2789,
"text": "The following example shows the usage of strncpy() function. Here we have used function memset() to clear the memory location."
},
{
"code": null,
"e": 3186,
"s": 2916,
"text": "#include <stdio.h>\n#include <string.h>\n\nint main () {\n char src[40];\n char dest[12];\n \n memset(dest, '\\0', sizeof(dest));\n strcpy(src, \"This is tutorialspoint.com\");\n strncpy(dest, src, 10);\n\n printf(\"Final copied string : %s\\n\", dest);\n \n return(0);\n}"
},
{
"code": null,
"e": 3268,
"s": 3186,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 3302,
"s": 3268,
"text": "Final copied string : This is tu\n"
},
{
"code": null,
"e": 3335,
"s": 3302,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3350,
"s": 3335,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3385,
"s": 3350,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3400,
"s": 3385,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3435,
"s": 3400,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3449,
"s": 3435,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3482,
"s": 3449,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3500,
"s": 3482,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3535,
"s": 3500,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3554,
"s": 3535,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3587,
"s": 3554,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3599,
"s": 3587,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3606,
"s": 3599,
"text": " Print"
},
{
"code": null,
"e": 3617,
"s": 3606,
"text": " Add Notes"
}
]
|
Fortran - File Input Output | Fortran allows you to read data from, and write data into files.
In the last chapter, you have seen how to read data from, and write data to the terminal. In this chapter you will study file input and output functionalities provided by Fortran.
You can read and write to one or more files. The OPEN, WRITE, READ and CLOSE statements allow you to achieve this.
Before using a file you must open the file. The open command is used to open files for reading or writing. The simplest form of the command is −
open (unit = number, file = "name").
However, the open statement may have a general form −
open (list-of-specifiers)
The following table describes the most commonly used specifiers −
[UNIT=] u
The unit number u could be any number in the range 9-99 and it indicates the file, you may choose any number but every open file in the program must have a unique number
IOSTAT= ios
It is the I/O status identifier and should be an integer variable. If the open statement is successful then the ios value returned is zero else a non-zero value.
ERR = err
It is a label to which the control jumps in case of any error.
FILE = fname
File name, a character string.
STATUS = sta
It shows the prior status of the file. A character string and can have one of the three values NEW, OLD or SCRATCH. A scratch file is created and deleted when closed or the program ends.
ACCESS = acc
It is the file access mode. Can have either of the two values, SEQUENTIAL or DIRECT. The default is SEQUENTIAL.
FORM = frm
It gives the formatting status of the file. Can have either of the two values FORMATTED or UNFORMATTED. The default is UNFORMATTED
RECL = rl
It specifies the length of each record in a direct access file.
After the file has been opened, it is accessed by read and write statements. Once done, it should be closed using the close statement.
The close statement has the following syntax −
close ([UNIT = ]u[,IOSTAT = ios,ERR = err,STATUS = sta])
Please note that the parameters in brackets are optional.
Example
This example demonstrates opening a new file for writing some data into the file.
program outputdata
implicit none
real, dimension(100) :: x, y
real, dimension(100) :: p, q
integer :: i
! data
do i=1,100
x(i) = i * 0.1
y(i) = sin(x(i)) * (1-cos(x(i)/3.0))
end do
! output data into a file
open(1, file = 'data1.dat', status = 'new')
do i=1,100
write(1,*) x(i), y(i)
end do
close(1)
end program outputdata
When the above code is compiled and executed, it creates the file data1.dat and writes the x and y array values into it. And then closes the file.
The read and write statements respectively are used for reading from and writing into a file respectively.
They have the following syntax −
read ([UNIT = ]u, [FMT = ]fmt, IOSTAT = ios, ERR = err, END = s)
write([UNIT = ]u, [FMT = ]fmt, IOSTAT = ios, ERR = err, END = s)
Most of the specifiers have already been discussed in the above table.
The END = s specifier is a statement label where the program jumps, when it reaches end-of-file.
Example
This example demonstrates reading from and writing into a file.
In this program we read from the file, we created in the last example, data1.dat, and display it on screen.
program outputdata
implicit none
real, dimension(100) :: x, y
real, dimension(100) :: p, q
integer :: i
! data
do i = 1,100
x(i) = i * 0.1
y(i) = sin(x(i)) * (1-cos(x(i)/3.0))
end do
! output data into a file
open(1, file = 'data1.dat', status='new')
do i = 1,100
write(1,*) x(i), y(i)
end do
close(1)
! opening the file for reading
open (2, file = 'data1.dat', status = 'old')
do i = 1,100
read(2,*) p(i), q(i)
end do
close(2)
do i = 1,100
write(*,*) p(i), q(i)
end do
end program outputdata
When the above code is compiled and executed, it produces the following result −
0.100000001 5.54589933E-05
0.200000003 4.41325130E-04
0.300000012 1.47636665E-03
0.400000006 3.45637114E-03
0.500000000 6.64328877E-03
0.600000024 1.12552457E-02
0.699999988 1.74576249E-02
0.800000012 2.53552198E-02
0.900000036 3.49861123E-02
1.00000000 4.63171229E-02
1.10000002 5.92407547E-02
1.20000005 7.35742599E-02
1.30000007 8.90605897E-02
1.39999998 0.105371222
1.50000000 0.122110792
1.60000002 0.138823599
1.70000005 0.155002072
1.80000007 0.170096487
1.89999998 0.183526158
2.00000000 0.194692180
2.10000014 0.202990443
2.20000005 0.207826138
2.29999995 0.208628103
2.40000010 0.204863414
2.50000000 0.196052119
2.60000014 0.181780845
2.70000005 0.161716297
2.79999995 0.135617107
2.90000010 0.103344671
3.00000000 6.48725405E-02
3.10000014 2.02930309E-02
3.20000005 -3.01767997E-02
3.29999995 -8.61928314E-02
3.40000010 -0.147283033
3.50000000 -0.212848678
3.60000014 -0.282169819
3.70000005 -0.354410470
3.79999995 -0.428629100
3.90000010 -0.503789663
4.00000000 -0.578774154
4.09999990 -0.652400017
4.20000029 -0.723436713
4.30000019 -0.790623367
4.40000010 -0.852691114
4.50000000 -0.908382416
4.59999990 -0.956472993
4.70000029 -0.995793998
4.80000019 -1.02525222
4.90000010 -1.04385209
5.00000000 -1.05071592
5.09999990 -1.04510069
5.20000029 -1.02641726
5.30000019 -0.994243503
5.40000010 -0.948338211
5.50000000 -0.888650239
5.59999990 -0.815326691
5.70000029 -0.728716135
5.80000019 -0.629372001
5.90000010 -0.518047631
6.00000000 -0.395693362
6.09999990 -0.263447165
6.20000029 -0.122622721
6.30000019 2.53026206E-02
6.40000010 0.178709000
6.50000000 0.335851669
6.59999990 0.494883657
6.70000029 0.653881252
6.80000019 0.810866773
6.90000010 0.963840425
7.00000000 1.11080539
7.09999990 1.24979746
7.20000029 1.37891412
7.30000019 1.49633956
7.40000010 1.60037732
7.50000000 1.68947268
7.59999990 1.76223695
7.70000029 1.81747139
7.80000019 1.85418403
7.90000010 1.87160957
8.00000000 1.86922085
8.10000038 1.84674001
8.19999981 1.80414569
8.30000019 1.74167395
8.40000057 1.65982044
8.50000000 1.55933595
8.60000038 1.44121361
8.69999981 1.30668485
8.80000019 1.15719533
8.90000057 0.994394958
9.00000000 0.820112705
9.10000038 0.636327863
9.19999981 0.445154816
9.30000019 0.248800844
9.40000057 4.95488606E-02
9.50000000 -0.150278628
9.60000038 -0.348357052
9.69999981 -0.542378068
9.80000019 -0.730095863
9.90000057 -0.909344316
10.0000000 -1.07807255
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2211,
"s": 2146,
"text": "Fortran allows you to read data from, and write data into files."
},
{
"code": null,
"e": 2391,
"s": 2211,
"text": "In the last chapter, you have seen how to read data from, and write data to the terminal. In this chapter you will study file input and output functionalities provided by Fortran."
},
{
"code": null,
"e": 2506,
"s": 2391,
"text": "You can read and write to one or more files. The OPEN, WRITE, READ and CLOSE statements allow you to achieve this."
},
{
"code": null,
"e": 2651,
"s": 2506,
"text": "Before using a file you must open the file. The open command is used to open files for reading or writing. The simplest form of the command is −"
},
{
"code": null,
"e": 2689,
"s": 2651,
"text": "open (unit = number, file = \"name\").\n"
},
{
"code": null,
"e": 2743,
"s": 2689,
"text": "However, the open statement may have a general form −"
},
{
"code": null,
"e": 2770,
"s": 2743,
"text": "open (list-of-specifiers)\n"
},
{
"code": null,
"e": 2836,
"s": 2770,
"text": "The following table describes the most commonly used specifiers −"
},
{
"code": null,
"e": 2846,
"s": 2836,
"text": "[UNIT=] u"
},
{
"code": null,
"e": 3016,
"s": 2846,
"text": "The unit number u could be any number in the range 9-99 and it indicates the file, you may choose any number but every open file in the program must have a unique number"
},
{
"code": null,
"e": 3028,
"s": 3016,
"text": "IOSTAT= ios"
},
{
"code": null,
"e": 3190,
"s": 3028,
"text": "It is the I/O status identifier and should be an integer variable. If the open statement is successful then the ios value returned is zero else a non-zero value."
},
{
"code": null,
"e": 3200,
"s": 3190,
"text": "ERR = err"
},
{
"code": null,
"e": 3263,
"s": 3200,
"text": "It is a label to which the control jumps in case of any error."
},
{
"code": null,
"e": 3276,
"s": 3263,
"text": "FILE = fname"
},
{
"code": null,
"e": 3307,
"s": 3276,
"text": "File name, a character string."
},
{
"code": null,
"e": 3320,
"s": 3307,
"text": "STATUS = sta"
},
{
"code": null,
"e": 3507,
"s": 3320,
"text": "It shows the prior status of the file. A character string and can have one of the three values NEW, OLD or SCRATCH. A scratch file is created and deleted when closed or the program ends."
},
{
"code": null,
"e": 3520,
"s": 3507,
"text": "ACCESS = acc"
},
{
"code": null,
"e": 3632,
"s": 3520,
"text": "It is the file access mode. Can have either of the two values, SEQUENTIAL or DIRECT. The default is SEQUENTIAL."
},
{
"code": null,
"e": 3643,
"s": 3632,
"text": "FORM = frm"
},
{
"code": null,
"e": 3774,
"s": 3643,
"text": "It gives the formatting status of the file. Can have either of the two values FORMATTED or UNFORMATTED. The default is UNFORMATTED"
},
{
"code": null,
"e": 3784,
"s": 3774,
"text": "RECL = rl"
},
{
"code": null,
"e": 3848,
"s": 3784,
"text": "It specifies the length of each record in a direct access file."
},
{
"code": null,
"e": 3983,
"s": 3848,
"text": "After the file has been opened, it is accessed by read and write statements. Once done, it should be closed using the close statement."
},
{
"code": null,
"e": 4030,
"s": 3983,
"text": "The close statement has the following syntax −"
},
{
"code": null,
"e": 4088,
"s": 4030,
"text": "close ([UNIT = ]u[,IOSTAT = ios,ERR = err,STATUS = sta])\n"
},
{
"code": null,
"e": 4146,
"s": 4088,
"text": "Please note that the parameters in brackets are optional."
},
{
"code": null,
"e": 4154,
"s": 4146,
"text": "Example"
},
{
"code": null,
"e": 4236,
"s": 4154,
"text": "This example demonstrates opening a new file for writing some data into the file."
},
{
"code": null,
"e": 4654,
"s": 4236,
"text": "program outputdata \nimplicit none\n\n real, dimension(100) :: x, y \n real, dimension(100) :: p, q\n integer :: i \n \n ! data \n do i=1,100 \n x(i) = i * 0.1 \n y(i) = sin(x(i)) * (1-cos(x(i)/3.0)) \n end do \n \n ! output data into a file \n open(1, file = 'data1.dat', status = 'new') \n do i=1,100 \n write(1,*) x(i), y(i) \n end do \n \n close(1) \n \nend program outputdata"
},
{
"code": null,
"e": 4801,
"s": 4654,
"text": "When the above code is compiled and executed, it creates the file data1.dat and writes the x and y array values into it. And then closes the file."
},
{
"code": null,
"e": 4908,
"s": 4801,
"text": "The read and write statements respectively are used for reading from and writing into a file respectively."
},
{
"code": null,
"e": 4941,
"s": 4908,
"text": "They have the following syntax −"
},
{
"code": null,
"e": 5072,
"s": 4941,
"text": "read ([UNIT = ]u, [FMT = ]fmt, IOSTAT = ios, ERR = err, END = s)\nwrite([UNIT = ]u, [FMT = ]fmt, IOSTAT = ios, ERR = err, END = s)\n"
},
{
"code": null,
"e": 5143,
"s": 5072,
"text": "Most of the specifiers have already been discussed in the above table."
},
{
"code": null,
"e": 5240,
"s": 5143,
"text": "The END = s specifier is a statement label where the program jumps, when it reaches end-of-file."
},
{
"code": null,
"e": 5248,
"s": 5240,
"text": "Example"
},
{
"code": null,
"e": 5312,
"s": 5248,
"text": "This example demonstrates reading from and writing into a file."
},
{
"code": null,
"e": 5420,
"s": 5312,
"text": "In this program we read from the file, we created in the last example, data1.dat, and display it on screen."
},
{
"code": null,
"e": 6056,
"s": 5420,
"text": "program outputdata \nimplicit none \n\n real, dimension(100) :: x, y \n real, dimension(100) :: p, q\n integer :: i \n \n ! data \n do i = 1,100 \n x(i) = i * 0.1 \n y(i) = sin(x(i)) * (1-cos(x(i)/3.0)) \n end do \n \n ! output data into a file \n open(1, file = 'data1.dat', status='new') \n do i = 1,100 \n write(1,*) x(i), y(i) \n end do \n close(1) \n\n ! opening the file for reading\n open (2, file = 'data1.dat', status = 'old')\n\n do i = 1,100 \n read(2,*) p(i), q(i)\n end do \n \n close(2)\n \n do i = 1,100 \n write(*,*) p(i), q(i)\n end do \n \nend program outputdata"
},
{
"code": null,
"e": 6137,
"s": 6056,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 8994,
"s": 6137,
"text": "0.100000001 5.54589933E-05\n0.200000003 4.41325130E-04\n0.300000012 1.47636665E-03\n0.400000006 3.45637114E-03\n0.500000000 6.64328877E-03\n0.600000024 1.12552457E-02\n0.699999988 1.74576249E-02\n0.800000012 2.53552198E-02\n0.900000036 3.49861123E-02\n1.00000000 4.63171229E-02\n1.10000002 5.92407547E-02\n1.20000005 7.35742599E-02\n1.30000007 8.90605897E-02\n1.39999998 0.105371222 \n1.50000000 0.122110792 \n1.60000002 0.138823599 \n1.70000005 0.155002072 \n1.80000007 0.170096487 \n1.89999998 0.183526158 \n2.00000000 0.194692180 \n2.10000014 0.202990443 \n2.20000005 0.207826138 \n2.29999995 0.208628103 \n2.40000010 0.204863414 \n2.50000000 0.196052119 \n2.60000014 0.181780845 \n2.70000005 0.161716297 \n2.79999995 0.135617107 \n2.90000010 0.103344671 \n3.00000000 6.48725405E-02\n3.10000014 2.02930309E-02\n3.20000005 -3.01767997E-02\n3.29999995 -8.61928314E-02\n3.40000010 -0.147283033 \n3.50000000 -0.212848678 \n3.60000014 -0.282169819 \n3.70000005 -0.354410470 \n3.79999995 -0.428629100 \n3.90000010 -0.503789663 \n4.00000000 -0.578774154 \n4.09999990 -0.652400017 \n4.20000029 -0.723436713 \n4.30000019 -0.790623367 \n4.40000010 -0.852691114 \n4.50000000 -0.908382416 \n4.59999990 -0.956472993 \n4.70000029 -0.995793998 \n4.80000019 -1.02525222 \n4.90000010 -1.04385209 \n5.00000000 -1.05071592 \n5.09999990 -1.04510069 \n5.20000029 -1.02641726 \n5.30000019 -0.994243503 \n5.40000010 -0.948338211 \n5.50000000 -0.888650239 \n5.59999990 -0.815326691 \n5.70000029 -0.728716135 \n5.80000019 -0.629372001 \n5.90000010 -0.518047631 \n6.00000000 -0.395693362 \n6.09999990 -0.263447165 \n6.20000029 -0.122622721 \n6.30000019 2.53026206E-02\n6.40000010 0.178709000 \n6.50000000 0.335851669 \n6.59999990 0.494883657 \n6.70000029 0.653881252 \n6.80000019 0.810866773 \n6.90000010 0.963840425 \n7.00000000 1.11080539 \n7.09999990 1.24979746 \n7.20000029 1.37891412 \n7.30000019 1.49633956 \n7.40000010 1.60037732 \n7.50000000 1.68947268 \n7.59999990 1.76223695 \n7.70000029 1.81747139 \n7.80000019 1.85418403 \n7.90000010 1.87160957 \n8.00000000 1.86922085 \n8.10000038 1.84674001 \n8.19999981 1.80414569 \n8.30000019 1.74167395 \n8.40000057 1.65982044 \n8.50000000 1.55933595 \n8.60000038 1.44121361 \n8.69999981 1.30668485 \n8.80000019 1.15719533 \n8.90000057 0.994394958 \n9.00000000 0.820112705 \n9.10000038 0.636327863 \n9.19999981 0.445154816 \n9.30000019 0.248800844 \n9.40000057 4.95488606E-02\n9.50000000 -0.150278628 \n9.60000038 -0.348357052 \n9.69999981 -0.542378068 \n9.80000019 -0.730095863 \n9.90000057 -0.909344316 \n10.0000000 -1.07807255 \n"
},
{
"code": null,
"e": 9001,
"s": 8994,
"text": " Print"
},
{
"code": null,
"e": 9012,
"s": 9001,
"text": " Add Notes"
}
]
|
Java Applet Class | 22 Apr, 2022
Java Applet is a special type of small Java program embedded in the webpage to generate dynamic content. The specialty of the Java applet is it runs inside the browser and works on the Client side (User interface side).
For Creating any applet in Java, we use the java.applet.Applet class. It has four Methods in its Life Cycle of Java Applet. The applet can be executed using the applet viewer utility provided by JDK. A Java Applet was created using the Applet class, i.e., part of the java.applet package.
The Applet class provides a standard interface between applets and their environment. The Applet class is the superclass of an applet that is embedded in a Web page or viewed by the Java Applet Viewer. The Java applet class gives several useful methods to give you complete control over the running of an Applet. Like initializing and destroying an applet, It also provides ways that load and display Web Colourful images and methods that load and play audio and Videos Clips and Cinematic Videos.
Java Applets based on the AWT(Abstract Window Toolkit) packages by extending its Applet classJava Applets is based on the Swing package by extending its JApplet Class in it.
Java Applets based on the AWT(Abstract Window Toolkit) packages by extending its Applet class
Java Applets is based on the Swing package by extending its JApplet Class in it.
Now We See The Life Cycle of an Applet and its Methods-
There are two ways to execute a Java Applet:
By using an HTML file
By using the appletviewer tool
Life Cycle Of java Applet Class has four main methods in it-
init()Start()Stop()Destroy()
init()
Start()
Stop()
Destroy()
1. void init(): This init() method is the first method of a java applet. This is used to initialize the applet when the applet begins to execute
2. void start(): void start() this method is called automatically after the init() method, and it is used to start the Applet and to implementation of an applet
3. void stop(): void stop() is used to stop the Applet or to stop the running applet
4. void destroy(): void destroy() is used to destroy the Applet / to Terminate the applet.
5. System.out.println(String): This Method Works from appletviewer, as not from browsers, and it Automatically opens an Output window.
6. ShowStatus(String): This Method Displays the String in the Applet’s status line, and each call overwrites the previous call, and You have to allow time to read the line.
7. String getParameter(String ParameterName): It Returns the value of a parameter defined in a Current Applet.
8. Image getImage(URL url): This method returns an Image object which contains an image specified at its location, url.
9. void play(URL url): This method can play an audio clip found at the specified location, url.
10. setStub: It sets this applet’s stub, which is done automatically by the system.
11. isActive: This method Determines if this current applet is active. Then Applet is marked active just before its start method is invoked. Then It becomes inactive immediately after its stop method when it is initialized.
The Applet class is just like any other class as an Applet Constructor is simply the subclass constructor of the Applet class. Therefore, Because the applet constructor is just like or any other constructor, it cannot be overridden, so Constructors perform any Necessary initialization for the new object or Create the new Object for it.
Applet() – It Constructs a new Applet.
Example of Applet: The Applet program using appletviewer-
Java
// This is a Simple Java Applet// program using appletviewer import java.applet.*;import java.awt.*; /*<applet code="AppletExp1" width=600 height=300></applet>*/ public class AppletExp1 extends Applet { public void init() { System.out.println("Initializing an applet"); } public void start() { System.out.println("Starting an applet"); } public void stop() { System.out.println("Stopping an applet"); } public void destroy() { System.out.println("Destroying an applet"); }}
By using Appletviewer, type the following command at the command prompt-
Output:
Then after An Window is Opening the Final applet Output Applet Window-
It runs inside the browser and works on the Client-side, so it takes less time to respond.
It is more Secured
It can be Executed By multi-platforms with any Browsers, i.e., Windows, Mac Os, Linux Os.
A plugin is required at the client browser(User Side) to execute an Applet.
rkbhola5
java-applet
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 248,
"s": 28,
"text": "Java Applet is a special type of small Java program embedded in the webpage to generate dynamic content. The specialty of the Java applet is it runs inside the browser and works on the Client side (User interface side)."
},
{
"code": null,
"e": 537,
"s": 248,
"text": "For Creating any applet in Java, we use the java.applet.Applet class. It has four Methods in its Life Cycle of Java Applet. The applet can be executed using the applet viewer utility provided by JDK. A Java Applet was created using the Applet class, i.e., part of the java.applet package."
},
{
"code": null,
"e": 1035,
"s": 537,
"text": "The Applet class provides a standard interface between applets and their environment. The Applet class is the superclass of an applet that is embedded in a Web page or viewed by the Java Applet Viewer. The Java applet class gives several useful methods to give you complete control over the running of an Applet. Like initializing and destroying an applet, It also provides ways that load and display Web Colourful images and methods that load and play audio and Videos Clips and Cinematic Videos."
},
{
"code": null,
"e": 1209,
"s": 1035,
"text": "Java Applets based on the AWT(Abstract Window Toolkit) packages by extending its Applet classJava Applets is based on the Swing package by extending its JApplet Class in it."
},
{
"code": null,
"e": 1303,
"s": 1209,
"text": "Java Applets based on the AWT(Abstract Window Toolkit) packages by extending its Applet class"
},
{
"code": null,
"e": 1384,
"s": 1303,
"text": "Java Applets is based on the Swing package by extending its JApplet Class in it."
},
{
"code": null,
"e": 1440,
"s": 1384,
"text": "Now We See The Life Cycle of an Applet and its Methods-"
},
{
"code": null,
"e": 1485,
"s": 1440,
"text": "There are two ways to execute a Java Applet:"
},
{
"code": null,
"e": 1507,
"s": 1485,
"text": "By using an HTML file"
},
{
"code": null,
"e": 1538,
"s": 1507,
"text": "By using the appletviewer tool"
},
{
"code": null,
"e": 1599,
"s": 1538,
"text": "Life Cycle Of java Applet Class has four main methods in it-"
},
{
"code": null,
"e": 1628,
"s": 1599,
"text": "init()Start()Stop()Destroy()"
},
{
"code": null,
"e": 1635,
"s": 1628,
"text": "init()"
},
{
"code": null,
"e": 1643,
"s": 1635,
"text": "Start()"
},
{
"code": null,
"e": 1650,
"s": 1643,
"text": "Stop()"
},
{
"code": null,
"e": 1660,
"s": 1650,
"text": "Destroy()"
},
{
"code": null,
"e": 1806,
"s": 1660,
"text": "1. void init(): This init() method is the first method of a java applet. This is used to initialize the applet when the applet begins to execute"
},
{
"code": null,
"e": 1967,
"s": 1806,
"text": "2. void start(): void start() this method is called automatically after the init() method, and it is used to start the Applet and to implementation of an applet"
},
{
"code": null,
"e": 2052,
"s": 1967,
"text": "3. void stop(): void stop() is used to stop the Applet or to stop the running applet"
},
{
"code": null,
"e": 2143,
"s": 2052,
"text": "4. void destroy(): void destroy() is used to destroy the Applet / to Terminate the applet."
},
{
"code": null,
"e": 2278,
"s": 2143,
"text": "5. System.out.println(String): This Method Works from appletviewer, as not from browsers, and it Automatically opens an Output window."
},
{
"code": null,
"e": 2451,
"s": 2278,
"text": "6. ShowStatus(String): This Method Displays the String in the Applet’s status line, and each call overwrites the previous call, and You have to allow time to read the line."
},
{
"code": null,
"e": 2562,
"s": 2451,
"text": "7. String getParameter(String ParameterName): It Returns the value of a parameter defined in a Current Applet."
},
{
"code": null,
"e": 2682,
"s": 2562,
"text": "8. Image getImage(URL url): This method returns an Image object which contains an image specified at its location, url."
},
{
"code": null,
"e": 2778,
"s": 2682,
"text": "9. void play(URL url): This method can play an audio clip found at the specified location, url."
},
{
"code": null,
"e": 2862,
"s": 2778,
"text": "10. setStub: It sets this applet’s stub, which is done automatically by the system."
},
{
"code": null,
"e": 3086,
"s": 2862,
"text": "11. isActive: This method Determines if this current applet is active. Then Applet is marked active just before its start method is invoked. Then It becomes inactive immediately after its stop method when it is initialized."
},
{
"code": null,
"e": 3424,
"s": 3086,
"text": "The Applet class is just like any other class as an Applet Constructor is simply the subclass constructor of the Applet class. Therefore, Because the applet constructor is just like or any other constructor, it cannot be overridden, so Constructors perform any Necessary initialization for the new object or Create the new Object for it."
},
{
"code": null,
"e": 3463,
"s": 3424,
"text": "Applet() – It Constructs a new Applet."
},
{
"code": null,
"e": 3522,
"s": 3463,
"text": "Example of Applet: The Applet program using appletviewer- "
},
{
"code": null,
"e": 3527,
"s": 3522,
"text": "Java"
},
{
"code": "// This is a Simple Java Applet// program using appletviewer import java.applet.*;import java.awt.*; /*<applet code=\"AppletExp1\" width=600 height=300></applet>*/ public class AppletExp1 extends Applet { public void init() { System.out.println(\"Initializing an applet\"); } public void start() { System.out.println(\"Starting an applet\"); } public void stop() { System.out.println(\"Stopping an applet\"); } public void destroy() { System.out.println(\"Destroying an applet\"); }}",
"e": 4069,
"s": 3527,
"text": null
},
{
"code": null,
"e": 4142,
"s": 4069,
"text": "By using Appletviewer, type the following command at the command prompt-"
},
{
"code": null,
"e": 4150,
"s": 4142,
"text": "Output:"
},
{
"code": null,
"e": 4221,
"s": 4150,
"text": "Then after An Window is Opening the Final applet Output Applet Window-"
},
{
"code": null,
"e": 4312,
"s": 4221,
"text": "It runs inside the browser and works on the Client-side, so it takes less time to respond."
},
{
"code": null,
"e": 4331,
"s": 4312,
"text": "It is more Secured"
},
{
"code": null,
"e": 4421,
"s": 4331,
"text": "It can be Executed By multi-platforms with any Browsers, i.e., Windows, Mac Os, Linux Os."
},
{
"code": null,
"e": 4497,
"s": 4421,
"text": "A plugin is required at the client browser(User Side) to execute an Applet."
},
{
"code": null,
"e": 4506,
"s": 4497,
"text": "rkbhola5"
},
{
"code": null,
"e": 4518,
"s": 4506,
"text": "java-applet"
},
{
"code": null,
"e": 4525,
"s": 4518,
"text": "Picked"
},
{
"code": null,
"e": 4530,
"s": 4525,
"text": "Java"
},
{
"code": null,
"e": 4535,
"s": 4530,
"text": "Java"
},
{
"code": null,
"e": 4633,
"s": 4535,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4648,
"s": 4633,
"text": "Stream In Java"
},
{
"code": null,
"e": 4669,
"s": 4648,
"text": "Introduction to Java"
},
{
"code": null,
"e": 4690,
"s": 4669,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4709,
"s": 4690,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4726,
"s": 4709,
"text": "Generics in Java"
},
{
"code": null,
"e": 4756,
"s": 4726,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 4782,
"s": 4756,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4798,
"s": 4782,
"text": "Strings in Java"
},
{
"code": null,
"e": 4835,
"s": 4798,
"text": "Differences between JDK, JRE and JVM"
}
]
|
What are the different phases of ReactJS component lifecycle ? | 19 Oct, 2021
Lifecycle methods: In ReactJS, the development of each component involves the use of different lifecycle methods. All the lifecycle methods used to create such components, together constitute the component’s lifecycle. They are defined as a series of functions invoked in various stages of a component. Each phase of the lifecycle components includes some specific lifecycle methods related to that particular phase. There are primarily 4 phases involved in the lifecycle of a reactive component, as follows.
InitializingMountingUpdatingUnmounting
Initializing
Mounting
Updating
Unmounting
Phase 1: Initializing
This is the initial phase of the React component lifecycle. As the name suggests, this phase involves all the declarations, definitions, and initialization of properties, default props as well as the initial state of the component required by the developer. In a class-based component, this is implemented in the constructor of the component. This phase occurs only once throughout the entire lifecycle. The methods included in this phase are:
getDefaultProps(): The method invoked immediately before the component is created or any props from the parent component are passed into the said (child) component. It is used to specify the default value of the props.
getInitialState(): The method invoked immediately before the component is created and used to specify the default value of the state.
Phase 2: Mounting
The second phase of the React component lifecycle, followed by the initialization phase, is the mounting phase. It commences when the component is positioned over the DOM container(meaning, an instance of the component is created and inserted into the DOM) and rendered on a webpage. It consists of 2 methods, namely:
componentWillMount(): The method invoked immediately before the component is positioned on the DOM, i.e. right before the component is rendered on the screen for the very first time.
componentDidMount(): The method invoked immediately after the component is positioned on the DOM, i.e. right after the component is rendered on the screen for the very first time.
Phase 3: UpdatingThe third phase of the ReactJS Component Lifecycle is the Updation phase. Followed by the mounting phase, it updates the states and properties that were declared and initialized during the initialization phase (if at all any changes are required). It is also responsible for handling user interaction and passing data within the component hierarchy. Unlike the initialization phase, this phase can be repeated multiple times. Some of the lifecycle methods falling into this category are as follows:
componentWillReceiveProps(): The method invoked immediately before the props of a mounted component get reassigned. It accepts new props which may/may not be the same as the original props.
shouldComponentUpdate(): The method invoked before deciding whether the newly rendered props are required to be displayed on the webpage or not. It is useful in those scenarios when there is such a requirement not to display the new props on the screen.
componentWillUpdate(): The method invoked immediately before the component is re-rendered after updating the states and/or properties.
componentDidUpdate(): The method invoked immediately after the component is re-rendered after updating the states and/or properties.
Phase 4: UnmountingUnmounting is the last phase of the ReactJS component lifecycle. This phase includes those lifecycle methods which are used when a component is getting detached from the DOM container(meaning, the instance of the component being destroyed and unmounted from the DOM). It is also responsible for performing the required cleanup tasks. Once unmounted, a component can not be re-mounted again.
componentWillUnmount(): The method invoked immediately before the component is removed from the DOM at last, i.e. right when the component is completely removed from the page and this shows the end of its lifecycle.
Example: Creating React Application:
Step 1: Create a new react application using the following command:npx create-react-app demo-app
Step 1: Create a new react application using the following command:
npx create-react-app demo-app
Step 2: Move into your project directory using the following command:cd demo-app
Step 2: Move into your project directory using the following command:
cd demo-app
Example: Now write down the following code in the App.js file.
App.js
import React, { Component } from "react"; class App extends Component { constructor(props) { super(props); this.state = { myState: "GeeksforGeeks" }; this.changeMyState = this.changeMyState.bind(this); } render() { return ( <div style={{ textAlign: "center", marginTop: "5%", color: "#006600" }}> <h1>Phases of ReactJS Component Lifecycle</h1> <h3> {this.state.myState}</h3> <button onClick={this.changeMyState}>Click Me!</button> </div> ); } componentWillMount() { console.log("Phase 2: MOUNTING -> Component Will Mount!"); } componentDidMount() { console.log("Phase 2: MOUNTING -> Component Did Mount!"); } // Changing in state changeMyState() { this.setState({ myState: "GeeksforGeeks Tutorial on Phases of ReactJS Lifecycle Methods!", }); } // Props receiver function componentWillReceiveProps(newProps) { console.log("Phase 3: UPDATING -> Component Will Receive Props!"); } shouldComponentUpdate(newProps, newState) { // Phase 3: UPDATING return true; } // Updation of component componentWillUpdate(nextProps, nextState) { console.log("Phase 3: UPDATING -> Component Will update!"); } componentDidUpdate(prevProps, prevState) { console.log("Phase 3: UPDATING -> Component Did update!"); } // Unmount of component componentWillUnmount() { console.log("Phase 3: UNMOUNTING -> Component Will unmount!"); }} export default App;
Run the file: You can save this file and then run your App locally on localhost:3000 using this command:
npm start
Output:
ruhelaa48
abhishek0719kadiyan
saurabh1990aror
Picked
React-Questions
ReactJS-Basics
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": "\n19 Oct, 2021"
},
{
"code": null,
"e": 537,
"s": 28,
"text": "Lifecycle methods: In ReactJS, the development of each component involves the use of different lifecycle methods. All the lifecycle methods used to create such components, together constitute the component’s lifecycle. They are defined as a series of functions invoked in various stages of a component. Each phase of the lifecycle components includes some specific lifecycle methods related to that particular phase. There are primarily 4 phases involved in the lifecycle of a reactive component, as follows."
},
{
"code": null,
"e": 576,
"s": 537,
"text": "InitializingMountingUpdatingUnmounting"
},
{
"code": null,
"e": 589,
"s": 576,
"text": "Initializing"
},
{
"code": null,
"e": 598,
"s": 589,
"text": "Mounting"
},
{
"code": null,
"e": 607,
"s": 598,
"text": "Updating"
},
{
"code": null,
"e": 618,
"s": 607,
"text": "Unmounting"
},
{
"code": null,
"e": 641,
"s": 618,
"text": "Phase 1: Initializing "
},
{
"code": null,
"e": 1085,
"s": 641,
"text": "This is the initial phase of the React component lifecycle. As the name suggests, this phase involves all the declarations, definitions, and initialization of properties, default props as well as the initial state of the component required by the developer. In a class-based component, this is implemented in the constructor of the component. This phase occurs only once throughout the entire lifecycle. The methods included in this phase are:"
},
{
"code": null,
"e": 1304,
"s": 1085,
"text": "getDefaultProps(): The method invoked immediately before the component is created or any props from the parent component are passed into the said (child) component. It is used to specify the default value of the props."
},
{
"code": null,
"e": 1439,
"s": 1304,
"text": "getInitialState(): The method invoked immediately before the component is created and used to specify the default value of the state."
},
{
"code": null,
"e": 1457,
"s": 1439,
"text": "Phase 2: Mounting"
},
{
"code": null,
"e": 1775,
"s": 1457,
"text": "The second phase of the React component lifecycle, followed by the initialization phase, is the mounting phase. It commences when the component is positioned over the DOM container(meaning, an instance of the component is created and inserted into the DOM) and rendered on a webpage. It consists of 2 methods, namely:"
},
{
"code": null,
"e": 1958,
"s": 1775,
"text": "componentWillMount(): The method invoked immediately before the component is positioned on the DOM, i.e. right before the component is rendered on the screen for the very first time."
},
{
"code": null,
"e": 2138,
"s": 1958,
"text": "componentDidMount(): The method invoked immediately after the component is positioned on the DOM, i.e. right after the component is rendered on the screen for the very first time."
},
{
"code": null,
"e": 2654,
"s": 2138,
"text": "Phase 3: UpdatingThe third phase of the ReactJS Component Lifecycle is the Updation phase. Followed by the mounting phase, it updates the states and properties that were declared and initialized during the initialization phase (if at all any changes are required). It is also responsible for handling user interaction and passing data within the component hierarchy. Unlike the initialization phase, this phase can be repeated multiple times. Some of the lifecycle methods falling into this category are as follows:"
},
{
"code": null,
"e": 2844,
"s": 2654,
"text": "componentWillReceiveProps(): The method invoked immediately before the props of a mounted component get reassigned. It accepts new props which may/may not be the same as the original props."
},
{
"code": null,
"e": 3098,
"s": 2844,
"text": "shouldComponentUpdate(): The method invoked before deciding whether the newly rendered props are required to be displayed on the webpage or not. It is useful in those scenarios when there is such a requirement not to display the new props on the screen."
},
{
"code": null,
"e": 3233,
"s": 3098,
"text": "componentWillUpdate(): The method invoked immediately before the component is re-rendered after updating the states and/or properties."
},
{
"code": null,
"e": 3366,
"s": 3233,
"text": "componentDidUpdate(): The method invoked immediately after the component is re-rendered after updating the states and/or properties."
},
{
"code": null,
"e": 3777,
"s": 3366,
"text": "Phase 4: UnmountingUnmounting is the last phase of the ReactJS component lifecycle. This phase includes those lifecycle methods which are used when a component is getting detached from the DOM container(meaning, the instance of the component being destroyed and unmounted from the DOM). It is also responsible for performing the required cleanup tasks. Once unmounted, a component can not be re-mounted again. "
},
{
"code": null,
"e": 3994,
"s": 3777,
"text": "componentWillUnmount(): The method invoked immediately before the component is removed from the DOM at last, i.e. right when the component is completely removed from the page and this shows the end of its lifecycle. "
},
{
"code": null,
"e": 4031,
"s": 3994,
"text": "Example: Creating React Application:"
},
{
"code": null,
"e": 4128,
"s": 4031,
"text": "Step 1: Create a new react application using the following command:npx create-react-app demo-app"
},
{
"code": null,
"e": 4196,
"s": 4128,
"text": "Step 1: Create a new react application using the following command:"
},
{
"code": null,
"e": 4226,
"s": 4196,
"text": "npx create-react-app demo-app"
},
{
"code": null,
"e": 4307,
"s": 4226,
"text": "Step 2: Move into your project directory using the following command:cd demo-app"
},
{
"code": null,
"e": 4377,
"s": 4307,
"text": "Step 2: Move into your project directory using the following command:"
},
{
"code": null,
"e": 4389,
"s": 4377,
"text": "cd demo-app"
},
{
"code": null,
"e": 4452,
"s": 4389,
"text": "Example: Now write down the following code in the App.js file."
},
{
"code": null,
"e": 4459,
"s": 4452,
"text": "App.js"
},
{
"code": "import React, { Component } from \"react\"; class App extends Component { constructor(props) { super(props); this.state = { myState: \"GeeksforGeeks\" }; this.changeMyState = this.changeMyState.bind(this); } render() { return ( <div style={{ textAlign: \"center\", marginTop: \"5%\", color: \"#006600\" }}> <h1>Phases of ReactJS Component Lifecycle</h1> <h3> {this.state.myState}</h3> <button onClick={this.changeMyState}>Click Me!</button> </div> ); } componentWillMount() { console.log(\"Phase 2: MOUNTING -> Component Will Mount!\"); } componentDidMount() { console.log(\"Phase 2: MOUNTING -> Component Did Mount!\"); } // Changing in state changeMyState() { this.setState({ myState: \"GeeksforGeeks Tutorial on Phases of ReactJS Lifecycle Methods!\", }); } // Props receiver function componentWillReceiveProps(newProps) { console.log(\"Phase 3: UPDATING -> Component Will Receive Props!\"); } shouldComponentUpdate(newProps, newState) { // Phase 3: UPDATING return true; } // Updation of component componentWillUpdate(nextProps, nextState) { console.log(\"Phase 3: UPDATING -> Component Will update!\"); } componentDidUpdate(prevProps, prevState) { console.log(\"Phase 3: UPDATING -> Component Did update!\"); } // Unmount of component componentWillUnmount() { console.log(\"Phase 3: UNMOUNTING -> Component Will unmount!\"); }} export default App;",
"e": 5918,
"s": 4459,
"text": null
},
{
"code": null,
"e": 6023,
"s": 5918,
"text": "Run the file: You can save this file and then run your App locally on localhost:3000 using this command:"
},
{
"code": null,
"e": 6033,
"s": 6023,
"text": "npm start"
},
{
"code": null,
"e": 6041,
"s": 6033,
"text": "Output:"
},
{
"code": null,
"e": 6051,
"s": 6041,
"text": "ruhelaa48"
},
{
"code": null,
"e": 6071,
"s": 6051,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 6087,
"s": 6071,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 6094,
"s": 6087,
"text": "Picked"
},
{
"code": null,
"e": 6110,
"s": 6094,
"text": "React-Questions"
},
{
"code": null,
"e": 6125,
"s": 6110,
"text": "ReactJS-Basics"
},
{
"code": null,
"e": 6133,
"s": 6125,
"text": "ReactJS"
},
{
"code": null,
"e": 6150,
"s": 6133,
"text": "Web Technologies"
}
]
|
Choose element(s) from List with different probability in Python | 11 Oct, 2020
Have you ever wondered how to select random elements from a list with different probability in Python? In this article, we will discuss how to do the same. Let’s first consider the below example.
Python3
import random sam_Lst = [10, 20, 3, 4, 100]ran = random.choice(sam_Lst)print(ran)
In the above example, the probability of getting any element from the list is equal. But we want such methods in which the probability of choosing one element from the list is different. This is known as the weighted random choice in Python. In order to find weighted random choices in Python, there exist two ways:
Relative weightsCumulative weights
Relative weights
Cumulative weights
The function which will help us in this situation is random.choices(). This function allows making weighted random choices in python with replacement.
Syntax:
random.choices(population, weights=None, *, cum_weights=None, k=1)
Here, the ‘weight’ parameter plays an important role.
Case 1: Using Relative weights
The weight assigned to an element is known as relative weight.
Example 1:
Python3
import random # Creating a number listnum_lst = [1, 22, 43, 19, 13, 29] print(random.choices(num_lst, weights=( 14, 25, 30, 45, 55, 10), k=6))
Output:
[19, 19, 13, 22, 13, 13]
In the above example, we assign weights to every element of the list. The weight of the element ‘13′ is highest i.e 55, so the probability of its occurrence is maximum. As we can see in the output, element 13 occurs 3 times, 19 occurs 2 times, and so on. So, now the probability of choosing an element from the list is different.
Example 2:
Python3
import random # Creating a name listname_lst = ['October', 'November', 'December', 'January', 'March', 'June'] print(random.choices(name_lst, weights=( 40, 25, 30, 5, 15, 80), k=3))
Output:
['June', 'October', 'June']
In the above example, the weight of element ‘June’ is maximum so its probability of selection will be maximum. And here, k=3 which means we are choosing only the top 3 elements from the list.
Example 3:
Python3
import random # Creating a name listname_lst = ['Fit', 'Infected', 'Recovered', 'Danger'] # Using FOR loop# to choose the element from list with# different probabilityfor i in range(6): print("Random choice", i+1) randomele = random.choices(name_lst, weights=( 50, 80, 10, 5), k=1) print(randomele[0])
Output:
Random choice 1
Recovered
Random choice 2
Danger
Random choice 3
Infected
Random choice 4
Infected
Random choice 5
Infected
Random choice 6
Fit
In the above example, we use FOR loop to choose an element from a list with a different probability.
Case 2: Using Cumulative weights
The cumulative weight of an element is determined by adding the weight of its previous element and its own weight.
Example 1:
Python3
import random # Creating a number listnum_lst = [1, 22, 93, 19, 13, 25] print(random.choices(num_lst, cum_weights=( 7, 13, 15, 20, 25, 20), k=6))
Output:
[1, 22, 93, 22, 19, 1]
In the above example, the cumulative weight of element ‘19′ is maximum, so the probability of its selection will also be maximum.
Example 2:
Python3
import random # Creating a name listname_lst = ['October', 'November', 'December', 'January', 'March', 'June'] print(random.choices(name_lst, cum_weights=( 40, 20, 3, 7, 15, 15), k=3))
Output:
['January', 'March', 'January']
In the above example, we choose k=3 so we get the top 3 elements that have the maximum probability of selection.
Example 3:
Python3
import random # Creating a name list name_lst = ['October', 'November', 'December', 'January', 'March', 'June'] # Using FOR loop# to choose the element from list with# different probabilityfor i in range(6): print("Random choice", i+1) randomele = random.choices(name_lst, cum_weights=( 7, 13, 15, 20, 25, 20), k=1) print(randomele[0])
Output:
Random choice 1
November
Random choice 2
January
Random choice 3
October
Random choice 4
December
Random choice 5
November
Random choice 6
January
In the above example, we use FOR loop to choose an element from a list with a different probability.
Note: The value of k depends on the users, and since its relative weight so the total sum of weights can exceed 100.
Python-random
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Oct, 2020"
},
{
"code": null,
"e": 224,
"s": 28,
"text": "Have you ever wondered how to select random elements from a list with different probability in Python? In this article, we will discuss how to do the same. Let’s first consider the below example."
},
{
"code": null,
"e": 232,
"s": 224,
"text": "Python3"
},
{
"code": "import random sam_Lst = [10, 20, 3, 4, 100]ran = random.choice(sam_Lst)print(ran)",
"e": 315,
"s": 232,
"text": null
},
{
"code": null,
"e": 631,
"s": 315,
"text": "In the above example, the probability of getting any element from the list is equal. But we want such methods in which the probability of choosing one element from the list is different. This is known as the weighted random choice in Python. In order to find weighted random choices in Python, there exist two ways:"
},
{
"code": null,
"e": 666,
"s": 631,
"text": "Relative weightsCumulative weights"
},
{
"code": null,
"e": 683,
"s": 666,
"text": "Relative weights"
},
{
"code": null,
"e": 702,
"s": 683,
"text": "Cumulative weights"
},
{
"code": null,
"e": 853,
"s": 702,
"text": "The function which will help us in this situation is random.choices(). This function allows making weighted random choices in python with replacement."
},
{
"code": null,
"e": 861,
"s": 853,
"text": "Syntax:"
},
{
"code": null,
"e": 928,
"s": 861,
"text": "random.choices(population, weights=None, *, cum_weights=None, k=1)"
},
{
"code": null,
"e": 982,
"s": 928,
"text": "Here, the ‘weight’ parameter plays an important role."
},
{
"code": null,
"e": 1014,
"s": 982,
"text": "Case 1: Using Relative weights "
},
{
"code": null,
"e": 1077,
"s": 1014,
"text": "The weight assigned to an element is known as relative weight."
},
{
"code": null,
"e": 1089,
"s": 1077,
"text": "Example 1: "
},
{
"code": null,
"e": 1097,
"s": 1089,
"text": "Python3"
},
{
"code": "import random # Creating a number listnum_lst = [1, 22, 43, 19, 13, 29] print(random.choices(num_lst, weights=( 14, 25, 30, 45, 55, 10), k=6))",
"e": 1243,
"s": 1097,
"text": null
},
{
"code": null,
"e": 1251,
"s": 1243,
"text": "Output:"
},
{
"code": null,
"e": 1277,
"s": 1251,
"text": "[19, 19, 13, 22, 13, 13]\n"
},
{
"code": null,
"e": 1608,
"s": 1277,
"text": "In the above example, we assign weights to every element of the list. The weight of the element ‘13′ is highest i.e 55, so the probability of its occurrence is maximum. As we can see in the output, element 13 occurs 3 times, 19 occurs 2 times, and so on. So, now the probability of choosing an element from the list is different. "
},
{
"code": null,
"e": 1620,
"s": 1608,
"text": "Example 2: "
},
{
"code": null,
"e": 1628,
"s": 1620,
"text": "Python3"
},
{
"code": "import random # Creating a name listname_lst = ['October', 'November', 'December', 'January', 'March', 'June'] print(random.choices(name_lst, weights=( 40, 25, 30, 5, 15, 80), k=3))",
"e": 1826,
"s": 1628,
"text": null
},
{
"code": null,
"e": 1834,
"s": 1826,
"text": "Output:"
},
{
"code": null,
"e": 1862,
"s": 1834,
"text": "['June', 'October', 'June']"
},
{
"code": null,
"e": 2054,
"s": 1862,
"text": "In the above example, the weight of element ‘June’ is maximum so its probability of selection will be maximum. And here, k=3 which means we are choosing only the top 3 elements from the list."
},
{
"code": null,
"e": 2065,
"s": 2054,
"text": "Example 3:"
},
{
"code": null,
"e": 2073,
"s": 2065,
"text": "Python3"
},
{
"code": "import random # Creating a name listname_lst = ['Fit', 'Infected', 'Recovered', 'Danger'] # Using FOR loop# to choose the element from list with# different probabilityfor i in range(6): print(\"Random choice\", i+1) randomele = random.choices(name_lst, weights=( 50, 80, 10, 5), k=1) print(randomele[0])",
"e": 2403,
"s": 2073,
"text": null
},
{
"code": null,
"e": 2411,
"s": 2403,
"text": "Output:"
},
{
"code": null,
"e": 2556,
"s": 2411,
"text": "Random choice 1\nRecovered\nRandom choice 2\nDanger\nRandom choice 3\nInfected\nRandom choice 4\nInfected\nRandom choice 5\nInfected\nRandom choice 6\nFit\n"
},
{
"code": null,
"e": 2657,
"s": 2556,
"text": "In the above example, we use FOR loop to choose an element from a list with a different probability."
},
{
"code": null,
"e": 2690,
"s": 2657,
"text": "Case 2: Using Cumulative weights"
},
{
"code": null,
"e": 2805,
"s": 2690,
"text": "The cumulative weight of an element is determined by adding the weight of its previous element and its own weight."
},
{
"code": null,
"e": 2817,
"s": 2805,
"text": "Example 1: "
},
{
"code": null,
"e": 2825,
"s": 2817,
"text": "Python3"
},
{
"code": "import random # Creating a number listnum_lst = [1, 22, 93, 19, 13, 25] print(random.choices(num_lst, cum_weights=( 7, 13, 15, 20, 25, 20), k=6))",
"e": 2976,
"s": 2825,
"text": null
},
{
"code": null,
"e": 2984,
"s": 2976,
"text": "Output:"
},
{
"code": null,
"e": 3008,
"s": 2984,
"text": "[1, 22, 93, 22, 19, 1]\n"
},
{
"code": null,
"e": 3138,
"s": 3008,
"text": "In the above example, the cumulative weight of element ‘19′ is maximum, so the probability of its selection will also be maximum."
},
{
"code": null,
"e": 3149,
"s": 3138,
"text": "Example 2:"
},
{
"code": null,
"e": 3157,
"s": 3149,
"text": "Python3"
},
{
"code": "import random # Creating a name listname_lst = ['October', 'November', 'December', 'January', 'March', 'June'] print(random.choices(name_lst, cum_weights=( 40, 20, 3, 7, 15, 15), k=3))",
"e": 3356,
"s": 3157,
"text": null
},
{
"code": null,
"e": 3364,
"s": 3356,
"text": "Output:"
},
{
"code": null,
"e": 3397,
"s": 3364,
"text": "['January', 'March', 'January']\n"
},
{
"code": null,
"e": 3510,
"s": 3397,
"text": "In the above example, we choose k=3 so we get the top 3 elements that have the maximum probability of selection."
},
{
"code": null,
"e": 3521,
"s": 3510,
"text": "Example 3:"
},
{
"code": null,
"e": 3529,
"s": 3521,
"text": "Python3"
},
{
"code": "import random # Creating a name list name_lst = ['October', 'November', 'December', 'January', 'March', 'June'] # Using FOR loop# to choose the element from list with# different probabilityfor i in range(6): print(\"Random choice\", i+1) randomele = random.choices(name_lst, cum_weights=( 7, 13, 15, 20, 25, 20), k=1) print(randomele[0])",
"e": 3905,
"s": 3529,
"text": null
},
{
"code": null,
"e": 3913,
"s": 3905,
"text": "Output:"
},
{
"code": null,
"e": 4061,
"s": 3913,
"text": "Random choice 1\nNovember\nRandom choice 2\nJanuary\nRandom choice 3\nOctober\nRandom choice 4\nDecember\nRandom choice 5\nNovember\nRandom choice 6\nJanuary\n"
},
{
"code": null,
"e": 4162,
"s": 4061,
"text": "In the above example, we use FOR loop to choose an element from a list with a different probability."
},
{
"code": null,
"e": 4279,
"s": 4162,
"text": "Note: The value of k depends on the users, and since its relative weight so the total sum of weights can exceed 100."
},
{
"code": null,
"e": 4293,
"s": 4279,
"text": "Python-random"
},
{
"code": null,
"e": 4300,
"s": 4293,
"text": "Python"
},
{
"code": null,
"e": 4398,
"s": 4300,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4430,
"s": 4398,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4457,
"s": 4430,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4478,
"s": 4457,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4501,
"s": 4478,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4557,
"s": 4501,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4588,
"s": 4557,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4630,
"s": 4588,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4672,
"s": 4630,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4711,
"s": 4672,
"text": "Python | Get unique values from a list"
}
]
|
Query to find 2nd largest value in a column in Table | 11 Jun, 2019
Problem: Write a SQL query to find the 2nd largest value in a column in a table.
Examples:In the 1st example find the 2nd largest value in column “Income” and in the 2nd one find the 2nd largest value in “Cost”.
Input: Table name- Employee
+------+--------+
| Name | Income |
+------+--------+
| abc | 4000 |
| xyz | 4752 |
| qwe | 6579 |
+------+--------+
Output: 4752
Input: Table name- price_list
+-------------+--------+
| Item | Cost |
+-------------+--------+
| Apple | 150 |
| Banana | 175 |
| Mango | 200 |
| Pineapple | 180 |
+-------------+--------+
Output: 180
Method-1:
Syntax:
SELECT MAX (column_name)
FROM table_name
WHERE column_name NOT IN (SELECT Max (column_name)
FROM table_name);
First we selected the max from that column in the table then we searched for the max value again in that column with excluding the max value which has already been found, so it results in the 2nd maximum value.
Example-1:SELECT MAX (Income)
FROM Employee
WHERE Salary NOT IN (SELECT Max (Income)
FROM Employee);
SELECT MAX (Income)
FROM Employee
WHERE Salary NOT IN (SELECT Max (Income)
FROM Employee);
Example-2:SELECT MAX (Cost)
FROM price_list
WHERE Salary NOT IN (SELECT Max (Cost)
FROM price_list);
SELECT MAX (Cost)
FROM price_list
WHERE Salary NOT IN (SELECT Max (Cost)
FROM price_list);
Method-2:
Syntax:
SELECT column_name
FROM table_name e
WHERE 2 = (SELECT COUNT (DISTINCT column_name)
FROM table_name p
WHERE e.column_name<=p.column_name)
This is a nested sub query which is a generic SQL query to print the Nth largest value in column. For each record processed by outer query, inner query will be executed and will return how many records has records has value less than the current value. If you are looking for second highest value then your query will stop as soon as inner query will return 2.
Example-1:SELECT Income
FROM Employee e
WHERE 2=(SELECT COUNT(DISTINCT Income)
FROM Employee p
WHERE e.Income<=p.Income)
SELECT Income
FROM Employee e
WHERE 2=(SELECT COUNT(DISTINCT Income)
FROM Employee p
WHERE e.Income<=p.Income)
Example-2:SELECT Cost
FROM price_list e
WHERE 2=(SELECT COUNT(DISTINCT Cost)
FROM price_list p
WHERE e.Cost<=p.Cost)
SELECT Cost
FROM price_list e
WHERE 2=(SELECT COUNT(DISTINCT Cost)
FROM price_list p
WHERE e.Cost<=p.Cost)
DBMS-SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
SQL Trigger | Student Database
Introduction of B-Tree
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
CTE in SQL
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Jun, 2019"
},
{
"code": null,
"e": 133,
"s": 52,
"text": "Problem: Write a SQL query to find the 2nd largest value in a column in a table."
},
{
"code": null,
"e": 264,
"s": 133,
"text": "Examples:In the 1st example find the 2nd largest value in column “Income” and in the 2nd one find the 2nd largest value in “Cost”."
},
{
"code": null,
"e": 677,
"s": 264,
"text": "Input: Table name- Employee\n+------+--------+\n| Name | Income |\n+------+--------+\n| abc | 4000 |\n| xyz | 4752 |\n| qwe | 6579 |\n+------+--------+\n\nOutput: 4752\n\nInput: Table name- price_list\n+-------------+--------+\n| Item | Cost |\n+-------------+--------+\n| Apple | 150 |\n| Banana | 175 |\n| Mango | 200 |\n| Pineapple | 180 |\n+-------------+--------+\n\nOutput: 180 "
},
{
"code": null,
"e": 687,
"s": 677,
"text": "Method-1:"
},
{
"code": null,
"e": 695,
"s": 687,
"text": "Syntax:"
},
{
"code": null,
"e": 835,
"s": 695,
"text": "SELECT MAX (column_name) \nFROM table_name \nWHERE column_name NOT IN (SELECT Max (column_name) \n FROM table_name); "
},
{
"code": null,
"e": 1046,
"s": 835,
"text": "First we selected the max from that column in the table then we searched for the max value again in that column with excluding the max value which has already been found, so it results in the 2nd maximum value."
},
{
"code": null,
"e": 1172,
"s": 1046,
"text": "Example-1:SELECT MAX (Income) \nFROM Employee \nWHERE Salary NOT IN (SELECT Max (Income) \n FROM Employee); "
},
{
"code": null,
"e": 1288,
"s": 1172,
"text": "SELECT MAX (Income) \nFROM Employee \nWHERE Salary NOT IN (SELECT Max (Income) \n FROM Employee); "
},
{
"code": null,
"e": 1414,
"s": 1288,
"text": "Example-2:SELECT MAX (Cost) \nFROM price_list \nWHERE Salary NOT IN (SELECT Max (Cost) \n FROM price_list); "
},
{
"code": null,
"e": 1530,
"s": 1414,
"text": "SELECT MAX (Cost) \nFROM price_list \nWHERE Salary NOT IN (SELECT Max (Cost) \n FROM price_list); "
},
{
"code": null,
"e": 1540,
"s": 1530,
"text": "Method-2:"
},
{
"code": null,
"e": 1548,
"s": 1540,
"text": "Syntax:"
},
{
"code": null,
"e": 1710,
"s": 1548,
"text": "SELECT column_name\nFROM table_name e\nWHERE 2 = (SELECT COUNT (DISTINCT column_name) \n FROM table_name p\n WHERE e.column_name<=p.column_name) "
},
{
"code": null,
"e": 2071,
"s": 1710,
"text": "This is a nested sub query which is a generic SQL query to print the Nth largest value in column. For each record processed by outer query, inner query will be executed and will return how many records has records has value less than the current value. If you are looking for second highest value then your query will stop as soon as inner query will return 2."
},
{
"code": null,
"e": 2212,
"s": 2071,
"text": "Example-1:SELECT Income\nFROM Employee e\nWHERE 2=(SELECT COUNT(DISTINCT Income) \n FROM Employee p\n WHERE e.Income<=p.Income) "
},
{
"code": null,
"e": 2343,
"s": 2212,
"text": "SELECT Income\nFROM Employee e\nWHERE 2=(SELECT COUNT(DISTINCT Income) \n FROM Employee p\n WHERE e.Income<=p.Income) "
},
{
"code": null,
"e": 2480,
"s": 2343,
"text": "Example-2:SELECT Cost\nFROM price_list e\nWHERE 2=(SELECT COUNT(DISTINCT Cost) \n FROM price_list p\n WHERE e.Cost<=p.Cost) "
},
{
"code": null,
"e": 2607,
"s": 2480,
"text": "SELECT Cost\nFROM price_list e\nWHERE 2=(SELECT COUNT(DISTINCT Cost) \n FROM price_list p\n WHERE e.Cost<=p.Cost) "
},
{
"code": null,
"e": 2616,
"s": 2607,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 2621,
"s": 2616,
"text": "DBMS"
},
{
"code": null,
"e": 2625,
"s": 2621,
"text": "SQL"
},
{
"code": null,
"e": 2630,
"s": 2625,
"text": "DBMS"
},
{
"code": null,
"e": 2634,
"s": 2630,
"text": "SQL"
},
{
"code": null,
"e": 2732,
"s": 2634,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2743,
"s": 2732,
"text": "CTE in SQL"
},
{
"code": null,
"e": 2796,
"s": 2743,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 2854,
"s": 2796,
"text": "Introduction of DBMS (Database Management System) | Set 1"
},
{
"code": null,
"e": 2885,
"s": 2854,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 2908,
"s": 2885,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 2950,
"s": 2908,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 2994,
"s": 2950,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 3005,
"s": 2994,
"text": "CTE in SQL"
},
{
"code": null,
"e": 3026,
"s": 3005,
"text": "SQL | ALTER (RENAME)"
}
]
|
Maximum trains for which stoppage can be provided | 21 Nov, 2017
We are given n-platform and two main running railway track for both direction. Trains which needs to stop at your station must occupy one platform for their stoppage and the trains which need not to stop at your station will run away through either of main track without stopping. Now, each train has three value first arrival time, second departure time and third required platform number. We are given m such trains you have to tell maximum number of train for which you can provide stoppage at your station.
Examples:
Input : n = 3, m = 6
Train no.| Arrival Time |Dept. Time | Platform No.
1 | 10:00 | 10:30 | 1
2 | 10:10 | 10:30 | 1
3 | 10:00 | 10:20 | 2
4 | 10:30 | 12:30 | 2
5 | 12:00 | 12:30 | 3
6 | 09:00 | 10:05 | 1
Output : Maximum Stopped Trains = 5
Explanation : If train no. 1 will left
to go without stoppage then 2 and 6 can
easily be accommodated on platform 1.
And 3 and 4 on platform 2 and 5 on platform 3.
Input : n = 1, m = 3
Train no.|Arrival Time|Dept. Time | Platform No.
1 | 10:00 | 10:30 | 1
2 | 11:10 | 11:30 | 1
3 | 12:00 | 12:20 | 1
Output : Maximum Stopped Trains = 3
Explanation : All three trains can be easily
stopped at platform 1.
If we start with a single platform only then we have 1 platform and some trains with their arrival time and departure time and we have to maximize the number of trains on that platform. This task is similar as Activity Selection Problem. So, for n platforms we will simply make n-vectors and put the respective trains in those vectors according to platform number. After that by applying greedy approach we easily solve this problem.Note : We will take input in form of 4-digit integer for arrival and departure time as 1030 will represent 10:30 so that we may handle the data type easily.Also, we will choose a 2-D array for input as arr[m][3] where arr[i][0] denotes arrival time, arr[i][1] denotes departure time and arr[i][2] denotes the platform for ith train.
// CPP to design platform for maximum stoppage#include <bits/stdc++.h>using namespace std; // number of platforms and trains#define n 2#define m 5 // function to calculate maximum trains stoppageint maxStop(int arr[][3]){ // declaring vector of pairs for platform vector<pair<int, int> > vect[n + 1]; // Entering values in vector of pairs // as per platform number // make departure time first element // of pair for (int i = 0; i < m; i++) vect[arr[i][2]].push_back( make_pair(arr[i][1], arr[i][0])); // sort trains for each platform as per // dept. time for (int i = 0; i <= n; i++) sort(vect[i].begin(), vect[i].end()); // perform activity selection approach int count = 0; for (int i = 0; i <= n; i++) { if (vect[i].size() == 0) continue; // first train for each platform will // also be selected int x = 0; count++; for (int j = 1; j < vect[i].size(); j++) { if (vect[i][j].second >= vect[i][x].first) { x = j; count++; } } } return count;} // driver functionint main(){ int arr[m][3] = { 1000, 1030, 1, 1010, 1020, 1, 1025, 1040, 1, 1130, 1145, 2, 1130, 1140, 2 }; cout << "Maximum Stopped Trains = " << maxStop(arr); return 0;}
Output:
Maximum Stopped Trains = 3
Greedy
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Nov, 2017"
},
{
"code": null,
"e": 565,
"s": 54,
"text": "We are given n-platform and two main running railway track for both direction. Trains which needs to stop at your station must occupy one platform for their stoppage and the trains which need not to stop at your station will run away through either of main track without stopping. Now, each train has three value first arrival time, second departure time and third required platform number. We are given m such trains you have to tell maximum number of train for which you can provide stoppage at your station."
},
{
"code": null,
"e": 575,
"s": 565,
"text": "Examples:"
},
{
"code": null,
"e": 1427,
"s": 575,
"text": "Input : n = 3, m = 6 \nTrain no.| Arrival Time |Dept. Time | Platform No.\n 1 | 10:00 | 10:30 | 1\n 2 | 10:10 | 10:30 | 1\n 3 | 10:00 | 10:20 | 2\n 4 | 10:30 | 12:30 | 2\n 5 | 12:00 | 12:30 | 3\n 6 | 09:00 | 10:05 | 1\nOutput : Maximum Stopped Trains = 5\nExplanation : If train no. 1 will left \nto go without stoppage then 2 and 6 can \neasily be accommodated on platform 1. \nAnd 3 and 4 on platform 2 and 5 on platform 3.\n\nInput : n = 1, m = 3\nTrain no.|Arrival Time|Dept. Time | Platform No.\n 1 | 10:00 | 10:30 | 1\n 2 | 11:10 | 11:30 | 1\n 3 | 12:00 | 12:20 | 1\n \nOutput : Maximum Stopped Trains = 3\nExplanation : All three trains can be easily\nstopped at platform 1.\n"
},
{
"code": null,
"e": 2193,
"s": 1427,
"text": "If we start with a single platform only then we have 1 platform and some trains with their arrival time and departure time and we have to maximize the number of trains on that platform. This task is similar as Activity Selection Problem. So, for n platforms we will simply make n-vectors and put the respective trains in those vectors according to platform number. After that by applying greedy approach we easily solve this problem.Note : We will take input in form of 4-digit integer for arrival and departure time as 1030 will represent 10:30 so that we may handle the data type easily.Also, we will choose a 2-D array for input as arr[m][3] where arr[i][0] denotes arrival time, arr[i][1] denotes departure time and arr[i][2] denotes the platform for ith train."
},
{
"code": "// CPP to design platform for maximum stoppage#include <bits/stdc++.h>using namespace std; // number of platforms and trains#define n 2#define m 5 // function to calculate maximum trains stoppageint maxStop(int arr[][3]){ // declaring vector of pairs for platform vector<pair<int, int> > vect[n + 1]; // Entering values in vector of pairs // as per platform number // make departure time first element // of pair for (int i = 0; i < m; i++) vect[arr[i][2]].push_back( make_pair(arr[i][1], arr[i][0])); // sort trains for each platform as per // dept. time for (int i = 0; i <= n; i++) sort(vect[i].begin(), vect[i].end()); // perform activity selection approach int count = 0; for (int i = 0; i <= n; i++) { if (vect[i].size() == 0) continue; // first train for each platform will // also be selected int x = 0; count++; for (int j = 1; j < vect[i].size(); j++) { if (vect[i][j].second >= vect[i][x].first) { x = j; count++; } } } return count;} // driver functionint main(){ int arr[m][3] = { 1000, 1030, 1, 1010, 1020, 1, 1025, 1040, 1, 1130, 1145, 2, 1130, 1140, 2 }; cout << \"Maximum Stopped Trains = \" << maxStop(arr); return 0;}",
"e": 3656,
"s": 2193,
"text": null
},
{
"code": null,
"e": 3664,
"s": 3656,
"text": "Output:"
},
{
"code": null,
"e": 3692,
"s": 3664,
"text": "Maximum Stopped Trains = 3\n"
},
{
"code": null,
"e": 3699,
"s": 3692,
"text": "Greedy"
},
{
"code": null,
"e": 3706,
"s": 3699,
"text": "Greedy"
}
]
|
Digit DP | Introduction | 20 Jun, 2022
Prerequisite : How to solve a Dynamic Programming Problem ?There are many types of problems that ask to count the number of integers ‘x‘ between two integers say ‘a‘ and ‘b‘ such that x satisfies a specific property that can be related to its digits.So, if we say G(x) tells the number of such integers between 1 to x (inclusively), then the number of such integers between a and b can be given by G(b) – G(a-1). This is when Digit DP (Dynamic Programming) comes into action. All such integer counting problems that satisfy the above property can be solved by digit DP approach.
Key Concept:
Let given number x has n digits. The main idea of digit DP is to first represent the digits as an array of digits t[]. Let’s say a we have tntn-1tn-2 ... t2t1 as the decimal representation where ti (0 < i <= n) tells the i-th digit from the right. The leftmost digit tn is the most significant digit.
Now, after representing the given number this way we generate the numbers less than the given number and simultaneously calculate using DP, if the number satisfy the given property. We start generating integers having number of digits = 1 and then till number of digits = n. Integers having less number of digits than n can be analyzed by setting the leftmost digits to be zero.
Example Problem : Given two integers a and b. Your task is to print the sum of all the digits appearing in the integers between a and b.For example if a = 5 and b = 11, then answer is 38 (5 + 6 + 7 + 8 + 9 + 1 + 0 + 1 + 1)Constraints : 1 <= a < b <= 10^18Now we see that if we have calculated the answer for state having n-1 digits, i.e., tn-1 tn-2 ... t2 t1 and we need to calculate answer for state having n digitdtn tn-1 tn-2 ... t2 t1. So, clearly, we can use the result of the previous state instead of re-calculating it. Hence, it follows the overlapping property.Let’s think for a state for this DPOur DP state will be dp(idx, tight, sum)1) idx
It tells about the index value from right in the given integer
2) tight
This will tell if the current digits range is restricted or not. If the current digit’s range is not restricted then it will span from 0 to 9 (inclusively) else it will span from 0 to digit[idx] (inclusively).Example: consider our limiting integer to be 3245 and we need to calculate G(3245) index : 4 3 2 1 digits : 3 2 4 5
Unrestricted range: Now suppose the integer generated till now is : 3 1 * * ( * is empty place, where digits are to be inserted to form the integer).
index : 4 3 2 1
digits : 3 2 4 5
generated integer: 3 1 _ _
here, we see that index 2 has unrestricted range. Now index 2 can have digits from range 0 to 9(inclusively). For unrestricted range tight = 0Restricted range: Now suppose the integer generated till now is : 3 2 * * ( ‘*’ is an empty place, where digits are to be inserted to form the integer).
index : 4 3 2 1
digits : 3 2 4 5
generated integer: 3 2 _ _
here, we see that index 2 has a restricted range. Now index 2 can only have digits from range 0 to 4 (inclusively) For restricted range tight = 13) sum
This parameter will store the sum of digits in the generated integer from msd to idx.
Max value for this parameter sum can be 9*18 = 162, considering 18 digits in the integer
State Relation:The basic idea for state relation is very simple. We formulate the dp in top-down fashion. Let’s say we are at the msd having index idx. So initially the sum will be 0.Therefore, we will fill the digit at index by the digits in its range. Let’s say its range is from 0 to k (k<=9, depending on the tight value) and fetch the answer from the next state having index = idx-1 and sum = previous sum + digit chosen.
int ans = 0;
for (int i=0; i<=k; i++) {
ans += state(idx-1, newTight, sum+i)
}
state(idx,tight,sum) = ans;
How to calculate the newTight value? The new tight value from a state depends on its previous state. If tight value form the previous state is 1 and the digit at idx chosen is digit[idx](i.e the digit at idx in limiting integer) , then only our new tight will be 1 as it only then tells that the number formed till now is prefix of the limiting integer.
// digitTaken is the digit chosen
// digit[idx] is the digit in the limiting
// integer at index idx from right
// previouTight is the tight value form previous
// state
newTight = previousTight & (digitTake == digit[idx])
Below is the implementation of the above approach
CPP
Java
Python3
// Given two integers a and b. The task is to print// sum of all the digits appearing in the// integers between a and b#include "bits/stdc++.h"using namespace std; // Memoization for the state resultslong long dp[20][180][2]; // Stores the digits in x in a vector digitlong long getDigits(long long x, vector <int> &digit){ while (x) { digit.push_back(x%10); x /= 10; }} // Return sum of digits from 1 to integer in// digit vectorlong long digitSum(int idx, int sum, int tight, vector <int> &digit){ // base case if (idx == -1) return sum; // checking if already calculated this state if (dp[idx][sum][tight] != -1 and tight != 1) return dp[idx][sum][tight]; long long ret = 0; // calculating range value int k = (tight)? digit[idx] : 9; for (int i = 0; i <= k ; i++) { // calculating newTight value for next state int newTight = (digit[idx] == i)? tight : 0; // fetching answer from next state ret += digitSum(idx-1, sum+i, newTight, digit); } if (!tight) dp[idx][sum][tight] = ret; return ret;} // Returns sum of digits in numbers from a to b.int rangeDigitSum(int a, int b){ // initializing dp with -1 memset(dp, -1, sizeof(dp)); // storing digits of a-1 in digit vector vector<int> digitA; getDigits(a-1, digitA); // Finding sum of digits from 1 to "a-1" which is passed // as digitA. long long ans1 = digitSum(digitA.size()-1, 0, 1, digitA); // Storing digits of b in digit vector vector<int> digitB; getDigits(b, digitB); // Finding sum of digits from 1 to "b" which is passed // as digitB. long long ans2 = digitSum(digitB.size()-1, 0, 1, digitB); return (ans2 - ans1);} // driver function to call above functionint main(){ long long a = 123, b = 1024; cout << "digit sum for given range : " << rangeDigitSum(a, b) << endl; return 0;}
// Java program for above approach import java.util.ArrayList;import java.util.Arrays; // Given two integers a and b. The task is to print// sum of all the digits appearing in the// integers between a and bpublic class GFG { // Memoization for the state results static long dp[][][] = new long[20][180][2]; // Stores the digits in x in a vector digit static void getDigits(long x, ArrayList<Integer> digit) { while (x != 0) { digit.add((int)(x % 10)); x /= 10; } } // Return sum of digits from 1 to integer in // digit vector static long digitSum(int idx, int sum, int tight, ArrayList<Integer> digit) { // base case if (idx == -1) return sum; // checking if already calculated this state if (dp[idx][sum][tight] != -1 && tight != 1) return dp[idx][sum][tight]; long ret = 0; // calculating range value int k = (tight != 0) ? digit.get(idx) : 9; for (int i = 0; i <= k; i++) { // calculating newTight value for next state int newTight = (digit.get(idx) == i) ? tight : 0; // fetching answer from next state ret += digitSum(idx - 1, sum + i, newTight, digit); } if (tight != 0) dp[idx][sum][tight] = ret; return ret; } // Returns sum of digits in numbers from a to b. static int rangeDigitSum(int a, int b) { // initializing dp with -1 for (int i = 0; i < 20; i++) for (int j = 0; j < 180; j++) for (int k = 0; k < 2; k++) dp[i][j][k] = -1; // storing digits of a-1 in digit vector ArrayList<Integer> digitA = new ArrayList<Integer>(); getDigits(a - 1, digitA); // Finding sum of digits from 1 to "a-1" which is // passed as digitA. long ans1 = digitSum(digitA.size() - 1, 0, 1, digitA); // Storing digits of b in digit vector ArrayList<Integer> digitB = new ArrayList<Integer>(); getDigits(b, digitB); // Finding sum of digits from 1 to "b" which is // passed as digitB. long ans2 = digitSum(digitB.size() - 1, 0, 1, digitB); return (int)(ans2 - ans1); } // driver function to call above function public static void main(String[] args) { int a = 123, b = 1024; System.out.println("digit sum for given range : " + rangeDigitSum(a, b)); }} // This code is contributed by Lovely Jain
# Given two integers a and b. The task is to# print sum of all the digits appearing in the# integers between a and b # Memoization for the state resultsdp = [[[-1 for i in range(2)] for j in range(180)]for k in range(20)] # Stores the digits in x in a list digitdef getDigits(x, digit): while x: digit.append(x % 10) x //= 10 # Return sum of digits from 1 to integer in digit listdef digitSum(index, sumof, tight, digit): # Base case if index == -1: return sumof # Checking if already calculated this state if dp[index][sumof][tight] != -1 and tight != 1: return dp[index][sumof][tight] ret = 0 # Calculating range value k = digit[index] if tight else 9 for i in range(0, k+1): # Calculating newTight value for nextstate newTight = tight if digit[index] == i else 0 # Fetching answer from next state ret += digitSum(index-1, sumof+i, newTight, digit) if not tight: dp[index][sumof][tight] = ret return ret # Returns sum of digits in numbers from a to bdef rangeDigitSum(a, b): digitA = [] # Storing digits of a-1 in digitA getDigits(a-1, digitA) # Finding sum of digits from 1 to "a-1" which is passed as digitA ans1 = digitSum(len(digitA)-1, 0, 1, digitA) digitB = [] # Storing digits of b in digitB getDigits(b, digitB) # Finding sum of digits from 1 to "b" which is passed as digitB ans2 = digitSum(len(digitB)-1, 0, 1, digitB) return ans2-ans1 a, b = 123, 1024print("digit sum for given range: ", rangeDigitSum(a, b)) # This code is contributed by rupasriachanta421
Output:
digit sum for given range : 12613
Time Complexity:There are total idx*sum*tight states and we are performing 0 to 9 iterations to visit every state. Therefore, The Time Complexity will be O(10*idx*sum*tight). Here, we observe that tight = 2 and idx can be max 18 for 64 bit unsigned integer and moreover, the sum will be max 9*18 ~ 200. So, overall we have 10*18*200*2 ~ 10^5 iterations which can be easily executed in 0.01 seconds.The above problem can also be solved using simple recursion without any memoization. The recursive solution for the above problem can be found here. We will be soon adding more problems on digit dp in our future posts.This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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.
sauravtygg
SahilSingh
sansa_stark
gulshankumarar231
rupasriachanta421
jainlovely450
digit-DP
Competitive Programming
Dynamic Programming
Dynamic Programming
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": 632,
"s": 52,
"text": "Prerequisite : How to solve a Dynamic Programming Problem ?There are many types of problems that ask to count the number of integers ‘x‘ between two integers say ‘a‘ and ‘b‘ such that x satisfies a specific property that can be related to its digits.So, if we say G(x) tells the number of such integers between 1 to x (inclusively), then the number of such integers between a and b can be given by G(b) – G(a-1). This is when Digit DP (Dynamic Programming) comes into action. All such integer counting problems that satisfy the above property can be solved by digit DP approach. "
},
{
"code": null,
"e": 645,
"s": 632,
"text": "Key Concept:"
},
{
"code": null,
"e": 948,
"s": 645,
"text": "Let given number x has n digits. The main idea of digit DP is to first represent the digits as an array of digits t[]. Let’s say a we have tntn-1tn-2 ... t2t1 as the decimal representation where ti (0 < i <= n) tells the i-th digit from the right. The leftmost digit tn is the most significant digit. "
},
{
"code": null,
"e": 1329,
"s": 948,
"text": "Now, after representing the given number this way we generate the numbers less than the given number and simultaneously calculate using DP, if the number satisfy the given property. We start generating integers having number of digits = 1 and then till number of digits = n. Integers having less number of digits than n can be analyzed by setting the leftmost digits to be zero. "
},
{
"code": null,
"e": 1983,
"s": 1329,
"text": "Example Problem : Given two integers a and b. Your task is to print the sum of all the digits appearing in the integers between a and b.For example if a = 5 and b = 11, then answer is 38 (5 + 6 + 7 + 8 + 9 + 1 + 0 + 1 + 1)Constraints : 1 <= a < b <= 10^18Now we see that if we have calculated the answer for state having n-1 digits, i.e., tn-1 tn-2 ... t2 t1 and we need to calculate answer for state having n digitdtn tn-1 tn-2 ... t2 t1. So, clearly, we can use the result of the previous state instead of re-calculating it. Hence, it follows the overlapping property.Let’s think for a state for this DPOur DP state will be dp(idx, tight, sum)1) idx "
},
{
"code": null,
"e": 2046,
"s": 1983,
"text": "It tells about the index value from right in the given integer"
},
{
"code": null,
"e": 2057,
"s": 2046,
"text": "2) tight "
},
{
"code": null,
"e": 2384,
"s": 2057,
"text": "This will tell if the current digits range is restricted or not. If the current digit’s range is not restricted then it will span from 0 to 9 (inclusively) else it will span from 0 to digit[idx] (inclusively).Example: consider our limiting integer to be 3245 and we need to calculate G(3245) index : 4 3 2 1 digits : 3 2 4 5 "
},
{
"code": null,
"e": 2535,
"s": 2384,
"text": "Unrestricted range: Now suppose the integer generated till now is : 3 1 * * ( * is empty place, where digits are to be inserted to form the integer). "
},
{
"code": null,
"e": 2604,
"s": 2535,
"text": " index : 4 3 2 1 \n digits : 3 2 4 5\n generated integer: 3 1 _ _ "
},
{
"code": null,
"e": 2900,
"s": 2604,
"text": "here, we see that index 2 has unrestricted range. Now index 2 can have digits from range 0 to 9(inclusively). For unrestricted range tight = 0Restricted range: Now suppose the integer generated till now is : 3 2 * * ( ‘*’ is an empty place, where digits are to be inserted to form the integer). "
},
{
"code": null,
"e": 2969,
"s": 2900,
"text": " index : 4 3 2 1 \n digits : 3 2 4 5\n generated integer: 3 2 _ _ "
},
{
"code": null,
"e": 3122,
"s": 2969,
"text": "here, we see that index 2 has a restricted range. Now index 2 can only have digits from range 0 to 4 (inclusively) For restricted range tight = 13) sum "
},
{
"code": null,
"e": 3210,
"s": 3122,
"text": "This parameter will store the sum of digits in the generated integer from msd to idx. "
},
{
"code": null,
"e": 3299,
"s": 3210,
"text": "Max value for this parameter sum can be 9*18 = 162, considering 18 digits in the integer"
},
{
"code": null,
"e": 3727,
"s": 3299,
"text": "State Relation:The basic idea for state relation is very simple. We formulate the dp in top-down fashion. Let’s say we are at the msd having index idx. So initially the sum will be 0.Therefore, we will fill the digit at index by the digits in its range. Let’s say its range is from 0 to k (k<=9, depending on the tight value) and fetch the answer from the next state having index = idx-1 and sum = previous sum + digit chosen. "
},
{
"code": null,
"e": 3838,
"s": 3727,
"text": "int ans = 0;\nfor (int i=0; i<=k; i++) {\n ans += state(idx-1, newTight, sum+i)\n}\n\nstate(idx,tight,sum) = ans;"
},
{
"code": null,
"e": 4193,
"s": 3838,
"text": "How to calculate the newTight value? The new tight value from a state depends on its previous state. If tight value form the previous state is 1 and the digit at idx chosen is digit[idx](i.e the digit at idx in limiting integer) , then only our new tight will be 1 as it only then tells that the number formed till now is prefix of the limiting integer. "
},
{
"code": null,
"e": 4443,
"s": 4193,
"text": "// digitTaken is the digit chosen\n// digit[idx] is the digit in the limiting \n// integer at index idx from right\n// previouTight is the tight value form previous \n// state\n\nnewTight = previousTight & (digitTake == digit[idx])"
},
{
"code": null,
"e": 4493,
"s": 4443,
"text": "Below is the implementation of the above approach"
},
{
"code": null,
"e": 4497,
"s": 4493,
"text": "CPP"
},
{
"code": null,
"e": 4502,
"s": 4497,
"text": "Java"
},
{
"code": null,
"e": 4510,
"s": 4502,
"text": "Python3"
},
{
"code": "// Given two integers a and b. The task is to print// sum of all the digits appearing in the// integers between a and b#include \"bits/stdc++.h\"using namespace std; // Memoization for the state resultslong long dp[20][180][2]; // Stores the digits in x in a vector digitlong long getDigits(long long x, vector <int> &digit){ while (x) { digit.push_back(x%10); x /= 10; }} // Return sum of digits from 1 to integer in// digit vectorlong long digitSum(int idx, int sum, int tight, vector <int> &digit){ // base case if (idx == -1) return sum; // checking if already calculated this state if (dp[idx][sum][tight] != -1 and tight != 1) return dp[idx][sum][tight]; long long ret = 0; // calculating range value int k = (tight)? digit[idx] : 9; for (int i = 0; i <= k ; i++) { // calculating newTight value for next state int newTight = (digit[idx] == i)? tight : 0; // fetching answer from next state ret += digitSum(idx-1, sum+i, newTight, digit); } if (!tight) dp[idx][sum][tight] = ret; return ret;} // Returns sum of digits in numbers from a to b.int rangeDigitSum(int a, int b){ // initializing dp with -1 memset(dp, -1, sizeof(dp)); // storing digits of a-1 in digit vector vector<int> digitA; getDigits(a-1, digitA); // Finding sum of digits from 1 to \"a-1\" which is passed // as digitA. long long ans1 = digitSum(digitA.size()-1, 0, 1, digitA); // Storing digits of b in digit vector vector<int> digitB; getDigits(b, digitB); // Finding sum of digits from 1 to \"b\" which is passed // as digitB. long long ans2 = digitSum(digitB.size()-1, 0, 1, digitB); return (ans2 - ans1);} // driver function to call above functionint main(){ long long a = 123, b = 1024; cout << \"digit sum for given range : \" << rangeDigitSum(a, b) << endl; return 0;}",
"e": 6456,
"s": 4510,
"text": null
},
{
"code": "// Java program for above approach import java.util.ArrayList;import java.util.Arrays; // Given two integers a and b. The task is to print// sum of all the digits appearing in the// integers between a and bpublic class GFG { // Memoization for the state results static long dp[][][] = new long[20][180][2]; // Stores the digits in x in a vector digit static void getDigits(long x, ArrayList<Integer> digit) { while (x != 0) { digit.add((int)(x % 10)); x /= 10; } } // Return sum of digits from 1 to integer in // digit vector static long digitSum(int idx, int sum, int tight, ArrayList<Integer> digit) { // base case if (idx == -1) return sum; // checking if already calculated this state if (dp[idx][sum][tight] != -1 && tight != 1) return dp[idx][sum][tight]; long ret = 0; // calculating range value int k = (tight != 0) ? digit.get(idx) : 9; for (int i = 0; i <= k; i++) { // calculating newTight value for next state int newTight = (digit.get(idx) == i) ? tight : 0; // fetching answer from next state ret += digitSum(idx - 1, sum + i, newTight, digit); } if (tight != 0) dp[idx][sum][tight] = ret; return ret; } // Returns sum of digits in numbers from a to b. static int rangeDigitSum(int a, int b) { // initializing dp with -1 for (int i = 0; i < 20; i++) for (int j = 0; j < 180; j++) for (int k = 0; k < 2; k++) dp[i][j][k] = -1; // storing digits of a-1 in digit vector ArrayList<Integer> digitA = new ArrayList<Integer>(); getDigits(a - 1, digitA); // Finding sum of digits from 1 to \"a-1\" which is // passed as digitA. long ans1 = digitSum(digitA.size() - 1, 0, 1, digitA); // Storing digits of b in digit vector ArrayList<Integer> digitB = new ArrayList<Integer>(); getDigits(b, digitB); // Finding sum of digits from 1 to \"b\" which is // passed as digitB. long ans2 = digitSum(digitB.size() - 1, 0, 1, digitB); return (int)(ans2 - ans1); } // driver function to call above function public static void main(String[] args) { int a = 123, b = 1024; System.out.println(\"digit sum for given range : \" + rangeDigitSum(a, b)); }} // This code is contributed by Lovely Jain",
"e": 9101,
"s": 6456,
"text": null
},
{
"code": "# Given two integers a and b. The task is to# print sum of all the digits appearing in the# integers between a and b # Memoization for the state resultsdp = [[[-1 for i in range(2)] for j in range(180)]for k in range(20)] # Stores the digits in x in a list digitdef getDigits(x, digit): while x: digit.append(x % 10) x //= 10 # Return sum of digits from 1 to integer in digit listdef digitSum(index, sumof, tight, digit): # Base case if index == -1: return sumof # Checking if already calculated this state if dp[index][sumof][tight] != -1 and tight != 1: return dp[index][sumof][tight] ret = 0 # Calculating range value k = digit[index] if tight else 9 for i in range(0, k+1): # Calculating newTight value for nextstate newTight = tight if digit[index] == i else 0 # Fetching answer from next state ret += digitSum(index-1, sumof+i, newTight, digit) if not tight: dp[index][sumof][tight] = ret return ret # Returns sum of digits in numbers from a to bdef rangeDigitSum(a, b): digitA = [] # Storing digits of a-1 in digitA getDigits(a-1, digitA) # Finding sum of digits from 1 to \"a-1\" which is passed as digitA ans1 = digitSum(len(digitA)-1, 0, 1, digitA) digitB = [] # Storing digits of b in digitB getDigits(b, digitB) # Finding sum of digits from 1 to \"b\" which is passed as digitB ans2 = digitSum(len(digitB)-1, 0, 1, digitB) return ans2-ans1 a, b = 123, 1024print(\"digit sum for given range: \", rangeDigitSum(a, b)) # This code is contributed by rupasriachanta421",
"e": 10766,
"s": 9101,
"text": null
},
{
"code": null,
"e": 10774,
"s": 10766,
"text": "Output:"
},
{
"code": null,
"e": 10808,
"s": 10774,
"text": "digit sum for given range : 12613"
},
{
"code": null,
"e": 11844,
"s": 10808,
"text": "Time Complexity:There are total idx*sum*tight states and we are performing 0 to 9 iterations to visit every state. Therefore, The Time Complexity will be O(10*idx*sum*tight). Here, we observe that tight = 2 and idx can be max 18 for 64 bit unsigned integer and moreover, the sum will be max 9*18 ~ 200. So, overall we have 10*18*200*2 ~ 10^5 iterations which can be easily executed in 0.01 seconds.The above problem can also be solved using simple recursion without any memoization. The recursive solution for the above problem can be found here. We will be soon adding more problems on digit dp in our future posts.This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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."
},
{
"code": null,
"e": 11855,
"s": 11844,
"text": "sauravtygg"
},
{
"code": null,
"e": 11866,
"s": 11855,
"text": "SahilSingh"
},
{
"code": null,
"e": 11878,
"s": 11866,
"text": "sansa_stark"
},
{
"code": null,
"e": 11896,
"s": 11878,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 11914,
"s": 11896,
"text": "rupasriachanta421"
},
{
"code": null,
"e": 11928,
"s": 11914,
"text": "jainlovely450"
},
{
"code": null,
"e": 11937,
"s": 11928,
"text": "digit-DP"
},
{
"code": null,
"e": 11961,
"s": 11937,
"text": "Competitive Programming"
},
{
"code": null,
"e": 11981,
"s": 11961,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 12001,
"s": 11981,
"text": "Dynamic Programming"
}
]
|
YouTube Media/Audio Download using Python – pafy | 05 Nov, 2021
This tutorial will help you download youtube video or audio with python using pafy library. Pafy library is used to retrieve YouTube content and metadata.
Features of Pafy(i) Retrieve metadata such as viewcount, duration, rating, author, thumbnail, keywords.(ii) Download video or audio at requested resolution / bitrate / format / filesize(iii) Command line tool (ytdl) for downloading directly from the command line(iv) Download video only (no audio) in m4v or webm format(v) Download audio only (no video) in ogg or m4a format(vi) Works with Python 2.6+ and 3.3+(vii) Optionally depends on youtube-dl (recommended; more stable)
Installation
virtualenv venv
pip install pafy
Library Imported
import pafy
Example1:Retrieve metadata such as viewcount, duration, rating, author, description.
import pafy # url of videourl = "https://www.youtube.com/watch?v=Ns4LCeeOFS4&t=320s" # instant createdvideo = pafy.new(url) # print titleprint(video.title) # print ratingprint(video.rating) # print viewcountprint(video.viewcount) # print author & video lengthprint(video.author, video.length) # print duration, likes, dislikes & descriptionprint(video.duration, video.likes, video.dislikes, video.description)
Output:
Dynamic Programming | Set 3 (Longest Increasing Subsequence) | GeeksforGeeks
4.30275249481
57739
GeeksforGeeks 396
00:06:36 180 38 Explanation for the article: https://www.geeksforgeeks.org/dynamic-programming-set-3-longest-increasing-subsequence/
Example2:Download best resolution video regardless of extension
import pafy url = "https://www.youtube.com/watch?v=eACohWVwTOc"video = pafy.new(url) streams = video.streamsfor i in streams: print(i) # get best resolution regardless of formatbest = video.getbest() print(best.resolution, best.extension) # Download the videobest.download()
Output:
normal:3gp@176x144
normal:3gp@320x180
normal:webm@640x360
normal:mp4@640x360
normal:mp4@1280x720
1280x720 mp4
25, 707, 969 Bytes [100.00%] received. Rate: [ 506 KB/s]. ETA: [0 secs]
Example3:Download video of a particular format specified (let say .3gp)
import pafy url = "https://www.youtube.com/watch?v=eACohWVwTOc"video = pafy.new(url) streams = video.streamsfor i in streams: print(i) # get best resolution of a specific format# set format out of(mp4, webm, flv or 3gp)best = video.getbest(preftype ="3gp") best.download()
Output:
normal:3gp@176x144
normal:3gp@320x180
normal:webm@640x360
normal:mp4@640x360
normal:mp4@1280x720
6, 049, 643 Bytes [100.00%] received. Rate: [ 241 KB/s]. ETA: [0 secs]
Example4:Download a specific format audio.
import pafy url = "https://www.youtube.com/watch?v =eACohWVwTOc"video = pafy.new(url) audiostreams = video.audiostreamsfor i in audiostreams: print(i.bitrate, i.extension, i.get_filesize()) audiostreams[3].download()
Output:
160k webm 1365668
160k webm 1811815
160k m4a 3470205
160k webm 3301003
160k webm 3588746
Example5:Download the bestaudio
import pafy url = "https://www.youtube.com/watch?v=eACohWVwTOc"video = pafy.new(url) bestaudio = video.getbestaudio()bestaudio.download()
Output:
References:https://pypi.python.org/pypi/pafy
python-utility
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 209,
"s": 54,
"text": "This tutorial will help you download youtube video or audio with python using pafy library. Pafy library is used to retrieve YouTube content and metadata."
},
{
"code": null,
"e": 685,
"s": 209,
"text": "Features of Pafy(i) Retrieve metadata such as viewcount, duration, rating, author, thumbnail, keywords.(ii) Download video or audio at requested resolution / bitrate / format / filesize(iii) Command line tool (ytdl) for downloading directly from the command line(iv) Download video only (no audio) in m4v or webm format(v) Download audio only (no video) in ogg or m4a format(vi) Works with Python 2.6+ and 3.3+(vii) Optionally depends on youtube-dl (recommended; more stable)"
},
{
"code": null,
"e": 698,
"s": 685,
"text": "Installation"
},
{
"code": null,
"e": 732,
"s": 698,
"text": "virtualenv venv\npip install pafy\n"
},
{
"code": null,
"e": 749,
"s": 732,
"text": "Library Imported"
},
{
"code": null,
"e": 762,
"s": 749,
"text": " import pafy"
},
{
"code": null,
"e": 847,
"s": 762,
"text": "Example1:Retrieve metadata such as viewcount, duration, rating, author, description."
},
{
"code": "import pafy # url of videourl = \"https://www.youtube.com/watch?v=Ns4LCeeOFS4&t=320s\" # instant createdvideo = pafy.new(url) # print titleprint(video.title) # print ratingprint(video.rating) # print viewcountprint(video.viewcount) # print author & video lengthprint(video.author, video.length) # print duration, likes, dislikes & descriptionprint(video.duration, video.likes, video.dislikes, video.description)",
"e": 1264,
"s": 847,
"text": null
},
{
"code": null,
"e": 1272,
"s": 1264,
"text": "Output:"
},
{
"code": null,
"e": 1521,
"s": 1272,
"text": "Dynamic Programming | Set 3 (Longest Increasing Subsequence) | GeeksforGeeks\n4.30275249481\n57739\nGeeksforGeeks 396\n00:06:36 180 38 Explanation for the article: https://www.geeksforgeeks.org/dynamic-programming-set-3-longest-increasing-subsequence/\n"
},
{
"code": null,
"e": 1585,
"s": 1521,
"text": "Example2:Download best resolution video regardless of extension"
},
{
"code": "import pafy url = \"https://www.youtube.com/watch?v=eACohWVwTOc\"video = pafy.new(url) streams = video.streamsfor i in streams: print(i) # get best resolution regardless of formatbest = video.getbest() print(best.resolution, best.extension) # Download the videobest.download()",
"e": 1872,
"s": 1585,
"text": null
},
{
"code": null,
"e": 1880,
"s": 1872,
"text": "Output:"
},
{
"code": null,
"e": 2068,
"s": 1880,
"text": "normal:3gp@176x144\nnormal:3gp@320x180\nnormal:webm@640x360\nnormal:mp4@640x360\nnormal:mp4@1280x720\n1280x720 mp4\n 25, 707, 969 Bytes [100.00%] received. Rate: [ 506 KB/s]. ETA: [0 secs] \n"
},
{
"code": null,
"e": 2140,
"s": 2068,
"text": "Example3:Download video of a particular format specified (let say .3gp)"
},
{
"code": "import pafy url = \"https://www.youtube.com/watch?v=eACohWVwTOc\"video = pafy.new(url) streams = video.streamsfor i in streams: print(i) # get best resolution of a specific format# set format out of(mp4, webm, flv or 3gp)best = video.getbest(preftype =\"3gp\") best.download()",
"e": 2424,
"s": 2140,
"text": null
},
{
"code": null,
"e": 2432,
"s": 2424,
"text": "Output:"
},
{
"code": null,
"e": 2607,
"s": 2432,
"text": "normal:3gp@176x144\nnormal:3gp@320x180\nnormal:webm@640x360\nnormal:mp4@640x360\nnormal:mp4@1280x720\n 6, 049, 643 Bytes [100.00%] received. Rate: [ 241 KB/s]. ETA: [0 secs] \n"
},
{
"code": null,
"e": 2650,
"s": 2607,
"text": "Example4:Download a specific format audio."
},
{
"code": "import pafy url = \"https://www.youtube.com/watch?v =eACohWVwTOc\"video = pafy.new(url) audiostreams = video.audiostreamsfor i in audiostreams: print(i.bitrate, i.extension, i.get_filesize()) audiostreams[3].download()",
"e": 2874,
"s": 2650,
"text": null
},
{
"code": null,
"e": 2882,
"s": 2874,
"text": "Output:"
},
{
"code": null,
"e": 2972,
"s": 2882,
"text": "160k webm 1365668\n160k webm 1811815\n160k m4a 3470205\n160k webm 3301003\n160k webm 3588746\n"
},
{
"code": null,
"e": 3004,
"s": 2972,
"text": "Example5:Download the bestaudio"
},
{
"code": "import pafy url = \"https://www.youtube.com/watch?v=eACohWVwTOc\"video = pafy.new(url) bestaudio = video.getbestaudio()bestaudio.download()",
"e": 3145,
"s": 3004,
"text": null
},
{
"code": null,
"e": 3153,
"s": 3145,
"text": "Output:"
},
{
"code": null,
"e": 3200,
"s": 3155,
"text": "References:https://pypi.python.org/pypi/pafy"
},
{
"code": null,
"e": 3215,
"s": 3200,
"text": "python-utility"
},
{
"code": null,
"e": 3222,
"s": 3215,
"text": "Python"
},
{
"code": null,
"e": 3239,
"s": 3222,
"text": "Web Technologies"
},
{
"code": null,
"e": 3337,
"s": 3239,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3379,
"s": 3337,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3401,
"s": 3379,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3427,
"s": 3401,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3459,
"s": 3427,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3488,
"s": 3459,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3550,
"s": 3488,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3583,
"s": 3550,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3644,
"s": 3583,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3694,
"s": 3644,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
How to Load XML Data into MySQL using PHP ? | 12 Jul, 2021
In this article, we are going to store data present in XML file into MySQL database using PHP in XAMPP server.
XML: Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. The design goals of XML focus on simplicity, generality, and usability across the Internet.
Example:
HTML
<?xml version="1.0" encoding="UTF-8"?><datas> <data> <id>1</id> <name>sravan</name> </data> <data> <id>2</id> <name>Ojaswi</name> </data> <data> <id>3</id> <name>Rohith</name> </data></datas>
Loading XML file: We will use simplexml_load_file() function to convert the well-formed XML document into the given file to an object.
Syntax:
SimpleXMLElement simplexml_load_file( string $filename,
string $class_name = "SimpleXMLElement",
int $options = 0, string $ns = "",
bool $is_prefix = FALSE )
Steps to Write and Execute code:
Start XAMPP
Identify number of attributes in xml file and create table in XAMPP. There are 4 attributes in XML file (input.xml is the file name). These are title, link. description, keywords. The database name is xmldata and table name is xml
Filename: input.xml
XML
<?xml version="1.0" encoding="UTF-8"?><items> <item> <title>PHP DATABASE CONNECTION</title> <link>https://www.geeksforgeeks.org/php-database-connection/ </link> <description> The collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development. </description> <keywords>PHP, XAMPP</keywords> </item> <item> <title>Screen density and Terminologies</title> <link>https://www.geeksforgeeks.org/screen-density-and-its-terminologies/ </link> <description> Screen Density is a calculation of the proportion of display character positions on the screen or an area of the screen containing something. </description> <keywords>software engineering</keywords> </item> <item> <title>DataProcessing vs DataCleaning</title> <link>https://www.geeksforgeeks.org/difference-between-data-cleaning-and-data-processing/ </link> <description> Data Processing: It is defined as Collection, manipulation, and processing of collected data for the required use. It is a task of converting data from a given form to a much more usable and desired form i.e. making it more meaningful and informative. Using Machine Learning algorithms, mathematical modelling and statistical knowledge, this entire process can be automated. This might seem to be simple but when it comes to really big organizations like Twitter, Facebook, Administrative bodies like Parliament, UNESCO and health sector </description> <keywords>Data Mining</keywords> </item> <item> <title>Predicting Air Quality Index</title> <link>https://www.geeksforgeeks.org/predicting-air-quality-index-using-python/ </link> <description> AQI: The air quality index is an index for reporting air quality on a daily basis. In other words, it is a measure of how air pollution affects one’s health within a short time period. The AQI is calculated based on the average concentration of a particular pollutant measured over a standard time interval. Generally, the time interval is 24 hours for most pollutants, 8 hours for carbon monoxide and ozone. </description> <keywords>Machine Learning, Python</keywords> </item></items>
Filename: index.php
PHP
<?php // Connect to database// Server - localhost// Username - root// Password - empty// Database name = xmldata$conn = mysqli_connect("localhost", "root", "", "xmldata"); $affectedRow = 0; // Load xml file else check connection$xml = simplexml_load_file("input.xml") or die("Error: Cannot create object"); // Assign valuesforeach ($xml->children() as $row) { $title = $row->title; $link = $row->link; $description = $row->description; $keywords = $row->keywords; // SQL query to insert data into xml table $sql = "INSERT INTO xml(title, link, description, keywords) VALUES ('" . $title . "','" . $link . "','" . $description . "','" . $keywords . "')"; $result = mysqli_query($conn, $sql); if (! empty($result)) { $affectedRow ++; } else { $error_message = mysqli_error($conn) . "\n"; }}?> <center><h2>GEEKS GOR GEEKS</h2></center><center><h1>XML Data storing in Database</h1></center><?phpif ($affectedRow > 0) { $message = $affectedRow . " records inserted";} else { $message = "No records inserted";} ?><style> body { max-width:550px; font-family: Arial; } .affected-row { background: #cae4ca; padding: 10px; margin-bottom: 20px; border: #bdd6bd 1px solid; border-radius: 2px; color: #6e716e; } .error-message { background: #eac0c0; padding: 10px; margin-bottom: 20px; border: #dab2b2 1px solid; border-radius: 2px; color: #5d5b5b; }</style> <div class="affected-row"> <?php echo $message; ?></div> <?php if (! empty($error_message)) { ?> <div class="error-message"> <?php echo nl2br($error_message); ?></div><?php } ?>
Execution steps:
1. Save 2 files in one folder in path: xampp/htdocs/gfg
2. Type localhost/gfg/index.php and see the output
output
Now check the data in xml stored in our database or not
saurabh1990aror
PHP-Misc
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
PHP | Ternary Operator
How to create admin login page using PHP?
How to send an email using PHPMailer ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jul, 2021"
},
{
"code": null,
"e": 139,
"s": 28,
"text": "In this article, we are going to store data present in XML file into MySQL database using PHP in XAMPP server."
},
{
"code": null,
"e": 403,
"s": 139,
"text": "XML: Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. The design goals of XML focus on simplicity, generality, and usability across the Internet."
},
{
"code": null,
"e": 412,
"s": 403,
"text": "Example:"
},
{
"code": null,
"e": 417,
"s": 412,
"text": "HTML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><datas> <data> <id>1</id> <name>sravan</name> </data> <data> <id>2</id> <name>Ojaswi</name> </data> <data> <id>3</id> <name>Rohith</name> </data></datas>",
"e": 669,
"s": 417,
"text": null
},
{
"code": null,
"e": 808,
"s": 673,
"text": "Loading XML file: We will use simplexml_load_file() function to convert the well-formed XML document into the given file to an object."
},
{
"code": null,
"e": 818,
"s": 810,
"text": "Syntax:"
},
{
"code": null,
"e": 1004,
"s": 820,
"text": "SimpleXMLElement simplexml_load_file( string $filename, \n string $class_name = \"SimpleXMLElement\",\n int $options = 0, string $ns = \"\", \n bool $is_prefix = FALSE )"
},
{
"code": null,
"e": 1039,
"s": 1006,
"text": "Steps to Write and Execute code:"
},
{
"code": null,
"e": 1053,
"s": 1041,
"text": "Start XAMPP"
},
{
"code": null,
"e": 1284,
"s": 1053,
"text": "Identify number of attributes in xml file and create table in XAMPP. There are 4 attributes in XML file (input.xml is the file name). These are title, link. description, keywords. The database name is xmldata and table name is xml"
},
{
"code": null,
"e": 1306,
"s": 1286,
"text": "Filename: input.xml"
},
{
"code": null,
"e": 1312,
"s": 1308,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><items> <item> <title>PHP DATABASE CONNECTION</title> <link>https://www.geeksforgeeks.org/php-database-connection/ </link> <description> The collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development. </description> <keywords>PHP, XAMPP</keywords> </item> <item> <title>Screen density and Terminologies</title> <link>https://www.geeksforgeeks.org/screen-density-and-its-terminologies/ </link> <description> Screen Density is a calculation of the proportion of display character positions on the screen or an area of the screen containing something. </description> <keywords>software engineering</keywords> </item> <item> <title>DataProcessing vs DataCleaning</title> <link>https://www.geeksforgeeks.org/difference-between-data-cleaning-and-data-processing/ </link> <description> Data Processing: It is defined as Collection, manipulation, and processing of collected data for the required use. It is a task of converting data from a given form to a much more usable and desired form i.e. making it more meaningful and informative. Using Machine Learning algorithms, mathematical modelling and statistical knowledge, this entire process can be automated. This might seem to be simple but when it comes to really big organizations like Twitter, Facebook, Administrative bodies like Parliament, UNESCO and health sector </description> <keywords>Data Mining</keywords> </item> <item> <title>Predicting Air Quality Index</title> <link>https://www.geeksforgeeks.org/predicting-air-quality-index-using-python/ </link> <description> AQI: The air quality index is an index for reporting air quality on a daily basis. In other words, it is a measure of how air pollution affects one’s health within a short time period. The AQI is calculated based on the average concentration of a particular pollutant measured over a standard time interval. Generally, the time interval is 24 hours for most pollutants, 8 hours for carbon monoxide and ozone. </description> <keywords>Machine Learning, Python</keywords> </item></items>",
"e": 4025,
"s": 1312,
"text": null
},
{
"code": null,
"e": 4049,
"s": 4029,
"text": "Filename: index.php"
},
{
"code": null,
"e": 4055,
"s": 4051,
"text": "PHP"
},
{
"code": "<?php // Connect to database// Server - localhost// Username - root// Password - empty// Database name = xmldata$conn = mysqli_connect(\"localhost\", \"root\", \"\", \"xmldata\"); $affectedRow = 0; // Load xml file else check connection$xml = simplexml_load_file(\"input.xml\") or die(\"Error: Cannot create object\"); // Assign valuesforeach ($xml->children() as $row) { $title = $row->title; $link = $row->link; $description = $row->description; $keywords = $row->keywords; // SQL query to insert data into xml table $sql = \"INSERT INTO xml(title, link, description, keywords) VALUES ('\" . $title . \"','\" . $link . \"','\" . $description . \"','\" . $keywords . \"')\"; $result = mysqli_query($conn, $sql); if (! empty($result)) { $affectedRow ++; } else { $error_message = mysqli_error($conn) . \"\\n\"; }}?> <center><h2>GEEKS GOR GEEKS</h2></center><center><h1>XML Data storing in Database</h1></center><?phpif ($affectedRow > 0) { $message = $affectedRow . \" records inserted\";} else { $message = \"No records inserted\";} ?><style> body { max-width:550px; font-family: Arial; } .affected-row { background: #cae4ca; padding: 10px; margin-bottom: 20px; border: #bdd6bd 1px solid; border-radius: 2px; color: #6e716e; } .error-message { background: #eac0c0; padding: 10px; margin-bottom: 20px; border: #dab2b2 1px solid; border-radius: 2px; color: #5d5b5b; }</style> <div class=\"affected-row\"> <?php echo $message; ?></div> <?php if (! empty($error_message)) { ?> <div class=\"error-message\"> <?php echo nl2br($error_message); ?></div><?php } ?>",
"e": 5792,
"s": 4055,
"text": null
},
{
"code": null,
"e": 5813,
"s": 5796,
"text": "Execution steps:"
},
{
"code": null,
"e": 5871,
"s": 5815,
"text": "1. Save 2 files in one folder in path: xampp/htdocs/gfg"
},
{
"code": null,
"e": 5926,
"s": 5875,
"text": "2. Type localhost/gfg/index.php and see the output"
},
{
"code": null,
"e": 5935,
"s": 5928,
"text": "output"
},
{
"code": null,
"e": 5993,
"s": 5937,
"text": "Now check the data in xml stored in our database or not"
},
{
"code": null,
"e": 6013,
"s": 5997,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 6022,
"s": 6013,
"text": "PHP-Misc"
},
{
"code": null,
"e": 6026,
"s": 6022,
"text": "PHP"
},
{
"code": null,
"e": 6039,
"s": 6026,
"text": "PHP Programs"
},
{
"code": null,
"e": 6056,
"s": 6039,
"text": "Web Technologies"
},
{
"code": null,
"e": 6060,
"s": 6056,
"text": "PHP"
},
{
"code": null,
"e": 6158,
"s": 6060,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6240,
"s": 6158,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 6285,
"s": 6240,
"text": "Difference between HTTP GET and POST Methods"
},
{
"code": null,
"e": 6336,
"s": 6285,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 6366,
"s": 6336,
"text": "PHP | file_exists( ) Function"
},
{
"code": null,
"e": 6389,
"s": 6366,
"text": "PHP | Ternary Operator"
},
{
"code": null,
"e": 6441,
"s": 6389,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 6523,
"s": 6441,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 6546,
"s": 6523,
"text": "PHP | Ternary Operator"
},
{
"code": null,
"e": 6588,
"s": 6546,
"text": "How to create admin login page using PHP?"
}
]
|
Concentration of Ore – Definition, Methods of Separation, Examples | 28 Nov, 2021
Metals are found in ore in the form of compounds with other elements. Metal extraction is the process of extracting metal from its ore. The techniques for extracting metals from their ores and refining them are referred to as metallurgy. There is no single procedure that can extract all of the metals. The procedures to be employed differ depending on the metal. The concentration of ore, or enrichment of ore, is one of the most important steps in the extraction of metal from its ore, and it is covered further below.
Ore is a deposit of one or more precious minerals in the Earth’s crust. Metals are essential to industry and trade, such as copper, gold, and iron, which are found in the most valuable ore deposits. Ore is a solid substance containing minerals or a combination of minerals from which metal can be recovered using a variety of procedures such as ore concentration, mental isolation, and metal refining. Ores are minerals that may be used to extract metals in a convenient and profitable manner.
There are no unpleasant impurities in ore, and it includes a high percentage of metal. Minerals are known to be present in ores. Ore is the solid material from which a pure metal can be extracted. Impurities, or undesirable minerals, are present in the ore minerals. Gangue refers to the undesired impurities found in ore, such as sand, rocky debris, and so on. These impurities or gangue must be removed before the metal can be extracted from the ore.
Minerals can be found in ores, as we all know. To extract minerals, we must first dig the mineral’s ore. It is necessary to remove the impurities present in an ore before extracting the metal. Minerals contain impurities, which are undesired elements. After being mined from the earth, the ore contains various undesired impurities such as sand, rough minerals, and so on. Gangue is a term for undesired impurities such as earthy materials, rocks, sandy materials, limestone, and so on.
The ores are concentrated on the basis of the type of impurities and their percentage proportion to remove these unwanted substances. We achieve a concentrated ore with a high percentage of metal by eliminating these impurities. The concentration of ore, also known as ore enrichment, is the process of removing gangue particles from ore in order to enhance the percentage of metal in the ore. The difference in physical or chemical properties of the ore and the impurities determines the procedures used to remove impurities from the ores. To obtain a concentrated ore containing a significantly higher percentage of the metal, the first step in metallurgy is to remove these undesired impurities from the ore. The physical or chemical properties of the gangue and ores determine the method employed to extract them from the ore. Ore concentration can be accomplished through a variety of methods, including hydraulic washing, magnetic separation, froth flotation, and leaching. The next sections go through some of the processes used to concentrate the ore.
The various processes for the concentration of various types of ores are as follows.
Hand-picking
It was the traditional system of directly concentrating ore with the hands. With the use of a hammer, the gangue or adhering solid matrix is removed from the ore in this procedure. The separation and identification of gangue are based on colour or lump form differences.
Hydraulic Washing
On passing the ore via an upward stream of water, the lighter gangue particles are separated from the heavier metal ore. This is a gravity separation method.
This process is used to enrich ores that are heavier than the gangue particles that are present in them. A stream of water is run through crushed and finely powdered ore in this procedure. Water washes away the lighter gangue particles, leaving the larger ore particles behind. This process is used to concentrate tin and lead oxide ores.
Froth Floatation Process
The purpose of this process is to extract gangue from sulphide ores. The ore is pulverised and mixed with water to form a suspension. Collectors and Froth Stabilizers are added to this. Collectors like pine oils, fatty acids, etc. boost the metal part of the ore’s non-wettability, allowing it to form a froth. Cresols, aniline, and other froth stabilisers keep the foam going. The oil lubricates the metal, while the water lubricates the gangue. The froth is created by constantly stirring up the suspension with paddles and air. To recover the metal, the frothy metal is skimmed off the top and dried.
This process is used to concentrate copper, lead, and zinc sulphide ores. The powdered ore is placed in a tank full of water in this procedure. After that, some pine oil is applied. The sulphide ore particles are wetted with pine oil in the tank, while the gangue particles are wetted with water. After that, the air is circulated through the mixture. This causes the water in the tank to agitate, which allows the sulphide ore particles to cling to the oil and rise to the surface as froth. Since gangue particles are heavier, they settle to the bottom of the water tank. The froth is separated and used to extract concentrated sulphide ore.
Magnetic Separation
To separate the ore and gangue, magnetic characteristics of either the ore or the gangue are used. The ore is first finely processed before being conveyed on a conveyor belt that passes over a magnetic roller. The magnetic ore stays on the belt, while the gangue slides off. By eliminating non-magnetic impurities, this process is utilised to concentrate magnetic ores of iron such as magnetite and chromite and manganese (pyrolusite). A magnetic separator is used in this procedure.
A magnetic separator is made out of two rollers and a leather belt. One of the two rollers has a magnet embedded in it. The finely powdered magnetic ore is dropped over the moving belt at one end in this way. The ore particles are attracted by the magnet and create a separate heap from the non-magnetic impurities when the powdered ore falls down from the moving belt at the other end with a magnetic roller.
Magnetic Separation
Question 1: In metallurgy, what process is utilised to concentrate sulphide ore?
Answer:
Sulphide ores are concentrated using the froth flotation process. The method is based on the foaming agent’s and water’s preferential wetting qualities.
Question 2: Which is the concentration of ore process that is based on gravity separation?
Answer:
Gravity separation, also known as hydraulic washing, is a separation technique that uses the specific gravity variations between metallic ore and gangue particles to separate the two.
Question 3: Give an example of a method for concentrating zinc sulphide ores.
Answer:
Zinc sulphide ores are concentrated using the froth floatation method.
Question 4: What is the significance of ore concentration?
Answer:
The concentration of ore is required because it is much easier to extract a metal once the impurities have been removed.
Question 5: Give an example of a method for concentrating lead oxide ores.
Answer:
Hydraulic washing is a concentration of ore method for lead oxide ores.
Picked
Class 10
School Chemistry
School Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 549,
"s": 28,
"text": "Metals are found in ore in the form of compounds with other elements. Metal extraction is the process of extracting metal from its ore. The techniques for extracting metals from their ores and refining them are referred to as metallurgy. There is no single procedure that can extract all of the metals. The procedures to be employed differ depending on the metal. The concentration of ore, or enrichment of ore, is one of the most important steps in the extraction of metal from its ore, and it is covered further below."
},
{
"code": null,
"e": 1044,
"s": 549,
"text": "Ore is a deposit of one or more precious minerals in the Earth’s crust. Metals are essential to industry and trade, such as copper, gold, and iron, which are found in the most valuable ore deposits. Ore is a solid substance containing minerals or a combination of minerals from which metal can be recovered using a variety of procedures such as ore concentration, mental isolation, and metal refining. Ores are minerals that may be used to extract metals in a convenient and profitable manner. "
},
{
"code": null,
"e": 1497,
"s": 1044,
"text": "There are no unpleasant impurities in ore, and it includes a high percentage of metal. Minerals are known to be present in ores. Ore is the solid material from which a pure metal can be extracted. Impurities, or undesirable minerals, are present in the ore minerals. Gangue refers to the undesired impurities found in ore, such as sand, rocky debris, and so on. These impurities or gangue must be removed before the metal can be extracted from the ore."
},
{
"code": null,
"e": 1984,
"s": 1497,
"text": "Minerals can be found in ores, as we all know. To extract minerals, we must first dig the mineral’s ore. It is necessary to remove the impurities present in an ore before extracting the metal. Minerals contain impurities, which are undesired elements. After being mined from the earth, the ore contains various undesired impurities such as sand, rough minerals, and so on. Gangue is a term for undesired impurities such as earthy materials, rocks, sandy materials, limestone, and so on."
},
{
"code": null,
"e": 3044,
"s": 1984,
"text": "The ores are concentrated on the basis of the type of impurities and their percentage proportion to remove these unwanted substances. We achieve a concentrated ore with a high percentage of metal by eliminating these impurities. The concentration of ore, also known as ore enrichment, is the process of removing gangue particles from ore in order to enhance the percentage of metal in the ore. The difference in physical or chemical properties of the ore and the impurities determines the procedures used to remove impurities from the ores. To obtain a concentrated ore containing a significantly higher percentage of the metal, the first step in metallurgy is to remove these undesired impurities from the ore. The physical or chemical properties of the gangue and ores determine the method employed to extract them from the ore. Ore concentration can be accomplished through a variety of methods, including hydraulic washing, magnetic separation, froth flotation, and leaching. The next sections go through some of the processes used to concentrate the ore."
},
{
"code": null,
"e": 3129,
"s": 3044,
"text": "The various processes for the concentration of various types of ores are as follows."
},
{
"code": null,
"e": 3142,
"s": 3129,
"text": "Hand-picking"
},
{
"code": null,
"e": 3413,
"s": 3142,
"text": "It was the traditional system of directly concentrating ore with the hands. With the use of a hammer, the gangue or adhering solid matrix is removed from the ore in this procedure. The separation and identification of gangue are based on colour or lump form differences."
},
{
"code": null,
"e": 3431,
"s": 3413,
"text": "Hydraulic Washing"
},
{
"code": null,
"e": 3589,
"s": 3431,
"text": "On passing the ore via an upward stream of water, the lighter gangue particles are separated from the heavier metal ore. This is a gravity separation method."
},
{
"code": null,
"e": 3928,
"s": 3589,
"text": "This process is used to enrich ores that are heavier than the gangue particles that are present in them. A stream of water is run through crushed and finely powdered ore in this procedure. Water washes away the lighter gangue particles, leaving the larger ore particles behind. This process is used to concentrate tin and lead oxide ores."
},
{
"code": null,
"e": 3953,
"s": 3928,
"text": "Froth Floatation Process"
},
{
"code": null,
"e": 4557,
"s": 3953,
"text": "The purpose of this process is to extract gangue from sulphide ores. The ore is pulverised and mixed with water to form a suspension. Collectors and Froth Stabilizers are added to this. Collectors like pine oils, fatty acids, etc. boost the metal part of the ore’s non-wettability, allowing it to form a froth. Cresols, aniline, and other froth stabilisers keep the foam going. The oil lubricates the metal, while the water lubricates the gangue. The froth is created by constantly stirring up the suspension with paddles and air. To recover the metal, the frothy metal is skimmed off the top and dried."
},
{
"code": null,
"e": 5200,
"s": 4557,
"text": "This process is used to concentrate copper, lead, and zinc sulphide ores. The powdered ore is placed in a tank full of water in this procedure. After that, some pine oil is applied. The sulphide ore particles are wetted with pine oil in the tank, while the gangue particles are wetted with water. After that, the air is circulated through the mixture. This causes the water in the tank to agitate, which allows the sulphide ore particles to cling to the oil and rise to the surface as froth. Since gangue particles are heavier, they settle to the bottom of the water tank. The froth is separated and used to extract concentrated sulphide ore."
},
{
"code": null,
"e": 5220,
"s": 5200,
"text": "Magnetic Separation"
},
{
"code": null,
"e": 5704,
"s": 5220,
"text": "To separate the ore and gangue, magnetic characteristics of either the ore or the gangue are used. The ore is first finely processed before being conveyed on a conveyor belt that passes over a magnetic roller. The magnetic ore stays on the belt, while the gangue slides off. By eliminating non-magnetic impurities, this process is utilised to concentrate magnetic ores of iron such as magnetite and chromite and manganese (pyrolusite). A magnetic separator is used in this procedure."
},
{
"code": null,
"e": 6114,
"s": 5704,
"text": "A magnetic separator is made out of two rollers and a leather belt. One of the two rollers has a magnet embedded in it. The finely powdered magnetic ore is dropped over the moving belt at one end in this way. The ore particles are attracted by the magnet and create a separate heap from the non-magnetic impurities when the powdered ore falls down from the moving belt at the other end with a magnetic roller."
},
{
"code": null,
"e": 6134,
"s": 6114,
"text": "Magnetic Separation"
},
{
"code": null,
"e": 6215,
"s": 6134,
"text": "Question 1: In metallurgy, what process is utilised to concentrate sulphide ore?"
},
{
"code": null,
"e": 6223,
"s": 6215,
"text": "Answer:"
},
{
"code": null,
"e": 6376,
"s": 6223,
"text": "Sulphide ores are concentrated using the froth flotation process. The method is based on the foaming agent’s and water’s preferential wetting qualities."
},
{
"code": null,
"e": 6467,
"s": 6376,
"text": "Question 2: Which is the concentration of ore process that is based on gravity separation?"
},
{
"code": null,
"e": 6475,
"s": 6467,
"text": "Answer:"
},
{
"code": null,
"e": 6659,
"s": 6475,
"text": "Gravity separation, also known as hydraulic washing, is a separation technique that uses the specific gravity variations between metallic ore and gangue particles to separate the two."
},
{
"code": null,
"e": 6737,
"s": 6659,
"text": "Question 3: Give an example of a method for concentrating zinc sulphide ores."
},
{
"code": null,
"e": 6745,
"s": 6737,
"text": "Answer:"
},
{
"code": null,
"e": 6816,
"s": 6745,
"text": "Zinc sulphide ores are concentrated using the froth floatation method."
},
{
"code": null,
"e": 6875,
"s": 6816,
"text": "Question 4: What is the significance of ore concentration?"
},
{
"code": null,
"e": 6883,
"s": 6875,
"text": "Answer:"
},
{
"code": null,
"e": 7004,
"s": 6883,
"text": "The concentration of ore is required because it is much easier to extract a metal once the impurities have been removed."
},
{
"code": null,
"e": 7079,
"s": 7004,
"text": "Question 5: Give an example of a method for concentrating lead oxide ores."
},
{
"code": null,
"e": 7087,
"s": 7079,
"text": "Answer:"
},
{
"code": null,
"e": 7159,
"s": 7087,
"text": "Hydraulic washing is a concentration of ore method for lead oxide ores."
},
{
"code": null,
"e": 7166,
"s": 7159,
"text": "Picked"
},
{
"code": null,
"e": 7175,
"s": 7166,
"text": "Class 10"
},
{
"code": null,
"e": 7192,
"s": 7175,
"text": "School Chemistry"
},
{
"code": null,
"e": 7208,
"s": 7192,
"text": "School Learning"
}
]
|
What is serialization in C#.NET? | Serialization converts objects into a byte stream and brings it to a form that it can be written on stream. This is done to save it to memory, file or database.
Serialization can be performed as −
All the members, even members that are read-only, are serialized.
It serializes the public fields and properties of an object into XML stream conforming to a specific XML Schema definition language document.
Let us see an example. Firstly set the stream −
FileStream fstream = new FileStream("d:\\new.txt", FileMode.OpenOrCreate);
BinaryFormatter formatter=new BinaryFormatter();
Now create an object of the class and call the constructor which has three parameters −
Employee emp = new Employee(030, "Tom", “Operations”);
Perform serialization −
formatter.Serialize(fStream, emp); | [
{
"code": null,
"e": 1348,
"s": 1187,
"text": "Serialization converts objects into a byte stream and brings it to a form that it can be written on stream. This is done to save it to memory, file or database."
},
{
"code": null,
"e": 1384,
"s": 1348,
"text": "Serialization can be performed as −"
},
{
"code": null,
"e": 1450,
"s": 1384,
"text": "All the members, even members that are read-only, are serialized."
},
{
"code": null,
"e": 1592,
"s": 1450,
"text": "It serializes the public fields and properties of an object into XML stream conforming to a specific XML Schema definition language document."
},
{
"code": null,
"e": 1640,
"s": 1592,
"text": "Let us see an example. Firstly set the stream −"
},
{
"code": null,
"e": 1764,
"s": 1640,
"text": "FileStream fstream = new FileStream(\"d:\\\\new.txt\", FileMode.OpenOrCreate);\nBinaryFormatter formatter=new BinaryFormatter();"
},
{
"code": null,
"e": 1852,
"s": 1764,
"text": "Now create an object of the class and call the constructor which has three parameters −"
},
{
"code": null,
"e": 1908,
"s": 1852,
"text": "Employee emp = new Employee(030, \"Tom\", “Operations”);\n"
},
{
"code": null,
"e": 1932,
"s": 1908,
"text": "Perform serialization −"
},
{
"code": null,
"e": 1967,
"s": 1932,
"text": "formatter.Serialize(fStream, emp);"
}
]
|
Python DSA-exercises Archives - GeeksforGeeks | Check for balanced parentheses in Python
k-nearest neighbor algorithm in Python
Python Program for Tower of Hanoi
Generate a graph using Dictionary in Python
Python Program to Reverse a linked list
Python Library for Linked List
Python Program for N Queen Problem | Backtracking-3
Check whether the given string is Palindrome using Stack
Python program to reverse the content of a file and store it in another file
Priority Queue using Queue and Heapdict module in Python | [
{
"code": null,
"e": 24171,
"s": 24130,
"text": "Check for balanced parentheses in Python"
},
{
"code": null,
"e": 24210,
"s": 24171,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 24244,
"s": 24210,
"text": "Python Program for Tower of Hanoi"
},
{
"code": null,
"e": 24288,
"s": 24244,
"text": "Generate a graph using Dictionary in Python"
},
{
"code": null,
"e": 24328,
"s": 24288,
"text": "Python Program to Reverse a linked list"
},
{
"code": null,
"e": 24359,
"s": 24328,
"text": "Python Library for Linked List"
},
{
"code": null,
"e": 24411,
"s": 24359,
"text": "Python Program for N Queen Problem | Backtracking-3"
},
{
"code": null,
"e": 24468,
"s": 24411,
"text": "Check whether the given string is Palindrome using Stack"
},
{
"code": null,
"e": 24545,
"s": 24468,
"text": "Python program to reverse the content of a file and store it in another file"
}
]
|
JavaScript localStorage | 02 Nov, 2021
JavaScript is one of the world’s most popular lightweight, interpreted compiled programming languages. It is synchronous and single-threaded. In JavaScript, the programs are called scripts. These scripts are executed as plain text. We can write them directly on our HTML page or use an external Javascript file. JavaScript can execute in the browser, and also on the server, or actually on any device that has a special program called the JavaScriptengine. JavaScript is used for both client-side and server-side developments.
HTML DOM Window localStorage is provided by Browser and it allows us to store data as key-value pairs in our web browser using an object. The localStorage is the read-only property of the window interface.
Data is stored as key-value pair and the keys are unique. The keys and the values are always in the UTF-16 DOM String format that is stored within localStorage.
The main features of localStorage are:
The storage is the origin(domain) bounded.The data will not get deleted even if the browser is closed or even OS reboot and will be available until we manually clear the Local Storage of our Browser.
The storage is the origin(domain) bounded.
The data will not get deleted even if the browser is closed or even OS reboot and will be available until we manually clear the Local Storage of our Browser.
Syntax:
ourStorage = window.localStorage;
The above will return a storage object which can be used to access the current origin’s local storage space.
Properties and methods provided by the localStorage object:
setItem( key , value ): stores key/value pair
getItem( key ): returns the value in front of key
key( index ): get the key on a given index
length: returns the number of stored items(data)
removeItem( key ): removes given key with its value
clear(): deletes everything from the storage
Example: The following snippet accesses the current domain’s localStorage object.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>JavaScript localStorage</title> <style> div { width: 300px; height: 200px; padding: 20px; border: 2px solid black; background-color: green; color: white; margin: auto; text-align: center; font-size: 1.5rem; } .box { box-sizing: border-box; } </style></head> <body> <div class="box">GeeksforGeeks</div> <script> // Saving data as key/value pair localStorage.setItem("name", "GeeksforGeeks"); localStorage.setItem("color", "green"); // Updating data localStorage.setItem("name", "GeeksforGeeks(GfG)"); localStorage.setItem("color", "Blue"); // Get the data by key let name = localStorage.getItem("name"); console.log("This is - ", name); let color = localStorage.getItem("color"); console.log("Value of color is - ", color); // Get key on a given position let key1 = localStorage.key(1); console.log(key1); // Get number of stored items let items = localStorage.length; console.log("Total number of items is ", items); // Remove key with its value localStorage.removeItem("color"); // Delete everything localStorage.clear(); </script></body> </html>
Output:
Note: To view the data in the browser’s Local Storage, do the following.
Open your code in the browser.Right-Click And Click on Inspect.Then go to the Applications tab on the toolbar.
Open your code in the browser.
Right-Click And Click on Inspect.
Then go to the Applications tab on the toolbar.
Saving data as key/value pair
Updating data
Get data, index of a key, and number of stored items
Remove a key with its value
Delete everything in storage
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Nov, 2021"
},
{
"code": null,
"e": 557,
"s": 28,
"text": "JavaScript is one of the world’s most popular lightweight, interpreted compiled programming languages. It is synchronous and single-threaded. In JavaScript, the programs are called scripts. These scripts are executed as plain text. We can write them directly on our HTML page or use an external Javascript file. JavaScript can execute in the browser, and also on the server, or actually on any device that has a special program called the JavaScriptengine. JavaScript is used for both client-side and server-side developments."
},
{
"code": null,
"e": 763,
"s": 557,
"text": "HTML DOM Window localStorage is provided by Browser and it allows us to store data as key-value pairs in our web browser using an object. The localStorage is the read-only property of the window interface."
},
{
"code": null,
"e": 924,
"s": 763,
"text": "Data is stored as key-value pair and the keys are unique. The keys and the values are always in the UTF-16 DOM String format that is stored within localStorage."
},
{
"code": null,
"e": 963,
"s": 924,
"text": "The main features of localStorage are:"
},
{
"code": null,
"e": 1163,
"s": 963,
"text": "The storage is the origin(domain) bounded.The data will not get deleted even if the browser is closed or even OS reboot and will be available until we manually clear the Local Storage of our Browser."
},
{
"code": null,
"e": 1206,
"s": 1163,
"text": "The storage is the origin(domain) bounded."
},
{
"code": null,
"e": 1364,
"s": 1206,
"text": "The data will not get deleted even if the browser is closed or even OS reboot and will be available until we manually clear the Local Storage of our Browser."
},
{
"code": null,
"e": 1375,
"s": 1366,
"text": "Syntax: "
},
{
"code": null,
"e": 1409,
"s": 1375,
"text": "ourStorage = window.localStorage;"
},
{
"code": null,
"e": 1518,
"s": 1409,
"text": "The above will return a storage object which can be used to access the current origin’s local storage space."
},
{
"code": null,
"e": 1578,
"s": 1518,
"text": "Properties and methods provided by the localStorage object:"
},
{
"code": null,
"e": 1624,
"s": 1578,
"text": "setItem( key , value ): stores key/value pair"
},
{
"code": null,
"e": 1674,
"s": 1624,
"text": "getItem( key ): returns the value in front of key"
},
{
"code": null,
"e": 1717,
"s": 1674,
"text": "key( index ): get the key on a given index"
},
{
"code": null,
"e": 1766,
"s": 1717,
"text": "length: returns the number of stored items(data)"
},
{
"code": null,
"e": 1818,
"s": 1766,
"text": "removeItem( key ): removes given key with its value"
},
{
"code": null,
"e": 1863,
"s": 1818,
"text": "clear(): deletes everything from the storage"
},
{
"code": null,
"e": 1946,
"s": 1863,
"text": "Example: The following snippet accesses the current domain’s localStorage object."
},
{
"code": null,
"e": 1951,
"s": 1946,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>JavaScript localStorage</title> <style> div { width: 300px; height: 200px; padding: 20px; border: 2px solid black; background-color: green; color: white; margin: auto; text-align: center; font-size: 1.5rem; } .box { box-sizing: border-box; } </style></head> <body> <div class=\"box\">GeeksforGeeks</div> <script> // Saving data as key/value pair localStorage.setItem(\"name\", \"GeeksforGeeks\"); localStorage.setItem(\"color\", \"green\"); // Updating data localStorage.setItem(\"name\", \"GeeksforGeeks(GfG)\"); localStorage.setItem(\"color\", \"Blue\"); // Get the data by key let name = localStorage.getItem(\"name\"); console.log(\"This is - \", name); let color = localStorage.getItem(\"color\"); console.log(\"Value of color is - \", color); // Get key on a given position let key1 = localStorage.key(1); console.log(key1); // Get number of stored items let items = localStorage.length; console.log(\"Total number of items is \", items); // Remove key with its value localStorage.removeItem(\"color\"); // Delete everything localStorage.clear(); </script></body> </html>",
"e": 3554,
"s": 1951,
"text": null
},
{
"code": null,
"e": 3563,
"s": 3554,
"text": "Output: "
},
{
"code": null,
"e": 3636,
"s": 3563,
"text": "Note: To view the data in the browser’s Local Storage, do the following."
},
{
"code": null,
"e": 3747,
"s": 3636,
"text": "Open your code in the browser.Right-Click And Click on Inspect.Then go to the Applications tab on the toolbar."
},
{
"code": null,
"e": 3778,
"s": 3747,
"text": "Open your code in the browser."
},
{
"code": null,
"e": 3812,
"s": 3778,
"text": "Right-Click And Click on Inspect."
},
{
"code": null,
"e": 3860,
"s": 3812,
"text": "Then go to the Applications tab on the toolbar."
},
{
"code": null,
"e": 3890,
"s": 3860,
"text": "Saving data as key/value pair"
},
{
"code": null,
"e": 3905,
"s": 3890,
"text": "Updating data "
},
{
"code": null,
"e": 3958,
"s": 3905,
"text": "Get data, index of a key, and number of stored items"
},
{
"code": null,
"e": 3986,
"s": 3958,
"text": "Remove a key with its value"
},
{
"code": null,
"e": 4015,
"s": 3986,
"text": "Delete everything in storage"
},
{
"code": null,
"e": 4036,
"s": 4015,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 4043,
"s": 4036,
"text": "Picked"
},
{
"code": null,
"e": 4054,
"s": 4043,
"text": "JavaScript"
},
{
"code": null,
"e": 4071,
"s": 4054,
"text": "Web Technologies"
},
{
"code": null,
"e": 4169,
"s": 4071,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4230,
"s": 4169,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4270,
"s": 4230,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4312,
"s": 4270,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4353,
"s": 4312,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4375,
"s": 4353,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 4408,
"s": 4375,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4470,
"s": 4408,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4531,
"s": 4470,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4581,
"s": 4531,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
PayPal Interview Experience | SDE 1 (On-Campus) - GeeksforGeeks | 18 Aug, 2020
Online Assessment: 2 Questions – 120 Minutes
Question 1 – Coloring nx3 board with 3 colors
An automated painting system needs a program that can paint an n x 3 grid in red, green and blue such that no row or column contains cells that are all the same color. Determine the number of valid patterns that can be painted given n rows. Since the number of patterns can be large, return the value modulo (10^9 + 7)
Sample Input: n = 4
Sample Output: 296490
Link (Same question): https://math.stackexchange.com/questions/3215805/coloring-a-3-times-n-board-using-3-colors
Question 2 – Social Media Connections
Social media connections can serve as a means of recognizing relationships among a group of people. These relationships can be represented as an undirected graph where edges join related people. A group of n social media friends is uniquely numbered from 1 to friend_nodes. The group of friends is expressed as a graph with friend_edges undirected edges, where each pair of best_friends is directly connected by an edge. A trio is defined as a group of three best friends. The friendship score for a person in a trio is defined as the number of best friends that person has outside the trio. The friendship sum for a trio is the sum of the trio’s friendship scores.
Given friendship connection data, create an undirected graph, and determine the minimum friendship sum for all trios of best friends in the group. If no such trio exists, return -1
Example Input:
friend_nodes = 6
friend_edges = 6
friends_from = [1, 2, 2, 3, 4, 5]
friends_to = [2, 4, 5, 5, 5, 6]
Example Output: 3
Explanation:
Trio formed is among {2, 4, 5}
Friends of 2 other than 4,5 are {1} => total count = 1
Friends of 4 other than 2,5 are {} => total count = 0
Friends of 5 other than 2,4 are {3, 6} => total count = 2
Sum of total count = 3
Technical Round 1
1. Split array into subarray with given conditions.
All the characters in each of the splitted subarray must not be in another subarray
Sample Input – “aabacadfgrdtyu”
Sample Output – {“aabaca”, “dfgrd”, “tyu”}
2. Are the given 2 intervals intersecting? (fully optimized)
Sample Input – [2, 5], [4, 7]
Sample Output – True
Sample Input – [2, 3], [4, 7]
Sample Output – False
Technical Round 2:
1. Find the word that comes more than 1 time in a string (Case Insensitive)
(Output the first occurrence of the word)
Sample Input - "Paypal is a good company but PayPal hires more than once"
Sample Output - ["Paypal"]
2. Any sorting algo (bubble sort) with time complexity, then optimize or use some faster algo with time complexity
Started with bubble sort – O(n^2) time
Finalised with merge sort – O(nlogn) time
Some other basic Computer Science questions on OS, DBMS, SQL etc
Some questions based on my resume and my projects.
Some more HR type questions
Final Round:
K frogs are there with a number assigned. There is 1 long queue with numbers from 1 to n. Frog with number 2 can visit 2, 4,6,8... And so with other frogs. What are the numbers in the queue that won’t be visited after all the frogs have done their visit?
A grid is present with many balloons. You have 1 arrow. What is the max no of balloons that u can shoot with that arrow? The angle of the shoot can be anything from 0 to 360 degrees.
Similar Question: https://www.geeksforgeeks.org/count-maximum-points-on-same-line/
My all rounds were good and solved most of the questions in one attempt. 3rd round was worst and was not able to solve any questions : (
My suggestions:
Don’t fake anything either in your resume or with your projects.
Be honest in your resume and don’t mention things you don’t know
Projects are an important part of the resume. Don’t mention projects done by your friends/ taken from GitHub
Have a good understanding of OS, DBMS, Network, etc (core CS subjects)
Be positive and have confidence in yourself
All the best for your interviews.
Marketing
On-Campus
PayPal
Interview Experiences
PayPal
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Amazon Interview Experience for SDE-1 (On-Campus)
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Zoho Interview | Set 1 (On-Campus)
Amazon Interview Experience for SDE-1
Amazon Interview Experience for SDE-1(Off-Campus)
Persistent Systems Interview Experience (Martian Program) | [
{
"code": null,
"e": 25174,
"s": 25146,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 25219,
"s": 25174,
"text": "Online Assessment: 2 Questions – 120 Minutes"
},
{
"code": null,
"e": 25265,
"s": 25219,
"text": "Question 1 – Coloring nx3 board with 3 colors"
},
{
"code": null,
"e": 25584,
"s": 25265,
"text": "An automated painting system needs a program that can paint an n x 3 grid in red, green and blue such that no row or column contains cells that are all the same color. Determine the number of valid patterns that can be painted given n rows. Since the number of patterns can be large, return the value modulo (10^9 + 7)"
},
{
"code": null,
"e": 25626,
"s": 25584,
"text": "Sample Input: n = 4\nSample Output: 296490"
},
{
"code": null,
"e": 25739,
"s": 25626,
"text": "Link (Same question): https://math.stackexchange.com/questions/3215805/coloring-a-3-times-n-board-using-3-colors"
},
{
"code": null,
"e": 25777,
"s": 25739,
"text": "Question 2 – Social Media Connections"
},
{
"code": null,
"e": 26443,
"s": 25777,
"text": "Social media connections can serve as a means of recognizing relationships among a group of people. These relationships can be represented as an undirected graph where edges join related people. A group of n social media friends is uniquely numbered from 1 to friend_nodes. The group of friends is expressed as a graph with friend_edges undirected edges, where each pair of best_friends is directly connected by an edge. A trio is defined as a group of three best friends. The friendship score for a person in a trio is defined as the number of best friends that person has outside the trio. The friendship sum for a trio is the sum of the trio’s friendship scores."
},
{
"code": null,
"e": 26624,
"s": 26443,
"text": "Given friendship connection data, create an undirected graph, and determine the minimum friendship sum for all trios of best friends in the group. If no such trio exists, return -1"
},
{
"code": null,
"e": 26757,
"s": 26624,
"text": "Example Input:\nfriend_nodes = 6\nfriend_edges = 6\nfriends_from = [1, 2, 2, 3, 4, 5]\nfriends_to = [2, 4, 5, 5, 5, 6]\nExample Output: 3"
},
{
"code": null,
"e": 26770,
"s": 26757,
"text": "Explanation:"
},
{
"code": null,
"e": 26991,
"s": 26770,
"text": "Trio formed is among {2, 4, 5}\nFriends of 2 other than 4,5 are {1} => total count = 1\nFriends of 4 other than 2,5 are {} => total count = 0\nFriends of 5 other than 2,4 are {3, 6} => total count = 2\nSum of total count = 3"
},
{
"code": null,
"e": 27009,
"s": 26991,
"text": "Technical Round 1"
},
{
"code": null,
"e": 27061,
"s": 27009,
"text": "1. Split array into subarray with given conditions."
},
{
"code": null,
"e": 27145,
"s": 27061,
"text": "All the characters in each of the splitted subarray must not be in another subarray"
},
{
"code": null,
"e": 27177,
"s": 27145,
"text": "Sample Input – “aabacadfgrdtyu”"
},
{
"code": null,
"e": 27220,
"s": 27177,
"text": "Sample Output – {“aabaca”, “dfgrd”, “tyu”}"
},
{
"code": null,
"e": 27281,
"s": 27220,
"text": "2. Are the given 2 intervals intersecting? (fully optimized)"
},
{
"code": null,
"e": 27311,
"s": 27281,
"text": "Sample Input – [2, 5], [4, 7]"
},
{
"code": null,
"e": 27332,
"s": 27311,
"text": "Sample Output – True"
},
{
"code": null,
"e": 27362,
"s": 27332,
"text": "Sample Input – [2, 3], [4, 7]"
},
{
"code": null,
"e": 27384,
"s": 27362,
"text": "Sample Output – False"
},
{
"code": null,
"e": 27403,
"s": 27384,
"text": "Technical Round 2:"
},
{
"code": null,
"e": 27479,
"s": 27403,
"text": "1. Find the word that comes more than 1 time in a string (Case Insensitive)"
},
{
"code": null,
"e": 27521,
"s": 27479,
"text": "(Output the first occurrence of the word)"
},
{
"code": null,
"e": 27622,
"s": 27521,
"text": "Sample Input - \"Paypal is a good company but PayPal hires more than once\"\nSample Output - [\"Paypal\"]"
},
{
"code": null,
"e": 27737,
"s": 27622,
"text": "2. Any sorting algo (bubble sort) with time complexity, then optimize or use some faster algo with time complexity"
},
{
"code": null,
"e": 27776,
"s": 27737,
"text": "Started with bubble sort – O(n^2) time"
},
{
"code": null,
"e": 27818,
"s": 27776,
"text": "Finalised with merge sort – O(nlogn) time"
},
{
"code": null,
"e": 27883,
"s": 27818,
"text": "Some other basic Computer Science questions on OS, DBMS, SQL etc"
},
{
"code": null,
"e": 27934,
"s": 27883,
"text": "Some questions based on my resume and my projects."
},
{
"code": null,
"e": 27962,
"s": 27934,
"text": "Some more HR type questions"
},
{
"code": null,
"e": 27975,
"s": 27962,
"text": "Final Round:"
},
{
"code": null,
"e": 28230,
"s": 27975,
"text": "K frogs are there with a number assigned. There is 1 long queue with numbers from 1 to n. Frog with number 2 can visit 2, 4,6,8... And so with other frogs. What are the numbers in the queue that won’t be visited after all the frogs have done their visit?"
},
{
"code": null,
"e": 28413,
"s": 28230,
"text": "A grid is present with many balloons. You have 1 arrow. What is the max no of balloons that u can shoot with that arrow? The angle of the shoot can be anything from 0 to 360 degrees."
},
{
"code": null,
"e": 28496,
"s": 28413,
"text": "Similar Question: https://www.geeksforgeeks.org/count-maximum-points-on-same-line/"
},
{
"code": null,
"e": 28633,
"s": 28496,
"text": "My all rounds were good and solved most of the questions in one attempt. 3rd round was worst and was not able to solve any questions : ("
},
{
"code": null,
"e": 28649,
"s": 28633,
"text": "My suggestions:"
},
{
"code": null,
"e": 28714,
"s": 28649,
"text": "Don’t fake anything either in your resume or with your projects."
},
{
"code": null,
"e": 28779,
"s": 28714,
"text": "Be honest in your resume and don’t mention things you don’t know"
},
{
"code": null,
"e": 28888,
"s": 28779,
"text": "Projects are an important part of the resume. Don’t mention projects done by your friends/ taken from GitHub"
},
{
"code": null,
"e": 28959,
"s": 28888,
"text": "Have a good understanding of OS, DBMS, Network, etc (core CS subjects)"
},
{
"code": null,
"e": 29003,
"s": 28959,
"text": "Be positive and have confidence in yourself"
},
{
"code": null,
"e": 29037,
"s": 29003,
"text": "All the best for your interviews."
},
{
"code": null,
"e": 29047,
"s": 29037,
"text": "Marketing"
},
{
"code": null,
"e": 29057,
"s": 29047,
"text": "On-Campus"
},
{
"code": null,
"e": 29064,
"s": 29057,
"text": "PayPal"
},
{
"code": null,
"e": 29086,
"s": 29064,
"text": "Interview Experiences"
},
{
"code": null,
"e": 29093,
"s": 29086,
"text": "PayPal"
},
{
"code": null,
"e": 29191,
"s": 29093,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29200,
"s": 29191,
"text": "Comments"
},
{
"code": null,
"e": 29213,
"s": 29200,
"text": "Old Comments"
},
{
"code": null,
"e": 29263,
"s": 29213,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 29322,
"s": 29263,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 29360,
"s": 29322,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 29396,
"s": 29360,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 29442,
"s": 29396,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 29507,
"s": 29442,
"text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022"
},
{
"code": null,
"e": 29542,
"s": 29507,
"text": "Zoho Interview | Set 1 (On-Campus)"
},
{
"code": null,
"e": 29580,
"s": 29542,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 29630,
"s": 29580,
"text": "Amazon Interview Experience for SDE-1(Off-Campus)"
}
]
|
How to accept all pending connection requests on LinkedIn using JavaScript ? - GeeksforGeeks | 24 May, 2021
Many times we get a lot of connection requests over LinkedIn, and we want to accept all of them but for that, we have to click the accept button for each connection request. With the help of the following way, we can accept all of them at once using JavaScript helping us to save our time and effort.
Approach:
Make a variable connection that points to an array of all the pending connections.
Run a loop to iterate all the pending connection.
Then click on the accept button of that connection request using the JavaScript click function.
Steps:
Go to the LinkedIn page or click here.
If you are not Signed in. You should Sign in to your account.
Open the My Network tab visible on the page.
Click on the Show more button to see all the connection requests.Note: The show more button will only be visible if you have more than 3 connection requests. Keep on clicking until all the connection requests are visible.
Open the developer console by pressing F12 or CTRL+SHIFT+I
Copy and paste the following script on the console and hit enter.
Javascript
var connection = document .querySelectorAll( '.invitation-card__action-btn.artdeco-button--secondary'); for(var i = 0; i < connection.length; i = i + 1) connection[i].click();
Output:
Before running script:
After running script:
Note:
Please ensure that there is a stable internet connection available so that the script runs smoothly.
The script will only work when all the connections are visible.
This tutorial is for educational purposes only.
tanmaygoyalpro
JavaScript-Misc
JavaScript
Technical Scripter
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 get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
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": 25300,
"s": 25272,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 25601,
"s": 25300,
"text": "Many times we get a lot of connection requests over LinkedIn, and we want to accept all of them but for that, we have to click the accept button for each connection request. With the help of the following way, we can accept all of them at once using JavaScript helping us to save our time and effort."
},
{
"code": null,
"e": 25611,
"s": 25601,
"text": "Approach:"
},
{
"code": null,
"e": 25694,
"s": 25611,
"text": "Make a variable connection that points to an array of all the pending connections."
},
{
"code": null,
"e": 25744,
"s": 25694,
"text": "Run a loop to iterate all the pending connection."
},
{
"code": null,
"e": 25840,
"s": 25744,
"text": "Then click on the accept button of that connection request using the JavaScript click function."
},
{
"code": null,
"e": 25847,
"s": 25840,
"text": "Steps:"
},
{
"code": null,
"e": 25886,
"s": 25847,
"text": "Go to the LinkedIn page or click here."
},
{
"code": null,
"e": 25948,
"s": 25886,
"text": "If you are not Signed in. You should Sign in to your account."
},
{
"code": null,
"e": 25993,
"s": 25948,
"text": "Open the My Network tab visible on the page."
},
{
"code": null,
"e": 26215,
"s": 25993,
"text": "Click on the Show more button to see all the connection requests.Note: The show more button will only be visible if you have more than 3 connection requests. Keep on clicking until all the connection requests are visible."
},
{
"code": null,
"e": 26274,
"s": 26215,
"text": "Open the developer console by pressing F12 or CTRL+SHIFT+I"
},
{
"code": null,
"e": 26340,
"s": 26274,
"text": "Copy and paste the following script on the console and hit enter."
},
{
"code": null,
"e": 26351,
"s": 26340,
"text": "Javascript"
},
{
"code": "var connection = document .querySelectorAll( '.invitation-card__action-btn.artdeco-button--secondary'); for(var i = 0; i < connection.length; i = i + 1) connection[i].click();",
"e": 26534,
"s": 26351,
"text": null
},
{
"code": null,
"e": 26542,
"s": 26534,
"text": "Output:"
},
{
"code": null,
"e": 26565,
"s": 26542,
"text": "Before running script:"
},
{
"code": null,
"e": 26587,
"s": 26565,
"text": "After running script:"
},
{
"code": null,
"e": 26594,
"s": 26587,
"text": "Note: "
},
{
"code": null,
"e": 26695,
"s": 26594,
"text": "Please ensure that there is a stable internet connection available so that the script runs smoothly."
},
{
"code": null,
"e": 26759,
"s": 26695,
"text": "The script will only work when all the connections are visible."
},
{
"code": null,
"e": 26807,
"s": 26759,
"text": "This tutorial is for educational purposes only."
},
{
"code": null,
"e": 26822,
"s": 26807,
"text": "tanmaygoyalpro"
},
{
"code": null,
"e": 26838,
"s": 26822,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 26849,
"s": 26838,
"text": "JavaScript"
},
{
"code": null,
"e": 26868,
"s": 26849,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26885,
"s": 26868,
"text": "Web Technologies"
},
{
"code": null,
"e": 26983,
"s": 26885,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26992,
"s": 26983,
"text": "Comments"
},
{
"code": null,
"e": 27005,
"s": 26992,
"text": "Old Comments"
},
{
"code": null,
"e": 27066,
"s": 27005,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27107,
"s": 27066,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27161,
"s": 27107,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27223,
"s": 27161,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27280,
"s": 27223,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 27322,
"s": 27280,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27355,
"s": 27322,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27417,
"s": 27355,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27460,
"s": 27417,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Count of Subarrays | Practice | GeeksforGeeks | Given an array of N positive integers Arr1, Arr2 ............ Arrn. The value of each contiguous subarray of given array is the maximum element present in that subarray. The task is to return the number of subarrays having value strictly greater than K.
Example 1:
Input:
N = 3, K = 2
Arr[] = {3, 2, 1}
Output: 3
Explanation: The subarrays having value
strictly greater than K are: [3], [3, 2]
and [3, 2, 1]. Thus there are 3 such
subarrays.
Example 2:
Input:
N = 4, K = 1
Arr[] = {1, 2, 3, 4}
Output: 9
Explanation: There are 9 subarrays having
value strictly greater than K.
Your Task:
Complete the function countSubarray() which takes an array arr, two integers n, k, as input parameters and returns an integer denoting the answer. You don't to print answer or take inputs.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 105
1 <= Arr[i] <= 105
0
duttasayan4532 months ago
class Solution{public:// #define ll long long
ll countSubarray(int arr[], int n, int k){ // To store count of subarrays with all // elements less than or equal to k. int s = 0; // Traversing the array. int i = 0; while (i < n) { // If element is greater than k, ignore. if (arr[i] > k) { i++; continue; } // Counting the subarray length whose // each element is less than equal to k. int count = 0; while (i < n && arr[i] <= k) { i++; count++; } // Summing number of subarray whose // maximum element is less than equal to k. s += ((count * (count + 1)) / 2); } return (n * (n + 1) / 2 - s);}
};
WHY MY CODE IS NOT OPTIMIZED?
WHY IT FAILED IT?
0
wallflower9 months ago
wallflower
https://ide.geeksforgeeks.o...
Java solution
0
Ankit Podder10 months ago
Ankit Podder
---------------------------------------------------------------------------------------------
class Solution{public:ll countSubarray(int arr[], int n, int k) { int s=-1,e=-1; long long ans=0; for(int i=0;i<n;i++) {="" if(arr[i]="">k) e=i; ans+=e-s; } return ans;}};
0
Imran Wahid11 months ago
Imran Wahid
Easy C++ solution in O(n) TC and O(1) SChttps://ide.geeksforgeeks.o...
0
Himanshu Dubey11 months ago
Himanshu Dubey
ll countSubarray(int a[], int n, int k) { int s=-1,e=-1; long long ans=0; for(int i=0;i<n;i++) {="" if(a[i]="">k)e=i; ans+=e-s; } return ans;}
0
Bikram Biswas1 year ago
Bikram Biswas
https://uploads.disquscdn.c...
0
Sarvesh Raut1 year ago
Sarvesh Raut
O(N) soln : ll countSubarray(int a[], int n, int k) { // code here ll ans = 1LL*((long long)n*(n+1))/2; int i=0 ; while(i<n){ if(a[i]="">k){i++ ;continue;} else{ ll len = 0 ; while(i<n &&="" a[i]<="k" ){="" i++="" ;="" len++;="" }="" ans-="1LL*((long" long)len*(len+1))="" 2;="" }="" }="" return="" ans="" ;="" }="" <="" code="">
0
Sarvesh Raut
This comment was deleted.
0
Sanjay Prajapati2 years ago
Sanjay Prajapati
Solution O(N): https://ide.geeksforgeeks.o...
0
aryan garg2 years ago
aryan garg
class Solution{public:// #define ll long long
ll countSubarray(int arr[], int n, int k) { ll count =0 ;
ll si = (ll)n ;
ll total = si*(si+1) ; total = total/2 ;
//cout<<"The total possible subarrays are : "<<total<<endl ;="" vector<int="">v ; // Stores the indices of those values having values smaller than equal to k.
for(int i=0; i<n; i++)="" {="" ll="" count="0" ;="" if(arr[i]="" <="k)" {="" while(i<n="" and="" arr[i]="" <="k)" {="" count++="" ;="" i++="" ;="" }="" cout<<"the="" total="" consecutive="" elements="" smaller="" are="" :="" "<<count<<endl;="" ll="" temp1="count*(count+1);" temp1="temp1/2" ;="" total="" -="temp1" ;="" }="" }="" return="" total="" ;="" }="" };="" this="" is="" my="" working="" solution="" :)="">
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": 493,
"s": 238,
"text": "Given an array of N positive integers Arr1, Arr2 ............ Arrn. The value of each contiguous subarray of given array is the maximum element present in that subarray. The task is to return the number of subarrays having value strictly greater than K."
},
{
"code": null,
"e": 504,
"s": 493,
"text": "Example 1:"
},
{
"code": null,
"e": 682,
"s": 504,
"text": "Input:\nN = 3, K = 2\nArr[] = {3, 2, 1}\nOutput: 3\nExplanation: The subarrays having value\nstrictly greater than K are: [3], [3, 2]\nand [3, 2, 1]. Thus there are 3 such\nsubarrays.\n"
},
{
"code": null,
"e": 693,
"s": 682,
"text": "Example 2:"
},
{
"code": null,
"e": 818,
"s": 693,
"text": "Input:\nN = 4, K = 1\nArr[] = {1, 2, 3, 4}\nOutput: 9\nExplanation: There are 9 subarrays having\nvalue strictly greater than K.\n"
},
{
"code": null,
"e": 1018,
"s": 818,
"text": "Your Task:\nComplete the function countSubarray() which takes an array arr, two integers n, k, as input parameters and returns an integer denoting the answer. You don't to print answer or take inputs."
},
{
"code": null,
"e": 1127,
"s": 1018,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 <= N <= 105\n1 <= Arr[i] <= 105"
},
{
"code": null,
"e": 1129,
"s": 1127,
"text": "0"
},
{
"code": null,
"e": 1155,
"s": 1129,
"text": "duttasayan4532 months ago"
},
{
"code": null,
"e": 1201,
"s": 1155,
"text": "class Solution{public:// #define ll long long"
},
{
"code": null,
"e": 1870,
"s": 1201,
"text": "ll countSubarray(int arr[], int n, int k){ // To store count of subarrays with all // elements less than or equal to k. int s = 0; // Traversing the array. int i = 0; while (i < n) { // If element is greater than k, ignore. if (arr[i] > k) { i++; continue; } // Counting the subarray length whose // each element is less than equal to k. int count = 0; while (i < n && arr[i] <= k) { i++; count++; } // Summing number of subarray whose // maximum element is less than equal to k. s += ((count * (count + 1)) / 2); } return (n * (n + 1) / 2 - s);}"
},
{
"code": null,
"e": 1873,
"s": 1870,
"text": "};"
},
{
"code": null,
"e": 1903,
"s": 1873,
"text": "WHY MY CODE IS NOT OPTIMIZED?"
},
{
"code": null,
"e": 1921,
"s": 1903,
"text": "WHY IT FAILED IT?"
},
{
"code": null,
"e": 1923,
"s": 1921,
"text": "0"
},
{
"code": null,
"e": 1946,
"s": 1923,
"text": "wallflower9 months ago"
},
{
"code": null,
"e": 1957,
"s": 1946,
"text": "wallflower"
},
{
"code": null,
"e": 1988,
"s": 1957,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 2002,
"s": 1988,
"text": "Java solution"
},
{
"code": null,
"e": 2004,
"s": 2002,
"text": "0"
},
{
"code": null,
"e": 2030,
"s": 2004,
"text": "Ankit Podder10 months ago"
},
{
"code": null,
"e": 2043,
"s": 2030,
"text": "Ankit Podder"
},
{
"code": null,
"e": 2137,
"s": 2043,
"text": "---------------------------------------------------------------------------------------------"
},
{
"code": null,
"e": 2366,
"s": 2137,
"text": "class Solution{public:ll countSubarray(int arr[], int n, int k) { int s=-1,e=-1; long long ans=0; for(int i=0;i<n;i++) {=\"\" if(arr[i]=\"\">k) e=i; ans+=e-s; } return ans;}};"
},
{
"code": null,
"e": 2368,
"s": 2366,
"text": "0"
},
{
"code": null,
"e": 2393,
"s": 2368,
"text": "Imran Wahid11 months ago"
},
{
"code": null,
"e": 2405,
"s": 2393,
"text": "Imran Wahid"
},
{
"code": null,
"e": 2476,
"s": 2405,
"text": "Easy C++ solution in O(n) TC and O(1) SChttps://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 2478,
"s": 2476,
"text": "0"
},
{
"code": null,
"e": 2506,
"s": 2478,
"text": "Himanshu Dubey11 months ago"
},
{
"code": null,
"e": 2521,
"s": 2506,
"text": "Himanshu Dubey"
},
{
"code": null,
"e": 2692,
"s": 2521,
"text": "ll countSubarray(int a[], int n, int k) { int s=-1,e=-1; long long ans=0; for(int i=0;i<n;i++) {=\"\" if(a[i]=\"\">k)e=i; ans+=e-s; } return ans;}"
},
{
"code": null,
"e": 2694,
"s": 2692,
"text": "0"
},
{
"code": null,
"e": 2718,
"s": 2694,
"text": "Bikram Biswas1 year ago"
},
{
"code": null,
"e": 2732,
"s": 2718,
"text": "Bikram Biswas"
},
{
"code": null,
"e": 2763,
"s": 2732,
"text": "https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 2765,
"s": 2763,
"text": "0"
},
{
"code": null,
"e": 2788,
"s": 2765,
"text": "Sarvesh Raut1 year ago"
},
{
"code": null,
"e": 2801,
"s": 2788,
"text": "Sarvesh Raut"
},
{
"code": null,
"e": 3173,
"s": 2801,
"text": "O(N) soln : ll countSubarray(int a[], int n, int k) { // code here ll ans = 1LL*((long long)n*(n+1))/2; int i=0 ; while(i<n){ if(a[i]=\"\">k){i++ ;continue;} else{ ll len = 0 ; while(i<n &&=\"\" a[i]<=\"k\" ){=\"\" i++=\"\" ;=\"\" len++;=\"\" }=\"\" ans-=\"1LL*((long\" long)len*(len+1))=\"\" 2;=\"\" }=\"\" }=\"\" return=\"\" ans=\"\" ;=\"\" }=\"\" <=\"\" code=\"\">"
},
{
"code": null,
"e": 3175,
"s": 3173,
"text": "0"
},
{
"code": null,
"e": 3188,
"s": 3175,
"text": "Sarvesh Raut"
},
{
"code": null,
"e": 3214,
"s": 3188,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3216,
"s": 3214,
"text": "0"
},
{
"code": null,
"e": 3244,
"s": 3216,
"text": "Sanjay Prajapati2 years ago"
},
{
"code": null,
"e": 3261,
"s": 3244,
"text": "Sanjay Prajapati"
},
{
"code": null,
"e": 3307,
"s": 3261,
"text": "Solution O(N): https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 3309,
"s": 3307,
"text": "0"
},
{
"code": null,
"e": 3331,
"s": 3309,
"text": "aryan garg2 years ago"
},
{
"code": null,
"e": 3342,
"s": 3331,
"text": "aryan garg"
},
{
"code": null,
"e": 3388,
"s": 3342,
"text": "class Solution{public:// #define ll long long"
},
{
"code": null,
"e": 3449,
"s": 3388,
"text": "ll countSubarray(int arr[], int n, int k) { ll count =0 ;"
},
{
"code": null,
"e": 3469,
"s": 3449,
"text": " ll si = (ll)n ;"
},
{
"code": null,
"e": 3518,
"s": 3469,
"text": " ll total = si*(si+1) ; total = total/2 ;"
},
{
"code": null,
"e": 3687,
"s": 3518,
"text": " //cout<<\"The total possible subarrays are : \"<<total<<endl ;=\"\" vector<int=\"\">v ; // Stores the indices of those values having values smaller than equal to k."
},
{
"code": null,
"e": 4106,
"s": 3687,
"text": " for(int i=0; i<n; i++)=\"\" {=\"\" ll=\"\" count=\"0\" ;=\"\" if(arr[i]=\"\" <=\"k)\" {=\"\" while(i<n=\"\" and=\"\" arr[i]=\"\" <=\"k)\" {=\"\" count++=\"\" ;=\"\" i++=\"\" ;=\"\" }=\"\" cout<<\"the=\"\" total=\"\" consecutive=\"\" elements=\"\" smaller=\"\" are=\"\" :=\"\" \"<<count<<endl;=\"\" ll=\"\" temp1=\"count*(count+1);\" temp1=\"temp1/2\" ;=\"\" total=\"\" -=\"temp1\" ;=\"\" }=\"\" }=\"\" return=\"\" total=\"\" ;=\"\" }=\"\" };=\"\" this=\"\" is=\"\" my=\"\" working=\"\" solution=\"\" :)=\"\">"
},
{
"code": null,
"e": 4252,
"s": 4106,
"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": 4288,
"s": 4252,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4298,
"s": 4288,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4308,
"s": 4298,
"text": "\nContest\n"
},
{
"code": null,
"e": 4371,
"s": 4308,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4519,
"s": 4371,
"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": 4727,
"s": 4519,
"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": 4833,
"s": 4727,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Perl | Mutable and Immutable parameters - GeeksforGeeks | 07 Jun, 2019
A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language, the user wants to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. These subroutines contain parameters which define the type and number of arguments that can be passed to the function at the time of function call. These arguments or parameters are used to evaluate the values passed to the function according to the expressions specified in the function. These values are then returned to the specified parameters and are passed to the calling function.
Example:
sub Function1(parameter1, parameter2){ statement; }
These type of parameters are those whose value can be modified within a function to which they are passed as a parameter. It means that when a parameter is passed to the function using the caller function, then its value is bound to the parameter in the called function, which means any changes done to the value in that function will also be reflected in the parameter of the caller function.
These parameters are of those types whose value can not be modified within a function to which they are passed as parameter. It means that when a parameter is passed to the function using the caller function, then the subroutine receives a value rather than a variable. Hence, any changes made to the function parameter are not reflected.
By default, the subroutine parameters in Perl are immutable, which means they cannot be changed within a function and one cannot accidentally modify the arguments of the caller function.In some languages, this process is known as ‘call by value’, which means the subroutine being called receives a value rather than the variable, and hence the parameters of the caller function are not modified.
Example:
#!/usr/bin/perl # Function Definitionsub Func(Int $variable){ # Operation to be performed $variable /= 2; } # Defining a local variablemy $value = 20; # Function Call with local variableprint Func($value);
Output:
Error: Cannot assign to an immutable value
To change the property of these parameters, traits are used. With the help of traits, the value of the parameter can be changed within a subroutine.
These are the predefined built-in subroutines that when used within a method, modify the behavior of the method when running at compile time. Traits can even be used to change the body of the method or simply tagging the method with metadata.Traits can be of multiple types depending upon their usage such as:
is cached trait caches the function’s return value automatically, based on the arguments that are being passed to it.
is rw trait allows the writable accessors to the subroutine parameters.
is copy trait allows changing the value of the parameter within the subroutine but without changing the argument in the caller function.
Example: Use of is copy trait
#!/usr/bin/perl # Function Definition using# 'is copy' traitsub Func(Int $variable is copy){ # Operation to be performed $variable += 5; } # Defining a local variablemy $value = 10; # Function Call with local variableprint Func($value), "\n"; # Checking if # $value gets updated or notprint $value;
Output:
15
10
In the above code, is copy trait is used because Perl by default, doesn’t allow the modification of arguments within a subroutine. This trait allows the program to assign the caller function’s parameter value to the parameter of the subroutine being called. But, this trait will only change the value of the argument in the called function.
Example: Use of is rw trait
#!/usr/bin/perl # Function Definition using# 'is rw' traitsub Func(Int $variable is rw){ # Operation to be performed $variable += 5; } # Defining a local variablemy $value = 10; # Function Call with local variableprint Func($value), "\n"; # Checking if # $value gets updated or notprint $value;
Output:
15
15
In the above code, when is rw is used instead of is copy trait, the value of the argument passed in the caller function also gets updated.
When is rw trait is used, the argument of the called function is bound with the argument of the caller function, so if any change is made in the former value, the latter gets updated immediately. This is because of the process termed as ‘call by reference’. Since, both the arguments refer to the same memory location(because of the is rw trait). This makes the parameters to be fully mutable.
Perl-function
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl Tutorial - Learn Perl With Examples
Perl | Basic Syntax of a Perl Program
Perl | Opening and Reading a File
Perl | index() Function
Perl | File Handling Introduction
Perl | Multidimensional Hashes
Perl | Data Types
Perl | Writing to a File
Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
Perl | defined() Function | [
{
"code": null,
"e": 24070,
"s": 24042,
"text": "\n07 Jun, 2019"
},
{
"code": null,
"e": 24741,
"s": 24070,
"text": "A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language, the user wants to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. These subroutines contain parameters which define the type and number of arguments that can be passed to the function at the time of function call. These arguments or parameters are used to evaluate the values passed to the function according to the expressions specified in the function. These values are then returned to the specified parameters and are passed to the calling function."
},
{
"code": null,
"e": 24750,
"s": 24741,
"text": "Example:"
},
{
"code": null,
"e": 24802,
"s": 24750,
"text": "sub Function1(parameter1, parameter2){ statement; }"
},
{
"code": null,
"e": 25196,
"s": 24802,
"text": "These type of parameters are those whose value can be modified within a function to which they are passed as a parameter. It means that when a parameter is passed to the function using the caller function, then its value is bound to the parameter in the called function, which means any changes done to the value in that function will also be reflected in the parameter of the caller function."
},
{
"code": null,
"e": 25535,
"s": 25196,
"text": "These parameters are of those types whose value can not be modified within a function to which they are passed as parameter. It means that when a parameter is passed to the function using the caller function, then the subroutine receives a value rather than a variable. Hence, any changes made to the function parameter are not reflected."
},
{
"code": null,
"e": 25931,
"s": 25535,
"text": "By default, the subroutine parameters in Perl are immutable, which means they cannot be changed within a function and one cannot accidentally modify the arguments of the caller function.In some languages, this process is known as ‘call by value’, which means the subroutine being called receives a value rather than the variable, and hence the parameters of the caller function are not modified."
},
{
"code": null,
"e": 25940,
"s": 25931,
"text": "Example:"
},
{
"code": "#!/usr/bin/perl # Function Definitionsub Func(Int $variable){ # Operation to be performed $variable /= 2; } # Defining a local variablemy $value = 20; # Function Call with local variableprint Func($value);",
"e": 26155,
"s": 25940,
"text": null
},
{
"code": null,
"e": 26163,
"s": 26155,
"text": "Output:"
},
{
"code": null,
"e": 26206,
"s": 26163,
"text": "Error: Cannot assign to an immutable value"
},
{
"code": null,
"e": 26355,
"s": 26206,
"text": "To change the property of these parameters, traits are used. With the help of traits, the value of the parameter can be changed within a subroutine."
},
{
"code": null,
"e": 26665,
"s": 26355,
"text": "These are the predefined built-in subroutines that when used within a method, modify the behavior of the method when running at compile time. Traits can even be used to change the body of the method or simply tagging the method with metadata.Traits can be of multiple types depending upon their usage such as:"
},
{
"code": null,
"e": 26783,
"s": 26665,
"text": "is cached trait caches the function’s return value automatically, based on the arguments that are being passed to it."
},
{
"code": null,
"e": 26855,
"s": 26783,
"text": "is rw trait allows the writable accessors to the subroutine parameters."
},
{
"code": null,
"e": 26992,
"s": 26855,
"text": "is copy trait allows changing the value of the parameter within the subroutine but without changing the argument in the caller function."
},
{
"code": null,
"e": 27022,
"s": 26992,
"text": "Example: Use of is copy trait"
},
{
"code": "#!/usr/bin/perl # Function Definition using# 'is copy' traitsub Func(Int $variable is copy){ # Operation to be performed $variable += 5; } # Defining a local variablemy $value = 10; # Function Call with local variableprint Func($value), \"\\n\"; # Checking if # $value gets updated or notprint $value;",
"e": 27331,
"s": 27022,
"text": null
},
{
"code": null,
"e": 27339,
"s": 27331,
"text": "Output:"
},
{
"code": null,
"e": 27345,
"s": 27339,
"text": "15\n10"
},
{
"code": null,
"e": 27686,
"s": 27345,
"text": "In the above code, is copy trait is used because Perl by default, doesn’t allow the modification of arguments within a subroutine. This trait allows the program to assign the caller function’s parameter value to the parameter of the subroutine being called. But, this trait will only change the value of the argument in the called function."
},
{
"code": null,
"e": 27714,
"s": 27686,
"text": "Example: Use of is rw trait"
},
{
"code": "#!/usr/bin/perl # Function Definition using# 'is rw' traitsub Func(Int $variable is rw){ # Operation to be performed $variable += 5; } # Defining a local variablemy $value = 10; # Function Call with local variableprint Func($value), \"\\n\"; # Checking if # $value gets updated or notprint $value;",
"e": 28019,
"s": 27714,
"text": null
},
{
"code": null,
"e": 28027,
"s": 28019,
"text": "Output:"
},
{
"code": null,
"e": 28033,
"s": 28027,
"text": "15\n15"
},
{
"code": null,
"e": 28172,
"s": 28033,
"text": "In the above code, when is rw is used instead of is copy trait, the value of the argument passed in the caller function also gets updated."
},
{
"code": null,
"e": 28566,
"s": 28172,
"text": "When is rw trait is used, the argument of the called function is bound with the argument of the caller function, so if any change is made in the former value, the latter gets updated immediately. This is because of the process termed as ‘call by reference’. Since, both the arguments refer to the same memory location(because of the is rw trait). This makes the parameters to be fully mutable."
},
{
"code": null,
"e": 28580,
"s": 28566,
"text": "Perl-function"
},
{
"code": null,
"e": 28585,
"s": 28580,
"text": "Perl"
},
{
"code": null,
"e": 28590,
"s": 28585,
"text": "Perl"
},
{
"code": null,
"e": 28688,
"s": 28590,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28729,
"s": 28688,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 28767,
"s": 28729,
"text": "Perl | Basic Syntax of a Perl Program"
},
{
"code": null,
"e": 28801,
"s": 28767,
"text": "Perl | Opening and Reading a File"
},
{
"code": null,
"e": 28825,
"s": 28801,
"text": "Perl | index() Function"
},
{
"code": null,
"e": 28859,
"s": 28825,
"text": "Perl | File Handling Introduction"
},
{
"code": null,
"e": 28890,
"s": 28859,
"text": "Perl | Multidimensional Hashes"
},
{
"code": null,
"e": 28908,
"s": 28890,
"text": "Perl | Data Types"
},
{
"code": null,
"e": 28933,
"s": 28908,
"text": "Perl | Writing to a File"
},
{
"code": null,
"e": 29033,
"s": 28933,
"text": "Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)"
}
]
|
How to change the aspect ratio of a plot in ggplot2 in R? | The aspect ratio of a chart can be changed in ggplot2 and this will be useful if we want a smaller image of the chart. Sometimes, we don’t have large space where the chart will be pasted therefore this functionality becomes useful. Mostly, in research reports we see charts that are of small size, hence R becomes helpful to create charts that can be pasted in the desired space. This can be done with the help of theme function.
Consider the below data frame −
> set.seed(100)
> x<-rpois(30,2)
> df<-data.frame(x)
Loading the ggplot2 package −
> library(ggplot2)
Creating the plot with aspect ratio 4/3 −
> ggplot(df,aes(x))+
+ geom_bar()+
+ theme(aspect.ratio=4/3)
Creating the plot with aspect ratio 16/9 −
> ggplot(df,aes(x))+
+ geom_bar()+
+ theme(aspect.ratio=16/9)
Creating the plot with aspect ratio 1, it gives us a square form −
> ggplot(df,aes(x))+
+ geom_bar()+
+ theme(aspect.ratio=1) | [
{
"code": null,
"e": 1492,
"s": 1062,
"text": "The aspect ratio of a chart can be changed in ggplot2 and this will be useful if we want a smaller image of the chart. Sometimes, we don’t have large space where the chart will be pasted therefore this functionality becomes useful. Mostly, in research reports we see charts that are of small size, hence R becomes helpful to create charts that can be pasted in the desired space. This can be done with the help of theme function."
},
{
"code": null,
"e": 1524,
"s": 1492,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1577,
"s": 1524,
"text": "> set.seed(100)\n> x<-rpois(30,2)\n> df<-data.frame(x)"
},
{
"code": null,
"e": 1607,
"s": 1577,
"text": "Loading the ggplot2 package −"
},
{
"code": null,
"e": 1626,
"s": 1607,
"text": "> library(ggplot2)"
},
{
"code": null,
"e": 1668,
"s": 1626,
"text": "Creating the plot with aspect ratio 4/3 −"
},
{
"code": null,
"e": 1729,
"s": 1668,
"text": "> ggplot(df,aes(x))+\n+ geom_bar()+\n+ theme(aspect.ratio=4/3)"
},
{
"code": null,
"e": 1772,
"s": 1729,
"text": "Creating the plot with aspect ratio 16/9 −"
},
{
"code": null,
"e": 1834,
"s": 1772,
"text": "> ggplot(df,aes(x))+\n+ geom_bar()+\n+ theme(aspect.ratio=16/9)"
},
{
"code": null,
"e": 1901,
"s": 1834,
"text": "Creating the plot with aspect ratio 1, it gives us a square form −"
},
{
"code": null,
"e": 1960,
"s": 1901,
"text": "> ggplot(df,aes(x))+\n+ geom_bar()+\n+ theme(aspect.ratio=1)"
}
]
|
Data Exploration 101 with Pandas. Pandas is one of the most powerful... | by Günter Röhrich | Towards Data Science | If you are new to data science, a student running out of time just ahead of an exam or you simply want to see how others may use Pandas to explore and analyse data, follow me here. For this quick introduction, we will use the daily temperature of major cities dataset which is available through Kaggle.com.
As a starting point for every data exploration task, it is necessary to import the dataset. Python makes this very easy through the ‘open()’ function, however as we are about to use pandas library anyways, the conventional open is not the way to go. Pandas provides a variety of read_ functions, that allows opening the file and converting it to a dataframe at the same time.
With just two lines you are importing data and create a dataframe object which is just brilliant to work with. Other than common Python data structures (think of a dictionary), operations can be performed on all, or just e filtered or even grouped set of data points . Just imagine you had to accomplish this task only using common data structures, this would be a nightmare.
Pandas provides you with incredibly handy and easy to apply possibilities to preview and modify and export data. In the next few lines, we will go through a couple of very useful examples to manipulate a dataframe. What you might observe, pandas is quite consistent (filtering, accessing rows, etc.) with other famous Python libraries, but also languages like R.
Almost every time a new dataset is analysed you might consider two things:
What are the ranges your data points lie in — this is essential in order to get a “feeling” for the data and also check on consistency, reliability and outliersDo you see invalid or missing values in your dataframe
What are the ranges your data points lie in — this is essential in order to get a “feeling” for the data and also check on consistency, reliability and outliers
Do you see invalid or missing values in your dataframe
Using just those to lines will allow you to examine your dataset and estimate, whether you might be required to do a lot more data cleansing. Clearly describe() makes no sense on Month, Day or Year, but AvgTemperature is essential to grasp. As we can see here, this measure is very likely not to be Celsius (mean temperature is 56 degrees), but Fahrenheit.
Month Day Year AvgTemperaturecount 2.906327e+06 2.906327e+06 2.906327e+06 2.906327e+06mean 6.469163e+00 1.571682e+01 2.006624e+03 5.600492e+01std 3.456489e+00 8.800534e+00 2.338226e+01 3.212359e+01min 1.000000e+00 0.000000e+00 2.000000e+02 -9.900000e+0125% 3.000000e+00 8.000000e+00 2.001000e+03 4.580000e+0150% 6.000000e+00 1.600000e+01 2.007000e+03 6.250000e+0175% 9.000000e+00 2.300000e+01 2.013000e+03 7.550000e+01max 1.200000e+01 3.100000e+01 2.020000e+03 1.100000e+02
Sometimes there are use cases that require that data extracts can be copied and inserted easily, I would recommend using to_markdown() function which provides great results for this purpose —indeed one of my favorites.
| | Country | AvgTemperature ||--------:|:----------|-----------------:|| 2906322 | US | 28 || 2906323 | US | 27.6 || 2906324 | US | 29 || 2906325 | US | 28.8 || 2906326 | US | 28.7 |
We further need to check whether there are “not a number” values. As we can see, only State has missing fields, which is totally fine for us. Keep in mind, for doing more sophisticated tasks like machine learning, removing as well as inter- or extrapolating missing data might be a key exercise for the data scientist.
Region FalseCountry FalseState TrueCity FalseMonth FalseDay FalseYear FalseAvgTemperature Falsedtype: bool
In order to get the unique values of a column the unique() function is very useful — we might use it on the grouped object as well.
data.Region.unique()array(['Africa', 'Asia', 'Australia/South Pacific', 'Europe', 'Middle East', 'North America', 'South/Central America & Carribean'], dtype=object)
You will likely have a much better feeling for the data, when the data is illustrated or summarized. If your data is numeric, you might find scatter or boxplots very handy.
Aside: There are many different libraries that allow plotting data in a very beautiful and quick manner. From a personal standpoint, data exploration without visualizations is often hard and a lot more time consuming as data irregularities may be identified quite a bit later in the process.
Here is just a quick look at another visualization that immediately provides a feeling for outliers, very dense scatter plot that combines a numeric and a categorical variable:
As we could see in the describe-table we initially created, temperature is given in Fahrenheit, for a non-American resident, it might get a bit more difficult to work with the data — especially when it comes to the “something seems wrong here”-part.
Pandas allows us to perform actions on columns in a very easy and straightforward way.
The more versatile approach is applying a function to the column. The result is the same as above, however, we can be a lot more creative in applying functions through this way.
Apply( ) allows the user to create sophisticated functions and apply them on a single or even several columns. Also note, other than defining a function (as our to_celsius function), lambda expressions can also be used very easily— this is probably most useful when used only once.
If you face complex modification tasks on a more frequent basis, you might want to build functions that are capable of parsing the cell values through regular expressions. In this case you might want to combine regular expressions with pandas’ apply function. If you feel you need a refresher on Regex for data science, take a look at the link below:
towardsdatascience.com
When data is grouped together, Pandas creates a groupby-object. There are plenty of functions that can be applied onto a grouped object like unique(), mean(), min() or max() — just to name a couple. Please note, you cannot directly “show” a groupby-object as this would result in an output like:
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x000001F2B6879CD0>
In order to obtain mean values, the following line will help:
data.groupby([‘Region’,’Country’,’State’,’City’,’Year’]).mean()
Again, mean values do not make any sense for month or days, hence it would be useful to omit these columns. Please also note that the above table would require to reset the index in order to show properly with per-line-entries.
Very often you might only be interested in a small portion of the given data. For this reason, the dataframe can be minimised to a smaller one through a simple filtering operation:
vienna = data[data['City']=='Vienna'].copy() # great city
The created copy of the dataframe will only comprise values where the ‘City’ is ‘Vienna’. If we needed additional filter requirements, pandas allows to concat criteria through ampersand or pipes.
In general, we could use the main dataframe to plot the relevant information, however I prefer using simple plotting operations on smaller datasets. Filtering data in the plot function makes it hard to read and understand. The advantages of using a dedicated copy of a dataframe becomes very clear when we are looking at the next lines of code:
With just 3 lines of code, we are able to produce a line chart including a linear trend:
If we counted the lines of code we used here and the number of data manipulations we made with those, there is no doubt that Pandas is a remarkably powerful tool to manipulate data without the need of extensive documentation reading and practice.
If you wanted to gain a better understanding of what we have covered in this article, I suggest starting with the documentation down below and going through the details that seem relevant for you. Keep in mind, like it is with every learning task, doing is better than (just) reading.
pandas.pydata.org
matplotlib.org
www.w3schools.com
As always, see you next time and stay safe!
Image by Gustav Gullstrand, Thanks! | [
{
"code": null,
"e": 479,
"s": 172,
"text": "If you are new to data science, a student running out of time just ahead of an exam or you simply want to see how others may use Pandas to explore and analyse data, follow me here. For this quick introduction, we will use the daily temperature of major cities dataset which is available through Kaggle.com."
},
{
"code": null,
"e": 855,
"s": 479,
"text": "As a starting point for every data exploration task, it is necessary to import the dataset. Python makes this very easy through the ‘open()’ function, however as we are about to use pandas library anyways, the conventional open is not the way to go. Pandas provides a variety of read_ functions, that allows opening the file and converting it to a dataframe at the same time."
},
{
"code": null,
"e": 1231,
"s": 855,
"text": "With just two lines you are importing data and create a dataframe object which is just brilliant to work with. Other than common Python data structures (think of a dictionary), operations can be performed on all, or just e filtered or even grouped set of data points . Just imagine you had to accomplish this task only using common data structures, this would be a nightmare."
},
{
"code": null,
"e": 1594,
"s": 1231,
"text": "Pandas provides you with incredibly handy and easy to apply possibilities to preview and modify and export data. In the next few lines, we will go through a couple of very useful examples to manipulate a dataframe. What you might observe, pandas is quite consistent (filtering, accessing rows, etc.) with other famous Python libraries, but also languages like R."
},
{
"code": null,
"e": 1669,
"s": 1594,
"text": "Almost every time a new dataset is analysed you might consider two things:"
},
{
"code": null,
"e": 1884,
"s": 1669,
"text": "What are the ranges your data points lie in — this is essential in order to get a “feeling” for the data and also check on consistency, reliability and outliersDo you see invalid or missing values in your dataframe"
},
{
"code": null,
"e": 2045,
"s": 1884,
"text": "What are the ranges your data points lie in — this is essential in order to get a “feeling” for the data and also check on consistency, reliability and outliers"
},
{
"code": null,
"e": 2100,
"s": 2045,
"text": "Do you see invalid or missing values in your dataframe"
},
{
"code": null,
"e": 2457,
"s": 2100,
"text": "Using just those to lines will allow you to examine your dataset and estimate, whether you might be required to do a lot more data cleansing. Clearly describe() makes no sense on Month, Day or Year, but AvgTemperature is essential to grasp. As we can see here, this measure is very likely not to be Celsius (mean temperature is 56 degrees), but Fahrenheit."
},
{
"code": null,
"e": 2982,
"s": 2457,
"text": " Month Day Year AvgTemperaturecount 2.906327e+06 2.906327e+06 2.906327e+06 2.906327e+06mean 6.469163e+00 1.571682e+01 2.006624e+03 5.600492e+01std 3.456489e+00 8.800534e+00 2.338226e+01 3.212359e+01min 1.000000e+00 0.000000e+00 2.000000e+02 -9.900000e+0125% 3.000000e+00 8.000000e+00 2.001000e+03 4.580000e+0150% 6.000000e+00 1.600000e+01 2.007000e+03 6.250000e+0175% 9.000000e+00 2.300000e+01 2.013000e+03 7.550000e+01max 1.200000e+01 3.100000e+01 2.020000e+03 1.100000e+02"
},
{
"code": null,
"e": 3201,
"s": 2982,
"text": "Sometimes there are use cases that require that data extracts can be copied and inserted easily, I would recommend using to_markdown() function which provides great results for this purpose —indeed one of my favorites."
},
{
"code": null,
"e": 3496,
"s": 3201,
"text": "| | Country | AvgTemperature ||--------:|:----------|-----------------:|| 2906322 | US | 28 || 2906323 | US | 27.6 || 2906324 | US | 29 || 2906325 | US | 28.8 || 2906326 | US | 28.7 |"
},
{
"code": null,
"e": 3815,
"s": 3496,
"text": "We further need to check whether there are “not a number” values. As we can see, only State has missing fields, which is totally fine for us. Keep in mind, for doing more sophisticated tasks like machine learning, removing as well as inter- or extrapolating missing data might be a key exercise for the data scientist."
},
{
"code": null,
"e": 4011,
"s": 3815,
"text": "Region FalseCountry FalseState TrueCity FalseMonth FalseDay FalseYear FalseAvgTemperature Falsedtype: bool"
},
{
"code": null,
"e": 4143,
"s": 4011,
"text": "In order to get the unique values of a column the unique() function is very useful — we might use it on the grouped object as well."
},
{
"code": null,
"e": 4321,
"s": 4143,
"text": "data.Region.unique()array(['Africa', 'Asia', 'Australia/South Pacific', 'Europe', 'Middle East', 'North America', 'South/Central America & Carribean'], dtype=object)"
},
{
"code": null,
"e": 4494,
"s": 4321,
"text": "You will likely have a much better feeling for the data, when the data is illustrated or summarized. If your data is numeric, you might find scatter or boxplots very handy."
},
{
"code": null,
"e": 4786,
"s": 4494,
"text": "Aside: There are many different libraries that allow plotting data in a very beautiful and quick manner. From a personal standpoint, data exploration without visualizations is often hard and a lot more time consuming as data irregularities may be identified quite a bit later in the process."
},
{
"code": null,
"e": 4963,
"s": 4786,
"text": "Here is just a quick look at another visualization that immediately provides a feeling for outliers, very dense scatter plot that combines a numeric and a categorical variable:"
},
{
"code": null,
"e": 5213,
"s": 4963,
"text": "As we could see in the describe-table we initially created, temperature is given in Fahrenheit, for a non-American resident, it might get a bit more difficult to work with the data — especially when it comes to the “something seems wrong here”-part."
},
{
"code": null,
"e": 5300,
"s": 5213,
"text": "Pandas allows us to perform actions on columns in a very easy and straightforward way."
},
{
"code": null,
"e": 5478,
"s": 5300,
"text": "The more versatile approach is applying a function to the column. The result is the same as above, however, we can be a lot more creative in applying functions through this way."
},
{
"code": null,
"e": 5760,
"s": 5478,
"text": "Apply( ) allows the user to create sophisticated functions and apply them on a single or even several columns. Also note, other than defining a function (as our to_celsius function), lambda expressions can also be used very easily— this is probably most useful when used only once."
},
{
"code": null,
"e": 6111,
"s": 5760,
"text": "If you face complex modification tasks on a more frequent basis, you might want to build functions that are capable of parsing the cell values through regular expressions. In this case you might want to combine regular expressions with pandas’ apply function. If you feel you need a refresher on Regex for data science, take a look at the link below:"
},
{
"code": null,
"e": 6134,
"s": 6111,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6430,
"s": 6134,
"text": "When data is grouped together, Pandas creates a groupby-object. There are plenty of functions that can be applied onto a grouped object like unique(), mean(), min() or max() — just to name a couple. Please note, you cannot directly “show” a groupby-object as this would result in an output like:"
},
{
"code": null,
"e": 6506,
"s": 6430,
"text": "<pandas.core.groupby.generic.DataFrameGroupBy object at 0x000001F2B6879CD0>"
},
{
"code": null,
"e": 6568,
"s": 6506,
"text": "In order to obtain mean values, the following line will help:"
},
{
"code": null,
"e": 6632,
"s": 6568,
"text": "data.groupby([‘Region’,’Country’,’State’,’City’,’Year’]).mean()"
},
{
"code": null,
"e": 6860,
"s": 6632,
"text": "Again, mean values do not make any sense for month or days, hence it would be useful to omit these columns. Please also note that the above table would require to reset the index in order to show properly with per-line-entries."
},
{
"code": null,
"e": 7041,
"s": 6860,
"text": "Very often you might only be interested in a small portion of the given data. For this reason, the dataframe can be minimised to a smaller one through a simple filtering operation:"
},
{
"code": null,
"e": 7099,
"s": 7041,
"text": "vienna = data[data['City']=='Vienna'].copy() # great city"
},
{
"code": null,
"e": 7295,
"s": 7099,
"text": "The created copy of the dataframe will only comprise values where the ‘City’ is ‘Vienna’. If we needed additional filter requirements, pandas allows to concat criteria through ampersand or pipes."
},
{
"code": null,
"e": 7640,
"s": 7295,
"text": "In general, we could use the main dataframe to plot the relevant information, however I prefer using simple plotting operations on smaller datasets. Filtering data in the plot function makes it hard to read and understand. The advantages of using a dedicated copy of a dataframe becomes very clear when we are looking at the next lines of code:"
},
{
"code": null,
"e": 7729,
"s": 7640,
"text": "With just 3 lines of code, we are able to produce a line chart including a linear trend:"
},
{
"code": null,
"e": 7976,
"s": 7729,
"text": "If we counted the lines of code we used here and the number of data manipulations we made with those, there is no doubt that Pandas is a remarkably powerful tool to manipulate data without the need of extensive documentation reading and practice."
},
{
"code": null,
"e": 8261,
"s": 7976,
"text": "If you wanted to gain a better understanding of what we have covered in this article, I suggest starting with the documentation down below and going through the details that seem relevant for you. Keep in mind, like it is with every learning task, doing is better than (just) reading."
},
{
"code": null,
"e": 8279,
"s": 8261,
"text": "pandas.pydata.org"
},
{
"code": null,
"e": 8294,
"s": 8279,
"text": "matplotlib.org"
},
{
"code": null,
"e": 8312,
"s": 8294,
"text": "www.w3schools.com"
},
{
"code": null,
"e": 8356,
"s": 8312,
"text": "As always, see you next time and stay safe!"
}
]
|
SAP HANA BI Development - Quick Guide | SAP HANA is an in-memory database which also provides HANA Modeling, Data Provisioning, and BI reporting features in a single application. SAP HANA is mostly used as a Data Warehouse for many organizations with Transaction system. SAP is providing HANA as a backend database for various different ERP and CRM based applications.
Following are a few common HANA based modules −
S/4 HANA (S/4 HANA Finance and Logistics)
SAP Business One
SAP Fiori
SAP HANA Data Modeling helps the user to model the application data and perform database functions such as creating schemas, tables, and views at run time. HANA data models are stored in HANA Repository and objects are activated at run time.
This is SAP site link for HANA Product details that shares all key features HANA provides − https://www.sap.com/products/hana.html
According to SAP - "Deployable on premise or in the cloud, SAP HANA is an in-memory data platform that lets you accelerate business processes, deliver more business intelligence, and simplify your IT environment. By providing the foundation for all your data needs, SAP HANA removes the burden of maintaining separate legacy systems and siloed data, so you can run live and make better business decisions in the new digital economy."
BI development is always a challenge for organizations with massive amount of historical data. Traditional databases or DW systems - SQL Server, BW or Oracle - doesn't support live reporting, as they are not capable of running the transaction system and Data Warehouse on the same system. In many organizations, transactional system and Data warehouse are kept separate, as running complex OLAP queries affect the performance of the systems significantly. ETL processes are used to perform extraction, transformation, and data load from SAP ECC to Data Warehouse.
When large number of concurrent OLTP transactions are made along with OLAP queries, there is a possibility of the system getting crashed. SAP HANA supports real-time data replication from the transaction system using SLT method, which is a trigger-based approach of data replication.
SAP HANA is an in-memory database, hence the data read is 1 million times faster as compared to traditional systems. Complex OLAP queries in a Business Intelligence report takes less time to run when DW system contains huge amount of historical data. HANA supports all aggregations on fly, and hence, there is no need to save aggregated table in the database. Due to different compression algorithms and column-based storage of table, HANA database requires less space to store more data as compared with other RDBMS systems.
SAP provides BusinessObjects as BI reporting and dashboard tool, used by many organizations who have SAP ERP implemented as the transaction system. SAP BusinessObjects consist of multiple tools for Business Intelligence reporting and dashboard −
Web Intelligence
Dashboard Designer (Earlier known as Xcelsius)
Universe Designer (For Semantic Layer)
SAP Crystal Reports
SAP Lumira
SAP Design Studio
BusinessObjects Explorer
Analysis for OLAP
All these tools are closely integrated with SAP BW and SAP HANA and support all data modeling and ETL features of SAP system. Web Intelligence is used for detailed reporting and uses Query Panel and Universe Designer as the semantic layer to connect to non-SAP data sources. Dashboard Designer is the dashboard tool which provides lot of predefined templates for creating static and dynamic charts.
Universe Designer (UDT/IDT) is a tool to build the semantic layer for non-SAP data sources as well as to build data models for HANA database objects. Different features such as parameters, filters, creating/deleting objects, business layer views, predefined queries for testing, aggregations and variable mapping can be defined using the semantic layer. When the semantic layer is finalized, it can be published to BO server repository and can be used in different Webi reports and Dashboards.
SAP Crystal Reports is used for pixel perfect reporting where users want to take printout of sales invoices, bills, sales orders, etc.
SAP Lumira is one of the emerging data visualization tools that provide the users with an option of ad-hoc dashboarding feature.
SAP Design Studio is also an advanced level dashboard tool and supports server side programming to create interactive dashboards for customers.
SAP BusinessObjects Explorer is a self-service BI tool to create dashboard views and data visualizations, and share them with other users in the team.
Analysis for OLAP is also a self-service multidimensional analysis tool and is suitable for reporting on SAP BW and SAP HANA.
The above picture shows all BI tools with solid lines, which can be directly connected and integrated with SAP HANA using an OLAP connection. The tools that need a relational connection using IDT to connect to HANA are shown with dotted lines.
SAP BusinessObjects was an individual product earlier. In 2008, SAP acquired this product and added it as one of the key tools for SAP BI reporting.
Following is the version history of SAP BO tool in reverse chronology −
SAP Business Objects Business Intelligence 4.2 Service Pack 04 (Release Date, 2017)
SAP Business Objects Business Intelligence 4.2 Service Pack 04 (Release Date, 2017)
SAP Business Objects Business Intelligence 4.2 Service Pack 03 (Released Date, September 2016)
SAP Business Objects Business Intelligence 4.2 Service Pack 03 (Released Date, September 2016)
SAP BusinessObjects Business Intelligence 4.2 (Release Date, 18-May-2016)
SAP BusinessObjects Business Intelligence 4.2 (Release Date, 18-May-2016)
SAP BusinessObjects Business Intelligence 4.1 (Release Date, 23- Nov-2013)
SAP BusinessObjects Business Intelligence 4.1 (Release Date, 23- Nov-2013)
SAP BusinessObjects Business Intelligence 4.0 (Release Date, 16-Sep-2011)
SAP BusinessObjects Business Intelligence 4.0 (Release Date, 16-Sep-2011)
SAP Business Objects XI R3.0
SAP Business Objects XI R3.0
SAP Business Objects XI R3.1
SAP Business Objects XI R3.1
Business Objects XI R1
Business Objects XI R1
Business Objects XI R2
Business Objects XI R2
Business Objects 6.x
Business Objects 6.x
Business Objects 5.x
Business Objects 5.x
Business Objects 4.x
Business Objects 4.x
Business Objects 3.x
Business Objects 3.x
Few of these tools can be directly accessed using a web interface known as BI Launchpad. BI Launchpad is a Java or HTML based interface of BusinessObjects tool to perform analytical reporting and data analysis. You can set the preference for your BI Launchpad that determines, which tool interface is launched via Launchpad.
Using Web or Internet Application to access Webi interface via BI Launchpad, you can perform the following tasks −
Create, edit, and refresh all the reports in Web Intelligence.
Create, edit, and refresh all the reports in Web Intelligence.
Create and edit all the queries in no data source (Universes) but not BEx queries in Web application.
Create and edit all the queries in no data source (Universes) but not BEx queries in Web application.
BI Launchpad has the following important tabs −
Home − Displays the recent messages, alerts, documents, and applications that can be run.
Home − Displays the recent messages, alerts, documents, and applications that can be run.
Documents − Displays the available documents and folders, making it easier to view, organize, and manage the documents.
Documents − Displays the available documents and folders, making it easier to view, organize, and manage the documents.
Any open Document − Displays each open document.
Any open Document − Displays each open document.
You can use the Application tab to start an application including Web Intelligence. You can use the Preference tab to define BI Launchpad preferences.
To get the BI Launchpad details and user credentials you can reach the BO Administrator. BI Launchpad has the following URL http://BOSERVER:8080/BOE/BI. To login to BI Launchpad, open the web browser and enter the Launchpad URL provided by your administrator. The following screen pops up.
In SAP BusinessObjects, different tool connects to HANA using different type of connections. Few of the tools connect to the Database layer - Tables, Views, etc. using a Relational connection to HANA database, however, other tools directly connect to Data Modeling layer using an OLAP connection.
An OLAP connection can be created in the Central Management Console (CMC) or a Relational connection and OLAP connection can also be defined in the Universe Designer.
A Relational connection is used to connect to the database layer in HANA. You can connect to database objects - tables, views, and design Data Foundation layer in the Information Design tool. You can also import tables and joins from the data source.
OLAP is a multidimensional connection that directly points to the business layer in a data model. It allows you to connect to the multidimensional schema directly and later, they can be used with SAP BusinessObjects reporting tools.
To connect to SAP NetWeaver BW, you can use SAP BICS client middleware to provide access to BEx query. Connections in IDT can be locally saved or they can be secured and published in a central repository.
Local connections are saved as .cnx files and they can be accessed by any user who is running IDT. Once you publish the connection to the repository, they are changed to a secured connection.
A secured connection is published into the repository and saved in the Connection folder. You can also create secured connections using Insert Relational and Insert OLAP connection commands from the repository resource view.
Let us see how to create a Relational connection that can be used to connect to HANA database layer to design Data Foundation layer for BOBJ reporting in a Universe.
Navigate to Information Design Tool → Click New → Project → Enter the Project Name → Finish. Right-click the Project name → New → Relational Connection.
In the next window, enter the name of Relational connection → Click the Next button.
To set up a connection to HANA database, select SAP HANA database 1.0 from the driver selection screen. In the following snapshot, we have selected SAP HANA → JDBC Drivers → Next.
Note that to connect to HANA database, you should have the following information −
Host Name
Instance Number
User Name
Password
You can also select from different authentication modes such as LDAP or any other mode, which is configured for HANA system login. Click the Next button.
In the next window, you will be prompted to enter Connection Parameters - Connection Pool Mode, Pool Timeout, Array Fetch Size, Array Bind Size, Login Tmeout, etc. Once you pass this information, click the Finish button.
This will create a Relational connection to source HANA database and it can be used to connect to Database layer objects for reporting. You can see the following information on the Connection parameter screen −
General
Login Parameter
Configuration Parameter
You can also edit any of the parameter value by the click of the edit button. When this connection is used in the Universe Designer, this will point to all database objects in HANA database. You can import tables, views from HANA database to build a data foundation layer of a Universe. To test the connection, click the Test Connection and you will get a message that the Connection is successful.
To publish this connection to BO repository so that it can be used by any tool, right-click the connection name and select Publish Connection to a Repository. This will create a new object in the project tab with .cns extension.
.cns − Secured Repository connection
.cnx-local unsecured − If you use this connection, it will not allow you to publish anything to the repository.
Note − In SAP BusinessObjects, most of the tools support Universe as the data source for reporting. Using a Relational connection, you can connect to any HANA database system, and import tables and views for Data Foundation Layer. Once .dfx is defined, it is required to develop a Business Layer on the top of this layer. When the Universe is published to BO server repository, it can be used by any BOBJ tool for reporting purpose.
An OLAP connection is used to connect to HANA Information view or a data model and to directly import all the business objects defined in the Business Layer for reporting.
To create a new OLAP connection, right-click the Project name → New → OLAP Connection.
In the next window, enter the Connection name, Description (Optional) and click Next.
Note − You point an OLAP connection to a specific cube or to complete HANA repository. When this connection is used in any BO Reporting tool, you can directly import all objects in HANA Modeling view or can also view all published information views in the repository and select any of them for reporting.
Next, select an OLAP middleware driver. It shows a list of all available OLAP data sources. You can select any OLAP data source as per requirement.
Note − You don't need to create a Data Foundation, as an OLAP directly hits the Business Layer. You can define dimensions, measures, and other properties at the Business Layer.
Select the suitable middleware driver to connect to OLAP data source and click Next. To connect to HANA views, select SAP HANA → SAP HANA Client.
To connect to HANA system, you need the following information −
Server Name
Instance Number
Authentication Details
When you fill the above details and click the Next button, you have an option asking if you want this connection to point to a specific cube or to all cubes in HANA repository.
Once this option is selected, click the Finish button at the bottom of the screen.
Now, you need to publish the connection to the Repository. Right-click Connection → Publish the Connection to the Repository.
When a new connection is created using Information Design tool, you have the following connection parameters that can be defined −
Connection Pool Mode − This is used to keep the connection active.
Connection Pool Mode − This is used to keep the connection active.
Pool Timeout − When you set the Connection Pool Mode to Keep the connection active for, it is the length of time in minutes to keep the connection open.
Pool Timeout − When you set the Connection Pool Mode to Keep the connection active for, it is the length of time in minutes to keep the connection open.
Array Fetch Size − This tells the maximum number of rows that can be fetched from the database.
Array Fetch Size − This tells the maximum number of rows that can be fetched from the database.
Let us consider an example. You enter a value of 25 and your query returns 150 rows. Hence, it will be fetched with 6 fetches of 25 rows each.
Array Bind Size − This field is not required for designing the Universe in IDT.
Login Timeout − It determines the minutes a connection attempts timeout and an error message is displayed.
There are various custom parameters that can also be defined such as ConnectInit, Hint.
SAP HANA Modeling is one of the key capabilities of HANA system. This allows to create multidimensional objects on top of HANA database objects to meet the business requirements for reporting. You can implement complex business logic using HANA information models to create a meaningful report for analysis.
SAP HANA Modeling is one of the key concepts in HANA BI reporting.
Using HANA Modeling, you can create complex data models as per business requirement to provide multiple views of transactional data stored in physical tables of HANA database.
Using HANA Modeling, you can create complex data models as per business requirement to provide multiple views of transactional data stored in physical tables of HANA database.
SAP HANA Modeling can only be done for column-based storage tables.
SAP HANA Modeling can only be done for column-based storage tables.
HANA Modeling views can be used directly by SAP BusinessObjects reporting tools such as Crystal Reports or Lumira using an OALP or HTTP connection.
HANA Modeling views can be used directly by SAP BusinessObjects reporting tools such as Crystal Reports or Lumira using an OALP or HTTP connection.
HANA supports different types of Modeling views such as - Attribute view is used to model characteristics, Analytic view is used to implement Star schema and Calculation view is used to implement complex logics, which are not possible with other type of views (Galaxy schema).
HANA supports different types of Modeling views such as - Attribute view is used to model characteristics, Analytic view is used to implement Star schema and Calculation view is used to implement complex logics, which are not possible with other type of views (Galaxy schema).
SAP HANA Modeling views can also be directly connected to third party tools such as MS Excel using HANA MDX Provider.
SAP HANA Modeling views can also be directly connected to third party tools such as MS Excel using HANA MDX Provider.
SAP HANA Modeling supports various features of Business Layer - Creating new calculated columns, new measures, input parameters, hierarchies, etc.
SAP HANA Modeling supports various features of Business Layer - Creating new calculated columns, new measures, input parameters, hierarchies, etc.
SAP HANA provides following three types of Information Views −
Attribute View
Analytic View
Calculation View
All HANA Modeling objects are stored in HANA Repository and it can be directly accessed using any BI tool via proper authentication. When these objects are imported in any of the reporting tools using an OLAP or HTTP connection, it also imports all the custom properties of that model.
SAP HANA suite also offers basic BI reporting functionalities, where you can create interactive charts using data in HANA models.
Like other BI reporting tools, you can add dimension and measure values to Label and Value axis. HANA provides the following options for BI analysis −
Analysis − This tab is used to add different dimension and measure values to different label axis. Filters can be applied as per business requirement.
Analysis − This tab is used to add different dimension and measure values to different label axis. Filters can be applied as per business requirement.
Distinct Values − This tab is used to see distinct values in data analysis for each of dimension.
Distinct Values − This tab is used to see distinct values in data analysis for each of dimension.
Raw Data − This tab shows all raw data coming from data model as per Business Layer parameters.
Raw Data − This tab shows all raw data coming from data model as per Business Layer parameters.
In a BI report, you can select from the following options: Chart, Table, Grid, or HTML.
In SAP HANA, input parameters are used to filter the data by passing an input from the user and to perform additional calculations at run time. The data is fetched based on the input value, when a view is executed.
Consider a scenario where an Input parameter is applied on the "Sold_Qty", i.e. when the Sold_Qty is greater than 20, then there is 10% discount on Total_Price. Otherwise, it remains the same.
Input parameters are created in HANA Modeling views using SAP HANA Studio. When these views are used in any BO reporting tool and the report is refreshed, users are prompted to pass an input value for a particular field. To create a new parameter, navigate to the Semantic section of HANA Modeling view.
Navigate to Parameters/Variables tab in the Semantic layer and click the "+" sign. Select Create Input Parameter as shown in the following screenshot.
This will open a new dialog box. Enter the technical name and description of the Input parameter. Select the Input Parameter type from the dropdown list.
We have the following input parameter types in HANA −
Direct − Using this parameter type, you can pass any value for the parameter.
Direct − Using this parameter type, you can pass any value for the parameter.
Column − This parameter type allows you to select any value from the list of distinct values available in a column in HANA view.
Column − This parameter type allows you to select any value from the list of distinct values available in a column in HANA view.
Derived from table − It is also possible to create dynamic values in a table and allows you to select any of available value from the list.
Derived from table − It is also possible to create dynamic values in a table and allows you to select any of available value from the list.
Static List − It is also possible to create a static list of values and provide an input during execution.
Static List − It is also possible to create a static list of values and provide an input during execution.
Note − You can also select the checkbox to make an Input Parameter a mandatory option.
You can select the data type of the input value, so that the system only accepts allowed value type for this field. This option varies as per parameter type. Following data type options are available −
Currency
Unit of Measure
Date
You can also pass Input parameter using SQL query. To view SQL query, navigate to the Data Preview tab of HANA Modeling view. Input parameter using SQL is passed using "PLACEHOLDER".
Next, click the "Show Log" and then double-click the message highlighted below. This will open a new window with the following SQL query.
('PLACEHOLDER' = ('$$ Sold_Qty $$', '20'))
WHERE ("REGION_NAME" IN ('NA') )
GROUP BY "NET_AMOUNT", "PROFIT";
In SAP HANA, Attribute Views are used to model characteristics. They are used to join Dimension tables or other Attribute Views. You can also copy a new Attribute View from the already existing Attribute Views inside other Packages, but that doesn't let you change the View Attributes.
Following are the key characteristics of HANA Attribute view.
Attribute Views are used in Analytical and Calculation Views for analysis to pass the master data.
Attribute Views are used in Analytical and Calculation Views for analysis to pass the master data.
They are similar to characteristics in BM and contain the master data.
They are similar to characteristics in BM and contain the master data.
Attribute Views are used for performance optimization in large size Dimension tables. You can limit the number of attributes in an Attribute View, which are further used for reporting and analysis purpose.
Attribute Views are used for performance optimization in large size Dimension tables. You can limit the number of attributes in an Attribute View, which are further used for reporting and analysis purpose.
Attribute Views are used to model the master data to give some context.
Attribute Views are used to model the master data to give some context.
In SAP HANA, all modeling objects are created inside the package and stored in HANA Repository. Choose the Package name under which you want to create an Attribute View. Right-click Package_Name → Go to New → Attribute View...
When you click Attribute View, a new window will open. Enter Attribute View name and description in this window and from the dropdown list, choose View Type and Sub-type.
Following are the categories of Attribute View sub-type −
Standard
Time
Derived
If you want to copy an existing Attribute view, you can use the "Copy From" option. When you click the "Copy From" option, it shows all other Attribute views that you can use to create a copy.
Time sub-type Attribute View is a special type of Attribute view that adds a Time Dimension to Data Foundation. When you enter the Attribute name, type, and sub-type and click Finish, it will open three work panes −
Scenario pane that has Data Foundation and Semantic Layer.
Scenario pane that has Data Foundation and Semantic Layer.
Details pane that shows the attribute of all tables added to Data Foundation and joining between them.
Details pane that shows the attribute of all tables added to Data Foundation and joining between them.
Output pane where you can add attributes from the Detail pane to filter in the report.
Output pane where you can add attributes from the Detail pane to filter in the report.
You can add Objects to Data Foundation, by clicking the '+' sign written next to Data Foundation. You can add multiple Dimension Tables and Attribute Views in the Scenario Pane and join them using a Primary Key.
When you click Add Objects "+" sign in Data Foundation, you will get a search bar from where you can add Dimension tables and Attribute views to the Scenario Pane. Once Tables or Attribute Views are added to Data Foundation, you can see all the columns on the right side pane. They can be joined using a Primary Key in the Details Pane as shown in the following screenshot.
Once the joining is complete, choose multiple attributes in the details pane, right-click and Add to Output. All columns will be added to the Output pane. Now click the Activate option and you will get a confirmation message in the job log.
Now you can right-click the Attribute View and go for Data Preview. Once you click Data Preview, it will show all the attributes that has been added to the Output pane under Available Objects.
SAP HANA also provides reporting feature for data analysis. These Objects can be added to Labels and Value axis by a right-click or by dragging the objects as shown in the following screenshot.
Analytic View is in the form of Star schema, wherein we join one Fact table to multiple Dimension tables. Analytic views use real power of SAP HANA to perform complex calculations and aggregate functions by joining tables in the form of Star schema and by executing Star schema queries.
Following are the key characteristics of SAP HANA Analytic View −
Analytic Views are used to perform complex calculations and Aggregate functions such as Sum, Count, Min, Max, etc.
Analytic Views are used to perform complex calculations and Aggregate functions such as Sum, Count, Min, Max, etc.
Analytic Views are designed to run Star schema queries.
Analytic Views are designed to run Star schema queries.
Each Analytic View has one Fact table surrounded by multiple dimension tables. Fact table contains a primary key for each Dim table and measures.
Each Analytic View has one Fact table surrounded by multiple dimension tables. Fact table contains a primary key for each Dim table and measures.
Analytic Views are similar to Info Objects and Info sets of SAP BW.
Analytic Views are similar to Info Objects and Info sets of SAP BW.
SAP BusinessObjects reporting tools can connect to Analytic view using an OLAP connection for reporting and dashboard.
SAP BusinessObjects reporting tools can connect to Analytic view using an OLAP connection for reporting and dashboard.
In SAP HANA, you can create an Analytic view to implement Star Schema queries. All these objects are created inside a Package and published to HANA Repository.
To create a new Analytic view, select the Package name under which you want to create it. Right-click the Package → Go to New Tab → Analytic View. When you click an Analytic View, a new window will open. Enter the View name and Description and from the dropdown list and choose the View Type and finally click Finish.
When you click Finish, you can see an Analytic View with Data Foundation and Star Join option. To add tables to the Analytic view, click the Data Foundation to add Dimension and Fact tables. Click the Star Join to add Attribute Views.
Add Dim and Fact tables to Data Foundation using "+" sign. In the following example, we have added 3 dim tables to Data Foundation: DIM_CUSTOMER, DIM_PRODUCT, DIM_REGION and 1 Fact table FCT_SALES to the Details Pane. A Join is applied to connect Dim tables to the Fact table using Primary Keys stored in the Fact table.
Select Attributes from Dim and Fact table to add to the Output pane as shown in the following screenshot. Change the data type of Facts, from the fact table to measures.
Navigate to the Semantic layer, select dimension and measures and click the data type if it is not picked by default. You can also use Auto-detection. Next, activate the View.
To activate the view, click the Arrow mark at the top (F8) button. Once you activate the view and click Data Preview, all attributes and measures will be added under the list of Available objects. Add Attributes to Labels Axis and Measure to Value axis for analysis purpose.
Calculation views are used to perform complex calculations, which are not possible with Attribute or Analytic view. You can also use Attribute and Analytic views while designing Calculation views.
Following are a few characteristics of Calculation Views −
Calculation Views are used to consume Analytic, Attribute, and other Calculation Views.
Calculation Views are used to consume Analytic, Attribute, and other Calculation Views.
There are two ways to create Calculation Views - Using SQL Editor or Graphical option.
There are two ways to create Calculation Views - Using SQL Editor or Graphical option.
It has built-in Union, Join, Projection, and Aggregation nodes.
It has built-in Union, Join, Projection, and Aggregation nodes.
SAP BusinessObjects reporting tools can connect to Calculation view using an OLAP connection for reporting and dashboard.
SAP BusinessObjects reporting tools can connect to Calculation view using an OLAP connection for reporting and dashboard.
Choose the Package name under which you want to create a Calculation View. Right-click the Package → Go to New → Calculation View. When you click the Calculation View, a new window will open.
Enter the view name, description and choose the view type as Calculation View, Sub-type Standard or Time (this is a special kind of View, which adds time dimension). You can use two types of Calculation View - Graphical and SQL Script.
Calculation view provides an option of using a Star Join or not to use a Star Join. Also, it has two different Data Categories −
Cube − When a user selects Cube as data category, the default node is Aggregation. You can choose Star Join with Cube dimension.
Cube − When a user selects Cube as data category, the default node is Aggregation. You can choose Star Join with Cube dimension.
Dimension − When a user selects Dimension as data category, the default node is Projection.
Dimension − When a user selects Dimension as data category, the default node is Projection.
When you use Calculation view with Star Join, it does not allow base column tables, Attribute Views, or Analytic views to add at data foundation. All Dimension tables must be changed to Dimension Calculation views to be used in Star Join. All Fact tables can be added and can use default nodes in Calculation View.
The following example shows how we can use Calculation View with Star Join.
You have four tables, two Dim tables, and two Fact tables. You have to find a list of all employees with their Joining date, Emp Name, empId, Salary, and Bonus.
It simplifies the design process. You need not create Analytical views and Attribute Views. Fact tables can be directly used as Projections.
It simplifies the design process. You need not create Analytical views and Attribute Views. Fact tables can be directly used as Projections.
3NF is possible with Star Join.
3NF is possible with Star Join.
This allows the use of other Attribute views and Analytic views using different nodes available in Calculation Join.
In the above screenshot, you can see two Analytic views - AN_Fact1 and AN_Fact2 - are used using node Projection 1 and Projection 2 and then joined with the help of a Join node.
SAP HANA is an in-memory database that supports all the features of a conventional database. You can perform all DDL, DML, and DCL statements on database objects. Users can create new tables, views, functions, triggers, and all other database functions using HANA Studio front-end.
Tables in HANA database can be accessed from HANA Studio in Catalogue tab under Schemas. New tables can be created using the following two methods −
Using SQL editor
Using GUI option
All the database objects - tables, views, and other objects can be used to design a Universe - Data Foundation layer and later to publish Business Layer to BO repository for BI reporting.
In SAP HANA Studio, open SQL editor by selecting the Schema name and click the circled option in the following screenshot. You can run all SQL queries in SQL editor, which are required to perform conventional database functions. You can create new tables, views by writing the CREATE command in the editor window or right-click the Schema name and write the following Create script.
Following is the Create table SQL command that can be used to create a column table in HANA database.
Create column Table Sample1 (
Cust_ID INTEGER,
Cust_NAME VARCHAR(10),
PRIMARY KEY (Cust_ID)
);
To insert the data, run the Insert statement in SQL editor. "Sample" is the table name.
Insert into Sample Values (101,'Jon');
Insert into Sample Values (201,'Tina');
Insert into Sample Values (301,'Jacob');
When the data is entered, you can see the data in this row-based table by going to Data Preview option. To see the data, right-click the table name → Open Data Preview.
All the database objects in SAP HANA system are maintained in CATALOG folder in HANA Studio. Following are the key capabilities of SAP HANA database system −
You can use high performance in-memory database for processing complex transactions and analytics. You can manage large database volumes in multitenant database containers.
You can use high performance in-memory database for processing complex transactions and analytics. You can manage large database volumes in multitenant database containers.
SAP HANA system combines OLAP and OLTP processing into a single in-memory database. It removes the disk bottlenecks, offering groundbreaking performance.
SAP HANA system combines OLAP and OLTP processing into a single in-memory database. It removes the disk bottlenecks, offering groundbreaking performance.
Using SAP HANA in-memory database component, you can run advanced analytical queries, which are complex in nature with high-speed transactions to get the correct, up-to-date responses in a fraction of a second.
Using SAP HANA in-memory database component, you can run advanced analytical queries, which are complex in nature with high-speed transactions to get the correct, up-to-date responses in a fraction of a second.
All the 2-dimensional objects exist in schemas in HANA database. Schemas are shown under the Catalog folder in HANA Studio. When you expand any of the schema, you can see different Relational objects - functions, indexes, views, and synonyms inside it.
If you open SAP HANA cockpit using the following link, you can see different database functions in HANA system: https://best:4303/sap/hana/admin/cockpit
To create a view in one table, write the following SQL statement.
create view view_name as
select ARTICLE_ID,ARTICLE_LABEL,CATEGORY,SALE_PRICE
from "AA_HANA11"."ARTICLE_LOOKUP";
You can drop a view using the Drop command, like we drop a table.
Drop view "AA_HANA11"."DEMO_TEST";
In older versions of SAP BusinessObjects (4.1 or earlier), the only option to connect Webi with HANA is with the use of the Universe. The Universe is designed on top of HANA views and then using Webi query panel, we can use objects in Webi report.
With the release of SAP BO 4.2, SAP provides multiple ways to connect Webi report to HANA views. Following are the four ways to connect Web Intelligence to HANA Modeling views −
Using Universe on top of HANA Modeling Views
Direct Webi connection with HANA Modeling views
SAP HANA Online connectivity
Using Free-Hand SQL
As mentioned earlier, we can develop HANA Views - Attribute, Analytic and Calculation views - using HANA Studio. To create a Universe, you have to create a Relational connection pointing to HANA DB schemas.
To create a new Relational connection, first start with a new project under Local Project view. Open Information Design Tool → Click New → Project → Enter the Project Name → Finish. This will create a new Project under Local Projects window.
Next, right-click the Project name → New → Relational Connection.
In the next window, enter Connection Name → Enter the connection/resource name → click Next.
You will be prompted to select a Middleware for connection. Select the middleware as per data source. You can select SAP or non-SAP as data source and set up a relational connection to the database.
Here, we have selected SAP from the list → SAP HANA database → JDBC → click Next.
In the next window, enter the Authentication mode, user name and password. Enter SAP HANA host name and Instance number, then click Next.
In the following window, define connection parameters such as - Time out, Array fetch size, Array Bind size, etc. Click Finish.
When you click the Finish button, this will create a new Relational Connection pointing to SAP HANA database with .cnx file extension. You can click Test Connection. The lower part of the Window tells you about connection parameters - Login parameters, configuration parameters, etc.
Click Test Connection → Successful. You have to publish this connection to the Repository to make it available for use.
To publish this connection, right-click the connection name → Publish connection to Repository → Enter BO repository password → Connect → Finish → Yes.
Now, create a Data Foundation using SAP HANA view. Right-click Connection name → Select New → Data Foundation.
Enter Resource Name and click Next. You can select Single source enabled or multi-source enabled as the data foundation type. Select multisource-enabled and pass the authentication details after selecting the connection.
After you click Next, select _SYS_BIC schema node, where all HANA views and column tables are stored. Add the required view from HANA to Data Foundation layer. You can develop the Business Layer on top of this data foundation, and it can be published to BO server repository for reporting purposes.
This feature is added to SAP BO 4.2 recently which allows direct connection to HANA Modeling views using an OLAP connection. When you connect to HANA Repository using an OLAP connection, you can connect to all Packages created in HANA system. You can select any of the package → Navigate to HANA views stored in the package.
Once these steps are performed, all dimensions and measures are added to the Query Panel in Webi. The developer can select any of the result objects from the list of available objects and click the run query to add those Webi report.
In SAP BO 4.2, there is an option of using HANA Online Connection that allows Webi client to connect directly to HANA views. There is no need to build a Webi query for using HANA Online connection option.
This option lists Relational connection only and when the connection is selected, it shows all the packages and corresponding views. When HANA view is selected, it directly connects to Webi Reporting Layer. There is no use of Query panel in this scenario.
In SAP BO 4.2, a new option - free-hand SQL - is introduced in Web Intelligence that connects directly to HANA views. When you connect using a Web Intelligence tool that connects using Free-hand SQL option, a tool lists down all HANA Relational connection from BOBJ server. When you select a Relational connection, a tool provides a query script editor to write the query.
To use Free-Hand SQL option, select a new Webi document, and in the data source list select Free-Hand SQL option.
Once you select this option, a query editor opens up. You can write a SELECT query to form Webi Query for reporting. On the right side, you have a Run Query option and the list of available objects in Webi tool.
To create a Universe in IDT, go to Start → All Programs → SAP Business Intelligence → SAP Business Objects BI Platform 4 Client Tool.
In Information Design Tool, you have to create a New Project. Go to File → New → Project. Enter the Project Name and Click Finish.
Once the project is created, next is to create an OLAP or Relational connection to connect to a data source - SAP HANA in this case. A Relational connection is used to connect to the Database layer to import tables and joins. An OLAP connection is used to connect to the multidimensional model like an Information View in SAP HANA.
Right-click on Project name → New → Select Relational Connection → Enter connection/resource name → Next. Select SAP from the list → SAP HANA → Select Drivers JDBC → Next → Enter details.
Enter the system details, username, password, and click Next. Then, click Finish. Under General Information → Click Test Connection → Successful.
You have to publish this connection to the Repository to make it available for use. Right-click the connection name → Publish the connection to the Repository → Enter BO repository password → Click Connect → Finish → Yes.
The next step is to create a Data Foundation Layer on this secure connection. Right-click .cns Repository connection → Click New Data Foundation.
Enter Resource Name and click Finish. It will show you a list of all available schemas in the database. You can add Tables and Joins from Schema to Data Foundation layer. This can be done by dragging the table or by a double-click. Apply the joins on Dimension and Fact tables to create a logical schema.
To define a Join, double-click the Join between tables. It will show you both the tables. You can select from different Joins as per data requirement and click Detect Cardinality to define the cardinality - 1:1, 1:n, n:n.
Next is to create a Business Layer on the Data Foundation. Click the Save All icon at the top of the screen. Then, right-click Data foundation .dfx → New Business Layer. Enter Resource Name → (Generating Business Layer for Data Foundation) Finish. It will add Business Layer .blx under the Local Project.
It will show a list of all dimensions and measures under Data Foundation. Define dimensions, measures, aggregation, etc.
To define an Aggregation, select from the Projection Function. You can hide few objects in the report if you want using the dropdown next to measures and dimension. You can select Hidden for a particular object.
Once you define the Business Layer, click Save All icon at the top of the screen as shown in the following screenshot. To publish a Universe to the Repository, right-click .blx → Publish → To a Repository.
Select Resources, then click Next. In the Publish Universe window, select Next → Select the Repository folder where you want to publish the Universe and click Finish.
In Universe Designer, it is also possible to create user prompts and filters in Business View Layer. Prompt is defined in Business Layer or Data Foundation that requires a user input or predefined input value.
A Prompt can have the following input types −
User input as a response to the prompt
A predefined fixed value
Prompt has the following properties.
Prompt to Users
If selected, the user is prompted to enter a value at runtime.
If cleared, a pre-defined value is entered at runtime for the parameter.
Prompt Text
The text for the prompt question or directive, if Prompt to Users is selected.
Set Values
Available when the Prompt to Users option is unselected. Allows to enter one or more values to be used for the parameter at the runtime.
Data Types
The data type required for the answer to the prompt.
Allow Multiple Values
If selected, allows the user to take multiple values from the list of values.
Keep Last Values
If selected, the last value chosen by the user is kept, when the prompt is re-run.
Index Aware Prompt
If selected, the key column is included in the prompt to restrict the values in a list. The key column is not visible to the user.
Associated List of Values
A list of values to provide values for the prompt.
Select Only from the List
If selected, the user is forced to select a member in the list.
Select Default Value
Allows to select values to be used as default.
In the Universe Designer, you can add a Prompt in Data Foundation and they are directly inherited to the Business Layer on top of Data foundation. Note: If there is a need to edit a Prompt, it can't be done in the Business Layer. You have to open Data Foundation for the same.
To insert a Prompt, click parameters and List of Values (LOVs) tab in the browsing pane → Click Insert Parameter icon.
It is possible to use LOVs, i.e. you can select the value of a prompt from the list of values associated with an object. It allows a data set to be restricted to the selected values. You can use LOVs for an object in Data Foundation or Business Layer. Different types of LOVs can be used.
LOVs based on Business Layer Objects. In this case, LOV is based on other query or on a hierarchy that includes −
Static LOVs − It includes a list of specified values manually or imported from the file.
Static LOVs − It includes a list of specified values manually or imported from the file.
LOVs based on SQL − It is a value returned by a specific SQL expression.
LOVs based on SQL − It is a value returned by a specific SQL expression.
Following properties can be edited for LOVs −
Column Name − This is used to edit the name of the column.
Column Name − This is used to edit the name of the column.
Key Column − You can select a column to be the index aware key.
Key Column − You can select a column to be the index aware key.
Data Type − This is used to define the data type for the column.
Data Type − This is used to define the data type for the column.
Hidden − When this option is selected, the column will not be displayed.
Hidden − When this option is selected, the column will not be displayed.
When the Universe is published to BO repository based on SAP HANA views, it can be directly used for reporting using the Query Panel. Universe contains data from SAP HANA/SAP BW or non-SAP data sources. Let us see how to build a query using the Universe.
Open Web Intelligence via BI Launchpad → Click New (Create a new Webi document). You will be prompted to select a Data Source.
Select a Universe as the data source and click 'Ok'. You will get a list of all available Universe. Select a Universe created on top of HANA view, which you want to use to create a Webi document. This will open a new window - Query Panel. In the query panel, on the left side of the screen, you will have a list of available objects. You will have Result Objects where you drag the objects from the left panel, which you want to add in a Webi document.
There will be Query Filter using which you can add different filters. Data Preview can be used to view data before it is added to Webi document. The Run Query tab at the top of the screen is used to run the query.
You can also add data from multiple sources in a single Webi document by adding multiple queries to the Query panel. You can add a new query by clicking the Add Query option. You again have the option of selecting a data source, from which you want to add a new query.
When you click the Run Query option on the top right corner of the screen, all the result objects will be added to the Webi document.
It is possible to connect to SAP HANA Modeling Views in SAP Lumira with a direct connection. You need to have HANA Host name, Instance/Port number, User name and password to connect. This can be done in the following two ways −
Connect to SAP HANA
Download from SAP HANA
It will show you all the HANA Modeling Views that have been recently used. Click the Next command button after selecting the option "Connect to SAP HANA". This will allow you to access the data in read mode and you can visualize the data in the form of charts.
You should know the following details of HANA system −
Host Name
Instance/Port Number
User Name and Password
Once you enter the details, click the Connect button.
Now, enter the dimensions and measures you want to add to the dataset. Click Create button. This will add data to the Prepare tab.
These objects can be directly used for dashboard development in Lumira to create new stories.
When you select a dataset in Lumira from HANA Repository, it is added to the Prepare tab. You can make changes to the dataset and once it is finalized you can move to "Visualize" tab to create interactive charts in Lumira on top of HANA Modeling views.
Follow are the steps to add a chart: Navigate to the "Visualize" tab and go to Chart Builder.
Select a chart type that you want to use in the Chart Builder. Bar Chart is the default chart type, but you can select any chart from the list.
The next step is to choose a measure and drag it to an axis on the Chart Canvas. To add a measure or dimension to the corresponding axis, click the '+' sign next to the axis name.
Select a dimension and add to the chart canvas or you can also drag it to the Chart Canvas. The text in the chart body guides you to the correct axis for the dimension.
Following chart types are available in SAP Lumira −
Comparison − These chart types are used to compare the difference between values. Common comparison chart types are −
Bar Chart
Column Chart
Radar Chart
Area Chart
Heat map
Percentage − These are used to show a percentage of parts in a chart. Common percentage type charts are −
Pie Chart
Donut Chart
Tree
Funnel Chart
Correlation − These are used to show the relationship between different values. Common chart types are −
Scatter Plot
Bubble Chart
Network Chart
Numeric Point
Tree
Trend − These are used to show the data patterns or possible patterns. Common chart types are −
Line Chart
Waterfall Chart
Box Plot
Parallel Coordinates Chart
Geographic − These are used to present the map of a country or globe present in the analysis. Common chart types are −
Geo Bubble Chart
Geo Choropleth Chart
Geo Pie Chart
Geo Map
You can connect to SAP HANA using Universe connectivity from the Dashboard. SAP Dashboard supports SAP HANA backed with the Universe created on top of HANA views and tables. You can consume Universe Designer .unx files using Query Browser option to develop the dashboard.
Query browser provides a flexible option to create a query on Universe and the results are embedded into a spreadsheet and bound dashboard components in the Dashboard Designer.
Open Dashboard Designer → File →New.
This opens a new untitled page with components, properties, object browser and a query browser pane. To add a query, click the Add Query button.
This will open a new dialog box that provides different options to select a data source - Universe on which you want to build a query. The Universe is built on top of HANA Views or tables using Universe Designer to create Data Foundation, and then the Business Layer is published to BO server.
Click Select a Universe on which you want to build a query and then click Next. It will take you to the next page, where you can build a query on the selected Universe.
In the next window, you have to select Result Objects from the Universe pane. Once you complete your query building, you can also check the preview of the result set using "Data Preview / Result Set pane" by clicking the refresh button. This shows you query run time and a number of rows fetched as shown in the following screenshot.
You have Usage Options tab at the top - which provides Refresh Option and Load Status. Refresh Option defines how the query will be refreshed. Load Status is used to define the Load status and configuration setting when the Dashboard is loading or is in idle status.
When the query is built on top of the Universe, next is to bound the result into a spreadsheet and map the Dashboard components with data. Now to insert the query result into a spreadsheet, select a particular result object and use the option "Insert in Spreadsheet" at the left bottom corner of the screen. This will bind the result set of that object to the "Select Range" dialog box.
In the above screenshot, you can see .unx file that shows the Universe name on which the query is created. Below that you have Result Objects - objects selected at the time of query building. On the right side of the screen, you have a spreadsheet where the result set from the query is bound.
To use Crystal Reports on top of SAP HANA views, you can use an OLAP connection, which directly points to the Business Layer in HANA Views. You can also connect to the Universe directly, which is created on top of SAP HANA views and tables. Crystal Reports can connect to multiple data sources that include −
Universe
SAP BEx Query
HANA view
Excel Spreadsheets
To connect to a data source, go to File → New → From Data Source.
Following are the three ways in which you can connect Crystal Reports to HANA system - Database layer or HANA views.
Crystal Reports 2011 SP4
JDBC
ODBC
Command objects and SQL
Expressions are available
Crystal Reports for Enterprise
4.0 SP4
JDBC
ODBC
Direct-to-data connections are available with FP3 and higher
Crystal Reports for Enterprise
4.0 SP4
Universe (.unx)
Relational Universe
Following are the scenarios, which define the direct connectivity to HANA or the use of a Universe −
When you already have a Universe published with the Business Layer
When a HANA view with a variable is required
When a Universe is not available
When a Universe is not available
When you are using Crystal Reports 2011 and not Crystal Reports for Enterprise for reporting
When you are using Crystal Reports 2011 and not Crystal Reports for Enterprise for reporting
When you are willing to use the custom SQL query using a Command Object or SQL Expression
When you are willing to use the custom SQL query using a Command Object or SQL Expression
When you want to access stored procedures, tables and views directly
When you want to access stored procedures, tables and views directly
To develop a report on top of HANA views, you can use direct connection to HANA views. You have to select SAP HANA Platform (Select a HANA view).
Once you click the New Server... option, it will open the Server Connections window. If you have an existing connection, you can use Import Connections. You can also add a new connection by clicking the "Add" button.
Once you click the Add button, you have to enter the following details −
Connection Display Name
HANA Server
HANA Server Instance
User Name
Once you connect to HANA system, it will display all OLAP metadata in HANA repository. You have to navigate to the required package and select view that you want to use.
You can select from an Analytic View or a Calculation view. Click OK and then the Next button at the bottom of the screen.
This will open all the dimensions and measure in the query panel. You have to drag all the objects to the Result Object fields. You can also add a filter at the query panel and click Finish. Then, choose from the following options −
Generate report
Show in page mode
You can navigate to Structure and Page mode to design the report.
Once the Crystal Report is created using a query, to make changes to the objects you have to go to the Edit Data Sources... option. When you click the option, it will open an Edit Query panel, where you can add/delete objects, apply filters, etc.
You can also edit an existing query by going to Data → Edit Data Sources as shown in the following image.
Once you are done with the changes, click Finish and all the changes will be applied to the data in the Crystal Report.
Using BW powered by SAP HANA, you can achieve excellent performance in analytical reporting and data loading using HANA in-memory database capabilities. All BW functions performed in SAP HANA benefits from in-memory database and calculation engines for faster data processing.
To create a BW Project in HANA, you can use SAP HANA Studio. Go to Windows → Open Perspective → Other.
Select BW Modeling → Click OK as shown in the following screenshot.
Next, go to File → New → Project.
In the next window, select SAP connection. You can select an existing connection or define a connection manually to add a new connection. System connections are maintained in the SAP Logon. Click OK.
In the next screen, as shown in the following screenshot enter the client, username and password. Click Next.
Now, enter the project name and click Finish.
Right-click your new root project folder and choose Attach SAP HANA System. Choose the preconfigured HANA system HDB and click Finish. Only connected SAP HANA system can be attached. Select HANA system → Finish.
To define a BW query on your InfoCube, select the InfoCube in BW Modeling Perspective, right-click and click New → BW Query and select the InfoProvider.
Enter the name and description and then click Finish. This is how you can add a BW query.
You can apply different functions in BW query. You can apply filters, define local formulas for calculation, etc.
To save BW query, click the Save button at the top of the screen.
Using SAP Design Studio, you can create new Analysis applications. SAP Design Studio provides a list of predefined template suitable to open in the web browser.
You can create an analysis application using different data sources - SAP BW or SAP HANA. To connect to SAP HANA, use the existing backend connections. Navigate to Tool → Preferences.
In the Preferences window, navigate to Application Design tab → Backend Connections.
To create a new connection to SAP HANA using HDB ODBC drivers, click the icon to add a connection.
In the ODBC Data Source Administrator, go to System DSN → click Add.
In a new window, search for the HDB ODBC database drivers. These drivers get installed when you install SAP HANA client. Click the Finish button.
In the new window, enter the following details of the HANA system.
HANA Host name
Port Number/Instance Number (3xx15, xx-instance number)
User name and Password for authentication and click OK
To perform the connection check, click the Connect button → Connection Successful. To see the new connection, click the Reload connection. To use the connection, you may need to reopen the Design Studio.
SAP Design Studio provides predefined templates that can be used to create new Analysis applications. These predefined templates are suitable to open in Web browsers or mobile platforms.
To create a new analysis application, navigate to Application → New.
In the next window, enter the Name of the application and Description. You can select the Template category.
SAP Design Studio also provides you the brief description of each template with the template name. Select the template and click the Finish button.
To create a dashboard, navigate to the Components view tab. Select any component from the list of available objects, and drag the component of your choice into the editor area.
The properties of this component are available for editing under the Properties view. In the Properties view, click the property you want to change. A field can have different values as per the following types −
Numeric − Such as layout properties
Numeric − Such as layout properties
String − Such as caption, etc.
String − Such as caption, etc.
Boolean − Such as True/False from the dropdown for Style, etc.
Boolean − Such as True/False from the dropdown for Style, etc.
Dialog Box
Dialog Box
To add data to your chart, navigate to Data Binding and select a data source from the list.
Similarly, you can define other properties of your chart. Following properties can be defined −
General
Display
Events
Layout
Once you assign a data source and manage chart properties, you can save the application by clicking the Save button at the top.
You can also connect to a Universe in Design Studio, which is based on SAP HANA views and tables. To connect to a Universe Data Source (UDS), go to the Data Source folder under Outline in a new analysis application → Right click → Add Data Source.
Let us see how to add a Universe as a data source. Click the Browse tab against Connection in the Add Data Source window.
Once you select a Universe, edit the query panel. Click the Edit Query specification. Add the dimensions and measures to result objects. You can expand each of these folders in the left pane and add objects to dimensions and measures.
You can add this data source to chart components or you can also go to Edit Initial View of data source and select Create Crosstab.
A Crosstab has been added to the editor area and this is how you can connect to the Universe based on SAP HANA views or tables.
It is possible to publish BI reports and dashboards to HANA BI platform. You can also publish dataset in SAP Lumira to HANA platform.
In SAP Lumira, you can see the saved dataset in Share tab under Dataset. To publish a dataset, navigate to Publish to SAP HANA.
To publish to HANA, you have to note that the only dataset is published to HANA server and not visualizations. Enter the details of HANA system, i.e. Server, Instance, User Password and click Connect.
You have an option to select a new Package and a View.
SAP HANA is an in-memory database that provides exceptional calculation capabilities, analytical reporting, and real-time application development. Key capabilities of SAP HANA is mentioned on SAP site link − https://www.sap.com/products/hana/features.html
Following are the advantages of using SAP HANA −
SAP HANA in-memory database services provide the capability of processing high-speed transactions and analytics. It helps in managing large database volumes using multitenant database containers and dynamic tiering across multi-tier storage.
Using HANA in-memory processing capability - text, predictive, spatial, graph, streaming, and time series - you can get answers to any business question and make smart decisions in real time.
Using SAP HANA, you can develop next-generation applications that combine analytics and transactions, and deploy them on any device.
SAP HANA helps the organization in getting accurate and complete view of business by accessing data from different sources. HANA provides real-time data replication and data quality to improve decision making from internal and external data sources.
SAP HANA ensures application availability and tools to monitor processes along with data and application security.
SAP HANA provides a dashboard to monitor all KPIs related to security. It helps in keeping communications, data storage, and application services secure with robust identity and access management control.
There are various certified and non-certified non-SAP BI tools that can connect to SAP HANA system for analytical reporting and dashboard requirements. Various tools such as Tableau, Microsoft Excel, and other BI tools can directly connect to HANA using custom SQL query, direct connection, or MDX provider for connection.
Let us see how we can connect Tableau and MS Excel to connect to HANA system for reporting.
You can connect Tableau to SAP HANA database and set up a data source for reporting. You have to install a driver to talk to the database and require HANA system details and authentication method.
Before you connect to HANA system, you should check the following prerequisites −
A driver should be installed for HANA to talk to the database. If the driver is not installed and you try to connect, Tableau displays an error message with a link to the Driver Download page. You can install drivers for Tableau connectivity from the following link −
https://www.tableau.com/support/drivers
Once you have the drivers installed, start Tableau desktop tool. Under Connect category, select SAP HANA. For a complete list of data connections, click More option.
Next, enter the name of the server that hosts the database you want to connect to and the authentication details.
You can also see an option of Initial SQL that specifies a SQL command to run at the beginning of every connection.
In the next window, select the Schema name from the dropdown list. You can also use the Search option at the top of the screen to find a particular schema. Once you select the schema name, add the table to the report canvas.
Drag the table to the canvas, and then select the sheet tab to start your analysis. By default, column labels are displayed instead of column names.
You also have an option to use Custom SQL option that allows you to connect to specific query and not to a full database.
You can also connect Microsoft Excel to HANA views using a MDX provider. MS Excel is considered as one of the most common BI reporting tool. Business users can connect to HANA database and draw Pivot tables and charts as per requirement.
Open Excel and navigate to Data tab → Click the option from other sources → Click Data connection wizard → Other/Advanced. Click Next and the Data link properties will open.
Next, select SAP HANA MDX Provider from this list to connect to any MDX data source → Enter HANA system details (server name, instance, user name and password) → Click Test Connection → Connection succeeded → OK.
Once you connect to HANA system, you can see a list of all packages in the dropdown list that are available in HANA repository. You can select an Information view → Click Next. Then, select Pivot table/others → OK. On the right side of the screen, you will see all the dimension and measure values that you can use to create charts.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2640,
"s": 2311,
"text": "SAP HANA is an in-memory database which also provides HANA Modeling, Data Provisioning, and BI reporting features in a single application. SAP HANA is mostly used as a Data Warehouse for many organizations with Transaction system. SAP is providing HANA as a backend database for various different ERP and CRM based applications."
},
{
"code": null,
"e": 2688,
"s": 2640,
"text": "Following are a few common HANA based modules −"
},
{
"code": null,
"e": 2730,
"s": 2688,
"text": "S/4 HANA (S/4 HANA Finance and Logistics)"
},
{
"code": null,
"e": 2747,
"s": 2730,
"text": "SAP Business One"
},
{
"code": null,
"e": 2757,
"s": 2747,
"text": "SAP Fiori"
},
{
"code": null,
"e": 2999,
"s": 2757,
"text": "SAP HANA Data Modeling helps the user to model the application data and perform database functions such as creating schemas, tables, and views at run time. HANA data models are stored in HANA Repository and objects are activated at run time."
},
{
"code": null,
"e": 3130,
"s": 2999,
"text": "This is SAP site link for HANA Product details that shares all key features HANA provides − https://www.sap.com/products/hana.html"
},
{
"code": null,
"e": 3564,
"s": 3130,
"text": "According to SAP - \"Deployable on premise or in the cloud, SAP HANA is an in-memory data platform that lets you accelerate business processes, deliver more business intelligence, and simplify your IT environment. By providing the foundation for all your data needs, SAP HANA removes the burden of maintaining separate legacy systems and siloed data, so you can run live and make better business decisions in the new digital economy.\""
},
{
"code": null,
"e": 4128,
"s": 3564,
"text": "BI development is always a challenge for organizations with massive amount of historical data. Traditional databases or DW systems - SQL Server, BW or Oracle - doesn't support live reporting, as they are not capable of running the transaction system and Data Warehouse on the same system. In many organizations, transactional system and Data warehouse are kept separate, as running complex OLAP queries affect the performance of the systems significantly. ETL processes are used to perform extraction, transformation, and data load from SAP ECC to Data Warehouse."
},
{
"code": null,
"e": 4412,
"s": 4128,
"text": "When large number of concurrent OLTP transactions are made along with OLAP queries, there is a possibility of the system getting crashed. SAP HANA supports real-time data replication from the transaction system using SLT method, which is a trigger-based approach of data replication."
},
{
"code": null,
"e": 4938,
"s": 4412,
"text": "SAP HANA is an in-memory database, hence the data read is 1 million times faster as compared to traditional systems. Complex OLAP queries in a Business Intelligence report takes less time to run when DW system contains huge amount of historical data. HANA supports all aggregations on fly, and hence, there is no need to save aggregated table in the database. Due to different compression algorithms and column-based storage of table, HANA database requires less space to store more data as compared with other RDBMS systems."
},
{
"code": null,
"e": 5184,
"s": 4938,
"text": "SAP provides BusinessObjects as BI reporting and dashboard tool, used by many organizations who have SAP ERP implemented as the transaction system. SAP BusinessObjects consist of multiple tools for Business Intelligence reporting and dashboard −"
},
{
"code": null,
"e": 5201,
"s": 5184,
"text": "Web Intelligence"
},
{
"code": null,
"e": 5248,
"s": 5201,
"text": "Dashboard Designer (Earlier known as Xcelsius)"
},
{
"code": null,
"e": 5287,
"s": 5248,
"text": "Universe Designer (For Semantic Layer)"
},
{
"code": null,
"e": 5307,
"s": 5287,
"text": "SAP Crystal Reports"
},
{
"code": null,
"e": 5318,
"s": 5307,
"text": "SAP Lumira"
},
{
"code": null,
"e": 5336,
"s": 5318,
"text": "SAP Design Studio"
},
{
"code": null,
"e": 5361,
"s": 5336,
"text": "BusinessObjects Explorer"
},
{
"code": null,
"e": 5379,
"s": 5361,
"text": "Analysis for OLAP"
},
{
"code": null,
"e": 5778,
"s": 5379,
"text": "All these tools are closely integrated with SAP BW and SAP HANA and support all data modeling and ETL features of SAP system. Web Intelligence is used for detailed reporting and uses Query Panel and Universe Designer as the semantic layer to connect to non-SAP data sources. Dashboard Designer is the dashboard tool which provides lot of predefined templates for creating static and dynamic charts."
},
{
"code": null,
"e": 6272,
"s": 5778,
"text": "Universe Designer (UDT/IDT) is a tool to build the semantic layer for non-SAP data sources as well as to build data models for HANA database objects. Different features such as parameters, filters, creating/deleting objects, business layer views, predefined queries for testing, aggregations and variable mapping can be defined using the semantic layer. When the semantic layer is finalized, it can be published to BO server repository and can be used in different Webi reports and Dashboards."
},
{
"code": null,
"e": 6407,
"s": 6272,
"text": "SAP Crystal Reports is used for pixel perfect reporting where users want to take printout of sales invoices, bills, sales orders, etc."
},
{
"code": null,
"e": 6536,
"s": 6407,
"text": "SAP Lumira is one of the emerging data visualization tools that provide the users with an option of ad-hoc dashboarding feature."
},
{
"code": null,
"e": 6680,
"s": 6536,
"text": "SAP Design Studio is also an advanced level dashboard tool and supports server side programming to create interactive dashboards for customers."
},
{
"code": null,
"e": 6831,
"s": 6680,
"text": "SAP BusinessObjects Explorer is a self-service BI tool to create dashboard views and data visualizations, and share them with other users in the team."
},
{
"code": null,
"e": 6957,
"s": 6831,
"text": "Analysis for OLAP is also a self-service multidimensional analysis tool and is suitable for reporting on SAP BW and SAP HANA."
},
{
"code": null,
"e": 7201,
"s": 6957,
"text": "The above picture shows all BI tools with solid lines, which can be directly connected and integrated with SAP HANA using an OLAP connection. The tools that need a relational connection using IDT to connect to HANA are shown with dotted lines."
},
{
"code": null,
"e": 7350,
"s": 7201,
"text": "SAP BusinessObjects was an individual product earlier. In 2008, SAP acquired this product and added it as one of the key tools for SAP BI reporting."
},
{
"code": null,
"e": 7422,
"s": 7350,
"text": "Following is the version history of SAP BO tool in reverse chronology −"
},
{
"code": null,
"e": 7506,
"s": 7422,
"text": "SAP Business Objects Business Intelligence 4.2 Service Pack 04 (Release Date, 2017)"
},
{
"code": null,
"e": 7590,
"s": 7506,
"text": "SAP Business Objects Business Intelligence 4.2 Service Pack 04 (Release Date, 2017)"
},
{
"code": null,
"e": 7685,
"s": 7590,
"text": "SAP Business Objects Business Intelligence 4.2 Service Pack 03 (Released Date, September 2016)"
},
{
"code": null,
"e": 7780,
"s": 7685,
"text": "SAP Business Objects Business Intelligence 4.2 Service Pack 03 (Released Date, September 2016)"
},
{
"code": null,
"e": 7854,
"s": 7780,
"text": "SAP BusinessObjects Business Intelligence 4.2 (Release Date, 18-May-2016)"
},
{
"code": null,
"e": 7928,
"s": 7854,
"text": "SAP BusinessObjects Business Intelligence 4.2 (Release Date, 18-May-2016)"
},
{
"code": null,
"e": 8003,
"s": 7928,
"text": "SAP BusinessObjects Business Intelligence 4.1 (Release Date, 23- Nov-2013)"
},
{
"code": null,
"e": 8078,
"s": 8003,
"text": "SAP BusinessObjects Business Intelligence 4.1 (Release Date, 23- Nov-2013)"
},
{
"code": null,
"e": 8152,
"s": 8078,
"text": "SAP BusinessObjects Business Intelligence 4.0 (Release Date, 16-Sep-2011)"
},
{
"code": null,
"e": 8226,
"s": 8152,
"text": "SAP BusinessObjects Business Intelligence 4.0 (Release Date, 16-Sep-2011)"
},
{
"code": null,
"e": 8255,
"s": 8226,
"text": "SAP Business Objects XI R3.0"
},
{
"code": null,
"e": 8284,
"s": 8255,
"text": "SAP Business Objects XI R3.0"
},
{
"code": null,
"e": 8313,
"s": 8284,
"text": "SAP Business Objects XI R3.1"
},
{
"code": null,
"e": 8342,
"s": 8313,
"text": "SAP Business Objects XI R3.1"
},
{
"code": null,
"e": 8365,
"s": 8342,
"text": "Business Objects XI R1"
},
{
"code": null,
"e": 8388,
"s": 8365,
"text": "Business Objects XI R1"
},
{
"code": null,
"e": 8411,
"s": 8388,
"text": "Business Objects XI R2"
},
{
"code": null,
"e": 8434,
"s": 8411,
"text": "Business Objects XI R2"
},
{
"code": null,
"e": 8455,
"s": 8434,
"text": "Business Objects 6.x"
},
{
"code": null,
"e": 8476,
"s": 8455,
"text": "Business Objects 6.x"
},
{
"code": null,
"e": 8497,
"s": 8476,
"text": "Business Objects 5.x"
},
{
"code": null,
"e": 8518,
"s": 8497,
"text": "Business Objects 5.x"
},
{
"code": null,
"e": 8539,
"s": 8518,
"text": "Business Objects 4.x"
},
{
"code": null,
"e": 8560,
"s": 8539,
"text": "Business Objects 4.x"
},
{
"code": null,
"e": 8581,
"s": 8560,
"text": "Business Objects 3.x"
},
{
"code": null,
"e": 8602,
"s": 8581,
"text": "Business Objects 3.x"
},
{
"code": null,
"e": 8927,
"s": 8602,
"text": "Few of these tools can be directly accessed using a web interface known as BI Launchpad. BI Launchpad is a Java or HTML based interface of BusinessObjects tool to perform analytical reporting and data analysis. You can set the preference for your BI Launchpad that determines, which tool interface is launched via Launchpad."
},
{
"code": null,
"e": 9042,
"s": 8927,
"text": "Using Web or Internet Application to access Webi interface via BI Launchpad, you can perform the following tasks −"
},
{
"code": null,
"e": 9105,
"s": 9042,
"text": "Create, edit, and refresh all the reports in Web Intelligence."
},
{
"code": null,
"e": 9168,
"s": 9105,
"text": "Create, edit, and refresh all the reports in Web Intelligence."
},
{
"code": null,
"e": 9270,
"s": 9168,
"text": "Create and edit all the queries in no data source (Universes) but not BEx queries in Web application."
},
{
"code": null,
"e": 9372,
"s": 9270,
"text": "Create and edit all the queries in no data source (Universes) but not BEx queries in Web application."
},
{
"code": null,
"e": 9420,
"s": 9372,
"text": "BI Launchpad has the following important tabs −"
},
{
"code": null,
"e": 9510,
"s": 9420,
"text": "Home − Displays the recent messages, alerts, documents, and applications that can be run."
},
{
"code": null,
"e": 9600,
"s": 9510,
"text": "Home − Displays the recent messages, alerts, documents, and applications that can be run."
},
{
"code": null,
"e": 9720,
"s": 9600,
"text": "Documents − Displays the available documents and folders, making it easier to view, organize, and manage the documents."
},
{
"code": null,
"e": 9840,
"s": 9720,
"text": "Documents − Displays the available documents and folders, making it easier to view, organize, and manage the documents."
},
{
"code": null,
"e": 9889,
"s": 9840,
"text": "Any open Document − Displays each open document."
},
{
"code": null,
"e": 9938,
"s": 9889,
"text": "Any open Document − Displays each open document."
},
{
"code": null,
"e": 10089,
"s": 9938,
"text": "You can use the Application tab to start an application including Web Intelligence. You can use the Preference tab to define BI Launchpad preferences."
},
{
"code": null,
"e": 10379,
"s": 10089,
"text": "To get the BI Launchpad details and user credentials you can reach the BO Administrator. BI Launchpad has the following URL http://BOSERVER:8080/BOE/BI. To login to BI Launchpad, open the web browser and enter the Launchpad URL provided by your administrator. The following screen pops up."
},
{
"code": null,
"e": 10676,
"s": 10379,
"text": "In SAP BusinessObjects, different tool connects to HANA using different type of connections. Few of the tools connect to the Database layer - Tables, Views, etc. using a Relational connection to HANA database, however, other tools directly connect to Data Modeling layer using an OLAP connection."
},
{
"code": null,
"e": 10843,
"s": 10676,
"text": "An OLAP connection can be created in the Central Management Console (CMC) or a Relational connection and OLAP connection can also be defined in the Universe Designer."
},
{
"code": null,
"e": 11094,
"s": 10843,
"text": "A Relational connection is used to connect to the database layer in HANA. You can connect to database objects - tables, views, and design Data Foundation layer in the Information Design tool. You can also import tables and joins from the data source."
},
{
"code": null,
"e": 11327,
"s": 11094,
"text": "OLAP is a multidimensional connection that directly points to the business layer in a data model. It allows you to connect to the multidimensional schema directly and later, they can be used with SAP BusinessObjects reporting tools."
},
{
"code": null,
"e": 11532,
"s": 11327,
"text": "To connect to SAP NetWeaver BW, you can use SAP BICS client middleware to provide access to BEx query. Connections in IDT can be locally saved or they can be secured and published in a central repository."
},
{
"code": null,
"e": 11724,
"s": 11532,
"text": "Local connections are saved as .cnx files and they can be accessed by any user who is running IDT. Once you publish the connection to the repository, they are changed to a secured connection."
},
{
"code": null,
"e": 11949,
"s": 11724,
"text": "A secured connection is published into the repository and saved in the Connection folder. You can also create secured connections using Insert Relational and Insert OLAP connection commands from the repository resource view."
},
{
"code": null,
"e": 12115,
"s": 11949,
"text": "Let us see how to create a Relational connection that can be used to connect to HANA database layer to design Data Foundation layer for BOBJ reporting in a Universe."
},
{
"code": null,
"e": 12268,
"s": 12115,
"text": "Navigate to Information Design Tool → Click New → Project → Enter the Project Name → Finish. Right-click the Project name → New → Relational Connection."
},
{
"code": null,
"e": 12353,
"s": 12268,
"text": "In the next window, enter the name of Relational connection → Click the Next button."
},
{
"code": null,
"e": 12533,
"s": 12353,
"text": "To set up a connection to HANA database, select SAP HANA database 1.0 from the driver selection screen. In the following snapshot, we have selected SAP HANA → JDBC Drivers → Next."
},
{
"code": null,
"e": 12616,
"s": 12533,
"text": "Note that to connect to HANA database, you should have the following information −"
},
{
"code": null,
"e": 12626,
"s": 12616,
"text": "Host Name"
},
{
"code": null,
"e": 12642,
"s": 12626,
"text": "Instance Number"
},
{
"code": null,
"e": 12652,
"s": 12642,
"text": "User Name"
},
{
"code": null,
"e": 12661,
"s": 12652,
"text": "Password"
},
{
"code": null,
"e": 12815,
"s": 12661,
"text": "You can also select from different authentication modes such as LDAP or any other mode, which is configured for HANA system login. Click the Next button."
},
{
"code": null,
"e": 13036,
"s": 12815,
"text": "In the next window, you will be prompted to enter Connection Parameters - Connection Pool Mode, Pool Timeout, Array Fetch Size, Array Bind Size, Login Tmeout, etc. Once you pass this information, click the Finish button."
},
{
"code": null,
"e": 13247,
"s": 13036,
"text": "This will create a Relational connection to source HANA database and it can be used to connect to Database layer objects for reporting. You can see the following information on the Connection parameter screen −"
},
{
"code": null,
"e": 13255,
"s": 13247,
"text": "General"
},
{
"code": null,
"e": 13271,
"s": 13255,
"text": "Login Parameter"
},
{
"code": null,
"e": 13295,
"s": 13271,
"text": "Configuration Parameter"
},
{
"code": null,
"e": 13694,
"s": 13295,
"text": "You can also edit any of the parameter value by the click of the edit button. When this connection is used in the Universe Designer, this will point to all database objects in HANA database. You can import tables, views from HANA database to build a data foundation layer of a Universe. To test the connection, click the Test Connection and you will get a message that the Connection is successful."
},
{
"code": null,
"e": 13923,
"s": 13694,
"text": "To publish this connection to BO repository so that it can be used by any tool, right-click the connection name and select Publish Connection to a Repository. This will create a new object in the project tab with .cns extension."
},
{
"code": null,
"e": 13960,
"s": 13923,
"text": ".cns − Secured Repository connection"
},
{
"code": null,
"e": 14072,
"s": 13960,
"text": ".cnx-local unsecured − If you use this connection, it will not allow you to publish anything to the repository."
},
{
"code": null,
"e": 14505,
"s": 14072,
"text": "Note − In SAP BusinessObjects, most of the tools support Universe as the data source for reporting. Using a Relational connection, you can connect to any HANA database system, and import tables and views for Data Foundation Layer. Once .dfx is defined, it is required to develop a Business Layer on the top of this layer. When the Universe is published to BO server repository, it can be used by any BOBJ tool for reporting purpose."
},
{
"code": null,
"e": 14677,
"s": 14505,
"text": "An OLAP connection is used to connect to HANA Information view or a data model and to directly import all the business objects defined in the Business Layer for reporting."
},
{
"code": null,
"e": 14764,
"s": 14677,
"text": "To create a new OLAP connection, right-click the Project name → New → OLAP Connection."
},
{
"code": null,
"e": 14850,
"s": 14764,
"text": "In the next window, enter the Connection name, Description (Optional) and click Next."
},
{
"code": null,
"e": 15155,
"s": 14850,
"text": "Note − You point an OLAP connection to a specific cube or to complete HANA repository. When this connection is used in any BO Reporting tool, you can directly import all objects in HANA Modeling view or can also view all published information views in the repository and select any of them for reporting."
},
{
"code": null,
"e": 15303,
"s": 15155,
"text": "Next, select an OLAP middleware driver. It shows a list of all available OLAP data sources. You can select any OLAP data source as per requirement."
},
{
"code": null,
"e": 15480,
"s": 15303,
"text": "Note − You don't need to create a Data Foundation, as an OLAP directly hits the Business Layer. You can define dimensions, measures, and other properties at the Business Layer."
},
{
"code": null,
"e": 15626,
"s": 15480,
"text": "Select the suitable middleware driver to connect to OLAP data source and click Next. To connect to HANA views, select SAP HANA → SAP HANA Client."
},
{
"code": null,
"e": 15690,
"s": 15626,
"text": "To connect to HANA system, you need the following information −"
},
{
"code": null,
"e": 15702,
"s": 15690,
"text": "Server Name"
},
{
"code": null,
"e": 15718,
"s": 15702,
"text": "Instance Number"
},
{
"code": null,
"e": 15741,
"s": 15718,
"text": "Authentication Details"
},
{
"code": null,
"e": 15918,
"s": 15741,
"text": "When you fill the above details and click the Next button, you have an option asking if you want this connection to point to a specific cube or to all cubes in HANA repository."
},
{
"code": null,
"e": 16001,
"s": 15918,
"text": "Once this option is selected, click the Finish button at the bottom of the screen."
},
{
"code": null,
"e": 16127,
"s": 16001,
"text": "Now, you need to publish the connection to the Repository. Right-click Connection → Publish the Connection to the Repository."
},
{
"code": null,
"e": 16258,
"s": 16127,
"text": "When a new connection is created using Information Design tool, you have the following connection parameters that can be defined −"
},
{
"code": null,
"e": 16325,
"s": 16258,
"text": "Connection Pool Mode − This is used to keep the connection active."
},
{
"code": null,
"e": 16392,
"s": 16325,
"text": "Connection Pool Mode − This is used to keep the connection active."
},
{
"code": null,
"e": 16545,
"s": 16392,
"text": "Pool Timeout − When you set the Connection Pool Mode to Keep the connection active for, it is the length of time in minutes to keep the connection open."
},
{
"code": null,
"e": 16698,
"s": 16545,
"text": "Pool Timeout − When you set the Connection Pool Mode to Keep the connection active for, it is the length of time in minutes to keep the connection open."
},
{
"code": null,
"e": 16794,
"s": 16698,
"text": "Array Fetch Size − This tells the maximum number of rows that can be fetched from the database."
},
{
"code": null,
"e": 16890,
"s": 16794,
"text": "Array Fetch Size − This tells the maximum number of rows that can be fetched from the database."
},
{
"code": null,
"e": 17033,
"s": 16890,
"text": "Let us consider an example. You enter a value of 25 and your query returns 150 rows. Hence, it will be fetched with 6 fetches of 25 rows each."
},
{
"code": null,
"e": 17113,
"s": 17033,
"text": "Array Bind Size − This field is not required for designing the Universe in IDT."
},
{
"code": null,
"e": 17220,
"s": 17113,
"text": "Login Timeout − It determines the minutes a connection attempts timeout and an error message is displayed."
},
{
"code": null,
"e": 17308,
"s": 17220,
"text": "There are various custom parameters that can also be defined such as ConnectInit, Hint."
},
{
"code": null,
"e": 17616,
"s": 17308,
"text": "SAP HANA Modeling is one of the key capabilities of HANA system. This allows to create multidimensional objects on top of HANA database objects to meet the business requirements for reporting. You can implement complex business logic using HANA information models to create a meaningful report for analysis."
},
{
"code": null,
"e": 17683,
"s": 17616,
"text": "SAP HANA Modeling is one of the key concepts in HANA BI reporting."
},
{
"code": null,
"e": 17859,
"s": 17683,
"text": "Using HANA Modeling, you can create complex data models as per business requirement to provide multiple views of transactional data stored in physical tables of HANA database."
},
{
"code": null,
"e": 18035,
"s": 17859,
"text": "Using HANA Modeling, you can create complex data models as per business requirement to provide multiple views of transactional data stored in physical tables of HANA database."
},
{
"code": null,
"e": 18103,
"s": 18035,
"text": "SAP HANA Modeling can only be done for column-based storage tables."
},
{
"code": null,
"e": 18171,
"s": 18103,
"text": "SAP HANA Modeling can only be done for column-based storage tables."
},
{
"code": null,
"e": 18319,
"s": 18171,
"text": "HANA Modeling views can be used directly by SAP BusinessObjects reporting tools such as Crystal Reports or Lumira using an OALP or HTTP connection."
},
{
"code": null,
"e": 18467,
"s": 18319,
"text": "HANA Modeling views can be used directly by SAP BusinessObjects reporting tools such as Crystal Reports or Lumira using an OALP or HTTP connection."
},
{
"code": null,
"e": 18744,
"s": 18467,
"text": "HANA supports different types of Modeling views such as - Attribute view is used to model characteristics, Analytic view is used to implement Star schema and Calculation view is used to implement complex logics, which are not possible with other type of views (Galaxy schema)."
},
{
"code": null,
"e": 19021,
"s": 18744,
"text": "HANA supports different types of Modeling views such as - Attribute view is used to model characteristics, Analytic view is used to implement Star schema and Calculation view is used to implement complex logics, which are not possible with other type of views (Galaxy schema)."
},
{
"code": null,
"e": 19139,
"s": 19021,
"text": "SAP HANA Modeling views can also be directly connected to third party tools such as MS Excel using HANA MDX Provider."
},
{
"code": null,
"e": 19257,
"s": 19139,
"text": "SAP HANA Modeling views can also be directly connected to third party tools such as MS Excel using HANA MDX Provider."
},
{
"code": null,
"e": 19404,
"s": 19257,
"text": "SAP HANA Modeling supports various features of Business Layer - Creating new calculated columns, new measures, input parameters, hierarchies, etc."
},
{
"code": null,
"e": 19551,
"s": 19404,
"text": "SAP HANA Modeling supports various features of Business Layer - Creating new calculated columns, new measures, input parameters, hierarchies, etc."
},
{
"code": null,
"e": 19614,
"s": 19551,
"text": "SAP HANA provides following three types of Information Views −"
},
{
"code": null,
"e": 19629,
"s": 19614,
"text": "Attribute View"
},
{
"code": null,
"e": 19643,
"s": 19629,
"text": "Analytic View"
},
{
"code": null,
"e": 19660,
"s": 19643,
"text": "Calculation View"
},
{
"code": null,
"e": 19946,
"s": 19660,
"text": "All HANA Modeling objects are stored in HANA Repository and it can be directly accessed using any BI tool via proper authentication. When these objects are imported in any of the reporting tools using an OLAP or HTTP connection, it also imports all the custom properties of that model."
},
{
"code": null,
"e": 20076,
"s": 19946,
"text": "SAP HANA suite also offers basic BI reporting functionalities, where you can create interactive charts using data in HANA models."
},
{
"code": null,
"e": 20227,
"s": 20076,
"text": "Like other BI reporting tools, you can add dimension and measure values to Label and Value axis. HANA provides the following options for BI analysis −"
},
{
"code": null,
"e": 20378,
"s": 20227,
"text": "Analysis − This tab is used to add different dimension and measure values to different label axis. Filters can be applied as per business requirement."
},
{
"code": null,
"e": 20529,
"s": 20378,
"text": "Analysis − This tab is used to add different dimension and measure values to different label axis. Filters can be applied as per business requirement."
},
{
"code": null,
"e": 20627,
"s": 20529,
"text": "Distinct Values − This tab is used to see distinct values in data analysis for each of dimension."
},
{
"code": null,
"e": 20725,
"s": 20627,
"text": "Distinct Values − This tab is used to see distinct values in data analysis for each of dimension."
},
{
"code": null,
"e": 20821,
"s": 20725,
"text": "Raw Data − This tab shows all raw data coming from data model as per Business Layer parameters."
},
{
"code": null,
"e": 20917,
"s": 20821,
"text": "Raw Data − This tab shows all raw data coming from data model as per Business Layer parameters."
},
{
"code": null,
"e": 21005,
"s": 20917,
"text": "In a BI report, you can select from the following options: Chart, Table, Grid, or HTML."
},
{
"code": null,
"e": 21220,
"s": 21005,
"text": "In SAP HANA, input parameters are used to filter the data by passing an input from the user and to perform additional calculations at run time. The data is fetched based on the input value, when a view is executed."
},
{
"code": null,
"e": 21413,
"s": 21220,
"text": "Consider a scenario where an Input parameter is applied on the \"Sold_Qty\", i.e. when the Sold_Qty is greater than 20, then there is 10% discount on Total_Price. Otherwise, it remains the same."
},
{
"code": null,
"e": 21717,
"s": 21413,
"text": "Input parameters are created in HANA Modeling views using SAP HANA Studio. When these views are used in any BO reporting tool and the report is refreshed, users are prompted to pass an input value for a particular field. To create a new parameter, navigate to the Semantic section of HANA Modeling view."
},
{
"code": null,
"e": 21868,
"s": 21717,
"text": "Navigate to Parameters/Variables tab in the Semantic layer and click the \"+\" sign. Select Create Input Parameter as shown in the following screenshot."
},
{
"code": null,
"e": 22022,
"s": 21868,
"text": "This will open a new dialog box. Enter the technical name and description of the Input parameter. Select the Input Parameter type from the dropdown list."
},
{
"code": null,
"e": 22076,
"s": 22022,
"text": "We have the following input parameter types in HANA −"
},
{
"code": null,
"e": 22154,
"s": 22076,
"text": "Direct − Using this parameter type, you can pass any value for the parameter."
},
{
"code": null,
"e": 22232,
"s": 22154,
"text": "Direct − Using this parameter type, you can pass any value for the parameter."
},
{
"code": null,
"e": 22361,
"s": 22232,
"text": "Column − This parameter type allows you to select any value from the list of distinct values available in a column in HANA view."
},
{
"code": null,
"e": 22490,
"s": 22361,
"text": "Column − This parameter type allows you to select any value from the list of distinct values available in a column in HANA view."
},
{
"code": null,
"e": 22630,
"s": 22490,
"text": "Derived from table − It is also possible to create dynamic values in a table and allows you to select any of available value from the list."
},
{
"code": null,
"e": 22770,
"s": 22630,
"text": "Derived from table − It is also possible to create dynamic values in a table and allows you to select any of available value from the list."
},
{
"code": null,
"e": 22877,
"s": 22770,
"text": "Static List − It is also possible to create a static list of values and provide an input during execution."
},
{
"code": null,
"e": 22984,
"s": 22877,
"text": "Static List − It is also possible to create a static list of values and provide an input during execution."
},
{
"code": null,
"e": 23071,
"s": 22984,
"text": "Note − You can also select the checkbox to make an Input Parameter a mandatory option."
},
{
"code": null,
"e": 23273,
"s": 23071,
"text": "You can select the data type of the input value, so that the system only accepts allowed value type for this field. This option varies as per parameter type. Following data type options are available −"
},
{
"code": null,
"e": 23282,
"s": 23273,
"text": "Currency"
},
{
"code": null,
"e": 23298,
"s": 23282,
"text": "Unit of Measure"
},
{
"code": null,
"e": 23303,
"s": 23298,
"text": "Date"
},
{
"code": null,
"e": 23486,
"s": 23303,
"text": "You can also pass Input parameter using SQL query. To view SQL query, navigate to the Data Preview tab of HANA Modeling view. Input parameter using SQL is passed using \"PLACEHOLDER\"."
},
{
"code": null,
"e": 23624,
"s": 23486,
"text": "Next, click the \"Show Log\" and then double-click the message highlighted below. This will open a new window with the following SQL query."
},
{
"code": null,
"e": 23739,
"s": 23624,
"text": "('PLACEHOLDER' = ('$$ Sold_Qty $$', '20'))\n WHERE (\"REGION_NAME\" IN ('NA') )\n GROUP BY \"NET_AMOUNT\", \"PROFIT\";"
},
{
"code": null,
"e": 24025,
"s": 23739,
"text": "In SAP HANA, Attribute Views are used to model characteristics. They are used to join Dimension tables or other Attribute Views. You can also copy a new Attribute View from the already existing Attribute Views inside other Packages, but that doesn't let you change the View Attributes."
},
{
"code": null,
"e": 24087,
"s": 24025,
"text": "Following are the key characteristics of HANA Attribute view."
},
{
"code": null,
"e": 24186,
"s": 24087,
"text": "Attribute Views are used in Analytical and Calculation Views for analysis to pass the master data."
},
{
"code": null,
"e": 24285,
"s": 24186,
"text": "Attribute Views are used in Analytical and Calculation Views for analysis to pass the master data."
},
{
"code": null,
"e": 24356,
"s": 24285,
"text": "They are similar to characteristics in BM and contain the master data."
},
{
"code": null,
"e": 24427,
"s": 24356,
"text": "They are similar to characteristics in BM and contain the master data."
},
{
"code": null,
"e": 24633,
"s": 24427,
"text": "Attribute Views are used for performance optimization in large size Dimension tables. You can limit the number of attributes in an Attribute View, which are further used for reporting and analysis purpose."
},
{
"code": null,
"e": 24839,
"s": 24633,
"text": "Attribute Views are used for performance optimization in large size Dimension tables. You can limit the number of attributes in an Attribute View, which are further used for reporting and analysis purpose."
},
{
"code": null,
"e": 24911,
"s": 24839,
"text": "Attribute Views are used to model the master data to give some context."
},
{
"code": null,
"e": 24983,
"s": 24911,
"text": "Attribute Views are used to model the master data to give some context."
},
{
"code": null,
"e": 25210,
"s": 24983,
"text": "In SAP HANA, all modeling objects are created inside the package and stored in HANA Repository. Choose the Package name under which you want to create an Attribute View. Right-click Package_Name → Go to New → Attribute View..."
},
{
"code": null,
"e": 25381,
"s": 25210,
"text": "When you click Attribute View, a new window will open. Enter Attribute View name and description in this window and from the dropdown list, choose View Type and Sub-type."
},
{
"code": null,
"e": 25439,
"s": 25381,
"text": "Following are the categories of Attribute View sub-type −"
},
{
"code": null,
"e": 25448,
"s": 25439,
"text": "Standard"
},
{
"code": null,
"e": 25453,
"s": 25448,
"text": "Time"
},
{
"code": null,
"e": 25461,
"s": 25453,
"text": "Derived"
},
{
"code": null,
"e": 25654,
"s": 25461,
"text": "If you want to copy an existing Attribute view, you can use the \"Copy From\" option. When you click the \"Copy From\" option, it shows all other Attribute views that you can use to create a copy."
},
{
"code": null,
"e": 25870,
"s": 25654,
"text": "Time sub-type Attribute View is a special type of Attribute view that adds a Time Dimension to Data Foundation. When you enter the Attribute name, type, and sub-type and click Finish, it will open three work panes −"
},
{
"code": null,
"e": 25929,
"s": 25870,
"text": "Scenario pane that has Data Foundation and Semantic Layer."
},
{
"code": null,
"e": 25988,
"s": 25929,
"text": "Scenario pane that has Data Foundation and Semantic Layer."
},
{
"code": null,
"e": 26091,
"s": 25988,
"text": "Details pane that shows the attribute of all tables added to Data Foundation and joining between them."
},
{
"code": null,
"e": 26194,
"s": 26091,
"text": "Details pane that shows the attribute of all tables added to Data Foundation and joining between them."
},
{
"code": null,
"e": 26281,
"s": 26194,
"text": "Output pane where you can add attributes from the Detail pane to filter in the report."
},
{
"code": null,
"e": 26368,
"s": 26281,
"text": "Output pane where you can add attributes from the Detail pane to filter in the report."
},
{
"code": null,
"e": 26580,
"s": 26368,
"text": "You can add Objects to Data Foundation, by clicking the '+' sign written next to Data Foundation. You can add multiple Dimension Tables and Attribute Views in the Scenario Pane and join them using a Primary Key."
},
{
"code": null,
"e": 26954,
"s": 26580,
"text": "When you click Add Objects \"+\" sign in Data Foundation, you will get a search bar from where you can add Dimension tables and Attribute views to the Scenario Pane. Once Tables or Attribute Views are added to Data Foundation, you can see all the columns on the right side pane. They can be joined using a Primary Key in the Details Pane as shown in the following screenshot."
},
{
"code": null,
"e": 27195,
"s": 26954,
"text": "Once the joining is complete, choose multiple attributes in the details pane, right-click and Add to Output. All columns will be added to the Output pane. Now click the Activate option and you will get a confirmation message in the job log."
},
{
"code": null,
"e": 27388,
"s": 27195,
"text": "Now you can right-click the Attribute View and go for Data Preview. Once you click Data Preview, it will show all the attributes that has been added to the Output pane under Available Objects."
},
{
"code": null,
"e": 27582,
"s": 27388,
"text": "SAP HANA also provides reporting feature for data analysis. These Objects can be added to Labels and Value axis by a right-click or by dragging the objects as shown in the following screenshot."
},
{
"code": null,
"e": 27869,
"s": 27582,
"text": "Analytic View is in the form of Star schema, wherein we join one Fact table to multiple Dimension tables. Analytic views use real power of SAP HANA to perform complex calculations and aggregate functions by joining tables in the form of Star schema and by executing Star schema queries."
},
{
"code": null,
"e": 27935,
"s": 27869,
"text": "Following are the key characteristics of SAP HANA Analytic View −"
},
{
"code": null,
"e": 28050,
"s": 27935,
"text": "Analytic Views are used to perform complex calculations and Aggregate functions such as Sum, Count, Min, Max, etc."
},
{
"code": null,
"e": 28165,
"s": 28050,
"text": "Analytic Views are used to perform complex calculations and Aggregate functions such as Sum, Count, Min, Max, etc."
},
{
"code": null,
"e": 28221,
"s": 28165,
"text": "Analytic Views are designed to run Star schema queries."
},
{
"code": null,
"e": 28277,
"s": 28221,
"text": "Analytic Views are designed to run Star schema queries."
},
{
"code": null,
"e": 28423,
"s": 28277,
"text": "Each Analytic View has one Fact table surrounded by multiple dimension tables. Fact table contains a primary key for each Dim table and measures."
},
{
"code": null,
"e": 28569,
"s": 28423,
"text": "Each Analytic View has one Fact table surrounded by multiple dimension tables. Fact table contains a primary key for each Dim table and measures."
},
{
"code": null,
"e": 28637,
"s": 28569,
"text": "Analytic Views are similar to Info Objects and Info sets of SAP BW."
},
{
"code": null,
"e": 28705,
"s": 28637,
"text": "Analytic Views are similar to Info Objects and Info sets of SAP BW."
},
{
"code": null,
"e": 28824,
"s": 28705,
"text": "SAP BusinessObjects reporting tools can connect to Analytic view using an OLAP connection for reporting and dashboard."
},
{
"code": null,
"e": 28943,
"s": 28824,
"text": "SAP BusinessObjects reporting tools can connect to Analytic view using an OLAP connection for reporting and dashboard."
},
{
"code": null,
"e": 29103,
"s": 28943,
"text": "In SAP HANA, you can create an Analytic view to implement Star Schema queries. All these objects are created inside a Package and published to HANA Repository."
},
{
"code": null,
"e": 29421,
"s": 29103,
"text": "To create a new Analytic view, select the Package name under which you want to create it. Right-click the Package → Go to New Tab → Analytic View. When you click an Analytic View, a new window will open. Enter the View name and Description and from the dropdown list and choose the View Type and finally click Finish."
},
{
"code": null,
"e": 29656,
"s": 29421,
"text": "When you click Finish, you can see an Analytic View with Data Foundation and Star Join option. To add tables to the Analytic view, click the Data Foundation to add Dimension and Fact tables. Click the Star Join to add Attribute Views."
},
{
"code": null,
"e": 29977,
"s": 29656,
"text": "Add Dim and Fact tables to Data Foundation using \"+\" sign. In the following example, we have added 3 dim tables to Data Foundation: DIM_CUSTOMER, DIM_PRODUCT, DIM_REGION and 1 Fact table FCT_SALES to the Details Pane. A Join is applied to connect Dim tables to the Fact table using Primary Keys stored in the Fact table."
},
{
"code": null,
"e": 30147,
"s": 29977,
"text": "Select Attributes from Dim and Fact table to add to the Output pane as shown in the following screenshot. Change the data type of Facts, from the fact table to measures."
},
{
"code": null,
"e": 30323,
"s": 30147,
"text": "Navigate to the Semantic layer, select dimension and measures and click the data type if it is not picked by default. You can also use Auto-detection. Next, activate the View."
},
{
"code": null,
"e": 30598,
"s": 30323,
"text": "To activate the view, click the Arrow mark at the top (F8) button. Once you activate the view and click Data Preview, all attributes and measures will be added under the list of Available objects. Add Attributes to Labels Axis and Measure to Value axis for analysis purpose."
},
{
"code": null,
"e": 30795,
"s": 30598,
"text": "Calculation views are used to perform complex calculations, which are not possible with Attribute or Analytic view. You can also use Attribute and Analytic views while designing Calculation views."
},
{
"code": null,
"e": 30854,
"s": 30795,
"text": "Following are a few characteristics of Calculation Views −"
},
{
"code": null,
"e": 30942,
"s": 30854,
"text": "Calculation Views are used to consume Analytic, Attribute, and other Calculation Views."
},
{
"code": null,
"e": 31030,
"s": 30942,
"text": "Calculation Views are used to consume Analytic, Attribute, and other Calculation Views."
},
{
"code": null,
"e": 31117,
"s": 31030,
"text": "There are two ways to create Calculation Views - Using SQL Editor or Graphical option."
},
{
"code": null,
"e": 31204,
"s": 31117,
"text": "There are two ways to create Calculation Views - Using SQL Editor or Graphical option."
},
{
"code": null,
"e": 31268,
"s": 31204,
"text": "It has built-in Union, Join, Projection, and Aggregation nodes."
},
{
"code": null,
"e": 31332,
"s": 31268,
"text": "It has built-in Union, Join, Projection, and Aggregation nodes."
},
{
"code": null,
"e": 31454,
"s": 31332,
"text": "SAP BusinessObjects reporting tools can connect to Calculation view using an OLAP connection for reporting and dashboard."
},
{
"code": null,
"e": 31576,
"s": 31454,
"text": "SAP BusinessObjects reporting tools can connect to Calculation view using an OLAP connection for reporting and dashboard."
},
{
"code": null,
"e": 31768,
"s": 31576,
"text": "Choose the Package name under which you want to create a Calculation View. Right-click the Package → Go to New → Calculation View. When you click the Calculation View, a new window will open."
},
{
"code": null,
"e": 32004,
"s": 31768,
"text": "Enter the view name, description and choose the view type as Calculation View, Sub-type Standard or Time (this is a special kind of View, which adds time dimension). You can use two types of Calculation View - Graphical and SQL Script."
},
{
"code": null,
"e": 32133,
"s": 32004,
"text": "Calculation view provides an option of using a Star Join or not to use a Star Join. Also, it has two different Data Categories −"
},
{
"code": null,
"e": 32262,
"s": 32133,
"text": "Cube − When a user selects Cube as data category, the default node is Aggregation. You can choose Star Join with Cube dimension."
},
{
"code": null,
"e": 32391,
"s": 32262,
"text": "Cube − When a user selects Cube as data category, the default node is Aggregation. You can choose Star Join with Cube dimension."
},
{
"code": null,
"e": 32483,
"s": 32391,
"text": "Dimension − When a user selects Dimension as data category, the default node is Projection."
},
{
"code": null,
"e": 32575,
"s": 32483,
"text": "Dimension − When a user selects Dimension as data category, the default node is Projection."
},
{
"code": null,
"e": 32890,
"s": 32575,
"text": "When you use Calculation view with Star Join, it does not allow base column tables, Attribute Views, or Analytic views to add at data foundation. All Dimension tables must be changed to Dimension Calculation views to be used in Star Join. All Fact tables can be added and can use default nodes in Calculation View."
},
{
"code": null,
"e": 32966,
"s": 32890,
"text": "The following example shows how we can use Calculation View with Star Join."
},
{
"code": null,
"e": 33127,
"s": 32966,
"text": "You have four tables, two Dim tables, and two Fact tables. You have to find a list of all employees with their Joining date, Emp Name, empId, Salary, and Bonus."
},
{
"code": null,
"e": 33268,
"s": 33127,
"text": "It simplifies the design process. You need not create Analytical views and Attribute Views. Fact tables can be directly used as Projections."
},
{
"code": null,
"e": 33409,
"s": 33268,
"text": "It simplifies the design process. You need not create Analytical views and Attribute Views. Fact tables can be directly used as Projections."
},
{
"code": null,
"e": 33441,
"s": 33409,
"text": "3NF is possible with Star Join."
},
{
"code": null,
"e": 33473,
"s": 33441,
"text": "3NF is possible with Star Join."
},
{
"code": null,
"e": 33590,
"s": 33473,
"text": "This allows the use of other Attribute views and Analytic views using different nodes available in Calculation Join."
},
{
"code": null,
"e": 33768,
"s": 33590,
"text": "In the above screenshot, you can see two Analytic views - AN_Fact1 and AN_Fact2 - are used using node Projection 1 and Projection 2 and then joined with the help of a Join node."
},
{
"code": null,
"e": 34050,
"s": 33768,
"text": "SAP HANA is an in-memory database that supports all the features of a conventional database. You can perform all DDL, DML, and DCL statements on database objects. Users can create new tables, views, functions, triggers, and all other database functions using HANA Studio front-end."
},
{
"code": null,
"e": 34199,
"s": 34050,
"text": "Tables in HANA database can be accessed from HANA Studio in Catalogue tab under Schemas. New tables can be created using the following two methods −"
},
{
"code": null,
"e": 34216,
"s": 34199,
"text": "Using SQL editor"
},
{
"code": null,
"e": 34233,
"s": 34216,
"text": "Using GUI option"
},
{
"code": null,
"e": 34421,
"s": 34233,
"text": "All the database objects - tables, views, and other objects can be used to design a Universe - Data Foundation layer and later to publish Business Layer to BO repository for BI reporting."
},
{
"code": null,
"e": 34804,
"s": 34421,
"text": "In SAP HANA Studio, open SQL editor by selecting the Schema name and click the circled option in the following screenshot. You can run all SQL queries in SQL editor, which are required to perform conventional database functions. You can create new tables, views by writing the CREATE command in the editor window or right-click the Schema name and write the following Create script."
},
{
"code": null,
"e": 34906,
"s": 34804,
"text": "Following is the Create table SQL command that can be used to create a column table in HANA database."
},
{
"code": null,
"e": 35010,
"s": 34906,
"text": "Create column Table Sample1 (\n Cust_ID INTEGER,\n Cust_NAME VARCHAR(10),\n PRIMARY KEY (Cust_ID)\n);"
},
{
"code": null,
"e": 35098,
"s": 35010,
"text": "To insert the data, run the Insert statement in SQL editor. \"Sample\" is the table name."
},
{
"code": null,
"e": 35218,
"s": 35098,
"text": "Insert into Sample Values (101,'Jon');\nInsert into Sample Values (201,'Tina');\nInsert into Sample Values (301,'Jacob');"
},
{
"code": null,
"e": 35387,
"s": 35218,
"text": "When the data is entered, you can see the data in this row-based table by going to Data Preview option. To see the data, right-click the table name → Open Data Preview."
},
{
"code": null,
"e": 35545,
"s": 35387,
"text": "All the database objects in SAP HANA system are maintained in CATALOG folder in HANA Studio. Following are the key capabilities of SAP HANA database system −"
},
{
"code": null,
"e": 35718,
"s": 35545,
"text": "You can use high performance in-memory database for processing complex transactions and analytics. You can manage large database volumes in multitenant database containers."
},
{
"code": null,
"e": 35891,
"s": 35718,
"text": "You can use high performance in-memory database for processing complex transactions and analytics. You can manage large database volumes in multitenant database containers."
},
{
"code": null,
"e": 36045,
"s": 35891,
"text": "SAP HANA system combines OLAP and OLTP processing into a single in-memory database. It removes the disk bottlenecks, offering groundbreaking performance."
},
{
"code": null,
"e": 36199,
"s": 36045,
"text": "SAP HANA system combines OLAP and OLTP processing into a single in-memory database. It removes the disk bottlenecks, offering groundbreaking performance."
},
{
"code": null,
"e": 36410,
"s": 36199,
"text": "Using SAP HANA in-memory database component, you can run advanced analytical queries, which are complex in nature with high-speed transactions to get the correct, up-to-date responses in a fraction of a second."
},
{
"code": null,
"e": 36621,
"s": 36410,
"text": "Using SAP HANA in-memory database component, you can run advanced analytical queries, which are complex in nature with high-speed transactions to get the correct, up-to-date responses in a fraction of a second."
},
{
"code": null,
"e": 36874,
"s": 36621,
"text": "All the 2-dimensional objects exist in schemas in HANA database. Schemas are shown under the Catalog folder in HANA Studio. When you expand any of the schema, you can see different Relational objects - functions, indexes, views, and synonyms inside it."
},
{
"code": null,
"e": 37027,
"s": 36874,
"text": "If you open SAP HANA cockpit using the following link, you can see different database functions in HANA system: https://best:4303/sap/hana/admin/cockpit"
},
{
"code": null,
"e": 37093,
"s": 37027,
"text": "To create a view in one table, write the following SQL statement."
},
{
"code": null,
"e": 37118,
"s": 37093,
"text": "create view view_name as"
},
{
"code": null,
"e": 37205,
"s": 37118,
"text": "select ARTICLE_ID,ARTICLE_LABEL,CATEGORY,SALE_PRICE\nfrom \"AA_HANA11\".\"ARTICLE_LOOKUP\";"
},
{
"code": null,
"e": 37271,
"s": 37205,
"text": "You can drop a view using the Drop command, like we drop a table."
},
{
"code": null,
"e": 37306,
"s": 37271,
"text": "Drop view \"AA_HANA11\".\"DEMO_TEST\";"
},
{
"code": null,
"e": 37554,
"s": 37306,
"text": "In older versions of SAP BusinessObjects (4.1 or earlier), the only option to connect Webi with HANA is with the use of the Universe. The Universe is designed on top of HANA views and then using Webi query panel, we can use objects in Webi report."
},
{
"code": null,
"e": 37732,
"s": 37554,
"text": "With the release of SAP BO 4.2, SAP provides multiple ways to connect Webi report to HANA views. Following are the four ways to connect Web Intelligence to HANA Modeling views −"
},
{
"code": null,
"e": 37777,
"s": 37732,
"text": "Using Universe on top of HANA Modeling Views"
},
{
"code": null,
"e": 37825,
"s": 37777,
"text": "Direct Webi connection with HANA Modeling views"
},
{
"code": null,
"e": 37854,
"s": 37825,
"text": "SAP HANA Online connectivity"
},
{
"code": null,
"e": 37874,
"s": 37854,
"text": "Using Free-Hand SQL"
},
{
"code": null,
"e": 38081,
"s": 37874,
"text": "As mentioned earlier, we can develop HANA Views - Attribute, Analytic and Calculation views - using HANA Studio. To create a Universe, you have to create a Relational connection pointing to HANA DB schemas."
},
{
"code": null,
"e": 38323,
"s": 38081,
"text": "To create a new Relational connection, first start with a new project under Local Project view. Open Information Design Tool → Click New → Project → Enter the Project Name → Finish. This will create a new Project under Local Projects window."
},
{
"code": null,
"e": 38389,
"s": 38323,
"text": "Next, right-click the Project name → New → Relational Connection."
},
{
"code": null,
"e": 38482,
"s": 38389,
"text": "In the next window, enter Connection Name → Enter the connection/resource name → click Next."
},
{
"code": null,
"e": 38681,
"s": 38482,
"text": "You will be prompted to select a Middleware for connection. Select the middleware as per data source. You can select SAP or non-SAP as data source and set up a relational connection to the database."
},
{
"code": null,
"e": 38763,
"s": 38681,
"text": "Here, we have selected SAP from the list → SAP HANA database → JDBC → click Next."
},
{
"code": null,
"e": 38901,
"s": 38763,
"text": "In the next window, enter the Authentication mode, user name and password. Enter SAP HANA host name and Instance number, then click Next."
},
{
"code": null,
"e": 39029,
"s": 38901,
"text": "In the following window, define connection parameters such as - Time out, Array fetch size, Array Bind size, etc. Click Finish."
},
{
"code": null,
"e": 39313,
"s": 39029,
"text": "When you click the Finish button, this will create a new Relational Connection pointing to SAP HANA database with .cnx file extension. You can click Test Connection. The lower part of the Window tells you about connection parameters - Login parameters, configuration parameters, etc."
},
{
"code": null,
"e": 39433,
"s": 39313,
"text": "Click Test Connection → Successful. You have to publish this connection to the Repository to make it available for use."
},
{
"code": null,
"e": 39585,
"s": 39433,
"text": "To publish this connection, right-click the connection name → Publish connection to Repository → Enter BO repository password → Connect → Finish → Yes."
},
{
"code": null,
"e": 39696,
"s": 39585,
"text": "Now, create a Data Foundation using SAP HANA view. Right-click Connection name → Select New → Data Foundation."
},
{
"code": null,
"e": 39917,
"s": 39696,
"text": "Enter Resource Name and click Next. You can select Single source enabled or multi-source enabled as the data foundation type. Select multisource-enabled and pass the authentication details after selecting the connection."
},
{
"code": null,
"e": 40216,
"s": 39917,
"text": "After you click Next, select _SYS_BIC schema node, where all HANA views and column tables are stored. Add the required view from HANA to Data Foundation layer. You can develop the Business Layer on top of this data foundation, and it can be published to BO server repository for reporting purposes."
},
{
"code": null,
"e": 40541,
"s": 40216,
"text": "This feature is added to SAP BO 4.2 recently which allows direct connection to HANA Modeling views using an OLAP connection. When you connect to HANA Repository using an OLAP connection, you can connect to all Packages created in HANA system. You can select any of the package → Navigate to HANA views stored in the package."
},
{
"code": null,
"e": 40775,
"s": 40541,
"text": "Once these steps are performed, all dimensions and measures are added to the Query Panel in Webi. The developer can select any of the result objects from the list of available objects and click the run query to add those Webi report."
},
{
"code": null,
"e": 40980,
"s": 40775,
"text": "In SAP BO 4.2, there is an option of using HANA Online Connection that allows Webi client to connect directly to HANA views. There is no need to build a Webi query for using HANA Online connection option."
},
{
"code": null,
"e": 41236,
"s": 40980,
"text": "This option lists Relational connection only and when the connection is selected, it shows all the packages and corresponding views. When HANA view is selected, it directly connects to Webi Reporting Layer. There is no use of Query panel in this scenario."
},
{
"code": null,
"e": 41609,
"s": 41236,
"text": "In SAP BO 4.2, a new option - free-hand SQL - is introduced in Web Intelligence that connects directly to HANA views. When you connect using a Web Intelligence tool that connects using Free-hand SQL option, a tool lists down all HANA Relational connection from BOBJ server. When you select a Relational connection, a tool provides a query script editor to write the query."
},
{
"code": null,
"e": 41723,
"s": 41609,
"text": "To use Free-Hand SQL option, select a new Webi document, and in the data source list select Free-Hand SQL option."
},
{
"code": null,
"e": 41935,
"s": 41723,
"text": "Once you select this option, a query editor opens up. You can write a SELECT query to form Webi Query for reporting. On the right side, you have a Run Query option and the list of available objects in Webi tool."
},
{
"code": null,
"e": 42069,
"s": 41935,
"text": "To create a Universe in IDT, go to Start → All Programs → SAP Business Intelligence → SAP Business Objects BI Platform 4 Client Tool."
},
{
"code": null,
"e": 42200,
"s": 42069,
"text": "In Information Design Tool, you have to create a New Project. Go to File → New → Project. Enter the Project Name and Click Finish."
},
{
"code": null,
"e": 42532,
"s": 42200,
"text": "Once the project is created, next is to create an OLAP or Relational connection to connect to a data source - SAP HANA in this case. A Relational connection is used to connect to the Database layer to import tables and joins. An OLAP connection is used to connect to the multidimensional model like an Information View in SAP HANA."
},
{
"code": null,
"e": 42720,
"s": 42532,
"text": "Right-click on Project name → New → Select Relational Connection → Enter connection/resource name → Next. Select SAP from the list → SAP HANA → Select Drivers JDBC → Next → Enter details."
},
{
"code": null,
"e": 42866,
"s": 42720,
"text": "Enter the system details, username, password, and click Next. Then, click Finish. Under General Information → Click Test Connection → Successful."
},
{
"code": null,
"e": 43088,
"s": 42866,
"text": "You have to publish this connection to the Repository to make it available for use. Right-click the connection name → Publish the connection to the Repository → Enter BO repository password → Click Connect → Finish → Yes."
},
{
"code": null,
"e": 43234,
"s": 43088,
"text": "The next step is to create a Data Foundation Layer on this secure connection. Right-click .cns Repository connection → Click New Data Foundation."
},
{
"code": null,
"e": 43539,
"s": 43234,
"text": "Enter Resource Name and click Finish. It will show you a list of all available schemas in the database. You can add Tables and Joins from Schema to Data Foundation layer. This can be done by dragging the table or by a double-click. Apply the joins on Dimension and Fact tables to create a logical schema."
},
{
"code": null,
"e": 43761,
"s": 43539,
"text": "To define a Join, double-click the Join between tables. It will show you both the tables. You can select from different Joins as per data requirement and click Detect Cardinality to define the cardinality - 1:1, 1:n, n:n."
},
{
"code": null,
"e": 44066,
"s": 43761,
"text": "Next is to create a Business Layer on the Data Foundation. Click the Save All icon at the top of the screen. Then, right-click Data foundation .dfx → New Business Layer. Enter Resource Name → (Generating Business Layer for Data Foundation) Finish. It will add Business Layer .blx under the Local Project."
},
{
"code": null,
"e": 44187,
"s": 44066,
"text": "It will show a list of all dimensions and measures under Data Foundation. Define dimensions, measures, aggregation, etc."
},
{
"code": null,
"e": 44399,
"s": 44187,
"text": "To define an Aggregation, select from the Projection Function. You can hide few objects in the report if you want using the dropdown next to measures and dimension. You can select Hidden for a particular object."
},
{
"code": null,
"e": 44605,
"s": 44399,
"text": "Once you define the Business Layer, click Save All icon at the top of the screen as shown in the following screenshot. To publish a Universe to the Repository, right-click .blx → Publish → To a Repository."
},
{
"code": null,
"e": 44772,
"s": 44605,
"text": "Select Resources, then click Next. In the Publish Universe window, select Next → Select the Repository folder where you want to publish the Universe and click Finish."
},
{
"code": null,
"e": 44982,
"s": 44772,
"text": "In Universe Designer, it is also possible to create user prompts and filters in Business View Layer. Prompt is defined in Business Layer or Data Foundation that requires a user input or predefined input value."
},
{
"code": null,
"e": 45028,
"s": 44982,
"text": "A Prompt can have the following input types −"
},
{
"code": null,
"e": 45067,
"s": 45028,
"text": "User input as a response to the prompt"
},
{
"code": null,
"e": 45092,
"s": 45067,
"text": "A predefined fixed value"
},
{
"code": null,
"e": 45129,
"s": 45092,
"text": "Prompt has the following properties."
},
{
"code": null,
"e": 45145,
"s": 45129,
"text": "Prompt to Users"
},
{
"code": null,
"e": 45208,
"s": 45145,
"text": "If selected, the user is prompted to enter a value at runtime."
},
{
"code": null,
"e": 45281,
"s": 45208,
"text": "If cleared, a pre-defined value is entered at runtime for the parameter."
},
{
"code": null,
"e": 45293,
"s": 45281,
"text": "Prompt Text"
},
{
"code": null,
"e": 45372,
"s": 45293,
"text": "The text for the prompt question or directive, if Prompt to Users is selected."
},
{
"code": null,
"e": 45383,
"s": 45372,
"text": "Set Values"
},
{
"code": null,
"e": 45520,
"s": 45383,
"text": "Available when the Prompt to Users option is unselected. Allows to enter one or more values to be used for the parameter at the runtime."
},
{
"code": null,
"e": 45531,
"s": 45520,
"text": "Data Types"
},
{
"code": null,
"e": 45584,
"s": 45531,
"text": "The data type required for the answer to the prompt."
},
{
"code": null,
"e": 45606,
"s": 45584,
"text": "Allow Multiple Values"
},
{
"code": null,
"e": 45684,
"s": 45606,
"text": "If selected, allows the user to take multiple values from the list of values."
},
{
"code": null,
"e": 45701,
"s": 45684,
"text": "Keep Last Values"
},
{
"code": null,
"e": 45784,
"s": 45701,
"text": "If selected, the last value chosen by the user is kept, when the prompt is re-run."
},
{
"code": null,
"e": 45803,
"s": 45784,
"text": "Index Aware Prompt"
},
{
"code": null,
"e": 45934,
"s": 45803,
"text": "If selected, the key column is included in the prompt to restrict the values in a list. The key column is not visible to the user."
},
{
"code": null,
"e": 45960,
"s": 45934,
"text": "Associated List of Values"
},
{
"code": null,
"e": 46011,
"s": 45960,
"text": "A list of values to provide values for the prompt."
},
{
"code": null,
"e": 46037,
"s": 46011,
"text": "Select Only from the List"
},
{
"code": null,
"e": 46101,
"s": 46037,
"text": "If selected, the user is forced to select a member in the list."
},
{
"code": null,
"e": 46122,
"s": 46101,
"text": "Select Default Value"
},
{
"code": null,
"e": 46169,
"s": 46122,
"text": "Allows to select values to be used as default."
},
{
"code": null,
"e": 46446,
"s": 46169,
"text": "In the Universe Designer, you can add a Prompt in Data Foundation and they are directly inherited to the Business Layer on top of Data foundation. Note: If there is a need to edit a Prompt, it can't be done in the Business Layer. You have to open Data Foundation for the same."
},
{
"code": null,
"e": 46565,
"s": 46446,
"text": "To insert a Prompt, click parameters and List of Values (LOVs) tab in the browsing pane → Click Insert Parameter icon."
},
{
"code": null,
"e": 46854,
"s": 46565,
"text": "It is possible to use LOVs, i.e. you can select the value of a prompt from the list of values associated with an object. It allows a data set to be restricted to the selected values. You can use LOVs for an object in Data Foundation or Business Layer. Different types of LOVs can be used."
},
{
"code": null,
"e": 46968,
"s": 46854,
"text": "LOVs based on Business Layer Objects. In this case, LOV is based on other query or on a hierarchy that includes −"
},
{
"code": null,
"e": 47057,
"s": 46968,
"text": "Static LOVs − It includes a list of specified values manually or imported from the file."
},
{
"code": null,
"e": 47146,
"s": 47057,
"text": "Static LOVs − It includes a list of specified values manually or imported from the file."
},
{
"code": null,
"e": 47219,
"s": 47146,
"text": "LOVs based on SQL − It is a value returned by a specific SQL expression."
},
{
"code": null,
"e": 47292,
"s": 47219,
"text": "LOVs based on SQL − It is a value returned by a specific SQL expression."
},
{
"code": null,
"e": 47338,
"s": 47292,
"text": "Following properties can be edited for LOVs −"
},
{
"code": null,
"e": 47397,
"s": 47338,
"text": "Column Name − This is used to edit the name of the column."
},
{
"code": null,
"e": 47456,
"s": 47397,
"text": "Column Name − This is used to edit the name of the column."
},
{
"code": null,
"e": 47520,
"s": 47456,
"text": "Key Column − You can select a column to be the index aware key."
},
{
"code": null,
"e": 47584,
"s": 47520,
"text": "Key Column − You can select a column to be the index aware key."
},
{
"code": null,
"e": 47649,
"s": 47584,
"text": "Data Type − This is used to define the data type for the column."
},
{
"code": null,
"e": 47714,
"s": 47649,
"text": "Data Type − This is used to define the data type for the column."
},
{
"code": null,
"e": 47787,
"s": 47714,
"text": "Hidden − When this option is selected, the column will not be displayed."
},
{
"code": null,
"e": 47860,
"s": 47787,
"text": "Hidden − When this option is selected, the column will not be displayed."
},
{
"code": null,
"e": 48115,
"s": 47860,
"text": "When the Universe is published to BO repository based on SAP HANA views, it can be directly used for reporting using the Query Panel. Universe contains data from SAP HANA/SAP BW or non-SAP data sources. Let us see how to build a query using the Universe."
},
{
"code": null,
"e": 48242,
"s": 48115,
"text": "Open Web Intelligence via BI Launchpad → Click New (Create a new Webi document). You will be prompted to select a Data Source."
},
{
"code": null,
"e": 48695,
"s": 48242,
"text": "Select a Universe as the data source and click 'Ok'. You will get a list of all available Universe. Select a Universe created on top of HANA view, which you want to use to create a Webi document. This will open a new window - Query Panel. In the query panel, on the left side of the screen, you will have a list of available objects. You will have Result Objects where you drag the objects from the left panel, which you want to add in a Webi document."
},
{
"code": null,
"e": 48909,
"s": 48695,
"text": "There will be Query Filter using which you can add different filters. Data Preview can be used to view data before it is added to Webi document. The Run Query tab at the top of the screen is used to run the query."
},
{
"code": null,
"e": 49178,
"s": 48909,
"text": "You can also add data from multiple sources in a single Webi document by adding multiple queries to the Query panel. You can add a new query by clicking the Add Query option. You again have the option of selecting a data source, from which you want to add a new query."
},
{
"code": null,
"e": 49312,
"s": 49178,
"text": "When you click the Run Query option on the top right corner of the screen, all the result objects will be added to the Webi document."
},
{
"code": null,
"e": 49540,
"s": 49312,
"text": "It is possible to connect to SAP HANA Modeling Views in SAP Lumira with a direct connection. You need to have HANA Host name, Instance/Port number, User name and password to connect. This can be done in the following two ways −"
},
{
"code": null,
"e": 49560,
"s": 49540,
"text": "Connect to SAP HANA"
},
{
"code": null,
"e": 49583,
"s": 49560,
"text": "Download from SAP HANA"
},
{
"code": null,
"e": 49844,
"s": 49583,
"text": "It will show you all the HANA Modeling Views that have been recently used. Click the Next command button after selecting the option \"Connect to SAP HANA\". This will allow you to access the data in read mode and you can visualize the data in the form of charts."
},
{
"code": null,
"e": 49899,
"s": 49844,
"text": "You should know the following details of HANA system −"
},
{
"code": null,
"e": 49909,
"s": 49899,
"text": "Host Name"
},
{
"code": null,
"e": 49930,
"s": 49909,
"text": "Instance/Port Number"
},
{
"code": null,
"e": 49953,
"s": 49930,
"text": "User Name and Password"
},
{
"code": null,
"e": 50007,
"s": 49953,
"text": "Once you enter the details, click the Connect button."
},
{
"code": null,
"e": 50138,
"s": 50007,
"text": "Now, enter the dimensions and measures you want to add to the dataset. Click Create button. This will add data to the Prepare tab."
},
{
"code": null,
"e": 50232,
"s": 50138,
"text": "These objects can be directly used for dashboard development in Lumira to create new stories."
},
{
"code": null,
"e": 50485,
"s": 50232,
"text": "When you select a dataset in Lumira from HANA Repository, it is added to the Prepare tab. You can make changes to the dataset and once it is finalized you can move to \"Visualize\" tab to create interactive charts in Lumira on top of HANA Modeling views."
},
{
"code": null,
"e": 50579,
"s": 50485,
"text": "Follow are the steps to add a chart: Navigate to the \"Visualize\" tab and go to Chart Builder."
},
{
"code": null,
"e": 50723,
"s": 50579,
"text": "Select a chart type that you want to use in the Chart Builder. Bar Chart is the default chart type, but you can select any chart from the list."
},
{
"code": null,
"e": 50903,
"s": 50723,
"text": "The next step is to choose a measure and drag it to an axis on the Chart Canvas. To add a measure or dimension to the corresponding axis, click the '+' sign next to the axis name."
},
{
"code": null,
"e": 51072,
"s": 50903,
"text": "Select a dimension and add to the chart canvas or you can also drag it to the Chart Canvas. The text in the chart body guides you to the correct axis for the dimension."
},
{
"code": null,
"e": 51124,
"s": 51072,
"text": "Following chart types are available in SAP Lumira −"
},
{
"code": null,
"e": 51242,
"s": 51124,
"text": "Comparison − These chart types are used to compare the difference between values. Common comparison chart types are −"
},
{
"code": null,
"e": 51252,
"s": 51242,
"text": "Bar Chart"
},
{
"code": null,
"e": 51265,
"s": 51252,
"text": "Column Chart"
},
{
"code": null,
"e": 51277,
"s": 51265,
"text": "Radar Chart"
},
{
"code": null,
"e": 51288,
"s": 51277,
"text": "Area Chart"
},
{
"code": null,
"e": 51297,
"s": 51288,
"text": "Heat map"
},
{
"code": null,
"e": 51403,
"s": 51297,
"text": "Percentage − These are used to show a percentage of parts in a chart. Common percentage type charts are −"
},
{
"code": null,
"e": 51413,
"s": 51403,
"text": "Pie Chart"
},
{
"code": null,
"e": 51425,
"s": 51413,
"text": "Donut Chart"
},
{
"code": null,
"e": 51430,
"s": 51425,
"text": "Tree"
},
{
"code": null,
"e": 51443,
"s": 51430,
"text": "Funnel Chart"
},
{
"code": null,
"e": 51548,
"s": 51443,
"text": "Correlation − These are used to show the relationship between different values. Common chart types are −"
},
{
"code": null,
"e": 51561,
"s": 51548,
"text": "Scatter Plot"
},
{
"code": null,
"e": 51574,
"s": 51561,
"text": "Bubble Chart"
},
{
"code": null,
"e": 51588,
"s": 51574,
"text": "Network Chart"
},
{
"code": null,
"e": 51602,
"s": 51588,
"text": "Numeric Point"
},
{
"code": null,
"e": 51607,
"s": 51602,
"text": "Tree"
},
{
"code": null,
"e": 51703,
"s": 51607,
"text": "Trend − These are used to show the data patterns or possible patterns. Common chart types are −"
},
{
"code": null,
"e": 51714,
"s": 51703,
"text": "Line Chart"
},
{
"code": null,
"e": 51730,
"s": 51714,
"text": "Waterfall Chart"
},
{
"code": null,
"e": 51739,
"s": 51730,
"text": "Box Plot"
},
{
"code": null,
"e": 51766,
"s": 51739,
"text": "Parallel Coordinates Chart"
},
{
"code": null,
"e": 51885,
"s": 51766,
"text": "Geographic − These are used to present the map of a country or globe present in the analysis. Common chart types are −"
},
{
"code": null,
"e": 51902,
"s": 51885,
"text": "Geo Bubble Chart"
},
{
"code": null,
"e": 51923,
"s": 51902,
"text": "Geo Choropleth Chart"
},
{
"code": null,
"e": 51937,
"s": 51923,
"text": "Geo Pie Chart"
},
{
"code": null,
"e": 51945,
"s": 51937,
"text": "Geo Map"
},
{
"code": null,
"e": 52217,
"s": 51945,
"text": "You can connect to SAP HANA using Universe connectivity from the Dashboard. SAP Dashboard supports SAP HANA backed with the Universe created on top of HANA views and tables. You can consume Universe Designer .unx files using Query Browser option to develop the dashboard."
},
{
"code": null,
"e": 52394,
"s": 52217,
"text": "Query browser provides a flexible option to create a query on Universe and the results are embedded into a spreadsheet and bound dashboard components in the Dashboard Designer."
},
{
"code": null,
"e": 52431,
"s": 52394,
"text": "Open Dashboard Designer → File →New."
},
{
"code": null,
"e": 52576,
"s": 52431,
"text": "This opens a new untitled page with components, properties, object browser and a query browser pane. To add a query, click the Add Query button."
},
{
"code": null,
"e": 52870,
"s": 52576,
"text": "This will open a new dialog box that provides different options to select a data source - Universe on which you want to build a query. The Universe is built on top of HANA Views or tables using Universe Designer to create Data Foundation, and then the Business Layer is published to BO server."
},
{
"code": null,
"e": 53039,
"s": 52870,
"text": "Click Select a Universe on which you want to build a query and then click Next. It will take you to the next page, where you can build a query on the selected Universe."
},
{
"code": null,
"e": 53373,
"s": 53039,
"text": "In the next window, you have to select Result Objects from the Universe pane. Once you complete your query building, you can also check the preview of the result set using \"Data Preview / Result Set pane\" by clicking the refresh button. This shows you query run time and a number of rows fetched as shown in the following screenshot."
},
{
"code": null,
"e": 53640,
"s": 53373,
"text": "You have Usage Options tab at the top - which provides Refresh Option and Load Status. Refresh Option defines how the query will be refreshed. Load Status is used to define the Load status and configuration setting when the Dashboard is loading or is in idle status."
},
{
"code": null,
"e": 54027,
"s": 53640,
"text": "When the query is built on top of the Universe, next is to bound the result into a spreadsheet and map the Dashboard components with data. Now to insert the query result into a spreadsheet, select a particular result object and use the option \"Insert in Spreadsheet\" at the left bottom corner of the screen. This will bind the result set of that object to the \"Select Range\" dialog box."
},
{
"code": null,
"e": 54321,
"s": 54027,
"text": "In the above screenshot, you can see .unx file that shows the Universe name on which the query is created. Below that you have Result Objects - objects selected at the time of query building. On the right side of the screen, you have a spreadsheet where the result set from the query is bound."
},
{
"code": null,
"e": 54630,
"s": 54321,
"text": "To use Crystal Reports on top of SAP HANA views, you can use an OLAP connection, which directly points to the Business Layer in HANA Views. You can also connect to the Universe directly, which is created on top of SAP HANA views and tables. Crystal Reports can connect to multiple data sources that include −"
},
{
"code": null,
"e": 54639,
"s": 54630,
"text": "Universe"
},
{
"code": null,
"e": 54653,
"s": 54639,
"text": "SAP BEx Query"
},
{
"code": null,
"e": 54663,
"s": 54653,
"text": "HANA view"
},
{
"code": null,
"e": 54682,
"s": 54663,
"text": "Excel Spreadsheets"
},
{
"code": null,
"e": 54748,
"s": 54682,
"text": "To connect to a data source, go to File → New → From Data Source."
},
{
"code": null,
"e": 54865,
"s": 54748,
"text": "Following are the three ways in which you can connect Crystal Reports to HANA system - Database layer or HANA views."
},
{
"code": null,
"e": 54890,
"s": 54865,
"text": "Crystal Reports 2011 SP4"
},
{
"code": null,
"e": 54895,
"s": 54890,
"text": "JDBC"
},
{
"code": null,
"e": 54900,
"s": 54895,
"text": "ODBC"
},
{
"code": null,
"e": 54950,
"s": 54900,
"text": "Command objects and SQL\nExpressions are available"
},
{
"code": null,
"e": 54981,
"s": 54950,
"text": "Crystal Reports for Enterprise"
},
{
"code": null,
"e": 54989,
"s": 54981,
"text": "4.0 SP4"
},
{
"code": null,
"e": 54994,
"s": 54989,
"text": "JDBC"
},
{
"code": null,
"e": 54999,
"s": 54994,
"text": "ODBC"
},
{
"code": null,
"e": 55060,
"s": 54999,
"text": "Direct-to-data connections are available with FP3 and higher"
},
{
"code": null,
"e": 55091,
"s": 55060,
"text": "Crystal Reports for Enterprise"
},
{
"code": null,
"e": 55099,
"s": 55091,
"text": "4.0 SP4"
},
{
"code": null,
"e": 55115,
"s": 55099,
"text": "Universe (.unx)"
},
{
"code": null,
"e": 55135,
"s": 55115,
"text": "Relational Universe"
},
{
"code": null,
"e": 55236,
"s": 55135,
"text": "Following are the scenarios, which define the direct connectivity to HANA or the use of a Universe −"
},
{
"code": null,
"e": 55303,
"s": 55236,
"text": "When you already have a Universe published with the Business Layer"
},
{
"code": null,
"e": 55348,
"s": 55303,
"text": "When a HANA view with a variable is required"
},
{
"code": null,
"e": 55381,
"s": 55348,
"text": "When a Universe is not available"
},
{
"code": null,
"e": 55414,
"s": 55381,
"text": "When a Universe is not available"
},
{
"code": null,
"e": 55507,
"s": 55414,
"text": "When you are using Crystal Reports 2011 and not Crystal Reports for Enterprise for reporting"
},
{
"code": null,
"e": 55600,
"s": 55507,
"text": "When you are using Crystal Reports 2011 and not Crystal Reports for Enterprise for reporting"
},
{
"code": null,
"e": 55690,
"s": 55600,
"text": "When you are willing to use the custom SQL query using a Command Object or SQL Expression"
},
{
"code": null,
"e": 55780,
"s": 55690,
"text": "When you are willing to use the custom SQL query using a Command Object or SQL Expression"
},
{
"code": null,
"e": 55849,
"s": 55780,
"text": "When you want to access stored procedures, tables and views directly"
},
{
"code": null,
"e": 55918,
"s": 55849,
"text": "When you want to access stored procedures, tables and views directly"
},
{
"code": null,
"e": 56064,
"s": 55918,
"text": "To develop a report on top of HANA views, you can use direct connection to HANA views. You have to select SAP HANA Platform (Select a HANA view)."
},
{
"code": null,
"e": 56281,
"s": 56064,
"text": "Once you click the New Server... option, it will open the Server Connections window. If you have an existing connection, you can use Import Connections. You can also add a new connection by clicking the \"Add\" button."
},
{
"code": null,
"e": 56354,
"s": 56281,
"text": "Once you click the Add button, you have to enter the following details −"
},
{
"code": null,
"e": 56378,
"s": 56354,
"text": "Connection Display Name"
},
{
"code": null,
"e": 56390,
"s": 56378,
"text": "HANA Server"
},
{
"code": null,
"e": 56411,
"s": 56390,
"text": "HANA Server Instance"
},
{
"code": null,
"e": 56421,
"s": 56411,
"text": "User Name"
},
{
"code": null,
"e": 56591,
"s": 56421,
"text": "Once you connect to HANA system, it will display all OLAP metadata in HANA repository. You have to navigate to the required package and select view that you want to use."
},
{
"code": null,
"e": 56714,
"s": 56591,
"text": "You can select from an Analytic View or a Calculation view. Click OK and then the Next button at the bottom of the screen."
},
{
"code": null,
"e": 56947,
"s": 56714,
"text": "This will open all the dimensions and measure in the query panel. You have to drag all the objects to the Result Object fields. You can also add a filter at the query panel and click Finish. Then, choose from the following options −"
},
{
"code": null,
"e": 56963,
"s": 56947,
"text": "Generate report"
},
{
"code": null,
"e": 56981,
"s": 56963,
"text": "Show in page mode"
},
{
"code": null,
"e": 57047,
"s": 56981,
"text": "You can navigate to Structure and Page mode to design the report."
},
{
"code": null,
"e": 57294,
"s": 57047,
"text": "Once the Crystal Report is created using a query, to make changes to the objects you have to go to the Edit Data Sources... option. When you click the option, it will open an Edit Query panel, where you can add/delete objects, apply filters, etc."
},
{
"code": null,
"e": 57400,
"s": 57294,
"text": "You can also edit an existing query by going to Data → Edit Data Sources as shown in the following image."
},
{
"code": null,
"e": 57520,
"s": 57400,
"text": "Once you are done with the changes, click Finish and all the changes will be applied to the data in the Crystal Report."
},
{
"code": null,
"e": 57797,
"s": 57520,
"text": "Using BW powered by SAP HANA, you can achieve excellent performance in analytical reporting and data loading using HANA in-memory database capabilities. All BW functions performed in SAP HANA benefits from in-memory database and calculation engines for faster data processing."
},
{
"code": null,
"e": 57900,
"s": 57797,
"text": "To create a BW Project in HANA, you can use SAP HANA Studio. Go to Windows → Open Perspective → Other."
},
{
"code": null,
"e": 57968,
"s": 57900,
"text": "Select BW Modeling → Click OK as shown in the following screenshot."
},
{
"code": null,
"e": 58002,
"s": 57968,
"text": "Next, go to File → New → Project."
},
{
"code": null,
"e": 58202,
"s": 58002,
"text": "In the next window, select SAP connection. You can select an existing connection or define a connection manually to add a new connection. System connections are maintained in the SAP Logon. Click OK."
},
{
"code": null,
"e": 58312,
"s": 58202,
"text": "In the next screen, as shown in the following screenshot enter the client, username and password. Click Next."
},
{
"code": null,
"e": 58358,
"s": 58312,
"text": "Now, enter the project name and click Finish."
},
{
"code": null,
"e": 58570,
"s": 58358,
"text": "Right-click your new root project folder and choose Attach SAP HANA System. Choose the preconfigured HANA system HDB and click Finish. Only connected SAP HANA system can be attached. Select HANA system → Finish."
},
{
"code": null,
"e": 58723,
"s": 58570,
"text": "To define a BW query on your InfoCube, select the InfoCube in BW Modeling Perspective, right-click and click New → BW Query and select the InfoProvider."
},
{
"code": null,
"e": 58813,
"s": 58723,
"text": "Enter the name and description and then click Finish. This is how you can add a BW query."
},
{
"code": null,
"e": 58927,
"s": 58813,
"text": "You can apply different functions in BW query. You can apply filters, define local formulas for calculation, etc."
},
{
"code": null,
"e": 58993,
"s": 58927,
"text": "To save BW query, click the Save button at the top of the screen."
},
{
"code": null,
"e": 59154,
"s": 58993,
"text": "Using SAP Design Studio, you can create new Analysis applications. SAP Design Studio provides a list of predefined template suitable to open in the web browser."
},
{
"code": null,
"e": 59338,
"s": 59154,
"text": "You can create an analysis application using different data sources - SAP BW or SAP HANA. To connect to SAP HANA, use the existing backend connections. Navigate to Tool → Preferences."
},
{
"code": null,
"e": 59423,
"s": 59338,
"text": "In the Preferences window, navigate to Application Design tab → Backend Connections."
},
{
"code": null,
"e": 59522,
"s": 59423,
"text": "To create a new connection to SAP HANA using HDB ODBC drivers, click the icon to add a connection."
},
{
"code": null,
"e": 59591,
"s": 59522,
"text": "In the ODBC Data Source Administrator, go to System DSN → click Add."
},
{
"code": null,
"e": 59737,
"s": 59591,
"text": "In a new window, search for the HDB ODBC database drivers. These drivers get installed when you install SAP HANA client. Click the Finish button."
},
{
"code": null,
"e": 59804,
"s": 59737,
"text": "In the new window, enter the following details of the HANA system."
},
{
"code": null,
"e": 59819,
"s": 59804,
"text": "HANA Host name"
},
{
"code": null,
"e": 59875,
"s": 59819,
"text": "Port Number/Instance Number (3xx15, xx-instance number)"
},
{
"code": null,
"e": 59930,
"s": 59875,
"text": "User name and Password for authentication and click OK"
},
{
"code": null,
"e": 60134,
"s": 59930,
"text": "To perform the connection check, click the Connect button → Connection Successful. To see the new connection, click the Reload connection. To use the connection, you may need to reopen the Design Studio."
},
{
"code": null,
"e": 60321,
"s": 60134,
"text": "SAP Design Studio provides predefined templates that can be used to create new Analysis applications. These predefined templates are suitable to open in Web browsers or mobile platforms."
},
{
"code": null,
"e": 60390,
"s": 60321,
"text": "To create a new analysis application, navigate to Application → New."
},
{
"code": null,
"e": 60499,
"s": 60390,
"text": "In the next window, enter the Name of the application and Description. You can select the Template category."
},
{
"code": null,
"e": 60647,
"s": 60499,
"text": "SAP Design Studio also provides you the brief description of each template with the template name. Select the template and click the Finish button."
},
{
"code": null,
"e": 60824,
"s": 60647,
"text": "To create a dashboard, navigate to the Components view tab. Select any component from the list of available objects, and drag the component of your choice into the editor area."
},
{
"code": null,
"e": 61036,
"s": 60824,
"text": "The properties of this component are available for editing under the Properties view. In the Properties view, click the property you want to change. A field can have different values as per the following types −"
},
{
"code": null,
"e": 61072,
"s": 61036,
"text": "Numeric − Such as layout properties"
},
{
"code": null,
"e": 61108,
"s": 61072,
"text": "Numeric − Such as layout properties"
},
{
"code": null,
"e": 61139,
"s": 61108,
"text": "String − Such as caption, etc."
},
{
"code": null,
"e": 61170,
"s": 61139,
"text": "String − Such as caption, etc."
},
{
"code": null,
"e": 61233,
"s": 61170,
"text": "Boolean − Such as True/False from the dropdown for Style, etc."
},
{
"code": null,
"e": 61296,
"s": 61233,
"text": "Boolean − Such as True/False from the dropdown for Style, etc."
},
{
"code": null,
"e": 61307,
"s": 61296,
"text": "Dialog Box"
},
{
"code": null,
"e": 61318,
"s": 61307,
"text": "Dialog Box"
},
{
"code": null,
"e": 61410,
"s": 61318,
"text": "To add data to your chart, navigate to Data Binding and select a data source from the list."
},
{
"code": null,
"e": 61506,
"s": 61410,
"text": "Similarly, you can define other properties of your chart. Following properties can be defined −"
},
{
"code": null,
"e": 61514,
"s": 61506,
"text": "General"
},
{
"code": null,
"e": 61522,
"s": 61514,
"text": "Display"
},
{
"code": null,
"e": 61529,
"s": 61522,
"text": "Events"
},
{
"code": null,
"e": 61536,
"s": 61529,
"text": "Layout"
},
{
"code": null,
"e": 61664,
"s": 61536,
"text": "Once you assign a data source and manage chart properties, you can save the application by clicking the Save button at the top."
},
{
"code": null,
"e": 61912,
"s": 61664,
"text": "You can also connect to a Universe in Design Studio, which is based on SAP HANA views and tables. To connect to a Universe Data Source (UDS), go to the Data Source folder under Outline in a new analysis application → Right click → Add Data Source."
},
{
"code": null,
"e": 62034,
"s": 61912,
"text": "Let us see how to add a Universe as a data source. Click the Browse tab against Connection in the Add Data Source window."
},
{
"code": null,
"e": 62269,
"s": 62034,
"text": "Once you select a Universe, edit the query panel. Click the Edit Query specification. Add the dimensions and measures to result objects. You can expand each of these folders in the left pane and add objects to dimensions and measures."
},
{
"code": null,
"e": 62401,
"s": 62269,
"text": "You can add this data source to chart components or you can also go to Edit Initial View of data source and select Create Crosstab."
},
{
"code": null,
"e": 62529,
"s": 62401,
"text": "A Crosstab has been added to the editor area and this is how you can connect to the Universe based on SAP HANA views or tables."
},
{
"code": null,
"e": 62663,
"s": 62529,
"text": "It is possible to publish BI reports and dashboards to HANA BI platform. You can also publish dataset in SAP Lumira to HANA platform."
},
{
"code": null,
"e": 62791,
"s": 62663,
"text": "In SAP Lumira, you can see the saved dataset in Share tab under Dataset. To publish a dataset, navigate to Publish to SAP HANA."
},
{
"code": null,
"e": 62992,
"s": 62791,
"text": "To publish to HANA, you have to note that the only dataset is published to HANA server and not visualizations. Enter the details of HANA system, i.e. Server, Instance, User Password and click Connect."
},
{
"code": null,
"e": 63047,
"s": 62992,
"text": "You have an option to select a new Package and a View."
},
{
"code": null,
"e": 63303,
"s": 63047,
"text": "SAP HANA is an in-memory database that provides exceptional calculation capabilities, analytical reporting, and real-time application development. Key capabilities of SAP HANA is mentioned on SAP site link − https://www.sap.com/products/hana/features.html"
},
{
"code": null,
"e": 63352,
"s": 63303,
"text": "Following are the advantages of using SAP HANA −"
},
{
"code": null,
"e": 63594,
"s": 63352,
"text": "SAP HANA in-memory database services provide the capability of processing high-speed transactions and analytics. It helps in managing large database volumes using multitenant database containers and dynamic tiering across multi-tier storage."
},
{
"code": null,
"e": 63786,
"s": 63594,
"text": "Using HANA in-memory processing capability - text, predictive, spatial, graph, streaming, and time series - you can get answers to any business question and make smart decisions in real time."
},
{
"code": null,
"e": 63919,
"s": 63786,
"text": "Using SAP HANA, you can develop next-generation applications that combine analytics and transactions, and deploy them on any device."
},
{
"code": null,
"e": 64169,
"s": 63919,
"text": "SAP HANA helps the organization in getting accurate and complete view of business by accessing data from different sources. HANA provides real-time data replication and data quality to improve decision making from internal and external data sources."
},
{
"code": null,
"e": 64284,
"s": 64169,
"text": "SAP HANA ensures application availability and tools to monitor processes along with data and application security."
},
{
"code": null,
"e": 64489,
"s": 64284,
"text": "SAP HANA provides a dashboard to monitor all KPIs related to security. It helps in keeping communications, data storage, and application services secure with robust identity and access management control."
},
{
"code": null,
"e": 64812,
"s": 64489,
"text": "There are various certified and non-certified non-SAP BI tools that can connect to SAP HANA system for analytical reporting and dashboard requirements. Various tools such as Tableau, Microsoft Excel, and other BI tools can directly connect to HANA using custom SQL query, direct connection, or MDX provider for connection."
},
{
"code": null,
"e": 64904,
"s": 64812,
"text": "Let us see how we can connect Tableau and MS Excel to connect to HANA system for reporting."
},
{
"code": null,
"e": 65101,
"s": 64904,
"text": "You can connect Tableau to SAP HANA database and set up a data source for reporting. You have to install a driver to talk to the database and require HANA system details and authentication method."
},
{
"code": null,
"e": 65183,
"s": 65101,
"text": "Before you connect to HANA system, you should check the following prerequisites −"
},
{
"code": null,
"e": 65451,
"s": 65183,
"text": "A driver should be installed for HANA to talk to the database. If the driver is not installed and you try to connect, Tableau displays an error message with a link to the Driver Download page. You can install drivers for Tableau connectivity from the following link −"
},
{
"code": null,
"e": 65491,
"s": 65451,
"text": "https://www.tableau.com/support/drivers"
},
{
"code": null,
"e": 65657,
"s": 65491,
"text": "Once you have the drivers installed, start Tableau desktop tool. Under Connect category, select SAP HANA. For a complete list of data connections, click More option."
},
{
"code": null,
"e": 65771,
"s": 65657,
"text": "Next, enter the name of the server that hosts the database you want to connect to and the authentication details."
},
{
"code": null,
"e": 65887,
"s": 65771,
"text": "You can also see an option of Initial SQL that specifies a SQL command to run at the beginning of every connection."
},
{
"code": null,
"e": 66112,
"s": 65887,
"text": "In the next window, select the Schema name from the dropdown list. You can also use the Search option at the top of the screen to find a particular schema. Once you select the schema name, add the table to the report canvas."
},
{
"code": null,
"e": 66261,
"s": 66112,
"text": "Drag the table to the canvas, and then select the sheet tab to start your analysis. By default, column labels are displayed instead of column names."
},
{
"code": null,
"e": 66383,
"s": 66261,
"text": "You also have an option to use Custom SQL option that allows you to connect to specific query and not to a full database."
},
{
"code": null,
"e": 66621,
"s": 66383,
"text": "You can also connect Microsoft Excel to HANA views using a MDX provider. MS Excel is considered as one of the most common BI reporting tool. Business users can connect to HANA database and draw Pivot tables and charts as per requirement."
},
{
"code": null,
"e": 66795,
"s": 66621,
"text": "Open Excel and navigate to Data tab → Click the option from other sources → Click Data connection wizard → Other/Advanced. Click Next and the Data link properties will open."
},
{
"code": null,
"e": 67008,
"s": 66795,
"text": "Next, select SAP HANA MDX Provider from this list to connect to any MDX data source → Enter HANA system details (server name, instance, user name and password) → Click Test Connection → Connection succeeded → OK."
},
{
"code": null,
"e": 67341,
"s": 67008,
"text": "Once you connect to HANA system, you can see a list of all packages in the dropdown list that are available in HANA repository. You can select an Information view → Click Next. Then, select Pivot table/others → OK. On the right side of the screen, you will see all the dimension and measure values that you can use to create charts."
},
{
"code": null,
"e": 67374,
"s": 67341,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 67388,
"s": 67374,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 67421,
"s": 67388,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 67433,
"s": 67421,
"text": " Neha Gupta"
},
{
"code": null,
"e": 67468,
"s": 67433,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 67483,
"s": 67468,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 67516,
"s": 67483,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 67531,
"s": 67516,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 67566,
"s": 67531,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 67578,
"s": 67566,
"text": " Neha Malik"
},
{
"code": null,
"e": 67613,
"s": 67578,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 67625,
"s": 67613,
"text": " Neha Malik"
},
{
"code": null,
"e": 67632,
"s": 67625,
"text": " Print"
},
{
"code": null,
"e": 67643,
"s": 67632,
"text": " Add Notes"
}
]
|
Redis - Server Flushall Command | Redis FLUSHALL deletes all the keys of all the existing databases, not just the currently selected one. This command never fails.
String reply.
Following is the basic syntax of Redis FLUSHALL command.
redis 127.0.0.1:6379> FLUSHALL
redis 127.0.0.1:6379> FLUSHALL
OK
22 Lectures
40 mins
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2175,
"s": 2045,
"text": "Redis FLUSHALL deletes all the keys of all the existing databases, not just the currently selected one. This command never fails."
},
{
"code": null,
"e": 2189,
"s": 2175,
"text": "String reply."
},
{
"code": null,
"e": 2246,
"s": 2189,
"text": "Following is the basic syntax of Redis FLUSHALL command."
},
{
"code": null,
"e": 2279,
"s": 2246,
"text": "redis 127.0.0.1:6379> FLUSHALL \n"
},
{
"code": null,
"e": 2316,
"s": 2279,
"text": "redis 127.0.0.1:6379> FLUSHALL \nOK\n"
},
{
"code": null,
"e": 2348,
"s": 2316,
"text": "\n 22 Lectures \n 40 mins\n"
},
{
"code": null,
"e": 2368,
"s": 2348,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2375,
"s": 2368,
"text": " Print"
},
{
"code": null,
"e": 2386,
"s": 2375,
"text": " Add Notes"
}
]
|
Convert String into Binary Sequence - GeeksforGeeks | 14 Jul, 2021
Given a string of character the task is to convert each character of a string into the equivalent binary number.Examples :
Input : GFG
Output : 1000111 1000110 1000111
Input : geeks
Output : 1100111 1100101 1100101 1101011 1110011
The idea is to first calculate the length of the string as n and then run a loop n times. In each iteration store ASCII value of character in variable val and then convert it into binary number and store result in array finally print the array in reverse order.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to convert// string into binary string#include <bits/stdc++.h>using namespace std; // utility functionvoid strToBinary(string s){ int n = s.length(); for (int i = 0; i <= n; i++) { // convert each char to // ASCII value int val = int(s[i]); // Convert ASCII value to binary string bin = ""; while (val > 0) { (val % 2)? bin.push_back('1') : bin.push_back('0'); val /= 2; } reverse(bin.begin(), bin.end()); cout << bin << " "; }} // driver codeint main(){ string s = "geeks"; strToBinary(s); return 0;}
// Java program to convert// string into binary stringimport java.util.*; class Node{ // utility function static void strToBinary(String s) { int n = s.length(); for (int i = 0; i < n; i++) { // convert each char to // ASCII value int val = Integer.valueOf(s.charAt(i)); // Convert ASCII value to binary String bin = ""; while (val > 0) { if (val % 2 == 1) { bin += '1'; } else bin += '0'; val /= 2; } bin = reverse(bin); System.out.print(bin + " "); } } static String reverse(String input) { char[] a = input.toCharArray(); int l, r = 0; r = a.length - 1; for (l = 0; l < r; l++, r--) { // Swap values of l and r char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a); } // Driver code public static void main(String[] args) { String s = "geeks"; strToBinary(s); }} // This code is contributed by 29AjayKumar
# Python 3 program to convert# string into binary string # utility functiondef strToBinary(s): bin_conv = [] for c in s: # convert each char to # ASCII value ascii_val = ord(c) # Convert ASCII value to binary binary_val = bin(ascii_val) bin_conv.append(binary_val[2:]) return (' '.join(bin_conv)) # Driver Codeif __name__ == '__main__': s = 'geeks' print (strToBinary(s)) # This code is contributed# by Vikas Chitturi
// C# program to convert// string into binary stringusing System; public class Node{ // utility function static void strToBinary(String s) { int n = s.Length; for (int i = 0; i < n; i++) { // convert each char to // ASCII value int val = s[i]; // Convert ASCII value to binary String bin = ""; while (val > 0) { if (val % 2 == 1) { bin += '1'; } else bin += '0'; val /= 2; } bin = reverse(bin); Console.Write(bin + " "); } } static String reverse(String input) { char[] a = input.ToCharArray(); int l, r = 0; r = a.Length - 1; for (l = 0; l < r; l++, r--) { // Swap values of l and r char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join("",a); } // Driver code public static void Main(String[] args) { String s = "geeks"; strToBinary(s); }} /* This code is contributed by PrinciRaj1992 */
<?php// PHP program to convert// string into binary string // utility functionfunction strToBinary($s){ $n = strlen($s); for ($i = 0; $i < $n; $i++) { // convert each char to // ASCII value $val = ord($s[$i]); // Convert ASCII value to // binary $bin = ""; while ($val > 0) { ($val % 2)? $bin=$bin.'1' : $bin=$bin.'0'; $val= floor($val / 2); } for($x = strlen($bin) - 1; $x >= 0; $x--) echo $bin[$x]; echo " "; }} // Driver code$s = "geeks";strToBinary($s); // This code is contributed by mits?>
<script>// Javascript program to convert// string into binary string // utility functionfunction strToBinary(s){ let n = s.length; for (let i = 0; i < n; i++) { // convert each char to // ASCII value let val = (s[i]).charCodeAt(0); // Convert ASCII value to binary let bin = ""; while (val > 0) { if (val % 2 == 1) { bin += '1'; } else bin += '0'; val = Math.floor(val/2); } bin = reverse(bin); document.write(bin + " "); }} function reverse(input){ a = input.split(""); let l, r = 0; r = a.length - 1; for (l = 0; l < r; l++, r--) { // Swap values of l and r let temp = a[l]; a[l] = a[r]; a[r] = temp; } return (a).join("");} // Driver codelet s = "geeks";strToBinary(s); // This code is contributed by rag2127</script>
Output :
1100111 1100101 1100101 1101011 1110011
YouTubeGeeksforGeeks500K subscribersConvert String into Binary Sequence | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0vgJghmGRJc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Mithun Kumar
Vikas Chitturi
29AjayKumar
princiraj1992
rag2127
binary-string
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 String Coding Problems for Interviews
Hill Cipher
Naive algorithm for Pattern Searching
Vigenère Cipher
How to Append a Character to a String in C
Convert character array to string in C++
Reverse words in a given String in Python
Print all the duplicates in the input string
sprintf() in C
Print all subsequences of a string | [
{
"code": null,
"e": 24772,
"s": 24744,
"text": "\n14 Jul, 2021"
},
{
"code": null,
"e": 24897,
"s": 24772,
"text": "Given a string of character the task is to convert each character of a string into the equivalent binary number.Examples : "
},
{
"code": null,
"e": 25013,
"s": 24897,
"text": " \nInput : GFG\nOutput : 1000111 1000110 1000111 \n\nInput : geeks\nOutput : 1100111 1100101 1100101 1101011 1110011 "
},
{
"code": null,
"e": 25278,
"s": 25015,
"text": "The idea is to first calculate the length of the string as n and then run a loop n times. In each iteration store ASCII value of character in variable val and then convert it into binary number and store result in array finally print the array in reverse order. "
},
{
"code": null,
"e": 25282,
"s": 25278,
"text": "C++"
},
{
"code": null,
"e": 25287,
"s": 25282,
"text": "Java"
},
{
"code": null,
"e": 25295,
"s": 25287,
"text": "Python3"
},
{
"code": null,
"e": 25298,
"s": 25295,
"text": "C#"
},
{
"code": null,
"e": 25302,
"s": 25298,
"text": "PHP"
},
{
"code": null,
"e": 25313,
"s": 25302,
"text": "Javascript"
},
{
"code": "// C++ program to convert// string into binary string#include <bits/stdc++.h>using namespace std; // utility functionvoid strToBinary(string s){ int n = s.length(); for (int i = 0; i <= n; i++) { // convert each char to // ASCII value int val = int(s[i]); // Convert ASCII value to binary string bin = \"\"; while (val > 0) { (val % 2)? bin.push_back('1') : bin.push_back('0'); val /= 2; } reverse(bin.begin(), bin.end()); cout << bin << \" \"; }} // driver codeint main(){ string s = \"geeks\"; strToBinary(s); return 0;}",
"e": 25970,
"s": 25313,
"text": null
},
{
"code": "// Java program to convert// string into binary stringimport java.util.*; class Node{ // utility function static void strToBinary(String s) { int n = s.length(); for (int i = 0; i < n; i++) { // convert each char to // ASCII value int val = Integer.valueOf(s.charAt(i)); // Convert ASCII value to binary String bin = \"\"; while (val > 0) { if (val % 2 == 1) { bin += '1'; } else bin += '0'; val /= 2; } bin = reverse(bin); System.out.print(bin + \" \"); } } static String reverse(String input) { char[] a = input.toCharArray(); int l, r = 0; r = a.length - 1; for (l = 0; l < r; l++, r--) { // Swap values of l and r char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a); } // Driver code public static void main(String[] args) { String s = \"geeks\"; strToBinary(s); }} // This code is contributed by 29AjayKumar",
"e": 27194,
"s": 25970,
"text": null
},
{
"code": "# Python 3 program to convert# string into binary string # utility functiondef strToBinary(s): bin_conv = [] for c in s: # convert each char to # ASCII value ascii_val = ord(c) # Convert ASCII value to binary binary_val = bin(ascii_val) bin_conv.append(binary_val[2:]) return (' '.join(bin_conv)) # Driver Codeif __name__ == '__main__': s = 'geeks' print (strToBinary(s)) # This code is contributed# by Vikas Chitturi",
"e": 27694,
"s": 27194,
"text": null
},
{
"code": "// C# program to convert// string into binary stringusing System; public class Node{ // utility function static void strToBinary(String s) { int n = s.Length; for (int i = 0; i < n; i++) { // convert each char to // ASCII value int val = s[i]; // Convert ASCII value to binary String bin = \"\"; while (val > 0) { if (val % 2 == 1) { bin += '1'; } else bin += '0'; val /= 2; } bin = reverse(bin); Console.Write(bin + \" \"); } } static String reverse(String input) { char[] a = input.ToCharArray(); int l, r = 0; r = a.Length - 1; for (l = 0; l < r; l++, r--) { // Swap values of l and r char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join(\"\",a); } // Driver code public static void Main(String[] args) { String s = \"geeks\"; strToBinary(s); }} /* This code is contributed by PrinciRaj1992 */",
"e": 28904,
"s": 27694,
"text": null
},
{
"code": "<?php// PHP program to convert// string into binary string // utility functionfunction strToBinary($s){ $n = strlen($s); for ($i = 0; $i < $n; $i++) { // convert each char to // ASCII value $val = ord($s[$i]); // Convert ASCII value to // binary $bin = \"\"; while ($val > 0) { ($val % 2)? $bin=$bin.'1' : $bin=$bin.'0'; $val= floor($val / 2); } for($x = strlen($bin) - 1; $x >= 0; $x--) echo $bin[$x]; echo \" \"; }} // Driver code$s = \"geeks\";strToBinary($s); // This code is contributed by mits?>",
"e": 29611,
"s": 28904,
"text": null
},
{
"code": "<script>// Javascript program to convert// string into binary string // utility functionfunction strToBinary(s){ let n = s.length; for (let i = 0; i < n; i++) { // convert each char to // ASCII value let val = (s[i]).charCodeAt(0); // Convert ASCII value to binary let bin = \"\"; while (val > 0) { if (val % 2 == 1) { bin += '1'; } else bin += '0'; val = Math.floor(val/2); } bin = reverse(bin); document.write(bin + \" \"); }} function reverse(input){ a = input.split(\"\"); let l, r = 0; r = a.length - 1; for (l = 0; l < r; l++, r--) { // Swap values of l and r let temp = a[l]; a[l] = a[r]; a[r] = temp; } return (a).join(\"\");} // Driver codelet s = \"geeks\";strToBinary(s); // This code is contributed by rag2127</script>",
"e": 30694,
"s": 29611,
"text": null
},
{
"code": null,
"e": 30705,
"s": 30694,
"text": "Output : "
},
{
"code": null,
"e": 30747,
"s": 30705,
"text": "1100111 1100101 1100101 1101011 1110011 "
},
{
"code": null,
"e": 31583,
"s": 30749,
"text": "YouTubeGeeksforGeeks500K subscribersConvert String into Binary Sequence | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=0vgJghmGRJc\" 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": 31598,
"s": 31585,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 31613,
"s": 31598,
"text": "Vikas Chitturi"
},
{
"code": null,
"e": 31625,
"s": 31613,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31639,
"s": 31625,
"text": "princiraj1992"
},
{
"code": null,
"e": 31647,
"s": 31639,
"text": "rag2127"
},
{
"code": null,
"e": 31661,
"s": 31647,
"text": "binary-string"
},
{
"code": null,
"e": 31669,
"s": 31661,
"text": "Strings"
},
{
"code": null,
"e": 31677,
"s": 31669,
"text": "Strings"
},
{
"code": null,
"e": 31775,
"s": 31677,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31784,
"s": 31775,
"text": "Comments"
},
{
"code": null,
"e": 31797,
"s": 31784,
"text": "Old Comments"
},
{
"code": null,
"e": 31842,
"s": 31797,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 31854,
"s": 31842,
"text": "Hill Cipher"
},
{
"code": null,
"e": 31892,
"s": 31854,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 31909,
"s": 31892,
"text": "Vigenère Cipher"
},
{
"code": null,
"e": 31952,
"s": 31909,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 31993,
"s": 31952,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 32035,
"s": 31993,
"text": "Reverse words in a given String in Python"
},
{
"code": null,
"e": 32080,
"s": 32035,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 32095,
"s": 32080,
"text": "sprintf() in C"
}
]
|
Power BI and Synapse, Part 1: The Art of the (Im)possible | by Nikola Ilic | Towards Data Science | By introducing Azure Synapse Analytics in late 2019, a whole new perspective was created when it comes to data treatment. Some core concepts, such as traditional data warehousing, came under more scrutiny, while various fresh approaches started to pop up after data nerds became aware of the new capabilities that Synapse brought to the table.
Not that Synapse made a strong impact on data ingestion, transformation, and storage options only — it also offered a whole new set of possibilities for data serving and visualization!
Therefore, in this series of blog posts, I will try to explore how Power BI works in synergy with the new platform. What options we, Power BI developers, have when working with Synapse? In which data analytics scenarios, Synapse will play on the edge, helping you to achieve the (im)possible? When would you want to take advantage of the innovative solutions within Synapse, and when would you be better sticking with more conventional approaches? What are the best practices when using Power BI — Synapse combo, and which parameters should you evaluate before making a final decision on which path to take.
Once we’re done, I believe that you should get a better understanding of the “pros” and “cons” for each of the available options when it comes to integration between Power BI and Synapse.
Since Power BI is already a mature and well-known product (it celebrated its 5th birthday last July), before we dive into the relationship between Power BI and Synapse, I believe that we will need to spend some time learning about the “younger” technology...
As I already mentioned, Synapse has been introduced about 2 years ago (late 2019.) and became generally available in March this year. Officially, it succeeded Azure SQL Data Warehouse (SQL DW) and was presented as an evolution of the SQL DW.
So, would it be fair if we think of Synapse as a “new kid on the block”, or just as a rebranding of the existing product?
Before we answer this question, let’s first take a look into traditional data warehousing architecture:
In a typical traditional data warehousing scenario, you would collect your data from multiple different sources, perform some transformations, data cleansing, etc. before putting consolidated data into a relational data warehouse. This was the focal point of your reporting solutions, a “single source of truth” for your data, and you could build various reports from there, using a whole range of tools — such as Crystal Reports, SSRS, or Power BI, if we talk about Microsoft’s solutions. You could also build an additional semantic layer using SSAS to create “cubes” (both tabular and multidimensional), and then target those cubes with reporting tools mentioned above (don’t forget good old Excel too).
Now, with Azure Synapse Analytics, you are getting all these (and many more) functionalities under one roof! Even if you don’t have SSAS included in Synapse by default, you can link it as an external service.
Can you recognize the object in the following picture?
Yes, that’s the famous “Swiss knife”. You can cut the paper, open a bottle of wine or beer, or cut some smaller items — all of that using one single tool!
So, if you’re asking yourself — what on Earth does a Swiss knife have in common with Synapse?! Well, you can think of Synapse as a single tool that can satisfy all your data needs.
Do you need to import data from multiple different sources? Synapse can do that. Do you need to transform data before serving it? Synapse can do that, too. Do you need to store the data? Synapse can do it for you. Do you need to query non-relational data, or even files directly? Synapse can do that.
Watch out now: do you need to query non-relational data, or even files directly, using plain old T-SQL? Synapse CAN DO THAT! Whaaaaat???!!!! Yes, you can write T-SQL to query data from CSV, JSON, or parquet files. But, more on that later in the series. Do you need to build machine learning models? Synapse can manage this for you. Finally, do you need to create your Power BI report straight from the Synapse? Yes, that is also possible!
As you may notice, Synapse is a one-stop service for all your data tasks.
When I’m explaining some technical stuff, I like to make comparisons to non-technical things, so that people without a technical background can understand the essential underlying concept.
Now, you probably know when you travel to a famous tourist city for the first time, you want to visit all the important places: museums, sightseeing, local attractions... And the majority of these cities offer you a “City Card”. You can use that one single card to enter all of the main city attractions, which saves your time and money.
You can think of Azure Synapse Studio as “that” kind of card. It’s a unified workspace for all different tasks — from data preparation, data warehousing, monitoring and manage resources, etc.
Now, we are ready to scratch under the surface and examine the core components of the Synapse Workspace.
The most important part is the Analytic Engines. There are three different engines within the Synapse Workspace. Two of them are SQL-flavored (Dedicated SQL Pool and Serverless SQL pool), while the third is based on Apache Spark (Apache Spark Pool).
Also, two of them are provisioned (Dedicated SQL Pool and Apache Spark Pool), while the third (Serverless SQL pool) works like a serverless solution. In the most simplified way, it looks something like this:
In this blog series, we will not analyze the Spark pool, as our focus will be SQL-based solutions, especially the Serverless SQL pool.
As soon as you create a Synapse Workspace, you will see a Serverless SQL pool under your SQL pools:
In my opinion, this is one of the revolutionary features of Synapse. Essentially, what a Serverless SQL pool could do for you is hardly beatable: you can query data directly within your data lake, without the need to transfer or copy it anywhere! Moreover, you can query the data in the data lake writing plain old T-SQL! Yes, CSV, JSON, and parquet files included!
Since it is a serverless system, you don’t need to set up any kind of infrastructure, or clusters. You can literally start querying your data as soon as your workspace is created! Serverless SQL pool works as a standalone Polybase service, so there are no costs for the resources reserved. You are only being charged for the volume of data processed by your queries (at the moment of writing, it is 5 $/1 TB). Just keep in mind, when you’re planning your workloads, that the minimal billing volume is 10 MB. This minimal threshold doesn’t apply to metadata queries, so you don’t have to worry that you will be charged at all if you execute something like:
SELECT * FROM sys.objects
Having this tool under your belt lets you think about an indefinite number of possible approaches:
You can quickly perform ad-hoc queries over data in the data lake before you decide what is the best possible way to gain more insights from it
You can build an additional logical layer, a kind of “abstract” data warehouse on top of raw, or non-relational data, without moving data to a physical storage
You can transform data directly in the data lake, and consume it directly from there (for example, using Power BI)
As already mentioned, you can use T-SQL to query the data directly from the data lake. And not just that! You can also write T-SQL to retrieve data from Spark tables and CosmosDB.
Writing T-SQL for querying non-SQL Server data is being achieved by using an extended version of the OPENROWSET function. Because of the non-native usage, there are obviously a few limitations regarding some T-SQL functionalities.
I strongly suggest reading this article on James Serra’s blog, where he collected and answered a lot of questions regarding the Serverless SQL pool.
There is also a great overview of the best practices related to the Serverless SQL pool here.
Yes, I know that it sounds like we need a magic wand to query the data directly from the parquet file using plain T-SQL...But, it’s possible! And, trust me, you don’t need to be a magician — some basic T-SQL knowledge will suffice.
In this example, I’ve used a sample NYC Taxi dataset. Data is stored in a parquet file, but I can use the OPENROWSET function within my T-SQL syntax to query the ~1.5 billion record dataset like it is stored in my SQL Server database! How cool is that!
Additionally, I can extend on this and perform all kinds of aggregations, groupings, where clauses...
If that wasn’t enough, watch this:
Here is the T-SQL code that was run over two parquet files:
WITH taxi_rides AS( SELECT CAST([tpepPickupDateTime] AS DATE) AS [current_day], COUNT(*) as rides_per_day FROM OPENROWSET( BULK 'https://azureopendatastorage.blob.core.windows.net/nyctlc/yellow/puYear=*/puMonth=*/*.parquet', FORMAT='PARQUET' ) AS [nyc] WHERE nyc.filepath(1) = '2016' GROUP BY CAST([tpepPickupDateTime] AS DATE)),public_holidays AS( SELECT holidayname as holiday, date FROM OPENROWSET( BULK 'https://azureopendatastorage.blob.core.windows.net/holidaydatacontainer/Processed/*.parquet', FORMAT='PARQUET' ) AS [holidays] WHERE countryorregion = 'United States' AND YEAR(date) = 2016)SELECT*FROM taxi_rides tLEFT OUTER JOIN public_holidays p on t.current_day = p.dateORDER BY current_day ASC
So, we created two CTEs, used the WHERE clause to filter the data, aggregate function, and finally joined CTEs like we were querying our “normal” SQL Server database...And, don’t forget, we were retrieving the data directly from two parquet files!
No, you don’t need to be Harry Potter to do this — using a Serverless SQL pool within Synapse Workspace is the only “trick” you should perform!
This was just a brief introduction to Synapse Analytics, an all-in-one solution for your data workloads. By no means have we covered all concepts and features within this platform — the idea was to get you started for using Synapse in synergy with Power BI.
Now, I hope that you’ve got a better overview and a big picture of the main capabilities that Synapse provides and that you can take advantage of those capabilities once you start using Synapse for building your Power BI reports.
Take your time, explore the Synapse, try different approaches for your data workloads, before we dive together into the next phase, where Power BI, and its integration with Synapse (especially with Serverless SQL pool), will be our focal point!
Thanks for reading!
Become a member and read every story on Medium! | [
{
"code": null,
"e": 515,
"s": 171,
"text": "By introducing Azure Synapse Analytics in late 2019, a whole new perspective was created when it comes to data treatment. Some core concepts, such as traditional data warehousing, came under more scrutiny, while various fresh approaches started to pop up after data nerds became aware of the new capabilities that Synapse brought to the table."
},
{
"code": null,
"e": 700,
"s": 515,
"text": "Not that Synapse made a strong impact on data ingestion, transformation, and storage options only — it also offered a whole new set of possibilities for data serving and visualization!"
},
{
"code": null,
"e": 1308,
"s": 700,
"text": "Therefore, in this series of blog posts, I will try to explore how Power BI works in synergy with the new platform. What options we, Power BI developers, have when working with Synapse? In which data analytics scenarios, Synapse will play on the edge, helping you to achieve the (im)possible? When would you want to take advantage of the innovative solutions within Synapse, and when would you be better sticking with more conventional approaches? What are the best practices when using Power BI — Synapse combo, and which parameters should you evaluate before making a final decision on which path to take."
},
{
"code": null,
"e": 1496,
"s": 1308,
"text": "Once we’re done, I believe that you should get a better understanding of the “pros” and “cons” for each of the available options when it comes to integration between Power BI and Synapse."
},
{
"code": null,
"e": 1755,
"s": 1496,
"text": "Since Power BI is already a mature and well-known product (it celebrated its 5th birthday last July), before we dive into the relationship between Power BI and Synapse, I believe that we will need to spend some time learning about the “younger” technology..."
},
{
"code": null,
"e": 1997,
"s": 1755,
"text": "As I already mentioned, Synapse has been introduced about 2 years ago (late 2019.) and became generally available in March this year. Officially, it succeeded Azure SQL Data Warehouse (SQL DW) and was presented as an evolution of the SQL DW."
},
{
"code": null,
"e": 2119,
"s": 1997,
"text": "So, would it be fair if we think of Synapse as a “new kid on the block”, or just as a rebranding of the existing product?"
},
{
"code": null,
"e": 2223,
"s": 2119,
"text": "Before we answer this question, let’s first take a look into traditional data warehousing architecture:"
},
{
"code": null,
"e": 2929,
"s": 2223,
"text": "In a typical traditional data warehousing scenario, you would collect your data from multiple different sources, perform some transformations, data cleansing, etc. before putting consolidated data into a relational data warehouse. This was the focal point of your reporting solutions, a “single source of truth” for your data, and you could build various reports from there, using a whole range of tools — such as Crystal Reports, SSRS, or Power BI, if we talk about Microsoft’s solutions. You could also build an additional semantic layer using SSAS to create “cubes” (both tabular and multidimensional), and then target those cubes with reporting tools mentioned above (don’t forget good old Excel too)."
},
{
"code": null,
"e": 3138,
"s": 2929,
"text": "Now, with Azure Synapse Analytics, you are getting all these (and many more) functionalities under one roof! Even if you don’t have SSAS included in Synapse by default, you can link it as an external service."
},
{
"code": null,
"e": 3193,
"s": 3138,
"text": "Can you recognize the object in the following picture?"
},
{
"code": null,
"e": 3348,
"s": 3193,
"text": "Yes, that’s the famous “Swiss knife”. You can cut the paper, open a bottle of wine or beer, or cut some smaller items — all of that using one single tool!"
},
{
"code": null,
"e": 3529,
"s": 3348,
"text": "So, if you’re asking yourself — what on Earth does a Swiss knife have in common with Synapse?! Well, you can think of Synapse as a single tool that can satisfy all your data needs."
},
{
"code": null,
"e": 3830,
"s": 3529,
"text": "Do you need to import data from multiple different sources? Synapse can do that. Do you need to transform data before serving it? Synapse can do that, too. Do you need to store the data? Synapse can do it for you. Do you need to query non-relational data, or even files directly? Synapse can do that."
},
{
"code": null,
"e": 4269,
"s": 3830,
"text": "Watch out now: do you need to query non-relational data, or even files directly, using plain old T-SQL? Synapse CAN DO THAT! Whaaaaat???!!!! Yes, you can write T-SQL to query data from CSV, JSON, or parquet files. But, more on that later in the series. Do you need to build machine learning models? Synapse can manage this for you. Finally, do you need to create your Power BI report straight from the Synapse? Yes, that is also possible!"
},
{
"code": null,
"e": 4343,
"s": 4269,
"text": "As you may notice, Synapse is a one-stop service for all your data tasks."
},
{
"code": null,
"e": 4532,
"s": 4343,
"text": "When I’m explaining some technical stuff, I like to make comparisons to non-technical things, so that people without a technical background can understand the essential underlying concept."
},
{
"code": null,
"e": 4870,
"s": 4532,
"text": "Now, you probably know when you travel to a famous tourist city for the first time, you want to visit all the important places: museums, sightseeing, local attractions... And the majority of these cities offer you a “City Card”. You can use that one single card to enter all of the main city attractions, which saves your time and money."
},
{
"code": null,
"e": 5062,
"s": 4870,
"text": "You can think of Azure Synapse Studio as “that” kind of card. It’s a unified workspace for all different tasks — from data preparation, data warehousing, monitoring and manage resources, etc."
},
{
"code": null,
"e": 5167,
"s": 5062,
"text": "Now, we are ready to scratch under the surface and examine the core components of the Synapse Workspace."
},
{
"code": null,
"e": 5417,
"s": 5167,
"text": "The most important part is the Analytic Engines. There are three different engines within the Synapse Workspace. Two of them are SQL-flavored (Dedicated SQL Pool and Serverless SQL pool), while the third is based on Apache Spark (Apache Spark Pool)."
},
{
"code": null,
"e": 5625,
"s": 5417,
"text": "Also, two of them are provisioned (Dedicated SQL Pool and Apache Spark Pool), while the third (Serverless SQL pool) works like a serverless solution. In the most simplified way, it looks something like this:"
},
{
"code": null,
"e": 5760,
"s": 5625,
"text": "In this blog series, we will not analyze the Spark pool, as our focus will be SQL-based solutions, especially the Serverless SQL pool."
},
{
"code": null,
"e": 5860,
"s": 5760,
"text": "As soon as you create a Synapse Workspace, you will see a Serverless SQL pool under your SQL pools:"
},
{
"code": null,
"e": 6226,
"s": 5860,
"text": "In my opinion, this is one of the revolutionary features of Synapse. Essentially, what a Serverless SQL pool could do for you is hardly beatable: you can query data directly within your data lake, without the need to transfer or copy it anywhere! Moreover, you can query the data in the data lake writing plain old T-SQL! Yes, CSV, JSON, and parquet files included!"
},
{
"code": null,
"e": 6882,
"s": 6226,
"text": "Since it is a serverless system, you don’t need to set up any kind of infrastructure, or clusters. You can literally start querying your data as soon as your workspace is created! Serverless SQL pool works as a standalone Polybase service, so there are no costs for the resources reserved. You are only being charged for the volume of data processed by your queries (at the moment of writing, it is 5 $/1 TB). Just keep in mind, when you’re planning your workloads, that the minimal billing volume is 10 MB. This minimal threshold doesn’t apply to metadata queries, so you don’t have to worry that you will be charged at all if you execute something like:"
},
{
"code": null,
"e": 6908,
"s": 6882,
"text": "SELECT * FROM sys.objects"
},
{
"code": null,
"e": 7007,
"s": 6908,
"text": "Having this tool under your belt lets you think about an indefinite number of possible approaches:"
},
{
"code": null,
"e": 7151,
"s": 7007,
"text": "You can quickly perform ad-hoc queries over data in the data lake before you decide what is the best possible way to gain more insights from it"
},
{
"code": null,
"e": 7311,
"s": 7151,
"text": "You can build an additional logical layer, a kind of “abstract” data warehouse on top of raw, or non-relational data, without moving data to a physical storage"
},
{
"code": null,
"e": 7426,
"s": 7311,
"text": "You can transform data directly in the data lake, and consume it directly from there (for example, using Power BI)"
},
{
"code": null,
"e": 7606,
"s": 7426,
"text": "As already mentioned, you can use T-SQL to query the data directly from the data lake. And not just that! You can also write T-SQL to retrieve data from Spark tables and CosmosDB."
},
{
"code": null,
"e": 7837,
"s": 7606,
"text": "Writing T-SQL for querying non-SQL Server data is being achieved by using an extended version of the OPENROWSET function. Because of the non-native usage, there are obviously a few limitations regarding some T-SQL functionalities."
},
{
"code": null,
"e": 7986,
"s": 7837,
"text": "I strongly suggest reading this article on James Serra’s blog, where he collected and answered a lot of questions regarding the Serverless SQL pool."
},
{
"code": null,
"e": 8080,
"s": 7986,
"text": "There is also a great overview of the best practices related to the Serverless SQL pool here."
},
{
"code": null,
"e": 8312,
"s": 8080,
"text": "Yes, I know that it sounds like we need a magic wand to query the data directly from the parquet file using plain T-SQL...But, it’s possible! And, trust me, you don’t need to be a magician — some basic T-SQL knowledge will suffice."
},
{
"code": null,
"e": 8565,
"s": 8312,
"text": "In this example, I’ve used a sample NYC Taxi dataset. Data is stored in a parquet file, but I can use the OPENROWSET function within my T-SQL syntax to query the ~1.5 billion record dataset like it is stored in my SQL Server database! How cool is that!"
},
{
"code": null,
"e": 8667,
"s": 8565,
"text": "Additionally, I can extend on this and perform all kinds of aggregations, groupings, where clauses..."
},
{
"code": null,
"e": 8702,
"s": 8667,
"text": "If that wasn’t enough, watch this:"
},
{
"code": null,
"e": 8762,
"s": 8702,
"text": "Here is the T-SQL code that was run over two parquet files:"
},
{
"code": null,
"e": 9590,
"s": 8762,
"text": "WITH taxi_rides AS( SELECT CAST([tpepPickupDateTime] AS DATE) AS [current_day], COUNT(*) as rides_per_day FROM OPENROWSET( BULK 'https://azureopendatastorage.blob.core.windows.net/nyctlc/yellow/puYear=*/puMonth=*/*.parquet', FORMAT='PARQUET' ) AS [nyc] WHERE nyc.filepath(1) = '2016' GROUP BY CAST([tpepPickupDateTime] AS DATE)),public_holidays AS( SELECT holidayname as holiday, date FROM OPENROWSET( BULK 'https://azureopendatastorage.blob.core.windows.net/holidaydatacontainer/Processed/*.parquet', FORMAT='PARQUET' ) AS [holidays] WHERE countryorregion = 'United States' AND YEAR(date) = 2016)SELECT*FROM taxi_rides tLEFT OUTER JOIN public_holidays p on t.current_day = p.dateORDER BY current_day ASC"
},
{
"code": null,
"e": 9838,
"s": 9590,
"text": "So, we created two CTEs, used the WHERE clause to filter the data, aggregate function, and finally joined CTEs like we were querying our “normal” SQL Server database...And, don’t forget, we were retrieving the data directly from two parquet files!"
},
{
"code": null,
"e": 9982,
"s": 9838,
"text": "No, you don’t need to be Harry Potter to do this — using a Serverless SQL pool within Synapse Workspace is the only “trick” you should perform!"
},
{
"code": null,
"e": 10240,
"s": 9982,
"text": "This was just a brief introduction to Synapse Analytics, an all-in-one solution for your data workloads. By no means have we covered all concepts and features within this platform — the idea was to get you started for using Synapse in synergy with Power BI."
},
{
"code": null,
"e": 10470,
"s": 10240,
"text": "Now, I hope that you’ve got a better overview and a big picture of the main capabilities that Synapse provides and that you can take advantage of those capabilities once you start using Synapse for building your Power BI reports."
},
{
"code": null,
"e": 10715,
"s": 10470,
"text": "Take your time, explore the Synapse, try different approaches for your data workloads, before we dive together into the next phase, where Power BI, and its integration with Synapse (especially with Serverless SQL pool), will be our focal point!"
},
{
"code": null,
"e": 10735,
"s": 10715,
"text": "Thanks for reading!"
}
]
|
JavaScript | Proxy() Object - GeeksforGeeks | 14 Feb, 2019
The proxy object in JavaScript is used to define the custom behavior of fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).
Syntax:
var p = new Proxy(target, handler);
Parameter: The proxy object accept two parameters as mentioned above and described below:
target: A target object (can be any sort of object including a function, class, or even another proxy) to wrap with Proxy.
handler: An object whose properties are functions which define the behavior of the proxy when an operation is performed on it.
Example:
<script>const Person = { Name: 'John Nash', Age: 25}; const handler = { // target represents the Person while prop represents // proxy property. get: function(target, prop) { if (prop === 'FirstName') { return target.Name.split(' ')[0]; } if (prop === 'LastName') { return target.Name.split(' ').pop(); } else { return Reflect.get(target,prop); } }}; const proxy1 = new Proxy(Person, handler); document.write(proxy1 + "<br>"); // Though there is no Property as FirstName and LastName, // still we get them as if they were property not function.document.write(proxy1.FirstName + "<br>");document.write(proxy1.LastName + "<br>"); </script>
Output:
[object Object]
John
Nash
Note: The above code can be run directly in terminal provided NodeJs is installed, else run it in a HTML file by pasting the above in script tag and check the output in console of any web browser.
javascript-object
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
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
How to read a local text file using JavaScript?
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": 24055,
"s": 24027,
"text": "\n14 Feb, 2019"
},
{
"code": null,
"e": 24225,
"s": 24055,
"text": "The proxy object in JavaScript is used to define the custom behavior of fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc)."
},
{
"code": null,
"e": 24233,
"s": 24225,
"text": "Syntax:"
},
{
"code": null,
"e": 24269,
"s": 24233,
"text": "var p = new Proxy(target, handler);"
},
{
"code": null,
"e": 24359,
"s": 24269,
"text": "Parameter: The proxy object accept two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 24482,
"s": 24359,
"text": "target: A target object (can be any sort of object including a function, class, or even another proxy) to wrap with Proxy."
},
{
"code": null,
"e": 24609,
"s": 24482,
"text": "handler: An object whose properties are functions which define the behavior of the proxy when an operation is performed on it."
},
{
"code": null,
"e": 24618,
"s": 24609,
"text": "Example:"
},
{
"code": " <script>const Person = { Name: 'John Nash', Age: 25}; const handler = { // target represents the Person while prop represents // proxy property. get: function(target, prop) { if (prop === 'FirstName') { return target.Name.split(' ')[0]; } if (prop === 'LastName') { return target.Name.split(' ').pop(); } else { return Reflect.get(target,prop); } }}; const proxy1 = new Proxy(Person, handler); document.write(proxy1 + \"<br>\"); // Though there is no Property as FirstName and LastName, // still we get them as if they were property not function.document.write(proxy1.FirstName + \"<br>\");document.write(proxy1.LastName + \"<br>\"); </script> ",
"e": 25406,
"s": 24618,
"text": null
},
{
"code": null,
"e": 25414,
"s": 25406,
"text": "Output:"
},
{
"code": null,
"e": 25441,
"s": 25414,
"text": "[object Object]\nJohn\nNash\n"
},
{
"code": null,
"e": 25638,
"s": 25441,
"text": "Note: The above code can be run directly in terminal provided NodeJs is installed, else run it in a HTML file by pasting the above in script tag and check the output in console of any web browser."
},
{
"code": null,
"e": 25656,
"s": 25638,
"text": "javascript-object"
},
{
"code": null,
"e": 25667,
"s": 25656,
"text": "JavaScript"
},
{
"code": null,
"e": 25684,
"s": 25667,
"text": "Web Technologies"
},
{
"code": null,
"e": 25782,
"s": 25684,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25791,
"s": 25782,
"text": "Comments"
},
{
"code": null,
"e": 25804,
"s": 25791,
"text": "Old Comments"
},
{
"code": null,
"e": 25865,
"s": 25804,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 25910,
"s": 25865,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 25982,
"s": 25910,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26028,
"s": 25982,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 26076,
"s": 26028,
"text": "How to read a local text file using JavaScript?"
},
{
"code": null,
"e": 26132,
"s": 26076,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26165,
"s": 26132,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26227,
"s": 26165,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26270,
"s": 26227,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
All about Pythonic Class: The Life Cycle | by Farhad Naeem | Towards Data Science | This is the second part of “All about Pythonic Class”. Now, our “Python Data Model” series —
Objects, Types, and Values; Python Data Model — Part 1All about Pythonic Class: The Birth and Style; Python Data Model — Part 2[a]All about Pythonic Class: The Life Cycle; Python Data Model — Part 2[b]
Objects, Types, and Values; Python Data Model — Part 1
All about Pythonic Class: The Birth and Style; Python Data Model — Part 2[a]
All about Pythonic Class: The Life Cycle; Python Data Model — Part 2[b]
In the previous chapter, we have shown How to write a basic class, What is the relation between class and object, and the differences between new-style and old-style class. We will start this chapter from where we left the previous one-
So what happens when we declare a class? How does the Python interpreter interpret it?
Two special methods are called under the hood when we call a class to form an object.
First, the interpreter calls __new__ method which is the ‘true’ constructor of a class. This special method then creates an object, in an unnamed location into the memory, with the correct type.
Then __init__ is called to initialize the class object with the previous object created by __new__. Most of the times we don’t need to declare a __new__ special method without an obvious reason. It mainly takes place in the background. Instantiating an object with __init__ is the most common and standard practice that is sufficient to serve most of our purposes.
It is an intricate process that creates a class behind the scene. It will also need in-depth knowledge of the design of the Python interpreter and the implementation of the language at its core. For the sake of simplicity, we will describe the process from a high-level point of view and write hypothetical or pseudo-codes of the backend process.
When we call a class to form an object, the interpreter calls type. It takes three parameters--type(classname, superclass, attribs) ortype("", (), {})
where the class name is the string representation of the declared class, the superclass is the tuple representation of class(es) from which our class will inherit properties and attributes is the dictionary representation of the class.__dict__.Let's declare a class normally
class Footballer(): game = "Football" def __init__(self, name, club): self.name = name self.club = club def a_method(self): return None print(Footballer.__dict__) # Output'''{'__module__': '__main__', 'game': 'Football', '__init__': <function Footballer.__init__ at 0x7f10c4563f28>, 'a_method': <function Footballer.a_method at 0x7f10c45777b8>, '__dict__': <attribute '__dict__' of 'Footballer' objects>, '__weakref__': <attribute '__weakref__' of 'Footballer' objects>, '__doc__': None}'''
Now we will write the same type of class using type metaclass
def outer_init(self, name, club): self.name = name self.club = club Footballer1 = type("Footballer1", (), {"game":"Soccer", "__init__": outer_init, "b_method": lambda self: None})print(Footballer1.__dict__) print(Footballer1.game) # Output'''{'game': 'Soccer', '__init__': <function outer_init at 0x7f10c4510488>, 'b_method': <function <lambda> at 0x7f10c4510f28>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Footballer1' objects>, '__weakref__': <attribute '__weakref__' of 'Footballer1' objects>, '__doc__': None}Soccer'''
Aha! we have just made a regular user-defined class using type metaclass!! What actually is going on here?When type is called, its __call__ method is executed that runs two more special methods--
type.__new__(typeclass, classname, superclasses, attributedict)the constructortype.__init__(cls, classname, superclasses, attributedict) the initiator/initializer
type.__new__(typeclass, classname, superclasses, attributedict)the constructor
type.__init__(cls, classname, superclasses, attributedict) the initiator/initializer
__new__(cls, [...) Special method __new__ is the very first method that is called when an object is created. Its first argument is the class itself following other arguments needed to form it. This function is rarely used and by default called by the interpreter during object creation.__init__(self, [...) The initializer special method initializes a class and gives the default attributes of an object. This method takes an object as the first parameter following other arguments for it. This is the most frequently used special method in the Python world.
The following pseudo-code shows how the Python interpreter creates an object from a class. Remember we have omitted the low-level things done by the interpreter for the sake of a basic understanding. Have a look at the self-explanatory code instructions
class Bar(): def __init__(self, obVar): self.obVar = obVar >>> obj = Bar("a string") ----------------[1]# putting object parameter into a temporary variable>>> tmpVar = Bar.__new__(Bar, "another string") >>> type(tmpVar)>>> __main__.Bar>>> tmpVar.obVar -------------------------[2]# the class is not initialised yet # It will throw errors>>> AttributeError Traceback (most recent call last)....AttributeError: 'Bar' object has no attribute 'obVar'------------------------------------------------------# initialise a temporary variable >>> tmpVar.__init__("a string") ---------------[3]>>> tmpVar.obVar>>> 'another string'>>> obVar = tmpVar >>> obVar.obVar>>> 'another string'
The Obj is behaving as we expected [1]. But, when we createdtmpVar by calling Bar.__new__ and trying to access obVar, it throws an error [2]. Thus, we need to initialize with the __init__ and after that, it will work nicely as the previous variable [3] .
P.S.- The method with double underscores on both sides of his name is known as special methods or magic methods. The special method is an “implementation detail” or low-level detail of CPython. Why do we call them magic methods? Because these methods add “magic” to our class. We will have two separate chapters for magic methods.
So far we have discussed almost every basic concept of a Python class. What we are going to discuss in this segment may be counted as a repetition of the previous segment, we are going to discuss more subtle details of a class.
When we run a Python programme, it spawns objects either from the built-in or user-defined classes in runtime. Each object needs memory once it is created. Python does not need the object when it accomplishes its assigned task. It becomes a piece of unwanted information or garbage.
On the other hand, the Python interpreter needs to free up memory periodically for further computation, space for new objects, programme efficiency, and memory security. When a piece of ‘garbage object’ is disposed it ceases to exist in the memory. The question is how long does a Python class exist and when does it cease to exist? The simplest answer is an object or class exists as long it
Holds a reference to its attributes or derivatives andIt is referenced by another object.
Holds a reference to its attributes or derivatives and
It is referenced by another object.
When neither of the two criteria is met, an object or class ceases to exist. The answer is the simplest one but a lot of things go on behind the scene. We are going to put light on a few of them.
The following class is designed to connect to a web server and print the status code, server info and then we will close the connection. We will ‘pack’ attributes into Response class from another namespace which will be a metaclass of type; as expected.
import requests # Another name spacevar = "a class variable." def __init__(self, url): self.__response = requests.get(url) self.code = self.__response.status_code def server_info(self): for key, val in self.__response.headers.items(): print(key, val) def __del__(self): ---------------------- [1] self.__response.close() print("[!] closing connection done...")# Injecting meta from another namespaceResponse = type('Response', (), {"classVar":var,"__init__": __init__, "server":server_info, "__del__":__del__}) # Let's connect to our home server on my father's desk resp = Response("http://192.168.0.19")print(type(Response))print(resp.code)resp.server()del resp # It will call the DE-CONSTRUCTOR# Output'''<class 'type'>401Date Fri, 25 Sep 2020 06:13:50 GMTServer Apache/2.4.38 (Raspbian)WWW-Authenticate Basic realm="Restricted Content"Content-Length 461Keep-Alive timeout=5, max=100Connection Keep-AliveContent-Type text/html; charset=iso-8859-1[!] closing connection done... # resp object destroyed'''
__del__(self) Special method __del__ can be termed the terminator or destructor responsible for the termination of an object or class.__del__ is a finalizer that is called during the garbage collection process of an object. This process takes place at some point when all the references to an object have been deleted.
In the above piece of code, we have omitted the low-level things done by the interpreter for the sake of a basic understanding. When we deleted the response object del resp the __del__ special method or the de-constructor is executed to wipe out the object from RAM.
The method is useful in special cases that require extra cleanup upon deletion, e.g. sockets and file objects. However, keep in mind the fact that __del__ is not guaranteed whether it will be executed even if the target object is still alive when the interpreter exits. So, it is a good practice to close any file or connection manually or by using a wrapper.
A class gives birth to an object. When an object ceases to exist in a namespace, hypothetically a class also needs not to exist in the space. A class can also be deleted like an ordinary object because a class itself is an object. The garbage collection process disposes of unnecessary objects for the sake of memory safety and efficient pieces of code.
Python has adopted two garbage collection mechanisms in CPython*
Reference CountingGenerational Garbage Collection
Reference Counting
Generational Garbage Collection
Between the two, the first one is used most often because the freedom of destroying an object in userspace might bring a disaster if implemented carelessly, e.g. any strong references to a destroyed object may become orphan/dangling ones and leak the memory.Reference counting is easy to implement but it cannot handle reference cycles which makes it more prone to a memory leak.
A class gets a type and reference count by default when it is created. Each time when we create an object by calling it, the interpreter increases its reference count. The reference count of an object or class increases when it is
Passed as a function argumentAssigned to another object or variableAppended to a listAdded as a property of a class etc.
Passed as a function argument
Assigned to another object or variable
Appended to a list
Added as a property of a class etc.
When this count reaches zero, the class ceases to exist in the memory which can be treated as the ‘death of a class’. In other words, the reference count of an object increases when it is referenced anywhere and decreases whenever it is dereferenced. The high-level codes we write cannot affect this low-level implementation although it is possible to handle garbage collection by hand using generational garbage collection or the gc module. Observe the following codes
import sys class Bar(): pass print(sys.getrefcount(Bar)) # default reference count is 5 a = Bar()b = Bar()c = Bar() print(sys.getrefcount(Bar)) # reference count increased by 3 del a , b , c print(sys.getrefcount(Bar)) # reference count decreased by 3 # Output'''585 '''
A reference cycle occurs when one or more Python objects refer to each other. So, in these cases deleting an object merely using del only decreases its reference counts and makes it inaccessible to a programme. It actually remains in the memory.For example
class Foo(): pass obj.var = obj
In the above example, we have created a reference cycle by assigning the object obj itself to its property obj.var. Only decreasing obj's reference count will not destroy it from the memory rather it needs generational garbage collection to be cleaned permanently. This implementation can be handled by the gc module in the high-level coding space.This is another way to 'kill a class'.
From these two parts, we tried to show 6 important facts about the Pythonic class. It is expected that now we have at least some basic ideas about how a Python class works and gets cleaned up from the memory behind the scene.
To cover up the Pythonic Data Model, we will have separate and more detailed articles on Magic Methods, Decorators, Metaprogramming, Pythonic inheritance, etc. A good understanding of the process enables a developer to utilize cent percent of the hidden power of Python and debugging complex issues when things get more Pythonic.
https://docs.python.org/3/reference/datamodel.htmlFluent Python by Luciano Ramalho. This is the book every Pythonista should read to sharpen their python skills.https://stackify.com/python-garbage-collection/
https://docs.python.org/3/reference/datamodel.html
Fluent Python by Luciano Ramalho. This is the book every Pythonista should read to sharpen their python skills. | [
{
"code": null,
"e": 264,
"s": 171,
"text": "This is the second part of “All about Pythonic Class”. Now, our “Python Data Model” series —"
},
{
"code": null,
"e": 466,
"s": 264,
"text": "Objects, Types, and Values; Python Data Model — Part 1All about Pythonic Class: The Birth and Style; Python Data Model — Part 2[a]All about Pythonic Class: The Life Cycle; Python Data Model — Part 2[b]"
},
{
"code": null,
"e": 521,
"s": 466,
"text": "Objects, Types, and Values; Python Data Model — Part 1"
},
{
"code": null,
"e": 598,
"s": 521,
"text": "All about Pythonic Class: The Birth and Style; Python Data Model — Part 2[a]"
},
{
"code": null,
"e": 670,
"s": 598,
"text": "All about Pythonic Class: The Life Cycle; Python Data Model — Part 2[b]"
},
{
"code": null,
"e": 907,
"s": 670,
"text": "In the previous chapter, we have shown How to write a basic class, What is the relation between class and object, and the differences between new-style and old-style class. We will start this chapter from where we left the previous one-"
},
{
"code": null,
"e": 994,
"s": 907,
"text": "So what happens when we declare a class? How does the Python interpreter interpret it?"
},
{
"code": null,
"e": 1080,
"s": 994,
"text": "Two special methods are called under the hood when we call a class to form an object."
},
{
"code": null,
"e": 1275,
"s": 1080,
"text": "First, the interpreter calls __new__ method which is the ‘true’ constructor of a class. This special method then creates an object, in an unnamed location into the memory, with the correct type."
},
{
"code": null,
"e": 1640,
"s": 1275,
"text": "Then __init__ is called to initialize the class object with the previous object created by __new__. Most of the times we don’t need to declare a __new__ special method without an obvious reason. It mainly takes place in the background. Instantiating an object with __init__ is the most common and standard practice that is sufficient to serve most of our purposes."
},
{
"code": null,
"e": 1987,
"s": 1640,
"text": "It is an intricate process that creates a class behind the scene. It will also need in-depth knowledge of the design of the Python interpreter and the implementation of the language at its core. For the sake of simplicity, we will describe the process from a high-level point of view and write hypothetical or pseudo-codes of the backend process."
},
{
"code": null,
"e": 2138,
"s": 1987,
"text": "When we call a class to form an object, the interpreter calls type. It takes three parameters--type(classname, superclass, attribs) ortype(\"\", (), {})"
},
{
"code": null,
"e": 2413,
"s": 2138,
"text": "where the class name is the string representation of the declared class, the superclass is the tuple representation of class(es) from which our class will inherit properties and attributes is the dictionary representation of the class.__dict__.Let's declare a class normally"
},
{
"code": null,
"e": 2940,
"s": 2413,
"text": "class Footballer(): game = \"Football\" def __init__(self, name, club): self.name = name self.club = club def a_method(self): return None print(Footballer.__dict__) # Output'''{'__module__': '__main__', 'game': 'Football', '__init__': <function Footballer.__init__ at 0x7f10c4563f28>, 'a_method': <function Footballer.a_method at 0x7f10c45777b8>, '__dict__': <attribute '__dict__' of 'Footballer' objects>, '__weakref__': <attribute '__weakref__' of 'Footballer' objects>, '__doc__': None}'''"
},
{
"code": null,
"e": 3002,
"s": 2940,
"text": "Now we will write the same type of class using type metaclass"
},
{
"code": null,
"e": 3555,
"s": 3002,
"text": "def outer_init(self, name, club): self.name = name self.club = club Footballer1 = type(\"Footballer1\", (), {\"game\":\"Soccer\", \"__init__\": outer_init, \"b_method\": lambda self: None})print(Footballer1.__dict__) print(Footballer1.game) # Output'''{'game': 'Soccer', '__init__': <function outer_init at 0x7f10c4510488>, 'b_method': <function <lambda> at 0x7f10c4510f28>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Footballer1' objects>, '__weakref__': <attribute '__weakref__' of 'Footballer1' objects>, '__doc__': None}Soccer'''"
},
{
"code": null,
"e": 3751,
"s": 3555,
"text": "Aha! we have just made a regular user-defined class using type metaclass!! What actually is going on here?When type is called, its __call__ method is executed that runs two more special methods--"
},
{
"code": null,
"e": 3914,
"s": 3751,
"text": "type.__new__(typeclass, classname, superclasses, attributedict)the constructortype.__init__(cls, classname, superclasses, attributedict) the initiator/initializer"
},
{
"code": null,
"e": 3993,
"s": 3914,
"text": "type.__new__(typeclass, classname, superclasses, attributedict)the constructor"
},
{
"code": null,
"e": 4078,
"s": 3993,
"text": "type.__init__(cls, classname, superclasses, attributedict) the initiator/initializer"
},
{
"code": null,
"e": 4637,
"s": 4078,
"text": "__new__(cls, [...) Special method __new__ is the very first method that is called when an object is created. Its first argument is the class itself following other arguments needed to form it. This function is rarely used and by default called by the interpreter during object creation.__init__(self, [...) The initializer special method initializes a class and gives the default attributes of an object. This method takes an object as the first parameter following other arguments for it. This is the most frequently used special method in the Python world."
},
{
"code": null,
"e": 4891,
"s": 4637,
"text": "The following pseudo-code shows how the Python interpreter creates an object from a class. Remember we have omitted the low-level things done by the interpreter for the sake of a basic understanding. Have a look at the self-explanatory code instructions"
},
{
"code": null,
"e": 5579,
"s": 4891,
"text": "class Bar(): def __init__(self, obVar): self.obVar = obVar >>> obj = Bar(\"a string\") ----------------[1]# putting object parameter into a temporary variable>>> tmpVar = Bar.__new__(Bar, \"another string\") >>> type(tmpVar)>>> __main__.Bar>>> tmpVar.obVar -------------------------[2]# the class is not initialised yet # It will throw errors>>> AttributeError Traceback (most recent call last)....AttributeError: 'Bar' object has no attribute 'obVar'------------------------------------------------------# initialise a temporary variable >>> tmpVar.__init__(\"a string\") ---------------[3]>>> tmpVar.obVar>>> 'another string'>>> obVar = tmpVar >>> obVar.obVar>>> 'another string' "
},
{
"code": null,
"e": 5834,
"s": 5579,
"text": "The Obj is behaving as we expected [1]. But, when we createdtmpVar by calling Bar.__new__ and trying to access obVar, it throws an error [2]. Thus, we need to initialize with the __init__ and after that, it will work nicely as the previous variable [3] ."
},
{
"code": null,
"e": 6165,
"s": 5834,
"text": "P.S.- The method with double underscores on both sides of his name is known as special methods or magic methods. The special method is an “implementation detail” or low-level detail of CPython. Why do we call them magic methods? Because these methods add “magic” to our class. We will have two separate chapters for magic methods."
},
{
"code": null,
"e": 6393,
"s": 6165,
"text": "So far we have discussed almost every basic concept of a Python class. What we are going to discuss in this segment may be counted as a repetition of the previous segment, we are going to discuss more subtle details of a class."
},
{
"code": null,
"e": 6676,
"s": 6393,
"text": "When we run a Python programme, it spawns objects either from the built-in or user-defined classes in runtime. Each object needs memory once it is created. Python does not need the object when it accomplishes its assigned task. It becomes a piece of unwanted information or garbage."
},
{
"code": null,
"e": 7069,
"s": 6676,
"text": "On the other hand, the Python interpreter needs to free up memory periodically for further computation, space for new objects, programme efficiency, and memory security. When a piece of ‘garbage object’ is disposed it ceases to exist in the memory. The question is how long does a Python class exist and when does it cease to exist? The simplest answer is an object or class exists as long it"
},
{
"code": null,
"e": 7159,
"s": 7069,
"text": "Holds a reference to its attributes or derivatives andIt is referenced by another object."
},
{
"code": null,
"e": 7214,
"s": 7159,
"text": "Holds a reference to its attributes or derivatives and"
},
{
"code": null,
"e": 7250,
"s": 7214,
"text": "It is referenced by another object."
},
{
"code": null,
"e": 7446,
"s": 7250,
"text": "When neither of the two criteria is met, an object or class ceases to exist. The answer is the simplest one but a lot of things go on behind the scene. We are going to put light on a few of them."
},
{
"code": null,
"e": 7700,
"s": 7446,
"text": "The following class is designed to connect to a web server and print the status code, server info and then we will close the connection. We will ‘pack’ attributes into Response class from another namespace which will be a metaclass of type; as expected."
},
{
"code": null,
"e": 8734,
"s": 7700,
"text": "import requests # Another name spacevar = \"a class variable.\" def __init__(self, url): self.__response = requests.get(url) self.code = self.__response.status_code def server_info(self): for key, val in self.__response.headers.items(): print(key, val) def __del__(self): ---------------------- [1] self.__response.close() print(\"[!] closing connection done...\")# Injecting meta from another namespaceResponse = type('Response', (), {\"classVar\":var,\"__init__\": __init__, \"server\":server_info, \"__del__\":__del__}) # Let's connect to our home server on my father's desk resp = Response(\"http://192.168.0.19\")print(type(Response))print(resp.code)resp.server()del resp # It will call the DE-CONSTRUCTOR# Output'''<class 'type'>401Date Fri, 25 Sep 2020 06:13:50 GMTServer Apache/2.4.38 (Raspbian)WWW-Authenticate Basic realm=\"Restricted Content\"Content-Length 461Keep-Alive timeout=5, max=100Connection Keep-AliveContent-Type text/html; charset=iso-8859-1[!] closing connection done... # resp object destroyed'''"
},
{
"code": null,
"e": 9053,
"s": 8734,
"text": "__del__(self) Special method __del__ can be termed the terminator or destructor responsible for the termination of an object or class.__del__ is a finalizer that is called during the garbage collection process of an object. This process takes place at some point when all the references to an object have been deleted."
},
{
"code": null,
"e": 9320,
"s": 9053,
"text": "In the above piece of code, we have omitted the low-level things done by the interpreter for the sake of a basic understanding. When we deleted the response object del resp the __del__ special method or the de-constructor is executed to wipe out the object from RAM."
},
{
"code": null,
"e": 9680,
"s": 9320,
"text": "The method is useful in special cases that require extra cleanup upon deletion, e.g. sockets and file objects. However, keep in mind the fact that __del__ is not guaranteed whether it will be executed even if the target object is still alive when the interpreter exits. So, it is a good practice to close any file or connection manually or by using a wrapper."
},
{
"code": null,
"e": 10034,
"s": 9680,
"text": "A class gives birth to an object. When an object ceases to exist in a namespace, hypothetically a class also needs not to exist in the space. A class can also be deleted like an ordinary object because a class itself is an object. The garbage collection process disposes of unnecessary objects for the sake of memory safety and efficient pieces of code."
},
{
"code": null,
"e": 10099,
"s": 10034,
"text": "Python has adopted two garbage collection mechanisms in CPython*"
},
{
"code": null,
"e": 10149,
"s": 10099,
"text": "Reference CountingGenerational Garbage Collection"
},
{
"code": null,
"e": 10168,
"s": 10149,
"text": "Reference Counting"
},
{
"code": null,
"e": 10200,
"s": 10168,
"text": "Generational Garbage Collection"
},
{
"code": null,
"e": 10580,
"s": 10200,
"text": "Between the two, the first one is used most often because the freedom of destroying an object in userspace might bring a disaster if implemented carelessly, e.g. any strong references to a destroyed object may become orphan/dangling ones and leak the memory.Reference counting is easy to implement but it cannot handle reference cycles which makes it more prone to a memory leak."
},
{
"code": null,
"e": 10811,
"s": 10580,
"text": "A class gets a type and reference count by default when it is created. Each time when we create an object by calling it, the interpreter increases its reference count. The reference count of an object or class increases when it is"
},
{
"code": null,
"e": 10932,
"s": 10811,
"text": "Passed as a function argumentAssigned to another object or variableAppended to a listAdded as a property of a class etc."
},
{
"code": null,
"e": 10962,
"s": 10932,
"text": "Passed as a function argument"
},
{
"code": null,
"e": 11001,
"s": 10962,
"text": "Assigned to another object or variable"
},
{
"code": null,
"e": 11020,
"s": 11001,
"text": "Appended to a list"
},
{
"code": null,
"e": 11056,
"s": 11020,
"text": "Added as a property of a class etc."
},
{
"code": null,
"e": 11526,
"s": 11056,
"text": "When this count reaches zero, the class ceases to exist in the memory which can be treated as the ‘death of a class’. In other words, the reference count of an object increases when it is referenced anywhere and decreases whenever it is dereferenced. The high-level codes we write cannot affect this low-level implementation although it is possible to handle garbage collection by hand using generational garbage collection or the gc module. Observe the following codes"
},
{
"code": null,
"e": 11805,
"s": 11526,
"text": "import sys class Bar(): pass print(sys.getrefcount(Bar)) # default reference count is 5 a = Bar()b = Bar()c = Bar() print(sys.getrefcount(Bar)) # reference count increased by 3 del a , b , c print(sys.getrefcount(Bar)) # reference count decreased by 3 # Output'''585 '''"
},
{
"code": null,
"e": 12062,
"s": 11805,
"text": "A reference cycle occurs when one or more Python objects refer to each other. So, in these cases deleting an object merely using del only decreases its reference counts and makes it inaccessible to a programme. It actually remains in the memory.For example"
},
{
"code": null,
"e": 12097,
"s": 12062,
"text": "class Foo(): pass obj.var = obj"
},
{
"code": null,
"e": 12484,
"s": 12097,
"text": "In the above example, we have created a reference cycle by assigning the object obj itself to its property obj.var. Only decreasing obj's reference count will not destroy it from the memory rather it needs generational garbage collection to be cleaned permanently. This implementation can be handled by the gc module in the high-level coding space.This is another way to 'kill a class'."
},
{
"code": null,
"e": 12710,
"s": 12484,
"text": "From these two parts, we tried to show 6 important facts about the Pythonic class. It is expected that now we have at least some basic ideas about how a Python class works and gets cleaned up from the memory behind the scene."
},
{
"code": null,
"e": 13040,
"s": 12710,
"text": "To cover up the Pythonic Data Model, we will have separate and more detailed articles on Magic Methods, Decorators, Metaprogramming, Pythonic inheritance, etc. A good understanding of the process enables a developer to utilize cent percent of the hidden power of Python and debugging complex issues when things get more Pythonic."
},
{
"code": null,
"e": 13249,
"s": 13040,
"text": "https://docs.python.org/3/reference/datamodel.htmlFluent Python by Luciano Ramalho. This is the book every Pythonista should read to sharpen their python skills.https://stackify.com/python-garbage-collection/"
},
{
"code": null,
"e": 13300,
"s": 13249,
"text": "https://docs.python.org/3/reference/datamodel.html"
}
]
|
How to randomize (shuffle) a JavaScript array? | To randomize a JavaScript array to display random elements, you can try to run the following code:
Live Demo
<html>
<body>
<script>
function randomFunc(myArr) {
var l = myArr.length, temp, index;
while (l > 0) {
index = Math.floor(Math.random() * l);
l--;
temp = myArr[l];
myArr[l] = myArr[index];
myArr[index] = temp;
}
return myArr;
}
var arr = [10, 20, 30, 40, 50];
document.write(randomFunc(arr));
</script>
</body>
</html>
20,50,40,30,10 | [
{
"code": null,
"e": 1161,
"s": 1062,
"text": "To randomize a JavaScript array to display random elements, you can try to run the following code:"
},
{
"code": null,
"e": 1171,
"s": 1161,
"text": "Live Demo"
},
{
"code": null,
"e": 1760,
"s": 1171,
"text": "<html> \n <body> \n <script> \n function randomFunc(myArr) { \n var l = myArr.length, temp, index; \n while (l > 0) { \n index = Math.floor(Math.random() * l); \n l--; \n temp = myArr[l]; \n myArr[l] = myArr[index]; \n myArr[index] = temp; \n } \n return myArr; \n } \n var arr = [10, 20, 30, 40, 50]; \n document.write(randomFunc(arr)); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 1775,
"s": 1760,
"text": "20,50,40,30,10"
}
]
|
Spring Boot - Admin Client | For monitoring and managing your microservice application via Spring Boot Admin Server, you should add the Spring Boot Admin starter client dependency and point out the Admin Server URI into the application properties file.
Note − For monitoring an application, you should enable the Spring Boot Actuator Endpoints for your Microservice application.
First, add the following Spring Boot Admin starter client dependency and Spring Boot starter actuator dependency in your build configuration file.
Maven users can add the following dependencies in your pom.xml file −
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>1.5.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Gradle users can add the following dependencies in your build.gradle file.
compile group: 'de.codecentric', name: 'spring-boot-admin-starter-client', version: '1.5.5'
compile('org.springframework.boot:spring-boot-starter-actuator')
Now, add the Spring Boot Admin Server URL into your application properties file.
For properties file users, add the following properties in the application.properties file.
spring.boot.admin.url = http://localhost:9090/
For YAML users, add the following property in application.yml file.
spring:
boot:
admin:
url: http://localhost:9000/
Now, create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands.
For Maven, you can use the command as shown −
mvn clean install
After “BUILD SUCCESS”, you can find the JAR file under the target directory.
For Gradle, you can use the command as shown −
gradle clean build
After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.
Now, run the JAR file by using the command shown −
java –jar <JARFILE>
Now, the application has started on the Tomcat port 9090 as shown −
Now hit the following URL from your web browser and see your spring Boot application is registered with Spring Boot Admin Server.
http://localhost:9090/
Now, click the Details button and the see the actuator endpoints in Admin Server UI.
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": 3249,
"s": 3025,
"text": "For monitoring and managing your microservice application via Spring Boot Admin Server, you should add the Spring Boot Admin starter client dependency and point out the Admin Server URI into the application properties file."
},
{
"code": null,
"e": 3375,
"s": 3249,
"text": "Note − For monitoring an application, you should enable the Spring Boot Actuator Endpoints for your Microservice application."
},
{
"code": null,
"e": 3522,
"s": 3375,
"text": "First, add the following Spring Boot Admin starter client dependency and Spring Boot starter actuator dependency in your build configuration file."
},
{
"code": null,
"e": 3592,
"s": 3522,
"text": "Maven users can add the following dependencies in your pom.xml file −"
},
{
"code": null,
"e": 3877,
"s": 3592,
"text": "<dependency>\n <groupId>de.codecentric</groupId>\n <artifactId>spring-boot-admin-starter-client</artifactId>\n <version>1.5.5</version>\n</dependency>\n<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-actuator</artifactId>\n</dependency>\n"
},
{
"code": null,
"e": 3952,
"s": 3877,
"text": "Gradle users can add the following dependencies in your build.gradle file."
},
{
"code": null,
"e": 4109,
"s": 3952,
"text": "compile group: 'de.codecentric', name: 'spring-boot-admin-starter-client', version: '1.5.5'\ncompile('org.springframework.boot:spring-boot-starter-actuator')"
},
{
"code": null,
"e": 4190,
"s": 4109,
"text": "Now, add the Spring Boot Admin Server URL into your application properties file."
},
{
"code": null,
"e": 4282,
"s": 4190,
"text": "For properties file users, add the following properties in the application.properties file."
},
{
"code": null,
"e": 4330,
"s": 4282,
"text": "spring.boot.admin.url = http://localhost:9090/\n"
},
{
"code": null,
"e": 4398,
"s": 4330,
"text": "For YAML users, add the following property in application.yml file."
},
{
"code": null,
"e": 4466,
"s": 4398,
"text": "spring:\n boot:\n admin:\n url: http://localhost:9000/\n"
},
{
"code": null,
"e": 4587,
"s": 4466,
"text": "Now, create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands."
},
{
"code": null,
"e": 4633,
"s": 4587,
"text": "For Maven, you can use the command as shown −"
},
{
"code": null,
"e": 4652,
"s": 4633,
"text": "mvn clean install\n"
},
{
"code": null,
"e": 4729,
"s": 4652,
"text": "After “BUILD SUCCESS”, you can find the JAR file under the target directory."
},
{
"code": null,
"e": 4776,
"s": 4729,
"text": "For Gradle, you can use the command as shown −"
},
{
"code": null,
"e": 4796,
"s": 4776,
"text": "gradle clean build\n"
},
{
"code": null,
"e": 4880,
"s": 4796,
"text": "After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory."
},
{
"code": null,
"e": 4931,
"s": 4880,
"text": "Now, run the JAR file by using the command shown −"
},
{
"code": null,
"e": 4953,
"s": 4931,
"text": "java –jar <JARFILE> \n"
},
{
"code": null,
"e": 5021,
"s": 4953,
"text": "Now, the application has started on the Tomcat port 9090 as shown −"
},
{
"code": null,
"e": 5151,
"s": 5021,
"text": "Now hit the following URL from your web browser and see your spring Boot application is registered with Spring Boot Admin Server."
},
{
"code": null,
"e": 5174,
"s": 5151,
"text": "http://localhost:9090/"
},
{
"code": null,
"e": 5259,
"s": 5174,
"text": "Now, click the Details button and the see the actuator endpoints in Admin Server UI."
},
{
"code": null,
"e": 5293,
"s": 5259,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5307,
"s": 5293,
"text": " Karthikeya T"
},
{
"code": null,
"e": 5340,
"s": 5307,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5355,
"s": 5340,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 5390,
"s": 5355,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5402,
"s": 5390,
"text": " Senol Atac"
},
{
"code": null,
"e": 5437,
"s": 5402,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5449,
"s": 5437,
"text": " Senol Atac"
},
{
"code": null,
"e": 5484,
"s": 5449,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5496,
"s": 5484,
"text": " Senol Atac"
},
{
"code": null,
"e": 5529,
"s": 5496,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5541,
"s": 5529,
"text": " Senol Atac"
},
{
"code": null,
"e": 5548,
"s": 5541,
"text": " Print"
},
{
"code": null,
"e": 5559,
"s": 5548,
"text": " Add Notes"
}
]
|
Python program to find Least Frequent Character in a String | When it is required to find the least frequent character in a string, ‘Counter’ is used to get the count of letters. The ‘min’ method is used to get the minimum of values in the string, i.e every letter’s count is stored along with the letter. The minimum is obtained.
Below is a demonstration of the same
from collections import Counter
my_str = "highland how"
print ("The string is : ")
print(my_str)
my_result = Counter(my_str)
my_result = min(my_result, key = my_result.get)
print ("The minimum of all characters in the string is : ")
print(my_result)
The string is :
highland how
The minimum of all characters in the string is :
a
The required packages are imported.
The required packages are imported.
A string is defined, and is displayed on the console.
A string is defined, and is displayed on the console.
The ‘Counter’ is used to get the count of every letter in the string.
The ‘Counter’ is used to get the count of every letter in the string.
This is assigned to a variable.
This is assigned to a variable.
The ‘min’ method is used to get the minimum of values.
The ‘min’ method is used to get the minimum of values.
This is assigned to the variable again.
This is assigned to the variable again.
This is displayed as output on the console.
This is displayed as output on the console. | [
{
"code": null,
"e": 1331,
"s": 1062,
"text": "When it is required to find the least frequent character in a string, ‘Counter’ is used to get the count of letters. The ‘min’ method is used to get the minimum of values in the string, i.e every letter’s count is stored along with the letter. The minimum is obtained."
},
{
"code": null,
"e": 1368,
"s": 1331,
"text": "Below is a demonstration of the same"
},
{
"code": null,
"e": 1622,
"s": 1368,
"text": "from collections import Counter\n\nmy_str = \"highland how\"\n\nprint (\"The string is : \")\nprint(my_str)\n\nmy_result = Counter(my_str)\nmy_result = min(my_result, key = my_result.get)\n\nprint (\"The minimum of all characters in the string is : \")\nprint(my_result)"
},
{
"code": null,
"e": 1702,
"s": 1622,
"text": "The string is :\nhighland how\nThe minimum of all characters in the string is :\na"
},
{
"code": null,
"e": 1738,
"s": 1702,
"text": "The required packages are imported."
},
{
"code": null,
"e": 1774,
"s": 1738,
"text": "The required packages are imported."
},
{
"code": null,
"e": 1828,
"s": 1774,
"text": "A string is defined, and is displayed on the console."
},
{
"code": null,
"e": 1882,
"s": 1828,
"text": "A string is defined, and is displayed on the console."
},
{
"code": null,
"e": 1952,
"s": 1882,
"text": "The ‘Counter’ is used to get the count of every letter in the string."
},
{
"code": null,
"e": 2022,
"s": 1952,
"text": "The ‘Counter’ is used to get the count of every letter in the string."
},
{
"code": null,
"e": 2054,
"s": 2022,
"text": "This is assigned to a variable."
},
{
"code": null,
"e": 2086,
"s": 2054,
"text": "This is assigned to a variable."
},
{
"code": null,
"e": 2141,
"s": 2086,
"text": "The ‘min’ method is used to get the minimum of values."
},
{
"code": null,
"e": 2196,
"s": 2141,
"text": "The ‘min’ method is used to get the minimum of values."
},
{
"code": null,
"e": 2236,
"s": 2196,
"text": "This is assigned to the variable again."
},
{
"code": null,
"e": 2276,
"s": 2236,
"text": "This is assigned to the variable again."
},
{
"code": null,
"e": 2320,
"s": 2276,
"text": "This is displayed as output on the console."
},
{
"code": null,
"e": 2364,
"s": 2320,
"text": "This is displayed as output on the console."
}
]
|
Rexx - TIME | This method returns the local time in the 24-hour clock format as shown in the following program.
hh:mm:ss (hours, minutes, and seconds)
TIME(options)
Options − This is the options for formatting the time value. They can be anyone of the following options −
Civil − This parameter returns the time in the format () wherein hh is hours, mm is minutes and xx is seconds
Civil − This parameter returns the time in the format () wherein hh is hours, mm is minutes and xx is seconds
Elapsed − This parameter returns the number of seconds and microseconds since the elapsed-time clock was started or reset
Elapsed − This parameter returns the number of seconds and microseconds since the elapsed-time clock was started or reset
Full − This parameter returns the number of microseconds since the date 1 January 0001
Full − This parameter returns the number of microseconds since the date 1 January 0001
Hours − This parameter returns the number of hours that have passed since midnight
Hours − This parameter returns the number of hours that have passed since midnight
Minutes − This parameter returns the number of minutes that have passed since midnight
Minutes − This parameter returns the number of minutes that have passed since midnight
Normal − This parameter returns the time in the default format hh:mm:ss
Normal − This parameter returns the time in the default format hh:mm:ss
Offset − This parameter returns the offset of the local time from UTC in microseconds.
Offset − This parameter returns the offset of the local time from UTC in microseconds.
This method returns the local time in the 24-hour clock format − hh:mm:ss (hours, minutes, and seconds).
/* Main program */
say TIME()
say TIME("C")
say TIME("H")
When we run the above program we will get the following result. This depends on the current time on the system.
The following program is just an example.
10:54:12
10:54am
10
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2437,
"s": 2339,
"text": "This method returns the local time in the 24-hour clock format as shown in the following program."
},
{
"code": null,
"e": 2478,
"s": 2437,
"text": "hh:mm:ss (hours, minutes, and seconds) \n"
},
{
"code": null,
"e": 2493,
"s": 2478,
"text": "TIME(options)\n"
},
{
"code": null,
"e": 2600,
"s": 2493,
"text": "Options − This is the options for formatting the time value. They can be anyone of the following options −"
},
{
"code": null,
"e": 2710,
"s": 2600,
"text": "Civil − This parameter returns the time in the format () wherein hh is hours, mm is minutes and xx is seconds"
},
{
"code": null,
"e": 2820,
"s": 2710,
"text": "Civil − This parameter returns the time in the format () wherein hh is hours, mm is minutes and xx is seconds"
},
{
"code": null,
"e": 2942,
"s": 2820,
"text": "Elapsed − This parameter returns the number of seconds and microseconds since the elapsed-time clock was started or reset"
},
{
"code": null,
"e": 3064,
"s": 2942,
"text": "Elapsed − This parameter returns the number of seconds and microseconds since the elapsed-time clock was started or reset"
},
{
"code": null,
"e": 3151,
"s": 3064,
"text": "Full − This parameter returns the number of microseconds since the date 1 January 0001"
},
{
"code": null,
"e": 3238,
"s": 3151,
"text": "Full − This parameter returns the number of microseconds since the date 1 January 0001"
},
{
"code": null,
"e": 3321,
"s": 3238,
"text": "Hours − This parameter returns the number of hours that have passed since midnight"
},
{
"code": null,
"e": 3404,
"s": 3321,
"text": "Hours − This parameter returns the number of hours that have passed since midnight"
},
{
"code": null,
"e": 3491,
"s": 3404,
"text": "Minutes − This parameter returns the number of minutes that have passed since midnight"
},
{
"code": null,
"e": 3578,
"s": 3491,
"text": "Minutes − This parameter returns the number of minutes that have passed since midnight"
},
{
"code": null,
"e": 3650,
"s": 3578,
"text": "Normal − This parameter returns the time in the default format hh:mm:ss"
},
{
"code": null,
"e": 3722,
"s": 3650,
"text": "Normal − This parameter returns the time in the default format hh:mm:ss"
},
{
"code": null,
"e": 3809,
"s": 3722,
"text": "Offset − This parameter returns the offset of the local time from UTC in microseconds."
},
{
"code": null,
"e": 3896,
"s": 3809,
"text": "Offset − This parameter returns the offset of the local time from UTC in microseconds."
},
{
"code": null,
"e": 4001,
"s": 3896,
"text": "This method returns the local time in the 24-hour clock format − hh:mm:ss (hours, minutes, and seconds)."
},
{
"code": null,
"e": 4062,
"s": 4001,
"text": "/* Main program */ \nsay TIME() \nsay TIME(\"C\") \nsay TIME(\"H\")"
},
{
"code": null,
"e": 4174,
"s": 4062,
"text": "When we run the above program we will get the following result. This depends on the current time on the system."
},
{
"code": null,
"e": 4216,
"s": 4174,
"text": "The following program is just an example."
},
{
"code": null,
"e": 4240,
"s": 4216,
"text": "10:54:12 \n10:54am \n10 \n"
},
{
"code": null,
"e": 4247,
"s": 4240,
"text": " Print"
},
{
"code": null,
"e": 4258,
"s": 4247,
"text": " Add Notes"
}
]
|
How to pass an arrayList to another activity using intents in Android? | This example demonstrates how do I pass an arrayList to another activity using intends in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/relativeLayout"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pass array to 2nd Activity"
android:layout_centerInParent="true" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity{
Button button;
ArrayList<String> numbers = new ArrayList<>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
numbers.add("ONE");
numbers.add("TWO");
numbers.add("THREE");
numbers.add("FOUR");
numbers.add("FIVE");
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key", numbers);
startActivity(intent);
}
});
}
}
Step 4 – Create a new Activity(SecondActivity) and add the following code in SecondActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.ArrayList;
public class SecondActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
textView = findViewById(R.id.textView);
ArrayList<String> numbersList = (ArrayList<String>) getIntent().getSerializableExtra("key");
textView.setText(String.valueOf(numbersList));
}
}
Step 5 – Add the following code in the activity_second.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text=""
android:textSize="24sp"
android:textStyle="bold"/>
</RelativeLayout>
Step 6 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".SecondActivity"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code. | [
{
"code": null,
"e": 1161,
"s": 1062,
"text": "This example demonstrates how do I pass an arrayList to another activity using intends in android."
},
{
"code": null,
"e": 1290,
"s": 1161,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1355,
"s": 1290,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1907,
"s": 1355,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:id=\"@+id/relativeLayout\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Pass array to 2nd Activity\"\n android:layout_centerInParent=\"true\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1964,
"s": 1907,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2943,
"s": 1964,
"text": "import android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity{\n Button button;\n ArrayList<String> numbers = new ArrayList<>();\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n button = findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n numbers.add(\"ONE\");\n numbers.add(\"TWO\");\n numbers.add(\"THREE\");\n numbers.add(\"FOUR\");\n numbers.add(\"FIVE\");\n Intent intent = new Intent(MainActivity.this, SecondActivity.class);\n intent.putExtra(\"key\", numbers);\n startActivity(intent);\n }\n });\n }\n}"
},
{
"code": null,
"e": 3040,
"s": 2943,
"text": "Step 4 – Create a new Activity(SecondActivity) and add the following code in SecondActivity.java"
},
{
"code": null,
"e": 3617,
"s": 3040,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\nimport java.util.ArrayList;\npublic class SecondActivity extends AppCompatActivity {\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_second);\n textView = findViewById(R.id.textView);\n ArrayList<String> numbersList = (ArrayList<String>) getIntent().getSerializableExtra(\"key\");\n textView.setText(String.valueOf(numbersList));\n }\n}"
},
{
"code": null,
"e": 3676,
"s": 3617,
"text": "Step 5 – Add the following code in the activity_second.xml"
},
{
"code": null,
"e": 4232,
"s": 3676,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".SecondActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 4287,
"s": 4232,
"text": "Step 6 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5016,
"s": 4287,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".SecondActivity\"></activity>\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5363,
"s": 5016,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 5404,
"s": 5363,
"text": "Click here to download the project code."
}
]
|
Greatest Common Divisor of Strings in Python | Suppose there are two strings A and B. We can say that A is divisible by B, when A is created by concatenating B one or more times. So if A = “abcabc”, and B = “abc”, then A is divisible by B. In this section, we will see what is the greatest common divisor of a String. So return the largest string that divides both of the strings. So if two strings are “ABABAB”, and “ABAB”, then GCD will be “AB”
To solve this, we will follow these steps −
temp := shorter string between A and B
m := length of temp
x := 1
res is an array and insert “” into the res
while A and B has substring of size x, then add the substring into the res, and increase x by 1
finally return the last element in the res array.
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def gcdOfStrings(self, str1, str2):
if len(str1)<=len(str2):
temp = str1
else:
temp = str2
m = len(temp)
x = 1
res=[""]
while x<=m:
if m%x==0 and temp[:x] * (len(str1)//x) == str1 and temp[:x] * (len(str2)//x) == str2:
res.append(temp[:x])
x+=1
return res[-1]
ob1 = Solution()
print(ob1.gcdOfStrings("ABABAB","ABAB"))
"ABABAB"
"ABAB"
AB | [
{
"code": null,
"e": 1462,
"s": 1062,
"text": "Suppose there are two strings A and B. We can say that A is divisible by B, when A is created by concatenating B one or more times. So if A = “abcabc”, and B = “abc”, then A is divisible by B. In this section, we will see what is the greatest common divisor of a String. So return the largest string that divides both of the strings. So if two strings are “ABABAB”, and “ABAB”, then GCD will be “AB”"
},
{
"code": null,
"e": 1506,
"s": 1462,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1545,
"s": 1506,
"text": "temp := shorter string between A and B"
},
{
"code": null,
"e": 1565,
"s": 1545,
"text": "m := length of temp"
},
{
"code": null,
"e": 1572,
"s": 1565,
"text": "x := 1"
},
{
"code": null,
"e": 1615,
"s": 1572,
"text": "res is an array and insert “” into the res"
},
{
"code": null,
"e": 1711,
"s": 1615,
"text": "while A and B has substring of size x, then add the substring into the res, and increase x by 1"
},
{
"code": null,
"e": 1761,
"s": 1711,
"text": "finally return the last element in the res array."
},
{
"code": null,
"e": 1831,
"s": 1761,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1842,
"s": 1831,
"text": " Live Demo"
},
{
"code": null,
"e": 2277,
"s": 1842,
"text": "class Solution(object):\n def gcdOfStrings(self, str1, str2):\n if len(str1)<=len(str2):\n temp = str1\n else:\n temp = str2\n m = len(temp)\n x = 1\n res=[\"\"]\n while x<=m:\n if m%x==0 and temp[:x] * (len(str1)//x) == str1 and temp[:x] * (len(str2)//x) == str2:\n res.append(temp[:x])\n x+=1\n return res[-1]\nob1 = Solution()\nprint(ob1.gcdOfStrings(\"ABABAB\",\"ABAB\"))"
},
{
"code": null,
"e": 2293,
"s": 2277,
"text": "\"ABABAB\"\n\"ABAB\""
},
{
"code": null,
"e": 2296,
"s": 2293,
"text": "AB"
}
]
|
Redis - Keys Type Command | Redis TYPE command is used to get the data type of the value stored in the key.
String reply, data type of the value stored in the key or none.
Following is the basic syntax of Redis TYPE command.
redis 127.0.0.1:6379> TYPE KEY_NAME
First, create some keys in Redis and set some values in it.
redis 127.0.0.1:6379> SET tutorial1 redis
OK
Now, check the type of the key.
redis 127.0.0.1:6379> TYPE tutorial1
string
22 Lectures
40 mins
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2125,
"s": 2045,
"text": "Redis TYPE command is used to get the data type of the value stored in the key."
},
{
"code": null,
"e": 2189,
"s": 2125,
"text": "String reply, data type of the value stored in the key or none."
},
{
"code": null,
"e": 2242,
"s": 2189,
"text": "Following is the basic syntax of Redis TYPE command."
},
{
"code": null,
"e": 2280,
"s": 2242,
"text": "redis 127.0.0.1:6379> TYPE KEY_NAME \n"
},
{
"code": null,
"e": 2340,
"s": 2280,
"text": "First, create some keys in Redis and set some values in it."
},
{
"code": null,
"e": 2388,
"s": 2340,
"text": "redis 127.0.0.1:6379> SET tutorial1 redis \nOK \n"
},
{
"code": null,
"e": 2420,
"s": 2388,
"text": "Now, check the type of the key."
},
{
"code": null,
"e": 2467,
"s": 2420,
"text": "redis 127.0.0.1:6379> TYPE tutorial1 \nstring \n"
},
{
"code": null,
"e": 2499,
"s": 2467,
"text": "\n 22 Lectures \n 40 mins\n"
},
{
"code": null,
"e": 2519,
"s": 2499,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2526,
"s": 2519,
"text": " Print"
},
{
"code": null,
"e": 2537,
"s": 2526,
"text": " Add Notes"
}
]
|
What are event attributes in jQuery? | jQuery events have attributes such as for keyup and keydown events, if the Ctrl key was pressed, timestamp when the event created, etc.
The following are some of the event properties/attributes available:
You can try to run the following code to learn how to work with jQuery event attributes:
Live Demo
<html>
<head>
<title>jQuery Attributes</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$('div').bind('click', function( event ){
alert('Event type is ' + event.type);
alert('pageX : ' + event.pageX);
alert('pageY : ' + event.pageY);
alert('Target : ' + event.target.innerHTML);
});
});
</script>
<style>
.div {
margin:10px;
padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class = "div" style = "background-color:blue;">ONE</div>
<div class = "div" style = "background-color:green;">TWO</div>
<div class = "div" style = "background-color:red;">THREE</div>
</body>
</html> | [
{
"code": null,
"e": 1198,
"s": 1062,
"text": "jQuery events have attributes such as for keyup and keydown events, if the Ctrl key was pressed, timestamp when the event created, etc."
},
{
"code": null,
"e": 1267,
"s": 1198,
"text": "The following are some of the event properties/attributes available:"
},
{
"code": null,
"e": 1356,
"s": 1267,
"text": "You can try to run the following code to learn how to work with jQuery event attributes:"
},
{
"code": null,
"e": 1366,
"s": 1356,
"text": "Live Demo"
},
{
"code": null,
"e": 2446,
"s": 1366,
"text": "<html>\n\n <head>\n <title>jQuery Attributes</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n \n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $('div').bind('click', function( event ){\n alert('Event type is ' + event.type);\n alert('pageX : ' + event.pageX);\n alert('pageY : ' + event.pageY);\n alert('Target : ' + event.target.innerHTML);\n });\n });\n </script>\n \n <style>\n .div {\n margin:10px;\n padding:12px;\n border:2px solid #666;\n width:60px;\n }\n </style>\n </head>\n \n <body>\n \n <p>Click on any square below to see the result:</p>\n \n <div class = \"div\" style = \"background-color:blue;\">ONE</div>\n <div class = \"div\" style = \"background-color:green;\">TWO</div>\n <div class = \"div\" style = \"background-color:red;\">THREE</div>\n \n </body>\n \n</html>"
}
]
|
Implementation of Stack in JavaScript | Following is the code to implement stack in JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: blueviolet;
}
button {
padding: 6px;
margin: 4px;
}
</style>
</head>
<body>
<h1>Implementation of Stack in JavaScript.</h1>
<div class="result"></div>
<br />
<input type="text" class="stackPush" /><button class="pushBtn">Push</button>
<button class="popBtn">Pop</button>
<button class="Btn">Display</button>
<h3>Click on the above buttons to perform stack operations</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
let pushBtnEle = document.querySelector(".pushBtn");
let popBtnEle = document.querySelector(".popBtn");
class Stack {
constructor() {
this.items = [];
this.top = 0;
}
}
Stack.prototype.push = function (ele) {
this.items[this.top] = ele;
this.top += 1;
};
Stack.prototype.pop = function () {
if (this.top === 0) {
return "Underflow: no more elements to delete";
}
tempNum = this.items[this.top - 1];
this.items.length -= 1;
return tempNum;
};
Stack.prototype.display = function () {
if (this.top == 0) {
return "Stack is empty";
}
for (let i = 0; i < this.top; i++) {
resEle.innerHTML += this.items[i] + " , ";
}
};
let stack1 = new Stack();
BtnEle.addEventListener("click", () => {
resEle.innerHTML = "";
stack1.display();
});
pushBtnEle.addEventListener("click", () => {
let ele = document.querySelector(".stackPush").value;
resEle.innerHTML = ele + " is pushed to the stack";
stack1.push(ele);
});
popBtnEle.addEventListener("click", () => {
resEle.innerHTML = stack1.pop() + " is popped from the stack";
});
</script>
</body>
</html>
On entering number in the field and clicking on ‘Push’ −
On clicking the ‘Pop’ button −
On clicking the ‘Display’ button when the stack is not empty − | [
{
"code": null,
"e": 1119,
"s": 1062,
"text": "Following is the code to implement stack in JavaScript −"
},
{
"code": null,
"e": 1130,
"s": 1119,
"text": " Live Demo"
},
{
"code": null,
"e": 3204,
"s": 1130,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n color: blueviolet;\n }\n button {\n padding: 6px;\n margin: 4px;\n }\n</style>\n</head>\n<body>\n<h1>Implementation of Stack in JavaScript.</h1>\n<div class=\"result\"></div>\n<br />\n<input type=\"text\" class=\"stackPush\" /><button class=\"pushBtn\">Push</button>\n<button class=\"popBtn\">Pop</button>\n<button class=\"Btn\">Display</button>\n<h3>Click on the above buttons to perform stack operations</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let BtnEle = document.querySelector(\".Btn\");\n let pushBtnEle = document.querySelector(\".pushBtn\");\n let popBtnEle = document.querySelector(\".popBtn\");\n class Stack {\n constructor() {\n this.items = [];\n this.top = 0;\n }\n }\n Stack.prototype.push = function (ele) {\n this.items[this.top] = ele;\n this.top += 1;\n };\n Stack.prototype.pop = function () {\n if (this.top === 0) {\n return \"Underflow: no more elements to delete\";\n }\n tempNum = this.items[this.top - 1];\n this.items.length -= 1;\n return tempNum;\n };\n Stack.prototype.display = function () {\n if (this.top == 0) {\n return \"Stack is empty\";\n }\n for (let i = 0; i < this.top; i++) {\n resEle.innerHTML += this.items[i] + \" , \";\n }\n };\n let stack1 = new Stack();\n BtnEle.addEventListener(\"click\", () => {\n resEle.innerHTML = \"\";\n stack1.display();\n });\n pushBtnEle.addEventListener(\"click\", () => {\n let ele = document.querySelector(\".stackPush\").value;\n resEle.innerHTML = ele + \" is pushed to the stack\";\n stack1.push(ele);\n });\n popBtnEle.addEventListener(\"click\", () => {\n resEle.innerHTML = stack1.pop() + \" is popped from the stack\";\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 3261,
"s": 3204,
"text": "On entering number in the field and clicking on ‘Push’ −"
},
{
"code": null,
"e": 3292,
"s": 3261,
"text": "On clicking the ‘Pop’ button −"
},
{
"code": null,
"e": 3355,
"s": 3292,
"text": "On clicking the ‘Display’ button when the stack is not empty −"
}
]
|
How to check if a process is exited from the system after executing Stop-Process command in PowerShell? | After killing the process using Stop-Process command in PowerShell, you can determine if the process is really terminated from the system with HasExited function.
For example, we will kill Notepad process and check if Notepad process still exists in the system?
$notepad = Get-Process notepad | Stop-Process
if($notepad.HasExited){"Process is terminated"}
else{"Process is still running"} | [
{
"code": null,
"e": 1225,
"s": 1062,
"text": "After killing the process using Stop-Process command in PowerShell, you can determine if the process is really terminated from the system with HasExited function."
},
{
"code": null,
"e": 1324,
"s": 1225,
"text": "For example, we will kill Notepad process and check if Notepad process still exists in the system?"
},
{
"code": null,
"e": 1451,
"s": 1324,
"text": "$notepad = Get-Process notepad | Stop-Process\nif($notepad.HasExited){\"Process is terminated\"}\nelse{\"Process is still running\"}"
}
]
|
Python Tutorial | Python is a popular programming language.
Python can be used on a server to create web applications.
With our "Try it Yourself" editor, you can edit Python code and view the result.
Click on the "Try it Yourself" button to see how it works.
In our File Handling section you will learn how to open, read, write, and
delete files.
Python File Handling
In our database section you will learn how to access and work with MySQL and MongoDB databases:
Python MySQL Tutorial
Python MongoDB Tutorial
Insert the missing part of the code below to output "Hello World".
("Hello World")
Start the Exercise
Learn by examples! This tutorial supplements all explanations with clarifying examples.
See All Python Examples
Test your Python skills with a quiz.
Python Quiz
You will also find complete function and method references:
Reference Overview
Built-in Functions
String Methods
List/Array Methods
Dictionary Methods
Tuple Methods
Set Methods
File Methods
Python Keywords
Python Exceptions
Python Glossary
Random Module
Requests Module
Math Module
CMath Module
Download Python from the official Python web site:
https://python.org
Get certified by completing the PYTHON course
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 42,
"s": 0,
"text": "Python is a popular programming language."
},
{
"code": null,
"e": 101,
"s": 42,
"text": "Python can be used on a server to create web applications."
},
{
"code": null,
"e": 182,
"s": 101,
"text": "With our \"Try it Yourself\" editor, you can edit Python code and view the result."
},
{
"code": null,
"e": 241,
"s": 182,
"text": "Click on the \"Try it Yourself\" button to see how it works."
},
{
"code": null,
"e": 330,
"s": 241,
"text": "In our File Handling section you will learn how to open, read, write, and \ndelete files."
},
{
"code": null,
"e": 351,
"s": 330,
"text": "Python File Handling"
},
{
"code": null,
"e": 447,
"s": 351,
"text": "In our database section you will learn how to access and work with MySQL and MongoDB databases:"
},
{
"code": null,
"e": 469,
"s": 447,
"text": "Python MySQL Tutorial"
},
{
"code": null,
"e": 493,
"s": 469,
"text": "Python MongoDB Tutorial"
},
{
"code": null,
"e": 560,
"s": 493,
"text": "Insert the missing part of the code below to output \"Hello World\"."
},
{
"code": null,
"e": 577,
"s": 560,
"text": "(\"Hello World\")\n"
},
{
"code": null,
"e": 596,
"s": 577,
"text": "Start the Exercise"
},
{
"code": null,
"e": 684,
"s": 596,
"text": "Learn by examples! This tutorial supplements all explanations with clarifying examples."
},
{
"code": null,
"e": 708,
"s": 684,
"text": "See All Python Examples"
},
{
"code": null,
"e": 745,
"s": 708,
"text": "Test your Python skills with a quiz."
},
{
"code": null,
"e": 757,
"s": 745,
"text": "Python Quiz"
},
{
"code": null,
"e": 817,
"s": 757,
"text": "You will also find complete function and method references:"
},
{
"code": null,
"e": 836,
"s": 817,
"text": "Reference Overview"
},
{
"code": null,
"e": 855,
"s": 836,
"text": "Built-in Functions"
},
{
"code": null,
"e": 870,
"s": 855,
"text": "String Methods"
},
{
"code": null,
"e": 889,
"s": 870,
"text": "List/Array Methods"
},
{
"code": null,
"e": 908,
"s": 889,
"text": "Dictionary Methods"
},
{
"code": null,
"e": 922,
"s": 908,
"text": "Tuple Methods"
},
{
"code": null,
"e": 934,
"s": 922,
"text": "Set Methods"
},
{
"code": null,
"e": 947,
"s": 934,
"text": "File Methods"
},
{
"code": null,
"e": 963,
"s": 947,
"text": "Python Keywords"
},
{
"code": null,
"e": 981,
"s": 963,
"text": "Python Exceptions"
},
{
"code": null,
"e": 997,
"s": 981,
"text": "Python Glossary"
},
{
"code": null,
"e": 1011,
"s": 997,
"text": "Random Module"
},
{
"code": null,
"e": 1027,
"s": 1011,
"text": "Requests Module"
},
{
"code": null,
"e": 1039,
"s": 1027,
"text": "Math Module"
},
{
"code": null,
"e": 1052,
"s": 1039,
"text": "CMath Module"
},
{
"code": null,
"e": 1124,
"s": 1052,
"text": "Download Python from the official Python web site:\n https://python.org"
},
{
"code": null,
"e": 1170,
"s": 1124,
"text": "Get certified by completing the PYTHON course"
},
{
"code": null,
"e": 1203,
"s": 1170,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1245,
"s": 1203,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1352,
"s": 1245,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1371,
"s": 1352,
"text": "[email protected]"
}
]
|
Find if an array of strings can be chained to form a circle | Set 2 - GeeksforGeeks | 07 Mar, 2022
Given an array of strings, find if the given strings can be chained to form a circle. A string X can be put before another string Y in a circle if the last character of X is the same as the first character of Y.
Examples:
Input: arr[] = {"geek", "king"}
Output: Yes, the given strings can be chained.
Note that the last character of first string is same
as first character of second string and vice versa is
also true.
Input: arr[] = {"for", "geek", "rig", "kaf"}
Output: Yes, the given strings can be chained.
The strings can be chained as "for", "rig", "geek"
and "kaf"
Input: arr[] = {"aab", "bac", "aaa", "cda"}
Output: Yes, the given strings can be chained.
The strings can be chained as "aaa", "aab", "bac"
and "cda"
Input: arr[] = {"aaa", "bbb", "baa", "aab"};
Output: Yes, the given strings can be chained.
The strings can be chained as "aaa", "aab", "bbb"
and "baa"
Input: arr[] = {"aaa"};
Output: Yes
Input: arr[] = {"aaa", "bbb"};
Output: No
Input : arr[] = ["abc", "efg", "cde", "ghi", "ija"]
Output : Yes
These strings can be reordered as, “abc”, “cde”, “efg”,
“ghi”, “ija”
Input : arr[] = [“ijk”, “kji”, “abc”, “cba”]
Output : No
We have discussed one approach to this problem in the below post. Find if an array of strings can be chained to form a circle | Set 1
In this post, another approach is discussed. We solve this problem by treating this as a graph problem, where vertices will be the first and last character of strings, and we will draw an edge between two vertices if they are the first and last character of the same string, so a number of edges in the graph will be same as the number of strings in the array. Graph representation of some string arrays are given in the below diagram,
Now it can be clearly seen after graph representation that if a loop among graph vertices is possible then we can reorder the strings otherwise not. As in the above diagram’s example, a loop can be found in the first and third array of string but not in the second array of string. Now to check whether this graph can have a loop which goes through all the vertices, we’ll check two conditions,
Indegree and Outdegree of each vertex should be the same.The graph should be strongly connected.
Indegree and Outdegree of each vertex should be the same.
The graph should be strongly connected.
The first condition can be checked easily by keeping two arrays, in and out for each character. For checking whether a graph is having a loop which goes through all vertices is the same as checking complete directed graph is strongly connected or not because if it has a loop which goes through all vertices then we can reach to any vertex from any other vertex that is, the graph will be strongly connected and the same argument can be given for reverse statement also.
Now for checking the second condition we will just run a DFS from any character and visit all reachable vertices from this, now if the graph has a loop then after this one DFS all vertices should be visited, if all vertices are visited then we will return true otherwise false so visiting all vertices in a single DFS flags a possible ordering among strings.
C++
Java
Python3
C#
Javascript
// C++ code to check if cyclic order is possible among strings// under given constraints#include <bits/stdc++.h>using namespace std;#define M 26 // Utility method for a depth first search among verticesvoid dfs(vector<int> g[], int u, vector<bool> &visit){ visit[u] = true; for (int i = 0; i < g[u].size(); ++i) if(!visit[g[u][i]]) dfs(g, g[u][i], visit);} // Returns true if all vertices are strongly connected// i.e. can be made as loopbool isConnected(vector<int> g[], vector<bool> &mark, int s){ // Initialize all vertices as not visited vector<bool> visit(M, false); // perform a dfs from s dfs(g, s, visit); // now loop through all characters for (int i = 0; i < M; i++) { /* I character is marked (i.e. it was first or last character of some string) then it should be visited in last dfs (as for looping, graph should be strongly connected) */ if (mark[i] && !visit[i]) return false; } // If we reach that means graph is connected return true;} // return true if an order among strings is possiblebool possibleOrderAmongString(string arr[], int N){ // Create an empty graph vector<int> g[M]; // Initialize all vertices as not marked vector<bool> mark(M, false); // Initialize indegree and outdegree of every // vertex as 0. vector<int> in(M, 0), out(M, 0); // Process all strings one by one for (int i = 0; i < N; i++) { // Find first and last characters int f = arr[i].front() - 'a'; int l = arr[i].back() - 'a'; // Mark the characters mark[f] = mark[l] = true; // increase indegree and outdegree count in[l]++; out[f]++; // Add an edge in graph g[f].push_back(l); } // If for any character indegree is not equal to // outdegree then ordering is not possible for (int i = 0; i < M; i++) if (in[i] != out[i]) return false; return isConnected(g, mark, arr[0].front() - 'a');} // Driver code to test above methodsint main(){ // string arr[] = {"abc", "efg", "cde", "ghi", "ija"}; string arr[] = {"ab", "bc", "cd", "de", "ed", "da"}; int N = sizeof(arr) / sizeof(arr[0]); if (possibleOrderAmongString(arr, N) == false) cout << "Ordering not possible\n"; else cout << "Ordering is possible\n"; return 0;}
// Java code to check if cyclic order is// possible among strings under given constraintsimport java.io.*;import java.util.*; class GFG{ // Return true if an order among strings is possible public static boolean possibleOrderAmongString( String s[], int n){ int m = 26; boolean mark[] = new boolean[m]; int in[] = new int[26]; int out[] = new int[26]; ArrayList< ArrayList<Integer>> adj = new ArrayList< ArrayList<Integer>>(); for(int i = 0; i < m; i++) adj.add(new ArrayList<>()); // Process all strings one by one for(int i = 0; i < n; i++) { // Find first and last characters int f = (int)(s[i].charAt(0) - 'a'); int l = (int)(s[i].charAt( s[i].length() - 1) - 'a'); // Mark the characters mark[f] = mark[l] = true; // Increase indegree and outdegree count in[l]++; out[f]++; // Add an edge in graph adj.get(f).add(l); } // If for any character indegree is not equal to // outdegree then ordering is not possible for(int i = 0; i < m; i++) { if (in[i] != out[i]) return false; } return isConnected(adj, mark, s[0].charAt(0) - 'a');} // Returns true if all vertices are strongly// connected i.e. can be made as looppublic static boolean isConnected( ArrayList<ArrayList<Integer>> adj, boolean mark[], int src){ boolean visited[] = new boolean[26]; // Perform a dfs from src dfs(adj, visited, src); for(int i = 0; i < 26; i++) { /* I character is marked (i.e. it was first or last character of some string) then it should be visited in last dfs (as for looping, graph should be strongly connected) */ if (mark[i] && !visited[i]) return false; } // If we reach that means graph is connected return true;} // Utility method for a depth first// search among verticespublic static void dfs(ArrayList<ArrayList<Integer>> adj, boolean visited[], int src){ visited[src] = true; for(int i = 0; i < adj.get(src).size(); i++) if (!visited[adj.get(src).get(i)]) dfs(adj, visited, adj.get(src).get(i));} // Driver codepublic static void main(String[] args){ String s[] = { "ab", "bc", "cd", "de", "ed", "da" }; int n = s.length; if (possibleOrderAmongString(s, n)) System.out.println("Ordering is possible"); else System.out.println("Ordering is not possible");}} // This code is contributed by parascoding
# Python3 code to check if# cyclic order is possible# among strings under given# constraintsM = 26 # Utility method for a depth# first search among verticesdef dfs(g, u, visit): visit[u] = True for i in range(len(g[u])): if(not visit[g[u][i]]): dfs(g, g[u][i], visit) # Returns true if all vertices# are strongly connected i.e.# can be made as loopdef isConnected(g, mark, s): # Initialize all vertices # as not visited visit = [False for i in range(M)] # Perform a dfs from s dfs(g, s, visit) # Now loop through # all characters for i in range(M): # I character is marked # (i.e. it was first or last # character of some string) # then it should be visited # in last dfs (as for looping, # graph should be strongly # connected) */ if(mark[i] and (not visit[i])): return False # If we reach that means # graph is connected return True # return true if an order among# strings is possibledef possibleOrderAmongString(arr, N): # Create an empty graph g = {} # Initialize all vertices # as not marked mark = [False for i in range(M)] # Initialize indegree and # outdegree of every # vertex as 0. In = [0 for i in range(M)] out = [0 for i in range(M)] # Process all strings # one by one for i in range(N): # Find first and last # characters f = (ord(arr[i][0]) - ord('a')) l = (ord(arr[i][-1]) - ord('a')) # Mark the characters mark[f] = True mark[l] = True # Increase indegree # and outdegree count In[l] += 1 out[f] += 1 if f not in g: g[f] = [] # Add an edge in graph g[f].append(l) # If for any character # indegree is not equal to # outdegree then ordering # is not possible for i in range(M): if(In[i] != out[i]): return False return isConnected(g, mark, ord(arr[0][0]) - ord('a')) # Driver codearr = ["ab", "bc", "cd", "de", "ed", "da"]N = len(arr)if(possibleOrderAmongString(arr, N) == False): print("Ordering not possible")else: print("Ordering is possible") # This code is contributed by avanitrachhadiya2155
// C# code to check if cyclic order is// possible among strings under given constraintsusing System;using System.Collections.Generic;class GFG { // Return true if an order among strings is possible static bool possibleOrderAmongString(string[] s, int n) { int m = 26; bool[] mark = new bool[m]; int[] In = new int[26]; int[] Out = new int[26]; List<List<int>> adj = new List<List<int>>(); for(int i = 0; i < m; i++) adj.Add(new List<int>()); // Process all strings one by one for(int i = 0; i < n; i++) { // Find first and last characters int f = (int)(s[i][0] - 'a'); int l = (int)(s[i][s[i].Length - 1] - 'a'); // Mark the characters mark[f] = mark[l] = true; // Increase indegree and outdegree count In[l]++; Out[f]++; // Add an edge in graph adj[f].Add(l); } // If for any character indegree is not equal to // outdegree then ordering is not possible for(int i = 0; i < m; i++) { if (In[i] != Out[i]) return false; } return isConnected(adj, mark, s[0][0] - 'a'); } // Returns true if all vertices are strongly // connected i.e. can be made as loop public static bool isConnected( List<List<int>> adj, bool[] mark, int src) { bool[] visited = new bool[26]; // Perform a dfs from src dfs(adj, visited, src); for(int i = 0; i < 26; i++) { /* I character is marked (i.e. it was first or last character of some string) then it should be visited in last dfs (as for looping, graph should be strongly connected) */ if (mark[i] && !visited[i]) return false; } // If we reach that means graph is connected return true; } // Utility method for a depth first // search among vertices public static void dfs(List<List<int>> adj, bool[] visited, int src) { visited[src] = true; for(int i = 0; i < adj[src].Count; i++) if (!visited[adj[src][i]]) dfs(adj, visited, adj[src][i]); } static void Main() { string[] s = { "ab", "bc", "cd", "de", "ed", "da" }; int n = s.Length; if (possibleOrderAmongString(s, n)) Console.Write("Ordering is possible"); else Console.Write("Ordering is not possible"); }} // This code is contributed by divyesh072019.
<script> // Javascript code to check if cyclic order is // possible among strings under given constraints // Return true if an order among strings is possible function possibleOrderAmongString(s, n) { let m = 26; let mark = new Array(m); mark.fill(false); let In = new Array(26); In.fill(0); let Out = new Array(26); Out.fill(0); let adj = []; for(let i = 0; i < m; i++) adj.push([]); // Process all strings one by one for(let i = 0; i < n; i++) { // Find first and last characters let f = (s[i][0].charCodeAt() - 'a'.charCodeAt()); let l = (s[i][s[i].length - 1].charCodeAt() - 'a'.charCodeAt()); // Mark the characters mark[f] = mark[l] = true; // Increase indegree and outdegree count In[l]++; Out[f]++; // Add an edge in graph adj[f].push(l); } // If for any character indegree is not equal to // outdegree then ordering is not possible for(let i = 0; i < m; i++) { if (In[i] != Out[i]) return false; } return isConnected(adj, mark, s[0][0].charCodeAt() - 'a'.charCodeAt()); } // Returns true if all vertices are strongly // connected i.e. can be made as loop function isConnected(adj, mark, src) { let visited = new Array(26); visited.fill(false); // Perform a dfs from src dfs(adj, visited, src); for(let i = 0; i < 26; i++) { /* I character is marked (i.e. it was first or last character of some string) then it should be visited in last dfs (as for looping, graph should be strongly connected) */ if (mark[i] && !visited[i]) return false; } // If we reach that means graph is connected return true; } // Utility method for a depth first // search among vertices function dfs(adj, visited, src) { visited[src] = true; for(let i = 0; i < adj[src].length; i++) if (!visited[adj[src][i]]) dfs(adj, visited, adj[src][i]); } let s = [ "ab", "bc", "cd", "de", "ed", "da" ]; let n = s.length; if (possibleOrderAmongString(s, n)) document.write("Ordering is possible"); else document.write("Ordering is not possible"); // This code is contributed by decode2207.</script>
Output:
Ordering is possible
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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.
Piyush_Karira
avanitrachhadiya2155
parascoding
divyesh072019
decode2207
simmytarika5
DFS
Graph
Strings
Strings
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ford-Fulkerson Algorithm for Maximum Flow Problem
Traveling Salesman Problem (TSP) Implementation
Hamiltonian Cycle | Backtracking-6
m Coloring Problem | Backtracking-5
Check whether a given graph is Bipartite or not
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4 | [
{
"code": null,
"e": 26269,
"s": 26241,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 26481,
"s": 26269,
"text": "Given an array of strings, find if the given strings can be chained to form a circle. A string X can be put before another string Y in a circle if the last character of X is the same as the first character of Y."
},
{
"code": null,
"e": 26492,
"s": 26481,
"text": "Examples: "
},
{
"code": null,
"e": 27425,
"s": 26492,
"text": "Input: arr[] = {\"geek\", \"king\"}\nOutput: Yes, the given strings can be chained.\nNote that the last character of first string is same\nas first character of second string and vice versa is\nalso true.\n\nInput: arr[] = {\"for\", \"geek\", \"rig\", \"kaf\"}\nOutput: Yes, the given strings can be chained.\nThe strings can be chained as \"for\", \"rig\", \"geek\" \nand \"kaf\"\n\nInput: arr[] = {\"aab\", \"bac\", \"aaa\", \"cda\"}\nOutput: Yes, the given strings can be chained.\nThe strings can be chained as \"aaa\", \"aab\", \"bac\" \nand \"cda\"\n\nInput: arr[] = {\"aaa\", \"bbb\", \"baa\", \"aab\"};\nOutput: Yes, the given strings can be chained.\nThe strings can be chained as \"aaa\", \"aab\", \"bbb\" \nand \"baa\"\n\nInput: arr[] = {\"aaa\"};\nOutput: Yes\n\nInput: arr[] = {\"aaa\", \"bbb\"};\nOutput: No\n\nInput : arr[] = [\"abc\", \"efg\", \"cde\", \"ghi\", \"ija\"]\nOutput : Yes\nThese strings can be reordered as, “abc”, “cde”, “efg”,\n“ghi”, “ija”\n\nInput : arr[] = [“ijk”, “kji”, “abc”, “cba”]\nOutput : No"
},
{
"code": null,
"e": 27559,
"s": 27425,
"text": "We have discussed one approach to this problem in the below post. Find if an array of strings can be chained to form a circle | Set 1"
},
{
"code": null,
"e": 27997,
"s": 27559,
"text": "In this post, another approach is discussed. We solve this problem by treating this as a graph problem, where vertices will be the first and last character of strings, and we will draw an edge between two vertices if they are the first and last character of the same string, so a number of edges in the graph will be same as the number of strings in the array. Graph representation of some string arrays are given in the below diagram, "
},
{
"code": null,
"e": 28393,
"s": 27997,
"text": "Now it can be clearly seen after graph representation that if a loop among graph vertices is possible then we can reorder the strings otherwise not. As in the above diagram’s example, a loop can be found in the first and third array of string but not in the second array of string. Now to check whether this graph can have a loop which goes through all the vertices, we’ll check two conditions, "
},
{
"code": null,
"e": 28490,
"s": 28393,
"text": "Indegree and Outdegree of each vertex should be the same.The graph should be strongly connected."
},
{
"code": null,
"e": 28548,
"s": 28490,
"text": "Indegree and Outdegree of each vertex should be the same."
},
{
"code": null,
"e": 28588,
"s": 28548,
"text": "The graph should be strongly connected."
},
{
"code": null,
"e": 29060,
"s": 28588,
"text": "The first condition can be checked easily by keeping two arrays, in and out for each character. For checking whether a graph is having a loop which goes through all vertices is the same as checking complete directed graph is strongly connected or not because if it has a loop which goes through all vertices then we can reach to any vertex from any other vertex that is, the graph will be strongly connected and the same argument can be given for reverse statement also. "
},
{
"code": null,
"e": 29420,
"s": 29060,
"text": "Now for checking the second condition we will just run a DFS from any character and visit all reachable vertices from this, now if the graph has a loop then after this one DFS all vertices should be visited, if all vertices are visited then we will return true otherwise false so visiting all vertices in a single DFS flags a possible ordering among strings. "
},
{
"code": null,
"e": 29424,
"s": 29420,
"text": "C++"
},
{
"code": null,
"e": 29429,
"s": 29424,
"text": "Java"
},
{
"code": null,
"e": 29437,
"s": 29429,
"text": "Python3"
},
{
"code": null,
"e": 29440,
"s": 29437,
"text": "C#"
},
{
"code": null,
"e": 29451,
"s": 29440,
"text": "Javascript"
},
{
"code": "// C++ code to check if cyclic order is possible among strings// under given constraints#include <bits/stdc++.h>using namespace std;#define M 26 // Utility method for a depth first search among verticesvoid dfs(vector<int> g[], int u, vector<bool> &visit){ visit[u] = true; for (int i = 0; i < g[u].size(); ++i) if(!visit[g[u][i]]) dfs(g, g[u][i], visit);} // Returns true if all vertices are strongly connected// i.e. can be made as loopbool isConnected(vector<int> g[], vector<bool> &mark, int s){ // Initialize all vertices as not visited vector<bool> visit(M, false); // perform a dfs from s dfs(g, s, visit); // now loop through all characters for (int i = 0; i < M; i++) { /* I character is marked (i.e. it was first or last character of some string) then it should be visited in last dfs (as for looping, graph should be strongly connected) */ if (mark[i] && !visit[i]) return false; } // If we reach that means graph is connected return true;} // return true if an order among strings is possiblebool possibleOrderAmongString(string arr[], int N){ // Create an empty graph vector<int> g[M]; // Initialize all vertices as not marked vector<bool> mark(M, false); // Initialize indegree and outdegree of every // vertex as 0. vector<int> in(M, 0), out(M, 0); // Process all strings one by one for (int i = 0; i < N; i++) { // Find first and last characters int f = arr[i].front() - 'a'; int l = arr[i].back() - 'a'; // Mark the characters mark[f] = mark[l] = true; // increase indegree and outdegree count in[l]++; out[f]++; // Add an edge in graph g[f].push_back(l); } // If for any character indegree is not equal to // outdegree then ordering is not possible for (int i = 0; i < M; i++) if (in[i] != out[i]) return false; return isConnected(g, mark, arr[0].front() - 'a');} // Driver code to test above methodsint main(){ // string arr[] = {\"abc\", \"efg\", \"cde\", \"ghi\", \"ija\"}; string arr[] = {\"ab\", \"bc\", \"cd\", \"de\", \"ed\", \"da\"}; int N = sizeof(arr) / sizeof(arr[0]); if (possibleOrderAmongString(arr, N) == false) cout << \"Ordering not possible\\n\"; else cout << \"Ordering is possible\\n\"; return 0;}",
"e": 31873,
"s": 29451,
"text": null
},
{
"code": "// Java code to check if cyclic order is// possible among strings under given constraintsimport java.io.*;import java.util.*; class GFG{ // Return true if an order among strings is possible public static boolean possibleOrderAmongString( String s[], int n){ int m = 26; boolean mark[] = new boolean[m]; int in[] = new int[26]; int out[] = new int[26]; ArrayList< ArrayList<Integer>> adj = new ArrayList< ArrayList<Integer>>(); for(int i = 0; i < m; i++) adj.add(new ArrayList<>()); // Process all strings one by one for(int i = 0; i < n; i++) { // Find first and last characters int f = (int)(s[i].charAt(0) - 'a'); int l = (int)(s[i].charAt( s[i].length() - 1) - 'a'); // Mark the characters mark[f] = mark[l] = true; // Increase indegree and outdegree count in[l]++; out[f]++; // Add an edge in graph adj.get(f).add(l); } // If for any character indegree is not equal to // outdegree then ordering is not possible for(int i = 0; i < m; i++) { if (in[i] != out[i]) return false; } return isConnected(adj, mark, s[0].charAt(0) - 'a');} // Returns true if all vertices are strongly// connected i.e. can be made as looppublic static boolean isConnected( ArrayList<ArrayList<Integer>> adj, boolean mark[], int src){ boolean visited[] = new boolean[26]; // Perform a dfs from src dfs(adj, visited, src); for(int i = 0; i < 26; i++) { /* I character is marked (i.e. it was first or last character of some string) then it should be visited in last dfs (as for looping, graph should be strongly connected) */ if (mark[i] && !visited[i]) return false; } // If we reach that means graph is connected return true;} // Utility method for a depth first// search among verticespublic static void dfs(ArrayList<ArrayList<Integer>> adj, boolean visited[], int src){ visited[src] = true; for(int i = 0; i < adj.get(src).size(); i++) if (!visited[adj.get(src).get(i)]) dfs(adj, visited, adj.get(src).get(i));} // Driver codepublic static void main(String[] args){ String s[] = { \"ab\", \"bc\", \"cd\", \"de\", \"ed\", \"da\" }; int n = s.length; if (possibleOrderAmongString(s, n)) System.out.println(\"Ordering is possible\"); else System.out.println(\"Ordering is not possible\");}} // This code is contributed by parascoding",
"e": 34522,
"s": 31873,
"text": null
},
{
"code": "# Python3 code to check if# cyclic order is possible# among strings under given# constraintsM = 26 # Utility method for a depth# first search among verticesdef dfs(g, u, visit): visit[u] = True for i in range(len(g[u])): if(not visit[g[u][i]]): dfs(g, g[u][i], visit) # Returns true if all vertices# are strongly connected i.e.# can be made as loopdef isConnected(g, mark, s): # Initialize all vertices # as not visited visit = [False for i in range(M)] # Perform a dfs from s dfs(g, s, visit) # Now loop through # all characters for i in range(M): # I character is marked # (i.e. it was first or last # character of some string) # then it should be visited # in last dfs (as for looping, # graph should be strongly # connected) */ if(mark[i] and (not visit[i])): return False # If we reach that means # graph is connected return True # return true if an order among# strings is possibledef possibleOrderAmongString(arr, N): # Create an empty graph g = {} # Initialize all vertices # as not marked mark = [False for i in range(M)] # Initialize indegree and # outdegree of every # vertex as 0. In = [0 for i in range(M)] out = [0 for i in range(M)] # Process all strings # one by one for i in range(N): # Find first and last # characters f = (ord(arr[i][0]) - ord('a')) l = (ord(arr[i][-1]) - ord('a')) # Mark the characters mark[f] = True mark[l] = True # Increase indegree # and outdegree count In[l] += 1 out[f] += 1 if f not in g: g[f] = [] # Add an edge in graph g[f].append(l) # If for any character # indegree is not equal to # outdegree then ordering # is not possible for i in range(M): if(In[i] != out[i]): return False return isConnected(g, mark, ord(arr[0][0]) - ord('a')) # Driver codearr = [\"ab\", \"bc\", \"cd\", \"de\", \"ed\", \"da\"]N = len(arr)if(possibleOrderAmongString(arr, N) == False): print(\"Ordering not possible\")else: print(\"Ordering is possible\") # This code is contributed by avanitrachhadiya2155",
"e": 36870,
"s": 34522,
"text": null
},
{
"code": "// C# code to check if cyclic order is// possible among strings under given constraintsusing System;using System.Collections.Generic;class GFG { // Return true if an order among strings is possible static bool possibleOrderAmongString(string[] s, int n) { int m = 26; bool[] mark = new bool[m]; int[] In = new int[26]; int[] Out = new int[26]; List<List<int>> adj = new List<List<int>>(); for(int i = 0; i < m; i++) adj.Add(new List<int>()); // Process all strings one by one for(int i = 0; i < n; i++) { // Find first and last characters int f = (int)(s[i][0] - 'a'); int l = (int)(s[i][s[i].Length - 1] - 'a'); // Mark the characters mark[f] = mark[l] = true; // Increase indegree and outdegree count In[l]++; Out[f]++; // Add an edge in graph adj[f].Add(l); } // If for any character indegree is not equal to // outdegree then ordering is not possible for(int i = 0; i < m; i++) { if (In[i] != Out[i]) return false; } return isConnected(adj, mark, s[0][0] - 'a'); } // Returns true if all vertices are strongly // connected i.e. can be made as loop public static bool isConnected( List<List<int>> adj, bool[] mark, int src) { bool[] visited = new bool[26]; // Perform a dfs from src dfs(adj, visited, src); for(int i = 0; i < 26; i++) { /* I character is marked (i.e. it was first or last character of some string) then it should be visited in last dfs (as for looping, graph should be strongly connected) */ if (mark[i] && !visited[i]) return false; } // If we reach that means graph is connected return true; } // Utility method for a depth first // search among vertices public static void dfs(List<List<int>> adj, bool[] visited, int src) { visited[src] = true; for(int i = 0; i < adj[src].Count; i++) if (!visited[adj[src][i]]) dfs(adj, visited, adj[src][i]); } static void Main() { string[] s = { \"ab\", \"bc\", \"cd\", \"de\", \"ed\", \"da\" }; int n = s.Length; if (possibleOrderAmongString(s, n)) Console.Write(\"Ordering is possible\"); else Console.Write(\"Ordering is not possible\"); }} // This code is contributed by divyesh072019.",
"e": 39615,
"s": 36870,
"text": null
},
{
"code": "<script> // Javascript code to check if cyclic order is // possible among strings under given constraints // Return true if an order among strings is possible function possibleOrderAmongString(s, n) { let m = 26; let mark = new Array(m); mark.fill(false); let In = new Array(26); In.fill(0); let Out = new Array(26); Out.fill(0); let adj = []; for(let i = 0; i < m; i++) adj.push([]); // Process all strings one by one for(let i = 0; i < n; i++) { // Find first and last characters let f = (s[i][0].charCodeAt() - 'a'.charCodeAt()); let l = (s[i][s[i].length - 1].charCodeAt() - 'a'.charCodeAt()); // Mark the characters mark[f] = mark[l] = true; // Increase indegree and outdegree count In[l]++; Out[f]++; // Add an edge in graph adj[f].push(l); } // If for any character indegree is not equal to // outdegree then ordering is not possible for(let i = 0; i < m; i++) { if (In[i] != Out[i]) return false; } return isConnected(adj, mark, s[0][0].charCodeAt() - 'a'.charCodeAt()); } // Returns true if all vertices are strongly // connected i.e. can be made as loop function isConnected(adj, mark, src) { let visited = new Array(26); visited.fill(false); // Perform a dfs from src dfs(adj, visited, src); for(let i = 0; i < 26; i++) { /* I character is marked (i.e. it was first or last character of some string) then it should be visited in last dfs (as for looping, graph should be strongly connected) */ if (mark[i] && !visited[i]) return false; } // If we reach that means graph is connected return true; } // Utility method for a depth first // search among vertices function dfs(adj, visited, src) { visited[src] = true; for(let i = 0; i < adj[src].length; i++) if (!visited[adj[src][i]]) dfs(adj, visited, adj[src][i]); } let s = [ \"ab\", \"bc\", \"cd\", \"de\", \"ed\", \"da\" ]; let n = s.length; if (possibleOrderAmongString(s, n)) document.write(\"Ordering is possible\"); else document.write(\"Ordering is not possible\"); // This code is contributed by decode2207.</script>",
"e": 42286,
"s": 39615,
"text": null
},
{
"code": null,
"e": 42295,
"s": 42286,
"text": "Output: "
},
{
"code": null,
"e": 42316,
"s": 42295,
"text": "Ordering is possible"
},
{
"code": null,
"e": 42740,
"s": 42316,
"text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. "
},
{
"code": null,
"e": 42754,
"s": 42740,
"text": "Piyush_Karira"
},
{
"code": null,
"e": 42775,
"s": 42754,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 42787,
"s": 42775,
"text": "parascoding"
},
{
"code": null,
"e": 42801,
"s": 42787,
"text": "divyesh072019"
},
{
"code": null,
"e": 42812,
"s": 42801,
"text": "decode2207"
},
{
"code": null,
"e": 42825,
"s": 42812,
"text": "simmytarika5"
},
{
"code": null,
"e": 42829,
"s": 42825,
"text": "DFS"
},
{
"code": null,
"e": 42835,
"s": 42829,
"text": "Graph"
},
{
"code": null,
"e": 42843,
"s": 42835,
"text": "Strings"
},
{
"code": null,
"e": 42851,
"s": 42843,
"text": "Strings"
},
{
"code": null,
"e": 42855,
"s": 42851,
"text": "DFS"
},
{
"code": null,
"e": 42861,
"s": 42855,
"text": "Graph"
},
{
"code": null,
"e": 42959,
"s": 42861,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43009,
"s": 42959,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 43057,
"s": 43009,
"text": "Traveling Salesman Problem (TSP) Implementation"
},
{
"code": null,
"e": 43092,
"s": 43057,
"text": "Hamiltonian Cycle | Backtracking-6"
},
{
"code": null,
"e": 43128,
"s": 43092,
"text": "m Coloring Problem | Backtracking-5"
},
{
"code": null,
"e": 43176,
"s": 43128,
"text": "Check whether a given graph is Bipartite or not"
},
{
"code": null,
"e": 43222,
"s": 43176,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 43247,
"s": 43222,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 43307,
"s": 43247,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 43322,
"s": 43307,
"text": "C++ Data Types"
}
]
|
Find distinct characters in distinct substrings of a string - GeeksforGeeks | 07 Sep, 2021
Given a string str, the task is to find the count of distinct characters in all the distinct sub-strings of the given string.Examples:
Input: str = “ABCA” Output: 18
Hence, 1 + 2 + 3 + 3 + 1 + 2 + 3 + 1 + 2 = 18Input: str = “AAAB” Output: 10
Approach: Take all possible sub-strings of the given string and use a set to check whether the current sub-string has been processed before. Now, for every distinct sub-string, count the distinct characters in it (again set can be used to do so). The sum of this count for all the distinct sub-strings is the final answer.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of distinct// characters in all the distinct// sub-strings of the given stringint countTotalDistinct(string str){ int cnt = 0; // To store all the sub-strings set<string> items; for (int i = 0; i < str.length(); ++i) { // To store the current sub-string string temp = ""; // To store the characters of the // current sub-string set<char> ans; for (int j = i; j < str.length(); ++j) { temp = temp + str[j]; ans.insert(str[j]); // If current sub-string hasn't // been stored before if (items.find(temp) == items.end()) { // Insert it into the set items.insert(temp); // Update the count of // distinct characters cnt += ans.size(); } } } return cnt;} // Driver codeint main(){ string str = "ABCA"; cout << countTotalDistinct(str); return 0;}
// Java implementation of the approachimport java.util.HashSet; class geeks{ // Function to return the count of distinct // characters in all the distinct // sub-strings of the given string public static int countTotalDistinct(String str) { int cnt = 0; // To store all the sub-strings HashSet<String> items = new HashSet<>(); for (int i = 0; i < str.length(); ++i) { // To store the current sub-string String temp = ""; // To store the characters of the // current sub-string HashSet<Character> ans = new HashSet<>(); for (int j = i; j < str.length(); ++j) { temp = temp + str.charAt(j); ans.add(str.charAt(j)); // If current sub-string hasn't // been stored before if (!items.contains(temp)) { // Insert it into the set items.add(temp); // Update the count of // distinct characters cnt += ans.size(); } } } return cnt; } // Driver code public static void main(String[] args) { String str = "ABCA"; System.out.println(countTotalDistinct(str)); }} // This code is contributed by// sanjeev2552
# Python3 implementation of the approach # Function to return the count of distinct# characters in all the distinct# sub-strings of the given stringdef countTotalDistinct(string) : cnt = 0; # To store all the sub-strings items = set(); for i in range(len(string)) : # To store the current sub-string temp = ""; # To store the characters of the # current sub-string ans = set(); for j in range(i, len(string)) : temp = temp + string[j]; ans.add(string[j]); # If current sub-string hasn't # been stored before if temp not in items : # Insert it into the set items.add(temp); # Update the count of # distinct characters cnt += len(ans); return cnt; # Driver codeif __name__ == "__main__" : string = "ABCA"; print(countTotalDistinct(string)); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System;using System.Collections.Generic; class geeks{ // Function to return the count of distinct // characters in all the distinct // sub-strings of the given string public static int countTotalDistinct(String str) { int cnt = 0; // To store all the sub-strings HashSet<String> items = new HashSet<String>(); for (int i = 0; i < str.Length; ++i) { // To store the current sub-string String temp = ""; // To store the characters of the // current sub-string HashSet<char> ans = new HashSet<char>(); for (int j = i; j < str.Length; ++j) { temp = temp + str[j]; ans.Add(str[j]); // If current sub-string hasn't // been stored before if (!items.Contains(temp)) { // Insert it into the set items.Add(temp); // Update the count of // distinct characters cnt += ans.Count; } } } return cnt; } // Driver code public static void Main(String[] args) { String str = "ABCA"; Console.WriteLine(countTotalDistinct(str)); }} // This code is contributed by 29AjayKumar
<script> // js implementation of the approach // Function to return the count of distinct// characters in all the distinct// sub-strings of the given stringfunction countTotalDistinct(str){ let cnt = 0; // To store all the sub-strings let items = new Set(); for (let i = 0; i < str.length; ++i) { // To store the current sub-string let temp = ""; // To store the characters of the // current sub-string let ans = new Set(); for (let j = i; j < str.length; ++j) { temp = temp + str[j]; ans.add(str[j]); // If current sub-string hasn't // been stored before if (!items.has(temp)) { // Insert it into the set items.add(temp); // Update the count of // distinct characters cnt += ans.size; } } } return cnt;} // Driver codelet str = "ABCA";document.write(countTotalDistinct(str)); </script>
18
Time complexity: O(n^2)
As the nested loop is used the complexity is order if n^2
Space complexity: O(n)
two sets of size n are used so the complexity would be O(2n) nothing but O(n).
ankthon
sanjeev2552
29AjayKumar
rohan07
pulamolusaimohan
cpp-map-functions
cpp-strings
substring
Strings
cpp-strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Array of Strings in C++ (5 Different Ways to Create)
Different methods to reverse a string in C/C++
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Top 50 String Coding Problems for Interviews
Check whether two strings are anagram of each other
Length of the longest substring without repeating characters | [
{
"code": null,
"e": 26833,
"s": 26805,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 26970,
"s": 26833,
"text": "Given a string str, the task is to find the count of distinct characters in all the distinct sub-strings of the given string.Examples: "
},
{
"code": null,
"e": 27003,
"s": 26970,
"text": "Input: str = “ABCA” Output: 18 "
},
{
"code": null,
"e": 27081,
"s": 27003,
"text": "Hence, 1 + 2 + 3 + 3 + 1 + 2 + 3 + 1 + 2 = 18Input: str = “AAAB” Output: 10 "
},
{
"code": null,
"e": 27458,
"s": 27083,
"text": "Approach: Take all possible sub-strings of the given string and use a set to check whether the current sub-string has been processed before. Now, for every distinct sub-string, count the distinct characters in it (again set can be used to do so). The sum of this count for all the distinct sub-strings is the final answer.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27462,
"s": 27458,
"text": "C++"
},
{
"code": null,
"e": 27467,
"s": 27462,
"text": "Java"
},
{
"code": null,
"e": 27475,
"s": 27467,
"text": "Python3"
},
{
"code": null,
"e": 27478,
"s": 27475,
"text": "C#"
},
{
"code": null,
"e": 27489,
"s": 27478,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of distinct// characters in all the distinct// sub-strings of the given stringint countTotalDistinct(string str){ int cnt = 0; // To store all the sub-strings set<string> items; for (int i = 0; i < str.length(); ++i) { // To store the current sub-string string temp = \"\"; // To store the characters of the // current sub-string set<char> ans; for (int j = i; j < str.length(); ++j) { temp = temp + str[j]; ans.insert(str[j]); // If current sub-string hasn't // been stored before if (items.find(temp) == items.end()) { // Insert it into the set items.insert(temp); // Update the count of // distinct characters cnt += ans.size(); } } } return cnt;} // Driver codeint main(){ string str = \"ABCA\"; cout << countTotalDistinct(str); return 0;}",
"e": 28570,
"s": 27489,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.HashSet; class geeks{ // Function to return the count of distinct // characters in all the distinct // sub-strings of the given string public static int countTotalDistinct(String str) { int cnt = 0; // To store all the sub-strings HashSet<String> items = new HashSet<>(); for (int i = 0; i < str.length(); ++i) { // To store the current sub-string String temp = \"\"; // To store the characters of the // current sub-string HashSet<Character> ans = new HashSet<>(); for (int j = i; j < str.length(); ++j) { temp = temp + str.charAt(j); ans.add(str.charAt(j)); // If current sub-string hasn't // been stored before if (!items.contains(temp)) { // Insert it into the set items.add(temp); // Update the count of // distinct characters cnt += ans.size(); } } } return cnt; } // Driver code public static void main(String[] args) { String str = \"ABCA\"; System.out.println(countTotalDistinct(str)); }} // This code is contributed by// sanjeev2552",
"e": 29955,
"s": 28570,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the count of distinct# characters in all the distinct# sub-strings of the given stringdef countTotalDistinct(string) : cnt = 0; # To store all the sub-strings items = set(); for i in range(len(string)) : # To store the current sub-string temp = \"\"; # To store the characters of the # current sub-string ans = set(); for j in range(i, len(string)) : temp = temp + string[j]; ans.add(string[j]); # If current sub-string hasn't # been stored before if temp not in items : # Insert it into the set items.add(temp); # Update the count of # distinct characters cnt += len(ans); return cnt; # Driver codeif __name__ == \"__main__\" : string = \"ABCA\"; print(countTotalDistinct(string)); # This code is contributed by AnkitRai01",
"e": 30944,
"s": 29955,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class geeks{ // Function to return the count of distinct // characters in all the distinct // sub-strings of the given string public static int countTotalDistinct(String str) { int cnt = 0; // To store all the sub-strings HashSet<String> items = new HashSet<String>(); for (int i = 0; i < str.Length; ++i) { // To store the current sub-string String temp = \"\"; // To store the characters of the // current sub-string HashSet<char> ans = new HashSet<char>(); for (int j = i; j < str.Length; ++j) { temp = temp + str[j]; ans.Add(str[j]); // If current sub-string hasn't // been stored before if (!items.Contains(temp)) { // Insert it into the set items.Add(temp); // Update the count of // distinct characters cnt += ans.Count; } } } return cnt; } // Driver code public static void Main(String[] args) { String str = \"ABCA\"; Console.WriteLine(countTotalDistinct(str)); }} // This code is contributed by 29AjayKumar",
"e": 32331,
"s": 30944,
"text": null
},
{
"code": "<script> // js implementation of the approach // Function to return the count of distinct// characters in all the distinct// sub-strings of the given stringfunction countTotalDistinct(str){ let cnt = 0; // To store all the sub-strings let items = new Set(); for (let i = 0; i < str.length; ++i) { // To store the current sub-string let temp = \"\"; // To store the characters of the // current sub-string let ans = new Set(); for (let j = i; j < str.length; ++j) { temp = temp + str[j]; ans.add(str[j]); // If current sub-string hasn't // been stored before if (!items.has(temp)) { // Insert it into the set items.add(temp); // Update the count of // distinct characters cnt += ans.size; } } } return cnt;} // Driver codelet str = \"ABCA\";document.write(countTotalDistinct(str)); </script>",
"e": 33334,
"s": 32331,
"text": null
},
{
"code": null,
"e": 33337,
"s": 33334,
"text": "18"
},
{
"code": null,
"e": 33364,
"s": 33339,
"text": "Time complexity: O(n^2) "
},
{
"code": null,
"e": 33422,
"s": 33364,
"text": "As the nested loop is used the complexity is order if n^2"
},
{
"code": null,
"e": 33445,
"s": 33422,
"text": "Space complexity: O(n)"
},
{
"code": null,
"e": 33524,
"s": 33445,
"text": "two sets of size n are used so the complexity would be O(2n) nothing but O(n)."
},
{
"code": null,
"e": 33532,
"s": 33524,
"text": "ankthon"
},
{
"code": null,
"e": 33544,
"s": 33532,
"text": "sanjeev2552"
},
{
"code": null,
"e": 33556,
"s": 33544,
"text": "29AjayKumar"
},
{
"code": null,
"e": 33564,
"s": 33556,
"text": "rohan07"
},
{
"code": null,
"e": 33581,
"s": 33564,
"text": "pulamolusaimohan"
},
{
"code": null,
"e": 33599,
"s": 33581,
"text": "cpp-map-functions"
},
{
"code": null,
"e": 33611,
"s": 33599,
"text": "cpp-strings"
},
{
"code": null,
"e": 33621,
"s": 33611,
"text": "substring"
},
{
"code": null,
"e": 33629,
"s": 33621,
"text": "Strings"
},
{
"code": null,
"e": 33641,
"s": 33629,
"text": "cpp-strings"
},
{
"code": null,
"e": 33649,
"s": 33641,
"text": "Strings"
},
{
"code": null,
"e": 33747,
"s": 33649,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33822,
"s": 33747,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 33858,
"s": 33822,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 33911,
"s": 33858,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 33958,
"s": 33911,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 33994,
"s": 33958,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 34032,
"s": 33994,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 34062,
"s": 34032,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 34107,
"s": 34062,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 34159,
"s": 34107,
"text": "Check whether two strings are anagram of each other"
}
]
|
How to List values for each Pandas group? - GeeksforGeeks | 20 Aug, 2020
In this article, we’ll see how we can display all the values of each group in which a dataframe is divided. The dataframe is first divided into groups using the DataFrame.groupby() method. Then we modify it such that each group contains the values in a list.
First, Let’s create a Dataframe:
Python3
# import pandas libraryimport pandas as pd # create a dataframedf = pd.DataFrame({'a': ['A', 'A', 'B', 'B', 'B', 'C', 'C', 'D'], 'b': [1, 2, 5, 3, 5, 4, 8, 6]})# show the dataframe df
Output:
Method 1: Using DataFrame.groupby() and Series.apply() together.Example: We’ll create lists of all values of each group and store it in new column called “listvalues”.
Python3
# import pandas libraryimport pandas as pd # create a dataframedf = pd.DataFrame({'a': ['A', 'A', 'B', 'B', 'B', 'C', 'C', 'D'], 'b': [1, 2, 5, 3, 5, 4, 8, 6]}) # convert values of each group# into a listgroups = df.groupby('a')['b'].apply(list) print(groups) # groups store in a new # column called listvaluesdf1 = groups.reset_index(name = 'listvalues')# show the dataframedf1
Output:
Method 2: Using DataFrame.groupby() and Series.agg().
Example: We use the lambda function inside the Series.agg() to convert the all values of a group to a list.
Python3
# import pandas libraryimport pandas as pd # create a dataframedf = pd.DataFrame( {'a': ['A', 'A', 'B', 'B', 'B', 'C', 'C', 'D'], 'b': [1, 2, 5, 3, 5, 4, 8, 6]} )# convert values of each group# into a listgroups = df.groupby('a').agg(lambda x: list(x)) print(groups)
Output:
Python pandas-groupby
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list | [
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 25906,
"s": 25647,
"text": "In this article, we’ll see how we can display all the values of each group in which a dataframe is divided. The dataframe is first divided into groups using the DataFrame.groupby() method. Then we modify it such that each group contains the values in a list."
},
{
"code": null,
"e": 25939,
"s": 25906,
"text": "First, Let’s create a Dataframe:"
},
{
"code": null,
"e": 25947,
"s": 25939,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # create a dataframedf = pd.DataFrame({'a': ['A', 'A', 'B', 'B', 'B', 'C', 'C', 'D'], 'b': [1, 2, 5, 3, 5, 4, 8, 6]})# show the dataframe df",
"e": 26269,
"s": 25947,
"text": null
},
{
"code": null,
"e": 26277,
"s": 26269,
"text": "Output:"
},
{
"code": null,
"e": 26445,
"s": 26277,
"text": "Method 1: Using DataFrame.groupby() and Series.apply() together.Example: We’ll create lists of all values of each group and store it in new column called “listvalues”."
},
{
"code": null,
"e": 26453,
"s": 26445,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # create a dataframedf = pd.DataFrame({'a': ['A', 'A', 'B', 'B', 'B', 'C', 'C', 'D'], 'b': [1, 2, 5, 3, 5, 4, 8, 6]}) # convert values of each group# into a listgroups = df.groupby('a')['b'].apply(list) print(groups) # groups store in a new # column called listvaluesdf1 = groups.reset_index(name = 'listvalues')# show the dataframedf1",
"e": 26998,
"s": 26453,
"text": null
},
{
"code": null,
"e": 27006,
"s": 26998,
"text": "Output:"
},
{
"code": null,
"e": 27060,
"s": 27006,
"text": "Method 2: Using DataFrame.groupby() and Series.agg()."
},
{
"code": null,
"e": 27168,
"s": 27060,
"text": "Example: We use the lambda function inside the Series.agg() to convert the all values of a group to a list."
},
{
"code": null,
"e": 27176,
"s": 27168,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # create a dataframedf = pd.DataFrame( {'a': ['A', 'A', 'B', 'B', 'B', 'C', 'C', 'D'], 'b': [1, 2, 5, 3, 5, 4, 8, 6]} )# convert values of each group# into a listgroups = df.groupby('a').agg(lambda x: list(x)) print(groups)",
"e": 27607,
"s": 27176,
"text": null
},
{
"code": null,
"e": 27615,
"s": 27607,
"text": "Output:"
},
{
"code": null,
"e": 27637,
"s": 27615,
"text": "Python pandas-groupby"
},
{
"code": null,
"e": 27651,
"s": 27637,
"text": "Python-pandas"
},
{
"code": null,
"e": 27658,
"s": 27651,
"text": "Python"
},
{
"code": null,
"e": 27756,
"s": 27658,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27788,
"s": 27756,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27830,
"s": 27788,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27872,
"s": 27830,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27928,
"s": 27872,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27955,
"s": 27928,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27986,
"s": 27955,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28015,
"s": 27986,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28037,
"s": 28015,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28073,
"s": 28037,
"text": "Python | Pandas dataframe.groupby()"
}
]
|
Python | Accordion in kivy - GeeksforGeeks | 04 Mar, 2022
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
Kivy Tutorial – Learn Kivy with Examples.
Accordion:
The Accordion widget is a form of menu where the options are stacked either vertically or horizontally and the item in focus (when touched) opens up to display its content.
It can contain many item instances, each of which should contain one root content widget. You will end up like a tree.The current implementation divides the AccordionItem into two parts:
One container for the title bar(made from kv template)One container for the content
One container for the title bar(made from kv template)
One container for the content
You can increase the default size of the title bar:
root = Accordion(min_space=60)
Or change the orientation to vertical:
root = Accordion(orientation=’vertical’)
The AccordionItem is more configurable and you can set your own title background when the item is collapsed or opened:
item = AccordionItem(background_normal=’image_when_collapsed.png’, background_selected=’image_when_selected.png’)
Basic Approach:
1) import kivy
2) import kivyApp
3) import Accordion, AccordionItem
4) import Label
5) Create App class
6) return Layout/widget/Class(according to requirement)
7) Run an instance of the class
Implementation of the Approach:
Python3
# How to use Accordion in kivy using .kv file # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Accordion widget is a form of menu# where the options are stacked either vertically# or horizontally and the item in focus# (when touched) opens up to display its content.from kivy.uix.accordion import Accordion, AccordionItem # Label is the text which we want# to add on our window, give to# the buttons and so onfrom kivy.uix.label import Label # Create the App classclass AccordionApp(App): def build(self): root = Accordion() root = Accordion(min_space = 60) # Providing the orientation root = Accordion(orientation ='vertical') # Adding text to each Accordion for x in range(5): item = AccordionItem(title ='Title % d' % x) item.add_widget(Label(text ='GFG is Good Website for CSE Students\n' * 5)) root.add_widget(item) # Return the root return root # Run the Appif __name__ == '__main__': AccordionApp().run()
Output:
saurabh1990aror
surindertarika1234
sumitgumber28
germanshephered48
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python | [
{
"code": null,
"e": 26070,
"s": 26042,
"text": "\n04 Mar, 2022"
},
{
"code": null,
"e": 26306,
"s": 26070,
"text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications."
},
{
"code": null,
"e": 26348,
"s": 26306,
"text": "Kivy Tutorial – Learn Kivy with Examples."
},
{
"code": null,
"e": 26359,
"s": 26348,
"text": "Accordion:"
},
{
"code": null,
"e": 26533,
"s": 26359,
"text": "The Accordion widget is a form of menu where the options are stacked either vertically or horizontally and the item in focus (when touched) opens up to display its content. "
},
{
"code": null,
"e": 26721,
"s": 26533,
"text": "It can contain many item instances, each of which should contain one root content widget. You will end up like a tree.The current implementation divides the AccordionItem into two parts: "
},
{
"code": null,
"e": 26805,
"s": 26721,
"text": "One container for the title bar(made from kv template)One container for the content"
},
{
"code": null,
"e": 26860,
"s": 26805,
"text": "One container for the title bar(made from kv template)"
},
{
"code": null,
"e": 26890,
"s": 26860,
"text": "One container for the content"
},
{
"code": null,
"e": 26944,
"s": 26890,
"text": "You can increase the default size of the title bar: "
},
{
"code": null,
"e": 26975,
"s": 26944,
"text": "root = Accordion(min_space=60)"
},
{
"code": null,
"e": 27015,
"s": 26975,
"text": "Or change the orientation to vertical: "
},
{
"code": null,
"e": 27056,
"s": 27015,
"text": "root = Accordion(orientation=’vertical’)"
},
{
"code": null,
"e": 27177,
"s": 27056,
"text": "The AccordionItem is more configurable and you can set your own title background when the item is collapsed or opened: "
},
{
"code": null,
"e": 27291,
"s": 27177,
"text": "item = AccordionItem(background_normal=’image_when_collapsed.png’, background_selected=’image_when_selected.png’)"
},
{
"code": null,
"e": 27499,
"s": 27291,
"text": "Basic Approach:\n1) import kivy\n2) import kivyApp\n3) import Accordion, AccordionItem\n4) import Label\n5) Create App class\n6) return Layout/widget/Class(according to requirement)\n7) Run an instance of the class"
},
{
"code": null,
"e": 27531,
"s": 27499,
"text": "Implementation of the Approach:"
},
{
"code": null,
"e": 27539,
"s": 27531,
"text": "Python3"
},
{
"code": "# How to use Accordion in kivy using .kv file # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Accordion widget is a form of menu# where the options are stacked either vertically# or horizontally and the item in focus# (when touched) opens up to display its content.from kivy.uix.accordion import Accordion, AccordionItem # Label is the text which we want# to add on our window, give to# the buttons and so onfrom kivy.uix.label import Label # Create the App classclass AccordionApp(App): def build(self): root = Accordion() root = Accordion(min_space = 60) # Providing the orientation root = Accordion(orientation ='vertical') # Adding text to each Accordion for x in range(5): item = AccordionItem(title ='Title % d' % x) item.add_widget(Label(text ='GFG is Good Website for CSE Students\\n' * 5)) root.add_widget(item) # Return the root return root # Run the Appif __name__ == '__main__': AccordionApp().run()",
"e": 28859,
"s": 27539,
"text": null
},
{
"code": null,
"e": 28868,
"s": 28859,
"text": "Output: "
},
{
"code": null,
"e": 28894,
"s": 28878,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 28913,
"s": 28894,
"text": "surindertarika1234"
},
{
"code": null,
"e": 28927,
"s": 28913,
"text": "sumitgumber28"
},
{
"code": null,
"e": 28945,
"s": 28927,
"text": "germanshephered48"
},
{
"code": null,
"e": 28956,
"s": 28945,
"text": "Python-gui"
},
{
"code": null,
"e": 28968,
"s": 28956,
"text": "Python-kivy"
},
{
"code": null,
"e": 28975,
"s": 28968,
"text": "Python"
},
{
"code": null,
"e": 29073,
"s": 28975,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29091,
"s": 29073,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29123,
"s": 29091,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29145,
"s": 29123,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29187,
"s": 29145,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29213,
"s": 29187,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29257,
"s": 29213,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29286,
"s": 29257,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29323,
"s": 29286,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29359,
"s": 29323,
"text": "Convert integer to string in Python"
}
]
|
C# - Passing Arrays as Function Arguments | You can pass an array as a function argument in C#. The following example demonstrates this −
using System;
namespace ArrayApplication {
class MyArray {
double getAverage(int[] arr, int size) {
int i;
double avg;
int sum = 0;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = (double)sum / size;
return avg;
}
static void Main(string[] args) {
MyArray app = new MyArray();
/* an int array with 5 elements */
int [] balance = new int[]{1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = app.getAverage(balance, 5 ) ;
/* output the returned value */
Console.WriteLine( "Average value is: {0} ", avg );
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Average value is: 214.4
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2364,
"s": 2270,
"text": "You can pass an array as a function argument in C#. The following example demonstrates this −"
},
{
"code": null,
"e": 3141,
"s": 2364,
"text": "using System;\n\nnamespace ArrayApplication {\n class MyArray {\n double getAverage(int[] arr, int size) {\n int i;\n double avg;\n int sum = 0;\n \n for (i = 0; i < size; ++i) {\n sum += arr[i];\n }\n avg = (double)sum / size;\n return avg;\n }\n static void Main(string[] args) {\n MyArray app = new MyArray();\n \n /* an int array with 5 elements */\n int [] balance = new int[]{1000, 2, 3, 17, 50};\n double avg;\n\n /* pass pointer to the array as an argument */\n avg = app.getAverage(balance, 5 ) ;\n\n /* output the returned value */\n Console.WriteLine( \"Average value is: {0} \", avg );\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 3222,
"s": 3141,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3247,
"s": 3222,
"text": "Average value is: 214.4\n"
},
{
"code": null,
"e": 3284,
"s": 3247,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 3297,
"s": 3284,
"text": " Raja Biswas"
},
{
"code": null,
"e": 3331,
"s": 3297,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3349,
"s": 3331,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 3382,
"s": 3349,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3396,
"s": 3382,
"text": " Peter Jepson"
},
{
"code": null,
"e": 3433,
"s": 3396,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 3448,
"s": 3433,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 3483,
"s": 3448,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 3498,
"s": 3483,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3533,
"s": 3498,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3545,
"s": 3533,
"text": " Eric Frick"
},
{
"code": null,
"e": 3552,
"s": 3545,
"text": " Print"
},
{
"code": null,
"e": 3563,
"s": 3552,
"text": " Add Notes"
}
]
|
How to get the number of occurrences of each letter in specified string in JavaScript ? - GeeksforGeeks | 28 Sep, 2021
Given a string, our task is finding the occurrence of a character in the string with the help of user-defined function.
Example:
Input : "hello"
Output : h occur 1 times
e occur 1 times
l occur 2 times
o occur 1 times
Explanation : here "hello" have 1 h, so it have 1 value.
as same e have 1, l have 2 , o have 1.
Example 2:
Input : "did"
Output: d occur 2 times
i occur 1 times
Approach 1: In this approach we use a map data structure to store the number of times characters occur.
First we initialize map with key each character of string and value for each is 0.
We iterate over string and increment value of the character.
Finally, print key-values of the map.
Example:
Javascript
<script>
//function to print occurrence of character
function printans( ans )
{
for( let [ key ,value] of ans)
{
// if()
console.log(`${key} occurs ${value} times` );
}
}
// function count occurrence of character
function count( str , outp_map )
{
for( let i = 0 ;i < str.length ;i++)
{
let k = outp_map.get(str[i]);
outp_map.set(str[i], k+1) ;
}
//calling print function
printans(outp_map);
}
//function create map to count character
function count_occurs( test , callback )
{
//checking string is valid or not
if( test.length === 0 )
{
console.log(" empty string ");
return ;
}
else
{
// map for storing count values
let ans = new Map();
for( let i = 0 ;i < test.length;i++)
{
ans.set(test[i], 0);
}
callback( test ,ans);
}
}
// test string
let test = "helloworld";
count_occurs( test ,count);
</script>
Output:
h occurs 1 times
e occurs 1 times
l occurs 3 times
o occurs 2 times
w occurs 1 times
r occurs 1 times
d occurs 1 times
Approach 2: In this approach, we use nested for loop to iterate over string and count for each character in the string.
First initialize count with value 0 for ith value of string.
Now we iterate over string if ith value matches with the character, increase the count value by 1.
Finally, print the value of count.
Example:
Javascript
<script>
// function that count character occurrences in string
function count_occur( str )
{
// checking string is valid or not
if( str.length == 0 )
{
console.log("Invalid string")
return;
}
//cor loop to iterate over string
for( let i = 0 ;i < str.length ;i++)
{
//variable counting occurrence
let count = 0;
for( let j = 0 ;j < str.length ;j++)
{
if( str[i] == str[j] && i > j )
{
break;
}
if( str[i] == str[j] )
{
count++;
}
}
if( count > 0)
console.log(`${str[i]} occurs ${count} times`);
}
}
// test string
let test_str = "gfghello";
count_occur( test_str);
</script>
Output:
g occurs 2 times
f occurs 1 times
h occurs 1 times
e occurs 1 times
l occurs 2 times
o occurs 1 times
simmytarika5
sagartomar9927
anikakapoor
surindertarika1234
JavaScript-Questions
javascript-string
Picked
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
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
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": 38042,
"s": 38011,
"text": " \n28 Sep, 2021\n"
},
{
"code": null,
"e": 38162,
"s": 38042,
"text": "Given a string, our task is finding the occurrence of a character in the string with the help of user-defined function."
},
{
"code": null,
"e": 38472,
"s": 38162,
"text": "Example:\nInput : \"hello\"\nOutput : h occur 1 times\n e occur 1 times\n l occur 2 times\n o occur 1 times\nExplanation : here \"hello\" have 1 h, so it have 1 value.\n as same e have 1, l have 2 , o have 1.\nExample 2:\nInput : \"did\"\nOutput: d occur 2 times \n i occur 1 times"
},
{
"code": null,
"e": 38576,
"s": 38472,
"text": "Approach 1: In this approach we use a map data structure to store the number of times characters occur."
},
{
"code": null,
"e": 38659,
"s": 38576,
"text": "First we initialize map with key each character of string and value for each is 0."
},
{
"code": null,
"e": 38720,
"s": 38659,
"text": "We iterate over string and increment value of the character."
},
{
"code": null,
"e": 38758,
"s": 38720,
"text": "Finally, print key-values of the map."
},
{
"code": null,
"e": 38768,
"s": 38758,
"text": "Example: "
},
{
"code": null,
"e": 38779,
"s": 38768,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n<script>\n \n//function to print occurrence of character\nfunction printans( ans )\n{\n for( let [ key ,value] of ans)\n {\n // if()\n console.log(`${key} occurs ${value} times` );\n \n }\n \n}\n \n// function count occurrence of character\nfunction count( str , outp_map )\n{\n for( let i = 0 ;i < str.length ;i++)\n { \n \n let k = outp_map.get(str[i]);\n outp_map.set(str[i], k+1) ;\n \n \n }\n //calling print function\n printans(outp_map);\n}\n \n//function create map to count character\nfunction count_occurs( test , callback )\n{\n //checking string is valid or not \n if( test.length === 0 )\n {\n console.log(\" empty string \");\n return ;\n }\n else\n { \n // map for storing count values\n let ans = new Map();\n for( let i = 0 ;i < test.length;i++)\n {\n ans.set(test[i], 0);\n }\n \n callback( test ,ans);\n \n }\n \n}\n \n// test string \nlet test = \"helloworld\";\ncount_occurs( test ,count);\n \n</script>\n\n\n\n\n\n",
"e": 39752,
"s": 38789,
"text": null
},
{
"code": null,
"e": 39761,
"s": 39752,
"text": " Output:"
},
{
"code": null,
"e": 39894,
"s": 39761,
"text": "h occurs 1 times\ne occurs 1 times\nl occurs 3 times\no occurs 2 times\nw occurs 1 times\nr occurs 1 times\nd occurs 1 times"
},
{
"code": null,
"e": 40015,
"s": 39894,
"text": "Approach 2: In this approach, we use nested for loop to iterate over string and count for each character in the string. "
},
{
"code": null,
"e": 40076,
"s": 40015,
"text": "First initialize count with value 0 for ith value of string."
},
{
"code": null,
"e": 40175,
"s": 40076,
"text": "Now we iterate over string if ith value matches with the character, increase the count value by 1."
},
{
"code": null,
"e": 40210,
"s": 40175,
"text": "Finally, print the value of count."
},
{
"code": null,
"e": 40220,
"s": 40210,
"text": "Example: "
},
{
"code": null,
"e": 40231,
"s": 40220,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n<script>\n \n// function that count character occurrences in string \nfunction count_occur( str )\n{\n // checking string is valid or not \n if( str.length == 0 )\n {\n console.log(\"Invalid string\")\n return;\n }\n //cor loop to iterate over string\n for( let i = 0 ;i < str.length ;i++)\n { \n //variable counting occurrence \n let count = 0;\n for( let j = 0 ;j < str.length ;j++)\n {\n if( str[i] == str[j] && i > j )\n {\n break;\n }\n if( str[i] == str[j] )\n {\n count++;\n }\n }\n if( count > 0)\n console.log(`${str[i]} occurs ${count} times`);\n \n }\n \n}\n \n// test string\nlet test_str = \"gfghello\";\ncount_occur( test_str);\n</script>\n\n\n\n\n\n",
"e": 40950,
"s": 40241,
"text": null
},
{
"code": null,
"e": 40959,
"s": 40950,
"text": " Output:"
},
{
"code": null,
"e": 41061,
"s": 40959,
"text": "g occurs 2 times\nf occurs 1 times\nh occurs 1 times\ne occurs 1 times\nl occurs 2 times\no occurs 1 times"
},
{
"code": null,
"e": 41074,
"s": 41061,
"text": "simmytarika5"
},
{
"code": null,
"e": 41089,
"s": 41074,
"text": "sagartomar9927"
},
{
"code": null,
"e": 41101,
"s": 41089,
"text": "anikakapoor"
},
{
"code": null,
"e": 41120,
"s": 41101,
"text": "surindertarika1234"
},
{
"code": null,
"e": 41143,
"s": 41120,
"text": "\nJavaScript-Questions\n"
},
{
"code": null,
"e": 41163,
"s": 41143,
"text": "\njavascript-string\n"
},
{
"code": null,
"e": 41172,
"s": 41163,
"text": "\nPicked\n"
},
{
"code": null,
"e": 41185,
"s": 41172,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 41204,
"s": 41185,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 41409,
"s": 41204,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 41454,
"s": 41409,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 41523,
"s": 41454,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 41584,
"s": 41523,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 41656,
"s": 41584,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 41683,
"s": 41656,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 41725,
"s": 41683,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 41758,
"s": 41725,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 41820,
"s": 41758,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 41863,
"s": 41820,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Count number of rows within each group in R DataFrame - GeeksforGeeks | 30 May, 2021
DataFrame in R Programming Language may contain columns where not all values are unique. The duplicate values in the dataframe can be sectioned together into one group. The frequencies corresponding to the same columns’ sequence can be captured using various external packages in R programming language.
The “dplyr” package in R is used to perform data enhancements and manipulations. We can use certain functions from this method that can help to realize our functionality.
Using tally() and group_by() method
group_by() method in R can be used to categorize data into groups based on either a single column or a group of multiple columns. All the plausible unique combinations of the input columns are stacked together as a single group.
Syntax:
group_by(args .. )
Where, the args contain a sequence of column to group data upon
The tally() method in R is used to summarize the data and count the number of values that each group belongs to. Upon successive application of these methods, the dataframe mutations are carried out to return a table where the particular input columns are returned in order of their appearance in the group_by() method, followed by a column ‘n’ containing frequency counts for these groups.
This method is considered to be better than other approaches because it returns detailed information about the column classes of the specified dataframe.
Example:
R
library("dplyr") # creating a dataframedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3]) print ("Original DataFrame")print (data_frame) # group by column1 values and count# the total in eachdata_frame %>% group_by(col1) %>%tally()
Output
[1] "Original DataFrame"
col1 col2
1 1 a
2 1 b
3 1 c
4 2 a
5 2 b
6 2 c
7 3 a
8 3 b
9 3 c >
# A tibble: 3 x 2
col1 n
<int> <int>
1 1 3
2 2 3
3 3 3
Using dplyr::count() method
The count() method can be applied to the input dataframe containing one or more columns and returns a frequency count corresponding to each of the groups. The columns returned on the application of this method is a proper subset of the columns of the original dataframe. The columns appearing in the result are the columns appearing in the count() method.
Syntax:
count(args .. ),
Where, the args contain a sequence of column to group data upon
Example:
R
library("dplyr") # creating a dataframedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3], col3 = c(1,4,1,2,2,3,1,2,2)) print ("Original DataFrame")print (data_frame) print ("Modified DataFrame") # count rows by col1 and col3 groupdata_frame %>% dplyr::count(col1, col3)
Output:
[1] "Original DataFrame"
col1 col2 col3
1 1 a 1
2 1 b 4
3 1 c 1
4 2 a 2
5 2 b 2
6 2 c 3
7 3 a 1
8 3 b 2
9 3 c 2
[1] "Modified DataFrame"
col1 col3 n
1 1 1 2
2 1 4 1
3 2 2 2
4 2 3 1
5 3 1 1
6 3 2 2
The data.table package in R can be used to retrieve and store data in an organized tabular structure. The .N attribute of the data_table indexing can be used to categorically keep a count of the frequency of the encountered specified columns’ combinations. The columns are specified in the “by” attribute using the list() method in R, which is an alternative to the group_by() method.
Syntax:
data_table[, .N, by = list(cols..)]
Example:
R
library(data.table) # creating a dataframedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3], col3 = c(1,4,1,2,2,3,1,2,2)) print ("Original DataFrame")print (data_frame) print ("Modified DataFrame")data_table <- data.table(data_frame)data_table[, .N, by = list(col1, col3)]
Output
[1] "Original DataFrame"
col1 col2 col3
1 1 a 1
2 1 b 4
3 1 c 1
4 2 a 2
5 2 b 2
6 2 c 3
7 3 a 1
8 3 b 2
9 3 c 2
[1] "Modified DataFrame"
col1 col3 N
1: 1 1 2
2: 1 4 1
3: 2 2 2
4: 2 3 1
5: 3 1 1
6: 3 2 2
aggregate() method in R programming language is a generic function used to summarize and evaluate both time series as well dataframes.
Syntax:
aggregate(formula, data, FUN)
Parameter :
formula : such as y ~ x where the y variables are numeric data to be split into groups according to the grouping x variables.
by – grouping elements
FUN – function to be applied
The function to be applied here is the length, which counts the frequency associated with each group. It computes the plausible combinations of all the columns mentioned in the formula, and displays each one with a frequency associated. Thus, it is used to perform an aggregation over all the columns.
Example:
R
data_frame <- data.frame(col1 = sample(1:2,9,replace = TRUE), col2 = letters[1:3], col3 = c(1,4,1,2,2,3,1,2,2)) print ("Original DataFrame")print (data_frame) print ("keeping a count of all groups") data_mod <- aggregate(col3 ~ col1 + col2, data = data_frame, FUN = length)print (data_mod)
Output
[1] "Original DataFrame"
col1 col2 col3
1 2 a 1
2 2 b 4
3 1 c 1
4 1 a 2
5 1 b 2
6 2 c 3
7 2 a 1
8 2 b 2
9 1 c 2
[1] "keeping a count of all groups"
col1 col2 col3
1 1 a 1
2 2 a 2
3 1 b 1
4 2 b 2
5 1 c 2
6 2 c 1
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
Remove rows with NA in one column of R DataFrame
How to filter R DataFrame by values in a column? | [
{
"code": null,
"e": 25965,
"s": 25937,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 26269,
"s": 25965,
"text": "DataFrame in R Programming Language may contain columns where not all values are unique. The duplicate values in the dataframe can be sectioned together into one group. The frequencies corresponding to the same columns’ sequence can be captured using various external packages in R programming language."
},
{
"code": null,
"e": 26440,
"s": 26269,
"text": "The “dplyr” package in R is used to perform data enhancements and manipulations. We can use certain functions from this method that can help to realize our functionality."
},
{
"code": null,
"e": 26476,
"s": 26440,
"text": "Using tally() and group_by() method"
},
{
"code": null,
"e": 26706,
"s": 26476,
"text": "group_by() method in R can be used to categorize data into groups based on either a single column or a group of multiple columns. All the plausible unique combinations of the input columns are stacked together as a single group. "
},
{
"code": null,
"e": 26714,
"s": 26706,
"text": "Syntax:"
},
{
"code": null,
"e": 26733,
"s": 26714,
"text": "group_by(args .. )"
},
{
"code": null,
"e": 26797,
"s": 26733,
"text": "Where, the args contain a sequence of column to group data upon"
},
{
"code": null,
"e": 27189,
"s": 26797,
"text": "The tally() method in R is used to summarize the data and count the number of values that each group belongs to. Upon successive application of these methods, the dataframe mutations are carried out to return a table where the particular input columns are returned in order of their appearance in the group_by() method, followed by a column ‘n’ containing frequency counts for these groups. "
},
{
"code": null,
"e": 27344,
"s": 27189,
"text": "This method is considered to be better than other approaches because it returns detailed information about the column classes of the specified dataframe. "
},
{
"code": null,
"e": 27353,
"s": 27344,
"text": "Example:"
},
{
"code": null,
"e": 27355,
"s": 27353,
"text": "R"
},
{
"code": "library(\"dplyr\") # creating a dataframedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3]) print (\"Original DataFrame\")print (data_frame) # group by column1 values and count# the total in eachdata_frame %>% group_by(col1) %>%tally()",
"e": 27639,
"s": 27355,
"text": null
},
{
"code": null,
"e": 27646,
"s": 27639,
"text": "Output"
},
{
"code": null,
"e": 27898,
"s": 27646,
"text": "[1] \"Original DataFrame\" \n col1 col2 \n1 1 a \n2 1 b \n3 1 c \n4 2 a \n5 2 b \n6 2 c \n7 3 a \n8 3 b \n9 3 c > \n# A tibble: 3 x 2 \ncol1 n \n<int> <int> \n1 1 3 \n2 2 3 \n3 3 3"
},
{
"code": null,
"e": 27926,
"s": 27898,
"text": "Using dplyr::count() method"
},
{
"code": null,
"e": 28283,
"s": 27926,
"text": "The count() method can be applied to the input dataframe containing one or more columns and returns a frequency count corresponding to each of the groups. The columns returned on the application of this method is a proper subset of the columns of the original dataframe. The columns appearing in the result are the columns appearing in the count() method. "
},
{
"code": null,
"e": 28291,
"s": 28283,
"text": "Syntax:"
},
{
"code": null,
"e": 28309,
"s": 28291,
"text": "count(args .. ), "
},
{
"code": null,
"e": 28373,
"s": 28309,
"text": "Where, the args contain a sequence of column to group data upon"
},
{
"code": null,
"e": 28382,
"s": 28373,
"text": "Example:"
},
{
"code": null,
"e": 28384,
"s": 28382,
"text": "R"
},
{
"code": "library(\"dplyr\") # creating a dataframedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3], col3 = c(1,4,1,2,2,3,1,2,2)) print (\"Original DataFrame\")print (data_frame) print (\"Modified DataFrame\") # count rows by col1 and col3 groupdata_frame %>% dplyr::count(col1, col3)",
"e": 28731,
"s": 28384,
"text": null
},
{
"code": null,
"e": 28739,
"s": 28731,
"text": "Output:"
},
{
"code": null,
"e": 29084,
"s": 28739,
"text": "[1] \"Original DataFrame\" \n col1 col2 col3 \n1 1 a 1 \n2 1 b 4 \n3 1 c 1 \n4 2 a 2 \n5 2 b 2 \n6 2 c 3 \n7 3 a 1 \n8 3 b 2 \n9 3 c 2 \n[1] \"Modified DataFrame\" \n col1 col3 n \n1 1 1 2 \n2 1 4 1 \n3 2 2 2 \n4 2 3 1 \n5 3 1 1 \n6 3 2 2"
},
{
"code": null,
"e": 29470,
"s": 29084,
"text": "The data.table package in R can be used to retrieve and store data in an organized tabular structure. The .N attribute of the data_table indexing can be used to categorically keep a count of the frequency of the encountered specified columns’ combinations. The columns are specified in the “by” attribute using the list() method in R, which is an alternative to the group_by() method. "
},
{
"code": null,
"e": 29478,
"s": 29470,
"text": "Syntax:"
},
{
"code": null,
"e": 29514,
"s": 29478,
"text": "data_table[, .N, by = list(cols..)]"
},
{
"code": null,
"e": 29523,
"s": 29514,
"text": "Example:"
},
{
"code": null,
"e": 29525,
"s": 29523,
"text": "R"
},
{
"code": "library(data.table) # creating a dataframedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3], col3 = c(1,4,1,2,2,3,1,2,2)) print (\"Original DataFrame\")print (data_frame) print (\"Modified DataFrame\")data_table <- data.table(data_frame)data_table[, .N, by = list(col1, col3)]",
"e": 29874,
"s": 29525,
"text": null
},
{
"code": null,
"e": 29881,
"s": 29874,
"text": "Output"
},
{
"code": null,
"e": 30224,
"s": 29881,
"text": "[1] \"Original DataFrame\" \n col1 col2 col3 \n1 1 a 1 \n2 1 b 4 \n3 1 c 1 \n4 2 a 2 \n5 2 b 2 \n6 2 c 3 \n7 3 a 1 \n8 3 b 2 \n9 3 c 2\n[1] \"Modified DataFrame\" \n col1 col3 N \n1: 1 1 2 \n2: 1 4 1 \n3: 2 2 2 \n4: 2 3 1 \n5: 3 1 1 \n6: 3 2 2"
},
{
"code": null,
"e": 30360,
"s": 30224,
"text": "aggregate() method in R programming language is a generic function used to summarize and evaluate both time series as well dataframes. "
},
{
"code": null,
"e": 30368,
"s": 30360,
"text": "Syntax:"
},
{
"code": null,
"e": 30398,
"s": 30368,
"text": "aggregate(formula, data, FUN)"
},
{
"code": null,
"e": 30411,
"s": 30398,
"text": "Parameter : "
},
{
"code": null,
"e": 30539,
"s": 30411,
"text": "formula : such as y ~ x where the y variables are numeric data to be split into groups according to the grouping x variables."
},
{
"code": null,
"e": 30563,
"s": 30539,
"text": "by – grouping elements "
},
{
"code": null,
"e": 30592,
"s": 30563,
"text": "FUN – function to be applied"
},
{
"code": null,
"e": 30894,
"s": 30592,
"text": "The function to be applied here is the length, which counts the frequency associated with each group. It computes the plausible combinations of all the columns mentioned in the formula, and displays each one with a frequency associated. Thus, it is used to perform an aggregation over all the columns."
},
{
"code": null,
"e": 30903,
"s": 30894,
"text": "Example:"
},
{
"code": null,
"e": 30905,
"s": 30903,
"text": "R"
},
{
"code": "data_frame <- data.frame(col1 = sample(1:2,9,replace = TRUE), col2 = letters[1:3], col3 = c(1,4,1,2,2,3,1,2,2)) print (\"Original DataFrame\")print (data_frame) print (\"keeping a count of all groups\") data_mod <- aggregate(col3 ~ col1 + col2, data = data_frame, FUN = length)print (data_mod)",
"e": 31264,
"s": 30905,
"text": null
},
{
"code": null,
"e": 31271,
"s": 31264,
"text": "Output"
},
{
"code": null,
"e": 31635,
"s": 31271,
"text": "[1] \"Original DataFrame\" \ncol1 col2 col3 \n1 2 a 1 \n2 2 b 4 \n3 1 c 1 \n4 1 a 2 \n5 1 b 2 \n6 2 c 3 \n7 2 a 1 \n8 2 b 2 \n9 1 c 2 \n[1] \"keeping a count of all groups\" \ncol1 col2 col3 \n1 1 a 1 \n2 2 a 2 \n3 1 b 1 \n4 2 b 2 \n5 1 c 2 \n6 2 c 1"
},
{
"code": null,
"e": 31642,
"s": 31635,
"text": "Picked"
},
{
"code": null,
"e": 31663,
"s": 31642,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 31675,
"s": 31663,
"text": "R-DataFrame"
},
{
"code": null,
"e": 31686,
"s": 31675,
"text": "R Language"
},
{
"code": null,
"e": 31697,
"s": 31686,
"text": "R Programs"
},
{
"code": null,
"e": 31795,
"s": 31697,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31847,
"s": 31795,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 31879,
"s": 31847,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 31923,
"s": 31879,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 31975,
"s": 31923,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 32010,
"s": 31975,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 32054,
"s": 32010,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 32112,
"s": 32054,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 32155,
"s": 32112,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 32204,
"s": 32155,
"text": "Remove rows with NA in one column of R DataFrame"
}
]
|
Distance of nearest cell having 1 in a binary matrix - GeeksforGeeks | 23 Mar, 2022
Given a binary matrix of N x M, containing at least a value 1. The task is to find the distance of nearest 1 in the matrix for each cell. The distance is calculated as |i1 – i2| + |j1 – j2|, where i1, j1 are the row number and column number of the current cell and i2, j2 are the row number and column number of the nearest cell having value 1.
Examples:
Input : N = 3, M = 4
mat[][] = { 0, 0, 0, 1,
0, 0, 1, 1,
0, 1, 1, 0 }
Output : 3 2 1 0
2 1 0 0
1 0 0 1
Explanation:
For cell at (0, 0), nearest 1 is at (0, 3),
so distance = (0 - 0) + (3 - 0) = 3.
Similarly, all the distance can be calculated.
Input : N = 3, M = 3
mat[][] = { 1, 0, 0,
0, 0, 1,
0, 1, 1 }
Output :
0 1 1
1 1 0
1 0 0
Explanation:
For cell at (0, 1), nearest 1 is at (0, 0), so distance
is 1. Similarly, all the distance can be calculated.
Method 1: This method uses a simple brute force approach to arrive at the solution.
Approach: The idea is to traverse the matrix for each cell and find the minimum distance, To find the minimum distance traverse the matrix and find the cell which contains 1 and calculates the distance between two cells and store the minimum distance.
Algorithm : Traverse the matrix from start to end (using two nested loops)For every element find the closest element which contains 1. To find the closest element traverse the matrix and find the minimum distance.Fill the minimum distance in the matrix.
Traverse the matrix from start to end (using two nested loops)For every element find the closest element which contains 1. To find the closest element traverse the matrix and find the minimum distance.Fill the minimum distance in the matrix.
Traverse the matrix from start to end (using two nested loops)
For every element find the closest element which contains 1. To find the closest element traverse the matrix and find the minimum distance.
Fill the minimum distance in the matrix.
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find distance of nearest// cell having 1 in a binary matrix.#include<bits/stdc++.h>#define N 3#define M 4using namespace std; // Print the distance of nearest cell// having 1 for each cell.void printDistance(int mat[N][M]){ int ans[N][M]; // Initialize the answer matrix with INT_MAX. for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) ans[i][j] = INT_MAX; // For each cell for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { // Traversing the whole matrix // to find the minimum distance. for (int k = 0; k < N; k++) for (int l = 0; l < M; l++) { // If cell contain 1, check // for minimum distance. if (mat[k][l] == 1) ans[i][j] = min(ans[i][j], abs(i-k) + abs(j-l)); } } // Printing the answer. for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) cout << ans[i][j] << " "; cout << endl; }} // Driven Programint main(){ int mat[N][M] = { 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0 }; printDistance(mat); return 0;}
// Java program to find distance of nearest// cell having 1 in a binary matrix. import java.io.*; class GFG { static int N = 3; static int M = 4; // Print the distance of nearest cell // having 1 for each cell. static void printDistance(int mat[][]) { int ans[][] = new int[N][M]; // Initialize the answer matrix with INT_MAX. for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) ans[i][j] = Integer.MAX_VALUE; // For each cell for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { // Traversing the whole matrix // to find the minimum distance. for (int k = 0; k < N; k++) for (int l = 0; l < M; l++) { // If cell contain 1, check // for minimum distance. if (mat[k][l] == 1) ans[i][j] = Math.min(ans[i][j], Math.abs(i-k) + Math.abs(j-l)); } } // Printing the answer. for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) System.out.print( ans[i][j] + " "); System.out.println(); } } // Driven Program public static void main (String[] args) { int mat[][] = { {0, 0, 0, 1}, {0, 0, 1, 1}, {0, 1, 1, 0} }; printDistance(mat); }} // This code is contributed by anuj_67.
# Python3 program to find distance of# nearest cell having 1 in a binary matrix. # Print distance of nearest cell# having 1 for each cell.def printDistance(mat): global N, M ans = [[None] * M for i in range(N)] # Initialize the answer matrix # with INT_MAX. for i in range(N): for j in range(M): ans[i][j] = 999999999999 # For each cell for i in range(N): for j in range(M): # Traversing the whole matrix # to find the minimum distance. for k in range(N): for l in range(M): # If cell contain 1, check # for minimum distance. if (mat[k][l] == 1): ans[i][j] = min(ans[i][j], abs(i - k) + abs(j - l)) # Printing the answer. for i in range(N): for j in range(M): print(ans[i][j], end = " ") print() # Driver CodeN = 3M = 4mat = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 0]] printDistance(mat) # This code is contributed by PranchalK
// C# program to find the distance of nearest// cell having 1 in a binary matrix. using System; class GFG { static int N = 3; static int M = 4; // Print the distance of nearest cell // having 1 for each cell. static void printDistance(int [,]mat) { int [,]ans = new int[N,M]; // Initialise the answer matrix with int.MaxValue. for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) ans[i,j] = int.MaxValue; // For each cell for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { // Traversing thewhole matrix // to find the minimum distance. for (int k = 0; k < N; k++) for (int l = 0; l < M; l++) { // If cell contain 1, check // for minimum distance. if (mat[k,l] == 1) ans[i,j] = Math.Min(ans[i,j], Math.Abs(i-k) + Math.Abs(j-l)); } } // Printing the answer. for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) Console.Write( ans[i,j] + " "); Console.WriteLine(); } } // Driven Program public static void Main () { int [,]mat = { {0, 0, 0, 1}, {0, 0, 1, 1}, {0, 1, 1, 0} }; printDistance(mat); }} // This code is contributed by anuj_67.
<?php// PHP program to find distance of nearest// cell having 1 in a binary matrix.$N = 3;$M = 4; // Print the distance of nearest cell// having 1 for each cell.function printDistance( $mat){ global $N,$M; $ans = array(array()); // Initialize the answer // matrix with INT_MAX. for($i = 0; $i < $N; $i++) for ( $j = 0; $j < $M; $j++) $ans[$i][$j] = PHP_INT_MAX; // For each cell for ( $i = 0; $i < $N; $i++) for ( $j = 0; $j < $M; $j++) { // Traversing the whole matrix // to find the minimum distance. for ($k = 0; $k < $N; $k++) for ( $l = 0; $l < $M; $l++) { // If cell contain 1, check // for minimum distance. if ($mat[$k][$l] == 1) $ans[$i][$j] = min($ans[$i][$j], abs($i-$k) + abs($j - $l)); } } // Printing the answer. for ( $i = 0; $i < $N; $i++) { for ( $j = 0; $j < $M; $j++) echo $ans[$i][$j] , " "; echo "\n"; }} // Driver Code $mat = array(array(0, 0, 0, 1), array(0, 0, 1, 1), array(0, 1, 1, 0)); printDistance($mat); // This code is contributed by anuj_67.?>
<script>// Javascript program to find distance of nearest// cell having 1 in a binary matrix. let N = 3; let M = 4; // Print the distance of nearest cell // having 1 for each cell.function printDistance(mat){ let ans= new Array(N); for(let i=0;i<N;i++) { ans[i]=new Array(M); for(let j = 0; j < M; j++) { ans[i][j] = Number.MAX_VALUE; } } // For each cell for (let i = 0; i < N; i++) for (let j = 0; j < M; j++) { // Traversing the whole matrix // to find the minimum distance. for (let k = 0; k < N; k++) for (let l = 0; l < M; l++) { // If cell contain 1, check // for minimum distance. if (mat[k][l] == 1) ans[i][j] = Math.min(ans[i][j], Math.abs(i-k) + Math.abs(j-l)); } } // Printing the answer. for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) document.write( ans[i][j] + " "); document.write("<br>"); } } // Driven Programlet mat = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 0]]printDistance(mat); // This code is contributed by patel2127</script>
3 2 1 0
2 1 0 0
1 0 0 1
Complexity Analysis:
Time Complexity: O(N2*M2). For every element in the matrix, the matrix is traversed and there are N*M elements So the time complexity is O(N2*M2).
Space Complexity: O(1). No extra space is required.
Method 1(a): Improved Brute-Force approach.
Approach: The idea is to load the 1’s i and j coordinates in the Matrix into a Queue and then traverse all the “0” Matrix elements and compare the distance between all the 1’s from Queue to get minimum distance.
Algorithm :Traverse once the Matrix and Load all 1’s i and j coordinates into the queue.Once loaded, Traverse all the Matrix elements. If the element is “0”, then check the minimum distance by de-queuing Queue elements one by one.Once distance for a “0” elements from “1” element is obtained, push back the 1’s coordinates back into queue again for the next “0” element.Determine Min distance from the individual distances for every “0” element.
Traverse once the Matrix and Load all 1’s i and j coordinates into the queue.
Once loaded, Traverse all the Matrix elements. If the element is “0”, then check the minimum distance by de-queuing Queue elements one by one.
Once distance for a “0” elements from “1” element is obtained, push back the 1’s coordinates back into queue again for the next “0” element.
Determine Min distance from the individual distances for every “0” element.
Implementation
Java
/*package whatever //do not write package name here */import java.io.*;import java.util.Arrays;import java.util.LinkedList;import java.util.Queue;class GFG { static class matrix_element { int row; int col; matrix_element(int row, int col) { this.row = row; this.col = col; } } static void printDistance(int arr[][]) { int Row_Count = arr.length; int Col_Count = arr[0].length; Queue<matrix_element> q = new LinkedList<matrix_element>(); // Adding all ones in queue for (int i = 0; i < Row_Count; i++) { for (int j = 0; j < Col_Count; j++) { if (arr[i][j] == 1) q.add(new matrix_element(i, j)); } } // In order to find min distance we will again // traverse all elements in Matrix. If its zero then // it will check against all 1's in Queue. Whatever // will be dequeued from queued, will be enqueued // back again. int Queue_Size = q.size(); for (int i = 0; i < Row_Count; i++) { for (int j = 0; j < Col_Count; j++) { int distance = 0; int min_distance = Integer.MAX_VALUE; if (arr[i][j] == 0) { for (int k = 0; k < Queue_Size; k++) { matrix_element One_Pos = q.poll(); int One_Row = One_Pos.row; int One_Col = One_Pos.col; distance = Math.abs(One_Row - i) + Math.abs(One_Col - j); min_distance = Math.min( min_distance, distance); if (min_distance == 1) { arr[i][j] = 1; q.add(new matrix_element( One_Row, One_Col)); break; } q.add(new matrix_element(One_Row, One_Col)); } arr[i][j] = min_distance; } else { arr[i][j] = 0; } } } // print the elements for (int i = 0; i < Row_Count; i++) { for (int j = 0; j < Col_Count; j++) System.out.print(arr[i][j] + " "); System.out.println(); } } public static void main(String[] args){ int arr[][] = { { 0, 0, 0, 1 }, { 0, 0, 1, 1 }, { 0, 1, 1, 0 } }; printDistance(arr); }}//// This code is contributed by prithi_raj
3 2 1 0
2 1 0 0
1 0 0 1
Method 2: This method uses the BFS or breadth-first search technique to arrive at the solution.
Approach: The idea is to use multisource Breadth-First Search. Consider each cell as a node and each boundary between any two adjacent cells be an edge. Number each cell from 1 to N*M. Now, push all the node whose corresponding cell value is 1 in the matrix in the queue. Apply BFS using this queue to find the minimum distance of the adjacent node.
Algorithm: Create a graph with values assigned from 1 to M*N to all vertices. The purpose is to store position and adjacent information.Create an empty queue.Traverse all matrix elements and insert positions of all 1s in queue.Now do a BFS traversal of graph using above created queue.Run a loop till the size of the queue is greater than 0 then extract the front node of the queue and remove it and insert all its adjacent and unmarked elements. Update the minimum distance as distance of current node +1 and insert the element in the queue.
Create a graph with values assigned from 1 to M*N to all vertices. The purpose is to store position and adjacent information.Create an empty queue.Traverse all matrix elements and insert positions of all 1s in queue.Now do a BFS traversal of graph using above created queue.Run a loop till the size of the queue is greater than 0 then extract the front node of the queue and remove it and insert all its adjacent and unmarked elements. Update the minimum distance as distance of current node +1 and insert the element in the queue.
Create a graph with values assigned from 1 to M*N to all vertices. The purpose is to store position and adjacent information.
Create an empty queue.
Traverse all matrix elements and insert positions of all 1s in queue.
Now do a BFS traversal of graph using above created queue.
Run a loop till the size of the queue is greater than 0 then extract the front node of the queue and remove it and insert all its adjacent and unmarked elements. Update the minimum distance as distance of current node +1 and insert the element in the queue.
Implementation:
C++
Python3
// C++ program to find distance of nearest// cell having 1 in a binary matrix.#include<bits/stdc++.h>#define MAX 500#define N 3#define M 4using namespace std; // Making a class of graph with bfs function.class graph{private: vector<int> g[MAX]; int n,m; public: graph(int a, int b) { n = a; m = b; } // Function to create graph with N*M nodes // considering each cell as a node and each // boundary as an edge. void createGraph() { int k = 1; // A number to be assigned to a cell for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { // If last row, then add edge on right side. if (i == n) { // If not bottom right cell. if (j != m) { g[k].push_back(k+1); g[k+1].push_back(k); } } // If last column, then add edge toward down. else if (j == m) { g[k].push_back(k+m); g[k+m].push_back(k); } // Else makes an edge in all four directions. else { g[k].push_back(k+1); g[k+1].push_back(k); g[k].push_back(k+m); g[k+m].push_back(k); } k++; } } } // BFS function to find minimum distance void bfs(bool visit[], int dist[], queue<int> q) { while (!q.empty()) { int temp = q.front(); q.pop(); for (int i = 0; i < g[temp].size(); i++) { if (visit[g[temp][i]] != 1) { dist[g[temp][i]] = min(dist[g[temp][i]], dist[temp]+1); q.push(g[temp][i]); visit[g[temp][i]] = 1; } } } } // Printing the solution. void print(int dist[]) { for (int i = 1, c = 1; i <= n*m; i++, c++) { cout << dist[i] << " "; if (c%m == 0) cout << endl; } }}; // Find minimum distancevoid findMinDistance(bool mat[N][M]){ // Creating a graph with nodes values assigned // from 1 to N x M and matrix adjacent. graph g1(N, M); g1.createGraph(); // To store minimum distance int dist[MAX]; // To mark each node as visited or not in BFS bool visit[MAX] = { 0 }; // Initialising the value of distance and visit. for (int i = 1; i <= M*N; i++) { dist[i] = INT_MAX; visit[i] = 0; } // Inserting nodes whose value in matrix // is 1 in the queue. int k = 1; queue<int> q; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (mat[i][j] == 1) { dist[k] = 0; visit[k] = 1; q.push(k); } k++; } } // Calling for Bfs with given Queue. g1.bfs(visit, dist, q); // Printing the solution. g1.print(dist);} // Driven Programint main(){ bool mat[N][M] = { 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0 }; findMinDistance(mat); return 0;}
# Python3 program to find distance of nearest# cell having 1 in a binary matrix.from collections import deque MAX = 500N = 3M = 4 # Making a class of graph with bfs function.g = [[] for i in range(MAX)]n, m = 0, 0 # Function to create graph with N*M nodes# considering each cell as a node and each# boundary as an edge.def createGraph(): global g, n, m # A number to be assigned to a cell k = 1 for i in range(1, n + 1): for j in range(1, m + 1): # If last row, then add edge on right side. if (i == n): # If not bottom right cell. if (j != m): g[k].append(k + 1) g[k + 1].append(k) # If last column, then add edge toward down. elif (j == m): g[k].append(k+m) g[k + m].append(k) # Else makes an edge in all four directions. else: g[k].append(k + 1) g[k + 1].append(k) g[k].append(k+m) g[k + m].append(k) k += 1 # BFS function to find minimum distancedef bfs(visit, dist, q): global g while (len(q) > 0): temp = q.popleft() for i in g[temp]: if (visit[i] != 1): dist[i] = min(dist[i], dist[temp] + 1) q.append(i) visit[i] = 1 return dist # Printing the solution.def prt(dist): c = 1 for i in range(1, n * m + 1): print(dist[i], end = " ") if (c % m == 0): print() c += 1 # Find minimum distancedef findMinDistance(mat): global g, n, m # Creating a graph with nodes values assigned # from 1 to N x M and matrix adjacent. n, m = N, M createGraph() # To store minimum distance dist = [0] * MAX # To mark each node as visited or not in BFS visit = [0] * MAX # Initialising the value of distance and visit. for i in range(1, M * N + 1): dist[i] = 10**9 visit[i] = 0 # Inserting nodes whose value in matrix # is 1 in the queue. k = 1 q = deque() for i in range(N): for j in range(M): if (mat[i][j] == 1): dist[k] = 0 visit[k] = 1 q.append(k) k += 1 # Calling for Bfs with given Queue. dist = bfs(visit, dist, q) # Printing the solution. prt(dist) # Driver codeif __name__ == '__main__': mat = [ [ 0, 0, 0, 1 ], [ 0, 0, 1, 1 ], [ 0, 1, 1, 0 ] ] findMinDistance(mat) # This code is contributed by mohit kumar 29
3 2 1 0
2 1 0 0
1 0 0 1
Complexity Analysis:
Time Complexity: O(N*M). In BFS traversal every element is traversed only once so time Complexity is O(M*N).
Space Complexity: O(M*N). To store every element in the matrix O(M*N) space is required.
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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.
vt_m
PranchalKatiyar
Akanksha_Rai
ManasChhabra2
andrew1234
mohit kumar 29
patel2127
khushboogoyal499
prithicogni89
Amazon
BFS
Graph
Matrix
Queue
Amazon
Matrix
Graph
Queue
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
Bellman–Ford Algorithm | DP-23
Detect Cycle in a Directed Graph
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Sudoku | Backtracking-7
Rat in a Maze | Backtracking-2
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) | [
{
"code": null,
"e": 25068,
"s": 25040,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 25413,
"s": 25068,
"text": "Given a binary matrix of N x M, containing at least a value 1. The task is to find the distance of nearest 1 in the matrix for each cell. The distance is calculated as |i1 – i2| + |j1 – j2|, where i1, j1 are the row number and column number of the current cell and i2, j2 are the row number and column number of the nearest cell having value 1."
},
{
"code": null,
"e": 25424,
"s": 25413,
"text": "Examples: "
},
{
"code": null,
"e": 26003,
"s": 25424,
"text": "Input : N = 3, M = 4\n mat[][] = { 0, 0, 0, 1,\n 0, 0, 1, 1,\n 0, 1, 1, 0 }\nOutput : 3 2 1 0\n 2 1 0 0\n 1 0 0 1\nExplanation:\nFor cell at (0, 0), nearest 1 is at (0, 3),\nso distance = (0 - 0) + (3 - 0) = 3.\nSimilarly, all the distance can be calculated.\n\nInput : N = 3, M = 3\n mat[][] = { 1, 0, 0, \n 0, 0, 1, \n 0, 1, 1 }\nOutput :\n 0 1 1 \n 1 1 0 \n 1 0 0 \nExplanation:\nFor cell at (0, 1), nearest 1 is at (0, 0), so distance\nis 1. Similarly, all the distance can be calculated."
},
{
"code": null,
"e": 26087,
"s": 26003,
"text": "Method 1: This method uses a simple brute force approach to arrive at the solution."
},
{
"code": null,
"e": 26339,
"s": 26087,
"text": "Approach: The idea is to traverse the matrix for each cell and find the minimum distance, To find the minimum distance traverse the matrix and find the cell which contains 1 and calculates the distance between two cells and store the minimum distance."
},
{
"code": null,
"e": 26593,
"s": 26339,
"text": "Algorithm : Traverse the matrix from start to end (using two nested loops)For every element find the closest element which contains 1. To find the closest element traverse the matrix and find the minimum distance.Fill the minimum distance in the matrix."
},
{
"code": null,
"e": 26835,
"s": 26593,
"text": "Traverse the matrix from start to end (using two nested loops)For every element find the closest element which contains 1. To find the closest element traverse the matrix and find the minimum distance.Fill the minimum distance in the matrix."
},
{
"code": null,
"e": 26898,
"s": 26835,
"text": "Traverse the matrix from start to end (using two nested loops)"
},
{
"code": null,
"e": 27038,
"s": 26898,
"text": "For every element find the closest element which contains 1. To find the closest element traverse the matrix and find the minimum distance."
},
{
"code": null,
"e": 27079,
"s": 27038,
"text": "Fill the minimum distance in the matrix."
},
{
"code": null,
"e": 27096,
"s": 27079,
"text": "Implementation: "
},
{
"code": null,
"e": 27100,
"s": 27096,
"text": "C++"
},
{
"code": null,
"e": 27105,
"s": 27100,
"text": "Java"
},
{
"code": null,
"e": 27113,
"s": 27105,
"text": "Python3"
},
{
"code": null,
"e": 27116,
"s": 27113,
"text": "C#"
},
{
"code": null,
"e": 27120,
"s": 27116,
"text": "PHP"
},
{
"code": null,
"e": 27131,
"s": 27120,
"text": "Javascript"
},
{
"code": "// C++ program to find distance of nearest// cell having 1 in a binary matrix.#include<bits/stdc++.h>#define N 3#define M 4using namespace std; // Print the distance of nearest cell// having 1 for each cell.void printDistance(int mat[N][M]){ int ans[N][M]; // Initialize the answer matrix with INT_MAX. for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) ans[i][j] = INT_MAX; // For each cell for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { // Traversing the whole matrix // to find the minimum distance. for (int k = 0; k < N; k++) for (int l = 0; l < M; l++) { // If cell contain 1, check // for minimum distance. if (mat[k][l] == 1) ans[i][j] = min(ans[i][j], abs(i-k) + abs(j-l)); } } // Printing the answer. for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) cout << ans[i][j] << \" \"; cout << endl; }} // Driven Programint main(){ int mat[N][M] = { 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0 }; printDistance(mat); return 0;}",
"e": 28394,
"s": 27131,
"text": null
},
{
"code": "// Java program to find distance of nearest// cell having 1 in a binary matrix. import java.io.*; class GFG { static int N = 3; static int M = 4; // Print the distance of nearest cell // having 1 for each cell. static void printDistance(int mat[][]) { int ans[][] = new int[N][M]; // Initialize the answer matrix with INT_MAX. for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) ans[i][j] = Integer.MAX_VALUE; // For each cell for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { // Traversing the whole matrix // to find the minimum distance. for (int k = 0; k < N; k++) for (int l = 0; l < M; l++) { // If cell contain 1, check // for minimum distance. if (mat[k][l] == 1) ans[i][j] = Math.min(ans[i][j], Math.abs(i-k) + Math.abs(j-l)); } } // Printing the answer. for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) System.out.print( ans[i][j] + \" \"); System.out.println(); } } // Driven Program public static void main (String[] args) { int mat[][] = { {0, 0, 0, 1}, {0, 0, 1, 1}, {0, 1, 1, 0} }; printDistance(mat); }} // This code is contributed by anuj_67.",
"e": 30060,
"s": 28394,
"text": null
},
{
"code": "# Python3 program to find distance of# nearest cell having 1 in a binary matrix. # Print distance of nearest cell# having 1 for each cell.def printDistance(mat): global N, M ans = [[None] * M for i in range(N)] # Initialize the answer matrix # with INT_MAX. for i in range(N): for j in range(M): ans[i][j] = 999999999999 # For each cell for i in range(N): for j in range(M): # Traversing the whole matrix # to find the minimum distance. for k in range(N): for l in range(M): # If cell contain 1, check # for minimum distance. if (mat[k][l] == 1): ans[i][j] = min(ans[i][j], abs(i - k) + abs(j - l)) # Printing the answer. for i in range(N): for j in range(M): print(ans[i][j], end = \" \") print() # Driver CodeN = 3M = 4mat = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 0]] printDistance(mat) # This code is contributed by PranchalK",
"e": 31176,
"s": 30060,
"text": null
},
{
"code": "// C# program to find the distance of nearest// cell having 1 in a binary matrix. using System; class GFG { static int N = 3; static int M = 4; // Print the distance of nearest cell // having 1 for each cell. static void printDistance(int [,]mat) { int [,]ans = new int[N,M]; // Initialise the answer matrix with int.MaxValue. for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) ans[i,j] = int.MaxValue; // For each cell for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { // Traversing thewhole matrix // to find the minimum distance. for (int k = 0; k < N; k++) for (int l = 0; l < M; l++) { // If cell contain 1, check // for minimum distance. if (mat[k,l] == 1) ans[i,j] = Math.Min(ans[i,j], Math.Abs(i-k) + Math.Abs(j-l)); } } // Printing the answer. for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) Console.Write( ans[i,j] + \" \"); Console.WriteLine(); } } // Driven Program public static void Main () { int [,]mat = { {0, 0, 0, 1}, {0, 0, 1, 1}, {0, 1, 1, 0} }; printDistance(mat); }} // This code is contributed by anuj_67.",
"e": 32805,
"s": 31176,
"text": null
},
{
"code": "<?php// PHP program to find distance of nearest// cell having 1 in a binary matrix.$N = 3;$M = 4; // Print the distance of nearest cell// having 1 for each cell.function printDistance( $mat){ global $N,$M; $ans = array(array()); // Initialize the answer // matrix with INT_MAX. for($i = 0; $i < $N; $i++) for ( $j = 0; $j < $M; $j++) $ans[$i][$j] = PHP_INT_MAX; // For each cell for ( $i = 0; $i < $N; $i++) for ( $j = 0; $j < $M; $j++) { // Traversing the whole matrix // to find the minimum distance. for ($k = 0; $k < $N; $k++) for ( $l = 0; $l < $M; $l++) { // If cell contain 1, check // for minimum distance. if ($mat[$k][$l] == 1) $ans[$i][$j] = min($ans[$i][$j], abs($i-$k) + abs($j - $l)); } } // Printing the answer. for ( $i = 0; $i < $N; $i++) { for ( $j = 0; $j < $M; $j++) echo $ans[$i][$j] , \" \"; echo \"\\n\"; }} // Driver Code $mat = array(array(0, 0, 0, 1), array(0, 0, 1, 1), array(0, 1, 1, 0)); printDistance($mat); // This code is contributed by anuj_67.?>",
"e": 34139,
"s": 32805,
"text": null
},
{
"code": "<script>// Javascript program to find distance of nearest// cell having 1 in a binary matrix. let N = 3; let M = 4; // Print the distance of nearest cell // having 1 for each cell.function printDistance(mat){ let ans= new Array(N); for(let i=0;i<N;i++) { ans[i]=new Array(M); for(let j = 0; j < M; j++) { ans[i][j] = Number.MAX_VALUE; } } // For each cell for (let i = 0; i < N; i++) for (let j = 0; j < M; j++) { // Traversing the whole matrix // to find the minimum distance. for (let k = 0; k < N; k++) for (let l = 0; l < M; l++) { // If cell contain 1, check // for minimum distance. if (mat[k][l] == 1) ans[i][j] = Math.min(ans[i][j], Math.abs(i-k) + Math.abs(j-l)); } } // Printing the answer. for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) document.write( ans[i][j] + \" \"); document.write(\"<br>\"); } } // Driven Programlet mat = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 0]]printDistance(mat); // This code is contributed by patel2127</script>",
"e": 35601,
"s": 34139,
"text": null
},
{
"code": null,
"e": 35629,
"s": 35601,
"text": "3 2 1 0 \n2 1 0 0 \n1 0 0 1 \n"
},
{
"code": null,
"e": 35651,
"s": 35629,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 35798,
"s": 35651,
"text": "Time Complexity: O(N2*M2). For every element in the matrix, the matrix is traversed and there are N*M elements So the time complexity is O(N2*M2)."
},
{
"code": null,
"e": 35850,
"s": 35798,
"text": "Space Complexity: O(1). No extra space is required."
},
{
"code": null,
"e": 35895,
"s": 35850,
"text": " Method 1(a): Improved Brute-Force approach."
},
{
"code": null,
"e": 36109,
"s": 35895,
"text": "Approach: The idea is to load the 1’s i and j coordinates in the Matrix into a Queue and then traverse all the “0” Matrix elements and compare the distance between all the 1’s from Queue to get minimum distance."
},
{
"code": null,
"e": 36555,
"s": 36109,
"text": "Algorithm :Traverse once the Matrix and Load all 1’s i and j coordinates into the queue.Once loaded, Traverse all the Matrix elements. If the element is “0”, then check the minimum distance by de-queuing Queue elements one by one.Once distance for a “0” elements from “1” element is obtained, push back the 1’s coordinates back into queue again for the next “0” element.Determine Min distance from the individual distances for every “0” element."
},
{
"code": null,
"e": 36633,
"s": 36555,
"text": "Traverse once the Matrix and Load all 1’s i and j coordinates into the queue."
},
{
"code": null,
"e": 36776,
"s": 36633,
"text": "Once loaded, Traverse all the Matrix elements. If the element is “0”, then check the minimum distance by de-queuing Queue elements one by one."
},
{
"code": null,
"e": 36917,
"s": 36776,
"text": "Once distance for a “0” elements from “1” element is obtained, push back the 1’s coordinates back into queue again for the next “0” element."
},
{
"code": null,
"e": 36993,
"s": 36917,
"text": "Determine Min distance from the individual distances for every “0” element."
},
{
"code": null,
"e": 37008,
"s": 36993,
"text": "Implementation"
},
{
"code": null,
"e": 37013,
"s": 37008,
"text": "Java"
},
{
"code": "/*package whatever //do not write package name here */import java.io.*;import java.util.Arrays;import java.util.LinkedList;import java.util.Queue;class GFG { static class matrix_element { int row; int col; matrix_element(int row, int col) { this.row = row; this.col = col; } } static void printDistance(int arr[][]) { int Row_Count = arr.length; int Col_Count = arr[0].length; Queue<matrix_element> q = new LinkedList<matrix_element>(); // Adding all ones in queue for (int i = 0; i < Row_Count; i++) { for (int j = 0; j < Col_Count; j++) { if (arr[i][j] == 1) q.add(new matrix_element(i, j)); } } // In order to find min distance we will again // traverse all elements in Matrix. If its zero then // it will check against all 1's in Queue. Whatever // will be dequeued from queued, will be enqueued // back again. int Queue_Size = q.size(); for (int i = 0; i < Row_Count; i++) { for (int j = 0; j < Col_Count; j++) { int distance = 0; int min_distance = Integer.MAX_VALUE; if (arr[i][j] == 0) { for (int k = 0; k < Queue_Size; k++) { matrix_element One_Pos = q.poll(); int One_Row = One_Pos.row; int One_Col = One_Pos.col; distance = Math.abs(One_Row - i) + Math.abs(One_Col - j); min_distance = Math.min( min_distance, distance); if (min_distance == 1) { arr[i][j] = 1; q.add(new matrix_element( One_Row, One_Col)); break; } q.add(new matrix_element(One_Row, One_Col)); } arr[i][j] = min_distance; } else { arr[i][j] = 0; } } } // print the elements for (int i = 0; i < Row_Count; i++) { for (int j = 0; j < Col_Count; j++) System.out.print(arr[i][j] + \" \"); System.out.println(); } } public static void main(String[] args){ int arr[][] = { { 0, 0, 0, 1 }, { 0, 0, 1, 1 }, { 0, 1, 1, 0 } }; printDistance(arr); }}//// This code is contributed by prithi_raj",
"e": 39758,
"s": 37013,
"text": null
},
{
"code": null,
"e": 39786,
"s": 39758,
"text": "3 2 1 0 \n2 1 0 0 \n1 0 0 1 \n"
},
{
"code": null,
"e": 39882,
"s": 39786,
"text": "Method 2: This method uses the BFS or breadth-first search technique to arrive at the solution."
},
{
"code": null,
"e": 40232,
"s": 39882,
"text": "Approach: The idea is to use multisource Breadth-First Search. Consider each cell as a node and each boundary between any two adjacent cells be an edge. Number each cell from 1 to N*M. Now, push all the node whose corresponding cell value is 1 in the matrix in the queue. Apply BFS using this queue to find the minimum distance of the adjacent node."
},
{
"code": null,
"e": 40775,
"s": 40232,
"text": "Algorithm: Create a graph with values assigned from 1 to M*N to all vertices. The purpose is to store position and adjacent information.Create an empty queue.Traverse all matrix elements and insert positions of all 1s in queue.Now do a BFS traversal of graph using above created queue.Run a loop till the size of the queue is greater than 0 then extract the front node of the queue and remove it and insert all its adjacent and unmarked elements. Update the minimum distance as distance of current node +1 and insert the element in the queue."
},
{
"code": null,
"e": 41307,
"s": 40775,
"text": "Create a graph with values assigned from 1 to M*N to all vertices. The purpose is to store position and adjacent information.Create an empty queue.Traverse all matrix elements and insert positions of all 1s in queue.Now do a BFS traversal of graph using above created queue.Run a loop till the size of the queue is greater than 0 then extract the front node of the queue and remove it and insert all its adjacent and unmarked elements. Update the minimum distance as distance of current node +1 and insert the element in the queue."
},
{
"code": null,
"e": 41433,
"s": 41307,
"text": "Create a graph with values assigned from 1 to M*N to all vertices. The purpose is to store position and adjacent information."
},
{
"code": null,
"e": 41456,
"s": 41433,
"text": "Create an empty queue."
},
{
"code": null,
"e": 41526,
"s": 41456,
"text": "Traverse all matrix elements and insert positions of all 1s in queue."
},
{
"code": null,
"e": 41585,
"s": 41526,
"text": "Now do a BFS traversal of graph using above created queue."
},
{
"code": null,
"e": 41843,
"s": 41585,
"text": "Run a loop till the size of the queue is greater than 0 then extract the front node of the queue and remove it and insert all its adjacent and unmarked elements. Update the minimum distance as distance of current node +1 and insert the element in the queue."
},
{
"code": null,
"e": 41860,
"s": 41843,
"text": "Implementation: "
},
{
"code": null,
"e": 41864,
"s": 41860,
"text": "C++"
},
{
"code": null,
"e": 41872,
"s": 41864,
"text": "Python3"
},
{
"code": "// C++ program to find distance of nearest// cell having 1 in a binary matrix.#include<bits/stdc++.h>#define MAX 500#define N 3#define M 4using namespace std; // Making a class of graph with bfs function.class graph{private: vector<int> g[MAX]; int n,m; public: graph(int a, int b) { n = a; m = b; } // Function to create graph with N*M nodes // considering each cell as a node and each // boundary as an edge. void createGraph() { int k = 1; // A number to be assigned to a cell for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { // If last row, then add edge on right side. if (i == n) { // If not bottom right cell. if (j != m) { g[k].push_back(k+1); g[k+1].push_back(k); } } // If last column, then add edge toward down. else if (j == m) { g[k].push_back(k+m); g[k+m].push_back(k); } // Else makes an edge in all four directions. else { g[k].push_back(k+1); g[k+1].push_back(k); g[k].push_back(k+m); g[k+m].push_back(k); } k++; } } } // BFS function to find minimum distance void bfs(bool visit[], int dist[], queue<int> q) { while (!q.empty()) { int temp = q.front(); q.pop(); for (int i = 0; i < g[temp].size(); i++) { if (visit[g[temp][i]] != 1) { dist[g[temp][i]] = min(dist[g[temp][i]], dist[temp]+1); q.push(g[temp][i]); visit[g[temp][i]] = 1; } } } } // Printing the solution. void print(int dist[]) { for (int i = 1, c = 1; i <= n*m; i++, c++) { cout << dist[i] << \" \"; if (c%m == 0) cout << endl; } }}; // Find minimum distancevoid findMinDistance(bool mat[N][M]){ // Creating a graph with nodes values assigned // from 1 to N x M and matrix adjacent. graph g1(N, M); g1.createGraph(); // To store minimum distance int dist[MAX]; // To mark each node as visited or not in BFS bool visit[MAX] = { 0 }; // Initialising the value of distance and visit. for (int i = 1; i <= M*N; i++) { dist[i] = INT_MAX; visit[i] = 0; } // Inserting nodes whose value in matrix // is 1 in the queue. int k = 1; queue<int> q; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (mat[i][j] == 1) { dist[k] = 0; visit[k] = 1; q.push(k); } k++; } } // Calling for Bfs with given Queue. g1.bfs(visit, dist, q); // Printing the solution. g1.print(dist);} // Driven Programint main(){ bool mat[N][M] = { 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0 }; findMinDistance(mat); return 0;}",
"e": 45222,
"s": 41872,
"text": null
},
{
"code": "# Python3 program to find distance of nearest# cell having 1 in a binary matrix.from collections import deque MAX = 500N = 3M = 4 # Making a class of graph with bfs function.g = [[] for i in range(MAX)]n, m = 0, 0 # Function to create graph with N*M nodes# considering each cell as a node and each# boundary as an edge.def createGraph(): global g, n, m # A number to be assigned to a cell k = 1 for i in range(1, n + 1): for j in range(1, m + 1): # If last row, then add edge on right side. if (i == n): # If not bottom right cell. if (j != m): g[k].append(k + 1) g[k + 1].append(k) # If last column, then add edge toward down. elif (j == m): g[k].append(k+m) g[k + m].append(k) # Else makes an edge in all four directions. else: g[k].append(k + 1) g[k + 1].append(k) g[k].append(k+m) g[k + m].append(k) k += 1 # BFS function to find minimum distancedef bfs(visit, dist, q): global g while (len(q) > 0): temp = q.popleft() for i in g[temp]: if (visit[i] != 1): dist[i] = min(dist[i], dist[temp] + 1) q.append(i) visit[i] = 1 return dist # Printing the solution.def prt(dist): c = 1 for i in range(1, n * m + 1): print(dist[i], end = \" \") if (c % m == 0): print() c += 1 # Find minimum distancedef findMinDistance(mat): global g, n, m # Creating a graph with nodes values assigned # from 1 to N x M and matrix adjacent. n, m = N, M createGraph() # To store minimum distance dist = [0] * MAX # To mark each node as visited or not in BFS visit = [0] * MAX # Initialising the value of distance and visit. for i in range(1, M * N + 1): dist[i] = 10**9 visit[i] = 0 # Inserting nodes whose value in matrix # is 1 in the queue. k = 1 q = deque() for i in range(N): for j in range(M): if (mat[i][j] == 1): dist[k] = 0 visit[k] = 1 q.append(k) k += 1 # Calling for Bfs with given Queue. dist = bfs(visit, dist, q) # Printing the solution. prt(dist) # Driver codeif __name__ == '__main__': mat = [ [ 0, 0, 0, 1 ], [ 0, 0, 1, 1 ], [ 0, 1, 1, 0 ] ] findMinDistance(mat) # This code is contributed by mohit kumar 29",
"e": 47918,
"s": 45222,
"text": null
},
{
"code": null,
"e": 47946,
"s": 47918,
"text": "3 2 1 0 \n2 1 0 0 \n1 0 0 1 \n"
},
{
"code": null,
"e": 47968,
"s": 47946,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 48077,
"s": 47968,
"text": "Time Complexity: O(N*M). In BFS traversal every element is traversed only once so time Complexity is O(M*N)."
},
{
"code": null,
"e": 48166,
"s": 48077,
"text": "Space Complexity: O(M*N). To store every element in the matrix O(M*N) space is required."
},
{
"code": null,
"e": 48587,
"s": 48166,
"text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. "
},
{
"code": null,
"e": 48592,
"s": 48587,
"text": "vt_m"
},
{
"code": null,
"e": 48608,
"s": 48592,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 48621,
"s": 48608,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 48635,
"s": 48621,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 48646,
"s": 48635,
"text": "andrew1234"
},
{
"code": null,
"e": 48661,
"s": 48646,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 48671,
"s": 48661,
"text": "patel2127"
},
{
"code": null,
"e": 48688,
"s": 48671,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 48702,
"s": 48688,
"text": "prithicogni89"
},
{
"code": null,
"e": 48709,
"s": 48702,
"text": "Amazon"
},
{
"code": null,
"e": 48713,
"s": 48709,
"text": "BFS"
},
{
"code": null,
"e": 48719,
"s": 48713,
"text": "Graph"
},
{
"code": null,
"e": 48726,
"s": 48719,
"text": "Matrix"
},
{
"code": null,
"e": 48732,
"s": 48726,
"text": "Queue"
},
{
"code": null,
"e": 48739,
"s": 48732,
"text": "Amazon"
},
{
"code": null,
"e": 48746,
"s": 48739,
"text": "Matrix"
},
{
"code": null,
"e": 48752,
"s": 48746,
"text": "Graph"
},
{
"code": null,
"e": 48758,
"s": 48752,
"text": "Queue"
},
{
"code": null,
"e": 48762,
"s": 48758,
"text": "BFS"
},
{
"code": null,
"e": 48860,
"s": 48762,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48869,
"s": 48860,
"text": "Comments"
},
{
"code": null,
"e": 48882,
"s": 48869,
"text": "Old Comments"
},
{
"code": null,
"e": 48940,
"s": 48882,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 48960,
"s": 48940,
"text": "Topological Sorting"
},
{
"code": null,
"e": 48991,
"s": 48960,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 49024,
"s": 48991,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 49057,
"s": 49024,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 49092,
"s": 49057,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 49136,
"s": 49092,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 49160,
"s": 49136,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 49191,
"s": 49160,
"text": "Rat in a Maze | Backtracking-2"
}
]
|
How To Visualize KPI Progress — Bullet Graph With 3 Measures | by Kiril Yunakov | Towards Data Science | Acouple of months ago, I was tasked to create a new dashboard for my team where the aim was to see what is the status for several key performance metrics compared to our plans and to a forecast. This is how I found the bullet chart type and made some modifications for the purpose of our business case. I believe that, especially if you are a new Tableau user, with this tutorial you will be able to learn and understand the fundamentals of Tableau and how to quickly adjust your visualizations.
Simply put, because it allows you to compare a specific dimension from 3 angles (3 different measures):
Actual performance (how much you have achieved already)
Plan / Target performance (how much you need to accomplish)
Forecast performance (how much you are going to achieve at the end of a period, based on the actual performance)
Also, by default in Tableau you can NOT build such a graph from the predefined options, because they allow you to use only 2 measures, and in our case we need 3 (Actual, Plan & Forecast performance).
As of today, where do we stand according to the plan?Where are we going to end at the end of the month if we keep the same pace?
As of today, where do we stand according to the plan?
Where are we going to end at the end of the month if we keep the same pace?
Level of complexity: Beginner
Time to complete: ~5 min.
Requirements: Formatted data, Tableau Public/Desktop
This is probably the most crucial step about the tutorial. Depending on your data, you might be in a situation where you’ll need first to pivot your data set. This is an important step because it will allow you to use all of the 3 measures (actual / plan / forecast) for each of your KPIs (turnover / new customers / cost) and basically apply them to the bullet graph. Here is the example data set I will be using:
Simply open Tableau and connect to your data source. In my case it is a simple csv file as shown above.
Select the #actual measure and by using drag and drop place it to the column shelf. Repeat for the #forecast and same for [abc] measure name but to the rows shelf.
Select any of the pills (#forecast in my case) on the columns shelf and from the drop down menu choose the Dual Axis option.
From the Marks card, under All, select “Bar”. This will change the type of the graph into a bar chart.
With this step you’ll see how important is the order of the pills at the Columns/Rows shelf. Currently, the #forecast measure is displayed over the #actual measure. This is due to the fact it is on the right of the #actual pill. In order to reverse them, we just drag and drop the #actual pill to the right side at the columns shelf. After you will see a small orange triangle, drop it there.
We have the #actual measure over the #forecast now, but in order to see it we need to change the size of the bars. From the Marks card select the SUM(actual) field and from the Size options, drag the slider to the left.
Right click on any of the axis (in my case it is the #forecast) and select Synchronize Axis.
Drag and drop the #plan measure from the Data pane to the Marks card of the SUM(actual) into the Detail option. This allow you to use this measure without impacting the view of the bullet chart directly.
From the Analytics pane, drag and drop the the Reference Line option over to the bar chart view and be sure to place it over the field per Cell, per sum(actual).
Then, a window will appear and from the options select:
Value — choose SUM(plan), with a calculation Sum
Line — change the color to Black and make it a bit thicker.
From the Analysis menu select Create a Calculated field (or just right click on the Data pane and select it from there). Give it a proper name and use the calculation as shown at the screenshot. With this field we can now see how much of the plan we have achieved as a ratio.
Then drag and drop the #actual to plan measure to the Marks card under SUM(actual) drop-down at the Label option.
Same as at the previous step, with the only difference that you need to drag and drop the new field at the Marks card under SUM(forecast) drop-down menu on the Details option.
With this step you’ll make it easier to identify with which KPI is on track and which needs more attention. Right click on Data pane, Create a Calculated field and use the following code:
IF [forecast to plan] > 1.2 then “Over Plan”ELSEIF [forecast to plan] < 0.8 then “Behind Plan”ELSE “On Plan”END
Once, created you can drag and drop the field at the SUM(forecast) drop-down menu at the Marks card on the Color option. We will adjust the colors later.
In order to add a summary box, you need at a few more measures to the SUM(forecast) drop-down menu at the Marks card. Drag and drop #actual and #plan.
Then right click on any of forecast bars at the view and select Annotate > Mark...
Keep only the actual, plan and forecast to plan measures. Repeat the same step for all of the other measure names (cost/ new customers).
Right click on each of both axis and uncheck Show Header.
Right click on the title Sheet 1 and rename it to KPIs Progress.
Right click on measure name and select Hide Field Labels for Rows.
Right click on the #actual to plan measure, Default Properties, Format Number -> Percentage with 0 decimal places. Repeat the steps for #forecast to plan measure as well.
Select SUM(actual) from the Marks card and choose the Label option. Set the Alignment to Middle Center and set the colour to white from the Font option.
Select SUM(forecast) from the Marks card and choose the Color option to apply appropriate colors for the different Statuses.
Right click on one of the Summary Boxes, select Format and change the Shading to None. Repeat the step for the other boxes.
To download the final Tableau workbook, just go to my Public Tableau page.
If you found this article useful, you disagree with some of the points, have questions or suggestions, please don’t hesitate to leave me a comment below. Your feedback is highly appreciated! | [
{
"code": null,
"e": 668,
"s": 172,
"text": "Acouple of months ago, I was tasked to create a new dashboard for my team where the aim was to see what is the status for several key performance metrics compared to our plans and to a forecast. This is how I found the bullet chart type and made some modifications for the purpose of our business case. I believe that, especially if you are a new Tableau user, with this tutorial you will be able to learn and understand the fundamentals of Tableau and how to quickly adjust your visualizations."
},
{
"code": null,
"e": 772,
"s": 668,
"text": "Simply put, because it allows you to compare a specific dimension from 3 angles (3 different measures):"
},
{
"code": null,
"e": 828,
"s": 772,
"text": "Actual performance (how much you have achieved already)"
},
{
"code": null,
"e": 888,
"s": 828,
"text": "Plan / Target performance (how much you need to accomplish)"
},
{
"code": null,
"e": 1001,
"s": 888,
"text": "Forecast performance (how much you are going to achieve at the end of a period, based on the actual performance)"
},
{
"code": null,
"e": 1201,
"s": 1001,
"text": "Also, by default in Tableau you can NOT build such a graph from the predefined options, because they allow you to use only 2 measures, and in our case we need 3 (Actual, Plan & Forecast performance)."
},
{
"code": null,
"e": 1330,
"s": 1201,
"text": "As of today, where do we stand according to the plan?Where are we going to end at the end of the month if we keep the same pace?"
},
{
"code": null,
"e": 1384,
"s": 1330,
"text": "As of today, where do we stand according to the plan?"
},
{
"code": null,
"e": 1460,
"s": 1384,
"text": "Where are we going to end at the end of the month if we keep the same pace?"
},
{
"code": null,
"e": 1490,
"s": 1460,
"text": "Level of complexity: Beginner"
},
{
"code": null,
"e": 1516,
"s": 1490,
"text": "Time to complete: ~5 min."
},
{
"code": null,
"e": 1569,
"s": 1516,
"text": "Requirements: Formatted data, Tableau Public/Desktop"
},
{
"code": null,
"e": 1984,
"s": 1569,
"text": "This is probably the most crucial step about the tutorial. Depending on your data, you might be in a situation where you’ll need first to pivot your data set. This is an important step because it will allow you to use all of the 3 measures (actual / plan / forecast) for each of your KPIs (turnover / new customers / cost) and basically apply them to the bullet graph. Here is the example data set I will be using:"
},
{
"code": null,
"e": 2088,
"s": 1984,
"text": "Simply open Tableau and connect to your data source. In my case it is a simple csv file as shown above."
},
{
"code": null,
"e": 2252,
"s": 2088,
"text": "Select the #actual measure and by using drag and drop place it to the column shelf. Repeat for the #forecast and same for [abc] measure name but to the rows shelf."
},
{
"code": null,
"e": 2377,
"s": 2252,
"text": "Select any of the pills (#forecast in my case) on the columns shelf and from the drop down menu choose the Dual Axis option."
},
{
"code": null,
"e": 2480,
"s": 2377,
"text": "From the Marks card, under All, select “Bar”. This will change the type of the graph into a bar chart."
},
{
"code": null,
"e": 2873,
"s": 2480,
"text": "With this step you’ll see how important is the order of the pills at the Columns/Rows shelf. Currently, the #forecast measure is displayed over the #actual measure. This is due to the fact it is on the right of the #actual pill. In order to reverse them, we just drag and drop the #actual pill to the right side at the columns shelf. After you will see a small orange triangle, drop it there."
},
{
"code": null,
"e": 3093,
"s": 2873,
"text": "We have the #actual measure over the #forecast now, but in order to see it we need to change the size of the bars. From the Marks card select the SUM(actual) field and from the Size options, drag the slider to the left."
},
{
"code": null,
"e": 3186,
"s": 3093,
"text": "Right click on any of the axis (in my case it is the #forecast) and select Synchronize Axis."
},
{
"code": null,
"e": 3390,
"s": 3186,
"text": "Drag and drop the #plan measure from the Data pane to the Marks card of the SUM(actual) into the Detail option. This allow you to use this measure without impacting the view of the bullet chart directly."
},
{
"code": null,
"e": 3552,
"s": 3390,
"text": "From the Analytics pane, drag and drop the the Reference Line option over to the bar chart view and be sure to place it over the field per Cell, per sum(actual)."
},
{
"code": null,
"e": 3608,
"s": 3552,
"text": "Then, a window will appear and from the options select:"
},
{
"code": null,
"e": 3657,
"s": 3608,
"text": "Value — choose SUM(plan), with a calculation Sum"
},
{
"code": null,
"e": 3717,
"s": 3657,
"text": "Line — change the color to Black and make it a bit thicker."
},
{
"code": null,
"e": 3993,
"s": 3717,
"text": "From the Analysis menu select Create a Calculated field (or just right click on the Data pane and select it from there). Give it a proper name and use the calculation as shown at the screenshot. With this field we can now see how much of the plan we have achieved as a ratio."
},
{
"code": null,
"e": 4107,
"s": 3993,
"text": "Then drag and drop the #actual to plan measure to the Marks card under SUM(actual) drop-down at the Label option."
},
{
"code": null,
"e": 4283,
"s": 4107,
"text": "Same as at the previous step, with the only difference that you need to drag and drop the new field at the Marks card under SUM(forecast) drop-down menu on the Details option."
},
{
"code": null,
"e": 4471,
"s": 4283,
"text": "With this step you’ll make it easier to identify with which KPI is on track and which needs more attention. Right click on Data pane, Create a Calculated field and use the following code:"
},
{
"code": null,
"e": 4583,
"s": 4471,
"text": "IF [forecast to plan] > 1.2 then “Over Plan”ELSEIF [forecast to plan] < 0.8 then “Behind Plan”ELSE “On Plan”END"
},
{
"code": null,
"e": 4737,
"s": 4583,
"text": "Once, created you can drag and drop the field at the SUM(forecast) drop-down menu at the Marks card on the Color option. We will adjust the colors later."
},
{
"code": null,
"e": 4888,
"s": 4737,
"text": "In order to add a summary box, you need at a few more measures to the SUM(forecast) drop-down menu at the Marks card. Drag and drop #actual and #plan."
},
{
"code": null,
"e": 4971,
"s": 4888,
"text": "Then right click on any of forecast bars at the view and select Annotate > Mark..."
},
{
"code": null,
"e": 5108,
"s": 4971,
"text": "Keep only the actual, plan and forecast to plan measures. Repeat the same step for all of the other measure names (cost/ new customers)."
},
{
"code": null,
"e": 5166,
"s": 5108,
"text": "Right click on each of both axis and uncheck Show Header."
},
{
"code": null,
"e": 5231,
"s": 5166,
"text": "Right click on the title Sheet 1 and rename it to KPIs Progress."
},
{
"code": null,
"e": 5298,
"s": 5231,
"text": "Right click on measure name and select Hide Field Labels for Rows."
},
{
"code": null,
"e": 5469,
"s": 5298,
"text": "Right click on the #actual to plan measure, Default Properties, Format Number -> Percentage with 0 decimal places. Repeat the steps for #forecast to plan measure as well."
},
{
"code": null,
"e": 5622,
"s": 5469,
"text": "Select SUM(actual) from the Marks card and choose the Label option. Set the Alignment to Middle Center and set the colour to white from the Font option."
},
{
"code": null,
"e": 5747,
"s": 5622,
"text": "Select SUM(forecast) from the Marks card and choose the Color option to apply appropriate colors for the different Statuses."
},
{
"code": null,
"e": 5871,
"s": 5747,
"text": "Right click on one of the Summary Boxes, select Format and change the Shading to None. Repeat the step for the other boxes."
},
{
"code": null,
"e": 5946,
"s": 5871,
"text": "To download the final Tableau workbook, just go to my Public Tableau page."
}
]
|
Tryit Editor v3.7 | CSS Grid Item
Tryit: The grid-area property | [
{
"code": null,
"e": 23,
"s": 9,
"text": "CSS Grid Item"
}
]
|
Print all neighbour nodes within distance K - GeeksforGeeks | 15 Nov, 2021
Given a graph of N nodes, E edges, a node X and a distance K. The task is to print all the nodes within the distance K from X.
Input:
Output: 4 5 2 7 3Neighbour nodes within distance 2 of node 4 are: 4 5 2 7 3
Approach: To print all the nodes that are at distance K or less than K. We can do it by applying dfs variation, that takes K node from where we have to print the distance until distance K.
dfs(K, node, -1, tree)
Here -1 indicates node parent. This recursive function basically prints the node and then calls the dfs(K-1, neighbour of node, node, tree). Base condition is K>0.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to print// the nearest K neighbour// nodes (including itself)#include <bits/stdc++.h>using namespace std; // Structure of an edgestruct arr { int from, to;}; // Recursive function to print// the neighbor nodes of a node// until K distancevoid dfs(int k, int node, int parent, const vector<vector<int> >& tree){ // Base condition if (k < 0) return; // Print the node cout << node << ' '; // Traverse the connected // nodes/adjacency list for (int i : tree[node]) { if (i != parent) { // node i becomes the parent // of its child node dfs(k - 1, i, node, tree); } }} // Function to print nodes under// distance kvoid print_under_dis_K(struct arr graph[], int node, int k, int v, int e){ // To make graph with // the given edges vector<vector<int> > tree(v + 1, vector<int>()); for (int i = 0; i < e; i++) { int from = graph[i].from; int to = graph[i].to; tree[from].push_back(to); tree[to].push_back(from); } dfs(k, node, -1, tree);} // Driver Codeint main(){ // Number of vertex and edges int v = 7, e = 6; // Given edges struct arr graph[v + 1] = { { 2, 1 }, { 2, 5 }, { 5, 4 }, { 5, 7 }, { 4, 3 }, { 7, 6 } }; // k is the required distance // upto which are neighbor // nodes should get printed int node = 4, k = 2; // function calling print_under_dis_K(graph, node, k, v, e); return 0;}
// Java program to print// the nearest K neighbour// nodes (including itself)import java.util.*; @SuppressWarnings("unchecked")class GFG{ // Structure of an edgepublic static class arr{ public int from, to; public arr(int from, int to) { this.from = from; this.to = to; }}; // Recursive function to print// the neighbor nodes of a node// until K distancestatic void dfs(int k, int node, int parent, ArrayList []tree){ // Base condition if (k < 0) return; // Print the node System.out.print(node + " "); ArrayList tmp = (ArrayList)tree[node]; // Traverse the connected // nodes/adjacency list for(int i : (ArrayList<Integer>)tmp) { if (i != parent) { // Node i becomes the parent // of its child node dfs(k - 1, i, node, tree); } }} // Function to print nodes under// distance kstatic void print_under_dis_K(arr []graph, int node, int k, int v, int e){ // To make graph with // the given edges ArrayList []tree = new ArrayList[v + 1]; for(int i = 0; i < v + 1; i++) { tree[i] = new ArrayList(); } for(int i = 0; i < e; i++) { int from = graph[i].from; int to = graph[i].to; tree[from].add(to); tree[to].add(from); } dfs(k, node, -1, tree);} // Driver Codepublic static void main(String[] args){ // Number of vertex and edges int v = 7, e = 6; // Given edges arr []graph = { new arr(2, 1), new arr(2, 5), new arr(5, 4), new arr(5, 7), new arr(4, 3), new arr(7, 6) }; // k is the required distance // upto which are neighbor // nodes should get printed int node = 4, k = 2; // Function calling print_under_dis_K(graph, node, k, v, e);}} // This code is contributed by pratham76
# Python3 program to print# the nearest K neighbour# nodes (including itself) tree = [[] for i in range(100)] # Recursive function to print# the neighbor nodes of a node# until K distancedef dfs(k, node, parent): # Base condition if (k < 0): return # Print the node print(node, end = " ") # Traverse the connected # nodes/adjacency list for i in tree[node]: if (i != parent): # node i becomes the parent # of its child node dfs(k - 1, i, node) # Function to print nodes under# distance kdef print_under_dis_K(graph, node, k, v, e): for i in range(e): fro = graph[i][0] to = graph[i][1] tree[fro].append(to) tree[to].append(fro) dfs(k, node, -1) # Driver Code # Number of vertex and edgesv = 7e = 6 # Given edgesgraph = [[ 2, 1 ], [ 2, 5 ], [ 5, 4 ], [ 5, 7 ], [ 4, 3 ], [ 7, 6 ]] # k is the required distance# upto which are neighbor# nodes should get prednode = 4k = 2 # function callingprint_under_dis_K(graph, node, k, v, e) # This code is contributed by Mohit Kumar
// C# program to print// the nearest K neighbour// nodes (including itself)using System;using System.Collections; class GFG{ // Structure of an edgepublic class arr{ public int from, to; public arr(int from, int to) { this.from = from; this.to = to; }}; // Recursive function to print// the neighbor nodes of a node// until K distancestatic void dfs(int k, int node, int parent, ArrayList []tree){ // Base condition if (k < 0) return; // Print the node Console.Write(node+" "); ArrayList tmp = (ArrayList)tree[node]; // Traverse the connected // nodes/adjacency list foreach (int i in tmp) { if (i != parent) { // node i becomes the parent // of its child node dfs(k - 1, i, node, tree); } }} // Function to print nodes under// distance kstatic void print_under_dis_K(arr []graph, int node, int k, int v, int e){ // To make graph with // the given edges ArrayList []tree = new ArrayList[v + 1]; for(int i = 0; i < v + 1; i++) { tree[i] = new ArrayList(); } for (int i = 0; i < e; i++) { int from = graph[i].from; int to = graph[i].to; tree[from].Add(to); tree[to].Add(from); } dfs(k, node, -1, tree);} // Driver Code public static void Main(string[] args) { // Number of vertex and edges int v = 7, e = 6; // Given edges arr []graph = { new arr( 2, 1 ), new arr( 2, 5 ), new arr( 5, 4 ), new arr( 5, 7 ), new arr( 4, 3 ), new arr( 7, 6 ) }; // k is the required distance // upto which are neighbor // nodes should get printed int node = 4, k = 2; // function calling print_under_dis_K(graph, node, k, v, e); }} // This code is contributed by rutvik_56
<script> // JavaScript program to print// the nearest K neighbour// nodes (including itself) // Structure of an edgeclass arr{ constructor(from,to) { this.from = from; this.to = to; }} // Recursive function to print// the neighbor nodes of a node// until K distancefunction dfs(k,node,parent,tree){ // Base condition if (k < 0) return; // Print the node document.write(node + " "); let tmp = tree[node]; // Traverse the connected // nodes/adjacency list for(let i=0;i<tmp.length;i++) { if (tmp[i] != parent) { // Node i becomes the parent // of its child node dfs(k - 1, tmp[i], node, tree); } }} // Function to print nodes under// distance kfunction print_under_dis_K(graph,node,k,v,e){ // To make graph with // the given edges let tree = new Array(v + 1); for(let i = 0; i < v + 1; i++) { tree[i] = []; } for(let i = 0; i < e; i++) { let from = graph[i].from; let to = graph[i].to; tree[from].push(to); tree[to].push(from); } dfs(k, node, -1, tree);} // Driver Code// Number of vertex and edges let v = 7, e = 6; // Given edges let graph = [ new arr(2, 1), new arr(2, 5), new arr(5, 4), new arr(5, 7), new arr(4, 3), new arr(7, 6) ]; // k is the required distance // upto which are neighbor // nodes should get printed let node = 4, k = 2; // Function calling print_under_dis_K(graph, node, k, v, e); // This code is contributed by unknown2108 </script>
4 5 2 7 3
mohit kumar 29
Akanksha_Rai
rutvik_56
pratham76
unknown2108
clintra
Amazon
DFS
Samsung
Trees
Graph
Amazon
Samsung
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Best First Search (Informed Search)
Longest Path in a Directed Acyclic Graph
Graph Coloring | Set 2 (Greedy Algorithm)
Find if there is a path between two vertices in a directed graph
Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)
Snake and Ladder Problem
Check if a given graph is tree or not
Tree, Back, Edge and Cross Edges in DFS of Graph
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
Real-time application of Data Structures | [
{
"code": null,
"e": 24675,
"s": 24647,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 24802,
"s": 24675,
"text": "Given a graph of N nodes, E edges, a node X and a distance K. The task is to print all the nodes within the distance K from X."
},
{
"code": null,
"e": 24811,
"s": 24802,
"text": "Input: "
},
{
"code": null,
"e": 24889,
"s": 24811,
"text": "Output: 4 5 2 7 3Neighbour nodes within distance 2 of node 4 are: 4 5 2 7 3 "
},
{
"code": null,
"e": 25079,
"s": 24889,
"text": "Approach: To print all the nodes that are at distance K or less than K. We can do it by applying dfs variation, that takes K node from where we have to print the distance until distance K. "
},
{
"code": null,
"e": 25102,
"s": 25079,
"text": "dfs(K, node, -1, tree)"
},
{
"code": null,
"e": 25266,
"s": 25102,
"text": "Here -1 indicates node parent. This recursive function basically prints the node and then calls the dfs(K-1, neighbour of node, node, tree). Base condition is K>0."
},
{
"code": null,
"e": 25319,
"s": 25266,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25323,
"s": 25319,
"text": "C++"
},
{
"code": null,
"e": 25328,
"s": 25323,
"text": "Java"
},
{
"code": null,
"e": 25336,
"s": 25328,
"text": "Python3"
},
{
"code": null,
"e": 25339,
"s": 25336,
"text": "C#"
},
{
"code": null,
"e": 25350,
"s": 25339,
"text": "Javascript"
},
{
"code": "// C++ program to print// the nearest K neighbour// nodes (including itself)#include <bits/stdc++.h>using namespace std; // Structure of an edgestruct arr { int from, to;}; // Recursive function to print// the neighbor nodes of a node// until K distancevoid dfs(int k, int node, int parent, const vector<vector<int> >& tree){ // Base condition if (k < 0) return; // Print the node cout << node << ' '; // Traverse the connected // nodes/adjacency list for (int i : tree[node]) { if (i != parent) { // node i becomes the parent // of its child node dfs(k - 1, i, node, tree); } }} // Function to print nodes under// distance kvoid print_under_dis_K(struct arr graph[], int node, int k, int v, int e){ // To make graph with // the given edges vector<vector<int> > tree(v + 1, vector<int>()); for (int i = 0; i < e; i++) { int from = graph[i].from; int to = graph[i].to; tree[from].push_back(to); tree[to].push_back(from); } dfs(k, node, -1, tree);} // Driver Codeint main(){ // Number of vertex and edges int v = 7, e = 6; // Given edges struct arr graph[v + 1] = { { 2, 1 }, { 2, 5 }, { 5, 4 }, { 5, 7 }, { 4, 3 }, { 7, 6 } }; // k is the required distance // upto which are neighbor // nodes should get printed int node = 4, k = 2; // function calling print_under_dis_K(graph, node, k, v, e); return 0;}",
"e": 26962,
"s": 25350,
"text": null
},
{
"code": "// Java program to print// the nearest K neighbour// nodes (including itself)import java.util.*; @SuppressWarnings(\"unchecked\")class GFG{ // Structure of an edgepublic static class arr{ public int from, to; public arr(int from, int to) { this.from = from; this.to = to; }}; // Recursive function to print// the neighbor nodes of a node// until K distancestatic void dfs(int k, int node, int parent, ArrayList []tree){ // Base condition if (k < 0) return; // Print the node System.out.print(node + \" \"); ArrayList tmp = (ArrayList)tree[node]; // Traverse the connected // nodes/adjacency list for(int i : (ArrayList<Integer>)tmp) { if (i != parent) { // Node i becomes the parent // of its child node dfs(k - 1, i, node, tree); } }} // Function to print nodes under// distance kstatic void print_under_dis_K(arr []graph, int node, int k, int v, int e){ // To make graph with // the given edges ArrayList []tree = new ArrayList[v + 1]; for(int i = 0; i < v + 1; i++) { tree[i] = new ArrayList(); } for(int i = 0; i < e; i++) { int from = graph[i].from; int to = graph[i].to; tree[from].add(to); tree[to].add(from); } dfs(k, node, -1, tree);} // Driver Codepublic static void main(String[] args){ // Number of vertex and edges int v = 7, e = 6; // Given edges arr []graph = { new arr(2, 1), new arr(2, 5), new arr(5, 4), new arr(5, 7), new arr(4, 3), new arr(7, 6) }; // k is the required distance // upto which are neighbor // nodes should get printed int node = 4, k = 2; // Function calling print_under_dis_K(graph, node, k, v, e);}} // This code is contributed by pratham76",
"e": 29014,
"s": 26962,
"text": null
},
{
"code": "# Python3 program to print# the nearest K neighbour# nodes (including itself) tree = [[] for i in range(100)] # Recursive function to print# the neighbor nodes of a node# until K distancedef dfs(k, node, parent): # Base condition if (k < 0): return # Print the node print(node, end = \" \") # Traverse the connected # nodes/adjacency list for i in tree[node]: if (i != parent): # node i becomes the parent # of its child node dfs(k - 1, i, node) # Function to print nodes under# distance kdef print_under_dis_K(graph, node, k, v, e): for i in range(e): fro = graph[i][0] to = graph[i][1] tree[fro].append(to) tree[to].append(fro) dfs(k, node, -1) # Driver Code # Number of vertex and edgesv = 7e = 6 # Given edgesgraph = [[ 2, 1 ], [ 2, 5 ], [ 5, 4 ], [ 5, 7 ], [ 4, 3 ], [ 7, 6 ]] # k is the required distance# upto which are neighbor# nodes should get prednode = 4k = 2 # function callingprint_under_dis_K(graph, node, k, v, e) # This code is contributed by Mohit Kumar",
"e": 30137,
"s": 29014,
"text": null
},
{
"code": "// C# program to print// the nearest K neighbour// nodes (including itself)using System;using System.Collections; class GFG{ // Structure of an edgepublic class arr{ public int from, to; public arr(int from, int to) { this.from = from; this.to = to; }}; // Recursive function to print// the neighbor nodes of a node// until K distancestatic void dfs(int k, int node, int parent, ArrayList []tree){ // Base condition if (k < 0) return; // Print the node Console.Write(node+\" \"); ArrayList tmp = (ArrayList)tree[node]; // Traverse the connected // nodes/adjacency list foreach (int i in tmp) { if (i != parent) { // node i becomes the parent // of its child node dfs(k - 1, i, node, tree); } }} // Function to print nodes under// distance kstatic void print_under_dis_K(arr []graph, int node, int k, int v, int e){ // To make graph with // the given edges ArrayList []tree = new ArrayList[v + 1]; for(int i = 0; i < v + 1; i++) { tree[i] = new ArrayList(); } for (int i = 0; i < e; i++) { int from = graph[i].from; int to = graph[i].to; tree[from].Add(to); tree[to].Add(from); } dfs(k, node, -1, tree);} // Driver Code public static void Main(string[] args) { // Number of vertex and edges int v = 7, e = 6; // Given edges arr []graph = { new arr( 2, 1 ), new arr( 2, 5 ), new arr( 5, 4 ), new arr( 5, 7 ), new arr( 4, 3 ), new arr( 7, 6 ) }; // k is the required distance // upto which are neighbor // nodes should get printed int node = 4, k = 2; // function calling print_under_dis_K(graph, node, k, v, e); }} // This code is contributed by rutvik_56",
"e": 32047,
"s": 30137,
"text": null
},
{
"code": "<script> // JavaScript program to print// the nearest K neighbour// nodes (including itself) // Structure of an edgeclass arr{ constructor(from,to) { this.from = from; this.to = to; }} // Recursive function to print// the neighbor nodes of a node// until K distancefunction dfs(k,node,parent,tree){ // Base condition if (k < 0) return; // Print the node document.write(node + \" \"); let tmp = tree[node]; // Traverse the connected // nodes/adjacency list for(let i=0;i<tmp.length;i++) { if (tmp[i] != parent) { // Node i becomes the parent // of its child node dfs(k - 1, tmp[i], node, tree); } }} // Function to print nodes under// distance kfunction print_under_dis_K(graph,node,k,v,e){ // To make graph with // the given edges let tree = new Array(v + 1); for(let i = 0; i < v + 1; i++) { tree[i] = []; } for(let i = 0; i < e; i++) { let from = graph[i].from; let to = graph[i].to; tree[from].push(to); tree[to].push(from); } dfs(k, node, -1, tree);} // Driver Code// Number of vertex and edges let v = 7, e = 6; // Given edges let graph = [ new arr(2, 1), new arr(2, 5), new arr(5, 4), new arr(5, 7), new arr(4, 3), new arr(7, 6) ]; // k is the required distance // upto which are neighbor // nodes should get printed let node = 4, k = 2; // Function calling print_under_dis_K(graph, node, k, v, e); // This code is contributed by unknown2108 </script>",
"e": 33787,
"s": 32047,
"text": null
},
{
"code": null,
"e": 33797,
"s": 33787,
"text": "4 5 2 7 3"
},
{
"code": null,
"e": 33814,
"s": 33799,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 33827,
"s": 33814,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 33837,
"s": 33827,
"text": "rutvik_56"
},
{
"code": null,
"e": 33847,
"s": 33837,
"text": "pratham76"
},
{
"code": null,
"e": 33859,
"s": 33847,
"text": "unknown2108"
},
{
"code": null,
"e": 33867,
"s": 33859,
"text": "clintra"
},
{
"code": null,
"e": 33874,
"s": 33867,
"text": "Amazon"
},
{
"code": null,
"e": 33878,
"s": 33874,
"text": "DFS"
},
{
"code": null,
"e": 33886,
"s": 33878,
"text": "Samsung"
},
{
"code": null,
"e": 33892,
"s": 33886,
"text": "Trees"
},
{
"code": null,
"e": 33898,
"s": 33892,
"text": "Graph"
},
{
"code": null,
"e": 33905,
"s": 33898,
"text": "Amazon"
},
{
"code": null,
"e": 33913,
"s": 33905,
"text": "Samsung"
},
{
"code": null,
"e": 33917,
"s": 33913,
"text": "DFS"
},
{
"code": null,
"e": 33923,
"s": 33917,
"text": "Graph"
},
{
"code": null,
"e": 34021,
"s": 33923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34030,
"s": 34021,
"text": "Comments"
},
{
"code": null,
"e": 34043,
"s": 34030,
"text": "Old Comments"
},
{
"code": null,
"e": 34079,
"s": 34043,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 34120,
"s": 34079,
"text": "Longest Path in a Directed Acyclic Graph"
},
{
"code": null,
"e": 34162,
"s": 34120,
"text": "Graph Coloring | Set 2 (Greedy Algorithm)"
},
{
"code": null,
"e": 34227,
"s": 34162,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 34297,
"s": 34227,
"text": "Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)"
},
{
"code": null,
"e": 34322,
"s": 34297,
"text": "Snake and Ladder Problem"
},
{
"code": null,
"e": 34360,
"s": 34322,
"text": "Check if a given graph is tree or not"
},
{
"code": null,
"e": 34409,
"s": 34360,
"text": "Tree, Back, Edge and Cross Edges in DFS of Graph"
},
{
"code": null,
"e": 34490,
"s": 34409,
"text": "Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)"
}
]
|
Skewed Binary Tree - GeeksforGeeks | 22 Jul, 2021
A skewed binary tree is a type of binary tree in which all the nodes have only either one child or no child.
Types of Skewed Binary trees
There are 2 special types of skewed tree:
1. Left Skewed Binary Tree: These are those skewed binary trees in which all the nodes are having a left child or no child at all. It is a left side dominated tree. All the right children remain as null.
Below is an example of a left-skewed tree:
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; // A Tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Driver codeint main(){ /* 1 / 2 / 3 */ Node* root = newNode(1); root->left = newNode(2); root->left->left = newNode(3); return 0;}
// Java implementation of above approachimport java.util.*; class GFG{ // A Tree nodestatic class Node{ int key; Node left, right;}; // Utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Driver codepublic static void main(String args[]){ /* 1 / 2 / 3 */ Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(3);}} // This code is contributed by Arnab Kundu
# Python3 implementation of the above approach # Class that represents an individual# node in a Binary Treeclass Node: def __init__(self, key): self.left = None self.right = None self.val = key # Driver code """ 1 / 2 / 3 """root = Node(1)root.left = Node(2)root.left.left = Node(2) # This code is contributed by dhruvsantoshwar
// C# implementation of above approachusing System; class GFG{ // A Tree node public class Node { public int key; public Node left, right; }; // Utility function to create a new node static Node newNode(int key) { Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp); } // Driver code public static void Main() { /* 1 / 2 / 3 */ Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(3); }} // This code is contributed by AnkitRai01
<script>// Javascript implementation of above approach // A Tree nodeclass Node{ constructor() { this.key=0; this.left=this.right=null; }} // Utility function to create a new nodefunction newNode(key){ let temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Driver code /* 1 / 2 / 3 */let root = newNode(1);root.left = newNode(2);root.left.left = newNode(3); // This code is contributed by avanitrachhadiya2155</script>
2. Right Skewed Binary Tree: These are those skewed binary trees in which all the nodes are having a right child or no child at all. It is a right side dominated tree. All the left children remain as null.
Below is an example of a right-skewed tree:
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; // A Tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Driver codeint main(){ /* 1 \ 2 \ 3 */ Node* root = newNode(1); root->right = newNode(2); root->right->right = newNode(3); return 0;}
// Java implementation of above approachimport java.util.*;class GFG{ // A Tree nodestatic class Node{ int key; Node left, right;}; // Utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Driver codepublic static void main(String args[]){ /* 1 \ 2 \ 3 */ Node root = newNode(1); root.right = newNode(2); root.right.right = newNode(3);}} // This code is contributed by Arnab Kundu
# Python3 implementation of the above approach # A Tree nodeclass Node: def __init__(self, key): self.left = None self.right = None self.val = key # Driver code""" 1 \ 2 \ 3 """root = Node(1)root.right = Node(2)root.right.right = Node(3) # This code is contributed by shivanisinghss2110
// C# implementation of above approachusing System; class GFG{ // A Tree nodepublic class Node{ public int key; public Node left, right;}; // Utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Driver codepublic static void Main(String []args){ /* 1 \ 2 \ 3 */ Node root = newNode(1); root.right = newNode(2); root.right.right = newNode(3);}} // This code is contributed by PrinciRaj1992
<script> // Javascript implementation of above approach // A Tree nodeclass Node{ constructor() { this.key = 0; this.left = this.right = null; }} // Utility function to create a new nodefunction newNode(key){ let temp = new Node(); temp.key = key; temp.left = temp.right = null; return(temp);} // Driver code /* 1 / 2 / 3 */let root = newNode(1);root.right = newNode(2);root.right.right = newNode(3); // This code is contributed by shivanisinghss2110 </script>
andrew1234
ankthon
princiraj1992
dhruvsantoshwar
avanitrachhadiya2155
shivanisinghss2110
Binary Tree
Data Structures
Tree
Data Structures
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Introduction to Tree Data Structure
Hash Map in Python
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree) | [
{
"code": null,
"e": 25017,
"s": 24989,
"text": "\n22 Jul, 2021"
},
{
"code": null,
"e": 25126,
"s": 25017,
"text": "A skewed binary tree is a type of binary tree in which all the nodes have only either one child or no child."
},
{
"code": null,
"e": 25156,
"s": 25126,
"text": "Types of Skewed Binary trees "
},
{
"code": null,
"e": 25199,
"s": 25156,
"text": "There are 2 special types of skewed tree: "
},
{
"code": null,
"e": 25403,
"s": 25199,
"text": "1. Left Skewed Binary Tree: These are those skewed binary trees in which all the nodes are having a left child or no child at all. It is a left side dominated tree. All the right children remain as null."
},
{
"code": null,
"e": 25446,
"s": 25403,
"text": "Below is an example of a left-skewed tree:"
},
{
"code": null,
"e": 25450,
"s": 25446,
"text": "C++"
},
{
"code": null,
"e": 25455,
"s": 25450,
"text": "Java"
},
{
"code": null,
"e": 25463,
"s": 25455,
"text": "Python3"
},
{
"code": null,
"e": 25466,
"s": 25463,
"text": "C#"
},
{
"code": null,
"e": 25477,
"s": 25466,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // A Tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Driver codeint main(){ /* 1 / 2 / 3 */ Node* root = newNode(1); root->left = newNode(2); root->left->left = newNode(3); return 0;}",
"e": 25958,
"s": 25477,
"text": null
},
{
"code": "// Java implementation of above approachimport java.util.*; class GFG{ // A Tree nodestatic class Node{ int key; Node left, right;}; // Utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Driver codepublic static void main(String args[]){ /* 1 / 2 / 3 */ Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(3);}} // This code is contributed by Arnab Kundu",
"e": 26530,
"s": 25958,
"text": null
},
{
"code": "# Python3 implementation of the above approach # Class that represents an individual# node in a Binary Treeclass Node: def __init__(self, key): self.left = None self.right = None self.val = key # Driver code \"\"\" 1 / 2 / 3 \"\"\"root = Node(1)root.left = Node(2)root.left.left = Node(2) # This code is contributed by dhruvsantoshwar",
"e": 26946,
"s": 26530,
"text": null
},
{
"code": "// C# implementation of above approachusing System; class GFG{ // A Tree node public class Node { public int key; public Node left, right; }; // Utility function to create a new node static Node newNode(int key) { Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp); } // Driver code public static void Main() { /* 1 / 2 / 3 */ Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(3); }} // This code is contributed by AnkitRai01",
"e": 27646,
"s": 26946,
"text": null
},
{
"code": "<script>// Javascript implementation of above approach // A Tree nodeclass Node{ constructor() { this.key=0; this.left=this.right=null; }} // Utility function to create a new nodefunction newNode(key){ let temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Driver code /* 1 / 2 / 3 */let root = newNode(1);root.left = newNode(2);root.left.left = newNode(3); // This code is contributed by avanitrachhadiya2155</script>",
"e": 28188,
"s": 27646,
"text": null
},
{
"code": null,
"e": 28394,
"s": 28188,
"text": "2. Right Skewed Binary Tree: These are those skewed binary trees in which all the nodes are having a right child or no child at all. It is a right side dominated tree. All the left children remain as null."
},
{
"code": null,
"e": 28438,
"s": 28394,
"text": "Below is an example of a right-skewed tree:"
},
{
"code": null,
"e": 28442,
"s": 28438,
"text": "C++"
},
{
"code": null,
"e": 28447,
"s": 28442,
"text": "Java"
},
{
"code": null,
"e": 28455,
"s": 28447,
"text": "Python3"
},
{
"code": null,
"e": 28458,
"s": 28455,
"text": "C#"
},
{
"code": null,
"e": 28469,
"s": 28458,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // A Tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Driver codeint main(){ /* 1 \\ 2 \\ 3 */ Node* root = newNode(1); root->right = newNode(2); root->right->right = newNode(3); return 0;}",
"e": 28953,
"s": 28469,
"text": null
},
{
"code": "// Java implementation of above approachimport java.util.*;class GFG{ // A Tree nodestatic class Node{ int key; Node left, right;}; // Utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Driver codepublic static void main(String args[]){ /* 1 \\ 2 \\ 3 */ Node root = newNode(1); root.right = newNode(2); root.right.right = newNode(3);}} // This code is contributed by Arnab Kundu",
"e": 29521,
"s": 28953,
"text": null
},
{
"code": "# Python3 implementation of the above approach # A Tree nodeclass Node: def __init__(self, key): self.left = None self.right = None self.val = key # Driver code\"\"\" 1 \\ 2 \\ 3 \"\"\"root = Node(1)root.right = Node(2)root.right.right = Node(3) # This code is contributed by shivanisinghss2110",
"e": 29923,
"s": 29521,
"text": null
},
{
"code": "// C# implementation of above approachusing System; class GFG{ // A Tree nodepublic class Node{ public int key; public Node left, right;}; // Utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Driver codepublic static void Main(String []args){ /* 1 \\ 2 \\ 3 */ Node root = newNode(1); root.right = newNode(2); root.right.right = newNode(3);}} // This code is contributed by PrinciRaj1992",
"e": 30510,
"s": 29923,
"text": null
},
{
"code": "<script> // Javascript implementation of above approach // A Tree nodeclass Node{ constructor() { this.key = 0; this.left = this.right = null; }} // Utility function to create a new nodefunction newNode(key){ let temp = new Node(); temp.key = key; temp.left = temp.right = null; return(temp);} // Driver code /* 1 / 2 / 3 */let root = newNode(1);root.right = newNode(2);root.right.right = newNode(3); // This code is contributed by shivanisinghss2110 </script>",
"e": 31059,
"s": 30510,
"text": null
},
{
"code": null,
"e": 31070,
"s": 31059,
"text": "andrew1234"
},
{
"code": null,
"e": 31078,
"s": 31070,
"text": "ankthon"
},
{
"code": null,
"e": 31092,
"s": 31078,
"text": "princiraj1992"
},
{
"code": null,
"e": 31108,
"s": 31092,
"text": "dhruvsantoshwar"
},
{
"code": null,
"e": 31129,
"s": 31108,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 31148,
"s": 31129,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 31160,
"s": 31148,
"text": "Binary Tree"
},
{
"code": null,
"e": 31176,
"s": 31160,
"text": "Data Structures"
},
{
"code": null,
"e": 31181,
"s": 31176,
"text": "Tree"
},
{
"code": null,
"e": 31197,
"s": 31181,
"text": "Data Structures"
},
{
"code": null,
"e": 31202,
"s": 31197,
"text": "Tree"
},
{
"code": null,
"e": 31300,
"s": 31202,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31309,
"s": 31300,
"text": "Comments"
},
{
"code": null,
"e": 31322,
"s": 31309,
"text": "Old Comments"
},
{
"code": null,
"e": 31371,
"s": 31322,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 31396,
"s": 31371,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 31423,
"s": 31396,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 31459,
"s": 31423,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 31478,
"s": 31459,
"text": "Hash Map in Python"
},
{
"code": null,
"e": 31528,
"s": 31478,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 31563,
"s": 31528,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 31597,
"s": 31563,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 31638,
"s": 31597,
"text": "Inorder Tree Traversal without Recursion"
}
]
|
How to copy items from one location to another location using PowerShell? | To copy items in PowerShell, one needs to use the Copy-Item cmdlet. When you use the Copy-Item, you need to provide the source file name and the destination file or folder name.
In the below example, we will copy a single file from the D:\Temp to the D:\Temp1 location.
Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp1\ -PassThru
PS C:\Windows\System32> Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp1\ -PassThru
Directory: D:\Temp1
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 20-01-2020 12:10 1148809 PowerShellcommands.csv
In the above example, PowerShellCommands.csv file will be copied from the D:\Temp to the D:\Temp1 location. If the file already exists then it simply overwrites the file without any prompt or error or warning.
When you use the –Passthru parameter in the command, it displays the output in the console.
You can also rename items when you use the copy command. For that, you need to mention a new file name to the destination parameter.
Copy-Item -Path D:\Temp\PowerShellcommands.csv
-Destination D:\Temp1\PowerShel lcommands1.csv -PassThru
PS C:\Windows\System32> Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp1\PowerShellcommands1.csv -PassThru
Directory: D:\Temp1
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 20-01-2020 12:10 1148809 PowerShellcommands1.csv
While copying item(s) to another location, their attributes are also copies with them.
When you copy files from the source folder to the destination folder, and if the destination folder doesn’t exist then files(s) won’t get copied and it will throw an exception of DirectoryNotFoundException.
For example, we will copy the above mentioned PowerShellcommands1.csv file to the unknown destination folder D:\Temp2 as shown below.
Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp2\PowerShel
lcommands.csv -PassThru
PS C:\Windows\System32> Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp2\PowerShellcommands.csv -PassThru
Copy-Item : Could not find a part of the path 'D:\Temp2\PowerShellcommands.csv'.
At line:1 char:1
+ Copy-Item -Path D:\Temp\PowerShellcommands.csv -Destination D:\Temp2\ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException
+ FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand | [
{
"code": null,
"e": 1240,
"s": 1062,
"text": "To copy items in PowerShell, one needs to use the Copy-Item cmdlet. When you use the Copy-Item, you need to provide the source file name and the destination file or folder name."
},
{
"code": null,
"e": 1332,
"s": 1240,
"text": "In the below example, we will copy a single file from the D:\\Temp to the D:\\Temp1 location."
},
{
"code": null,
"e": 1412,
"s": 1332,
"text": "Copy-Item -Path D:\\Temp\\PowerShellcommands.csv -Destination D:\\Temp1\\ -PassThru"
},
{
"code": null,
"e": 1722,
"s": 1412,
"text": "PS C:\\Windows\\System32> Copy-Item -Path D:\\Temp\\PowerShellcommands.csv -Destination D:\\Temp1\\ -PassThru\n Directory: D:\\Temp1\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a---- 20-01-2020 12:10 1148809 PowerShellcommands.csv\n\n"
},
{
"code": null,
"e": 1932,
"s": 1722,
"text": "In the above example, PowerShellCommands.csv file will be copied from the D:\\Temp to the D:\\Temp1 location. If the file already exists then it simply overwrites the file without any prompt or error or warning."
},
{
"code": null,
"e": 2024,
"s": 1932,
"text": "When you use the –Passthru parameter in the command, it displays the output in the console."
},
{
"code": null,
"e": 2157,
"s": 2024,
"text": "You can also rename items when you use the copy command. For that, you need to mention a new file name to the destination parameter."
},
{
"code": null,
"e": 2262,
"s": 2157,
"text": "Copy-Item -Path D:\\Temp\\PowerShellcommands.csv \n-Destination D:\\Temp1\\PowerShel lcommands1.csv -PassThru"
},
{
"code": null,
"e": 2594,
"s": 2262,
"text": "PS C:\\Windows\\System32> Copy-Item -Path D:\\Temp\\PowerShellcommands.csv -Destination D:\\Temp1\\PowerShellcommands1.csv -PassThru\n Directory: D:\\Temp1\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a---- 20-01-2020 12:10 1148809 PowerShellcommands1.csv"
},
{
"code": null,
"e": 2681,
"s": 2594,
"text": "While copying item(s) to another location, their attributes are also copies with them."
},
{
"code": null,
"e": 2888,
"s": 2681,
"text": "When you copy files from the source folder to the destination folder, and if the destination folder doesn’t exist then files(s) won’t get copied and it will throw an exception of DirectoryNotFoundException."
},
{
"code": null,
"e": 3022,
"s": 2888,
"text": "For example, we will copy the above mentioned PowerShellcommands1.csv file to the unknown destination folder D:\\Temp2 as shown below."
},
{
"code": null,
"e": 3125,
"s": 3022,
"text": "Copy-Item -Path D:\\Temp\\PowerShellcommands.csv -Destination D:\\Temp2\\PowerShel\nlcommands.csv -PassThru"
},
{
"code": null,
"e": 3698,
"s": 3125,
"text": "PS C:\\Windows\\System32> Copy-Item -Path D:\\Temp\\PowerShellcommands.csv -Destination D:\\Temp2\\PowerShellcommands.csv -PassThru\nCopy-Item : Could not find a part of the path 'D:\\Temp2\\PowerShellcommands.csv'.\nAt line:1 char:1\n+ Copy-Item -Path D:\\Temp\\PowerShellcommands.csv -Destination D:\\Temp2\\ ...\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n + CategoryInfo : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException\n + FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand"
}
]
|
PDFBox - Adding Text | In the previous chapter, we discussed how to add pages to a PDF document. In this chapter, we will discuss how to add text to an existing PDF document.
You can add contents to a document using the PDFBox library, this provides you a class named PDPageContentStream which contains the required methods to insert text, images, and other types of contents in a page of a PDFDocument.
Following are the steps to create an empty document and add contents to a page in it.
You can load an existing document using the load() method of the PDDocument class. Therefore, instantiate this class and load the required document as shown below.
File file = new File("Path of the document");
PDDocument doc = document.load(file);
You can get the required page in a document using the getPage() method. Retrieve the object of the required page by passing its index to this method as shown below.
PDPage page = doc.getPage(1);
You can insert various kinds of data elements using the object of the class PDPageContentStream. You need to pass the document object and the page object to the constructor of this class therefore, instantiate this class by passing these two objects created in the previous steps as shown below.
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
While inserting text in a PDF document, you can specify the start and end points of the text using the beginText() and endText() methods of the PDPageContentStream class as shown below.
contentStream.beginText();
.............................
code to add text content
.............................
contentStream.endText();
Therefore, begin the text using the beginText() method as shown below.
contentStream.beginText();
Using the newLineAtOffset() method, you can set the position on the content stream in the page.
//Setting the position for the line
contentStream.newLineAtOffset(25, 700);
You can set the font of the text to the required style using the setFont() method of the PDPageContentStream class as shown below. To this method you need to pass the type and size of the font.
contentStream.setFont( font_type, font_size );
You can insert the text into the page using the ShowText() method of the PDPageContentStream class as shown below. This method accepts the required text in the form of string.
contentStream.showText(text);
After inserting the text, you need to end the text using the endText() method of the PDPageContentStream class as shown below.
contentStream.endText();
Close the PDPageContentStream object using the close() method as shown below.
contentstream.close();
After adding the required content, save the PDF document using the save() method of the PDDocument class as shown in the following code block.
doc.save("Path");
Finally, close the document using the close() method of the PDDocument class as shown below.
doc.close();
This example demonstrates how to add contents to a page in a document. Here, we will create a Java program to load the PDF document named my_doc.pdf, which is saved in the path C:/PdfBox_Examples/, and add some text to it. Save this code in a file with name AddingContent.java.
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
public class AddingContent {
public static void main (String args[]) throws IOException {
//Loading an existing document
File file = new File("C:/PdfBox_Examples/my_doc.pdf");
PDDocument document = PDDocument.load(file);
//Retrieving the pages of the document
PDPage page = document.getPage(1);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
//Begin the Content stream
contentStream.beginText();
//Setting the font to the Content stream
contentStream.setFont(PDType1Font.TIMES_ROMAN, 12);
//Setting the position for the line
contentStream.newLineAtOffset(25, 500);
String text = "This is the sample document and we are adding content to it.";
//Adding text in the form of string
contentStream.showText(text);
//Ending the content stream
contentStream.endText();
System.out.println("Content added");
//Closing the content stream
contentStream.close();
//Saving the document
document.save(new File("C:/PdfBox_Examples/new.pdf"));
//Closing the document
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac AddingContent.java
java AddingContent
Upon execution, the above program adds the given text to the document and displays the following message.
Content added
If you verify the PDF Document new.pdf in the specified path, you can observe that the given content is added to the document as shown below.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2179,
"s": 2027,
"text": "In the previous chapter, we discussed how to add pages to a PDF document. In this chapter, we will discuss how to add text to an existing PDF document."
},
{
"code": null,
"e": 2408,
"s": 2179,
"text": "You can add contents to a document using the PDFBox library, this provides you a class named PDPageContentStream which contains the required methods to insert text, images, and other types of contents in a page of a PDFDocument."
},
{
"code": null,
"e": 2494,
"s": 2408,
"text": "Following are the steps to create an empty document and add contents to a page in it."
},
{
"code": null,
"e": 2658,
"s": 2494,
"text": "You can load an existing document using the load() method of the PDDocument class. Therefore, instantiate this class and load the required document as shown below."
},
{
"code": null,
"e": 2744,
"s": 2658,
"text": "File file = new File(\"Path of the document\"); \nPDDocument doc = document.load(file);\n"
},
{
"code": null,
"e": 2909,
"s": 2744,
"text": "You can get the required page in a document using the getPage() method. Retrieve the object of the required page by passing its index to this method as shown below."
},
{
"code": null,
"e": 2940,
"s": 2909,
"text": "PDPage page = doc.getPage(1);\n"
},
{
"code": null,
"e": 3236,
"s": 2940,
"text": "You can insert various kinds of data elements using the object of the class PDPageContentStream. You need to pass the document object and the page object to the constructor of this class therefore, instantiate this class by passing these two objects created in the previous steps as shown below."
},
{
"code": null,
"e": 3309,
"s": 3236,
"text": "PDPageContentStream contentStream = new PDPageContentStream(doc, page);\n"
},
{
"code": null,
"e": 3495,
"s": 3309,
"text": "While inserting text in a PDF document, you can specify the start and end points of the text using the beginText() and endText() methods of the PDPageContentStream class as shown below."
},
{
"code": null,
"e": 3637,
"s": 3495,
"text": "contentStream.beginText(); \n............................. \ncode to add text content \n............................. \ncontentStream.endText();\n"
},
{
"code": null,
"e": 3708,
"s": 3637,
"text": "Therefore, begin the text using the beginText() method as shown below."
},
{
"code": null,
"e": 3736,
"s": 3708,
"text": "contentStream.beginText();\n"
},
{
"code": null,
"e": 3832,
"s": 3736,
"text": "Using the newLineAtOffset() method, you can set the position on the content stream in the page."
},
{
"code": null,
"e": 3910,
"s": 3832,
"text": "//Setting the position for the line \ncontentStream.newLineAtOffset(25, 700);\n"
},
{
"code": null,
"e": 4104,
"s": 3910,
"text": "You can set the font of the text to the required style using the setFont() method of the PDPageContentStream class as shown below. To this method you need to pass the type and size of the font."
},
{
"code": null,
"e": 4152,
"s": 4104,
"text": "contentStream.setFont( font_type, font_size );\n"
},
{
"code": null,
"e": 4328,
"s": 4152,
"text": "You can insert the text into the page using the ShowText() method of the PDPageContentStream class as shown below. This method accepts the required text in the form of string."
},
{
"code": null,
"e": 4359,
"s": 4328,
"text": "contentStream.showText(text);\n"
},
{
"code": null,
"e": 4486,
"s": 4359,
"text": "After inserting the text, you need to end the text using the endText() method of the PDPageContentStream class as shown below."
},
{
"code": null,
"e": 4512,
"s": 4486,
"text": "contentStream.endText();\n"
},
{
"code": null,
"e": 4590,
"s": 4512,
"text": "Close the PDPageContentStream object using the close() method as shown below."
},
{
"code": null,
"e": 4614,
"s": 4590,
"text": "contentstream.close();\n"
},
{
"code": null,
"e": 4757,
"s": 4614,
"text": "After adding the required content, save the PDF document using the save() method of the PDDocument class as shown in the following code block."
},
{
"code": null,
"e": 4776,
"s": 4757,
"text": "doc.save(\"Path\");\n"
},
{
"code": null,
"e": 4869,
"s": 4776,
"text": "Finally, close the document using the close() method of the PDDocument class as shown below."
},
{
"code": null,
"e": 4883,
"s": 4869,
"text": "doc.close();\n"
},
{
"code": null,
"e": 5161,
"s": 4883,
"text": "This example demonstrates how to add contents to a page in a document. Here, we will create a Java program to load the PDF document named my_doc.pdf, which is saved in the path C:/PdfBox_Examples/, and add some text to it. Save this code in a file with name AddingContent.java."
},
{
"code": null,
"e": 6609,
"s": 5161,
"text": "import java.io.File; \nimport java.io.IOException;\n \nimport org.apache.pdfbox.pdmodel.PDDocument; \nimport org.apache.pdfbox.pdmodel.PDPage; \nimport org.apache.pdfbox.pdmodel.PDPageContentStream; \nimport org.apache.pdfbox.pdmodel.font.PDType1Font;\n \npublic class AddingContent {\n public static void main (String args[]) throws IOException {\n\n //Loading an existing document\n File file = new File(\"C:/PdfBox_Examples/my_doc.pdf\");\n PDDocument document = PDDocument.load(file);\n \n //Retrieving the pages of the document \n PDPage page = document.getPage(1);\n PDPageContentStream contentStream = new PDPageContentStream(document, page);\n \n //Begin the Content stream \n contentStream.beginText(); \n \n //Setting the font to the Content stream \n contentStream.setFont(PDType1Font.TIMES_ROMAN, 12);\n\n //Setting the position for the line \n contentStream.newLineAtOffset(25, 500);\n\n String text = \"This is the sample document and we are adding content to it.\";\n\n //Adding text in the form of string \n contentStream.showText(text); \n\n //Ending the content stream\n contentStream.endText();\n\n System.out.println(\"Content added\");\n\n //Closing the content stream\n contentStream.close();\n\n //Saving the document\n document.save(new File(\"C:/PdfBox_Examples/new.pdf\"));\n\n //Closing the document\n document.close();\n }\n}"
},
{
"code": null,
"e": 6703,
"s": 6609,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 6750,
"s": 6703,
"text": "javac AddingContent.java \njava AddingContent \n"
},
{
"code": null,
"e": 6856,
"s": 6750,
"text": "Upon execution, the above program adds the given text to the document and displays the following message."
},
{
"code": null,
"e": 6871,
"s": 6856,
"text": "Content added\n"
},
{
"code": null,
"e": 7013,
"s": 6871,
"text": "If you verify the PDF Document new.pdf in the specified path, you can observe that the given content is added to the document as shown below."
},
{
"code": null,
"e": 7020,
"s": 7013,
"text": " Print"
},
{
"code": null,
"e": 7031,
"s": 7020,
"text": " Add Notes"
}
]
|
jQuery - Theming | Jquery has two different styling themes as A And B.Each with different colors for buttons, bars, content blocks, and so on.
The syntax of J query theming as shown below −
<div data-role = "page" data-theme = "a|b">
A Simple of A theming Example as shown below −
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "stylesheet"
href = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src = "https://code.jquery.com/jquery-1.11.3.min.js">
</script>
<script src = "https://code.jquery.com/jquery-1.11.3.min.js">
</script>
<script
src = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js">
</script>
</head>
<body>
<div data-role = "page" id = "pageone" data-theme = "a">
<div data-role = "header">
<h1>Tutorials Point</h1>
</div>
<div data-role = "main" class = "ui-content">
<p>Text link</p>
<a href = "#">A Standard Text Link</a>
<a href = "#" class = "ui-btn">Link Button</a>
<p>A List View:</p>
<ul data-role = "listview" data-autodividers = "true" data-inset = "true">
<li><a href = "#">Android </a></li>
<li><a href = "#">IOS</a></li>
</ul>
<label for = "fullname">Input Field:</label>
<input type = "text" name = "fullname" id = "fullname"
placeholder = "Name..">
<label for = "switch">Toggle Switch:</label>
<select name = "switch" id = "switch" data-role = "slider">
<option value = "on">On</option>
<option value = "off" selected>Off</option>
</select>
</div>
<div data-role = "footer">
<h1>Tutorials point</h1>
</div>
</div>
</body>
</html>
This should produce following result −
Text link
A List View −
A
Android
I
IOS
A Simple of B theming Example as shown below −
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "stylesheet"
href = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src = "https://code.jquery.com/jquery-1.11.3.min.js">
</script>
<script src = "https://code.jquery.com/jquery-1.11.3.min.js">
</script>
<script
src = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js">
</script>
</head>
<body>
<div data-role = "page" id = "pageone" data-theme = "b">
<div data-role = "header">
<h1>Tutorials Point</h1>
</div>
<div data-role = "main" class = "ui-content">
<p>Text link</p>
<a href = "#">A Standard Text Link</a>
<a href = "#" class = "ui-btn">Link Button</a>
<p>A List View:</p>
<ul data-role = "listview" data-autodividers = "true" data-inset = "true">
<li><a href = "#">Android </a></li>
<li><a href = "#">IOS</a></li>
</ul>
<label for = "fullname">Input Field:</label>
<input type = "text" name = "fullname" id = "fullname"
placeholder = "Name..">
<label for = "switch">Toggle Switch:</label>
<select name = "switch" id = "switch" data-role = "slider">
<option value = "on">On</option>
<option value = "off" selected>Off</option>
</select>
</div>
<div data-role = "footer">
<h1>Tutorials point</h1>
</div>
</div>
</body>
</html>
This should produce following result −
Text link
A List View −
A
Android
I
IOS
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2446,
"s": 2322,
"text": "Jquery has two different styling themes as A And B.Each with different colors for buttons, bars, content blocks, and so on."
},
{
"code": null,
"e": 2493,
"s": 2446,
"text": "The syntax of J query theming as shown below −"
},
{
"code": null,
"e": 2538,
"s": 2493,
"text": "<div data-role = \"page\" data-theme = \"a|b\">\n"
},
{
"code": null,
"e": 2585,
"s": 2538,
"text": "A Simple of A theming Example as shown below −"
},
{
"code": null,
"e": 4293,
"s": 2585,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" \n href = \"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css\">\n\t\t\t\n <script src = \"https://code.jquery.com/jquery-1.11.3.min.js\">\n </script>\n <script src = \"https://code.jquery.com/jquery-1.11.3.min.js\">\n </script>\n <script \n src = \"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js\">\n </script>\n </head>\n\t\n <body>\n <div data-role = \"page\" id = \"pageone\" data-theme = \"a\">\n <div data-role = \"header\">\n <h1>Tutorials Point</h1>\n </div>\n\n <div data-role = \"main\" class = \"ui-content\">\n\t\t\t\n <p>Text link</p>\n <a href = \"#\">A Standard Text Link</a>\n <a href = \"#\" class = \"ui-btn\">Link Button</a>\n <p>A List View:</p>\n\t\t\t\t\n <ul data-role = \"listview\" data-autodividers = \"true\" data-inset = \"true\">\n <li><a href = \"#\">Android </a></li>\n <li><a href = \"#\">IOS</a></li>\n </ul>\n\t\t\t\t\n <label for = \"fullname\">Input Field:</label>\n <input type = \"text\" name = \"fullname\" id = \"fullname\" \n placeholder = \"Name..\"> \n <label for = \"switch\">Toggle Switch:</label>\n\t\t\t\t\n <select name = \"switch\" id = \"switch\" data-role = \"slider\">\n <option value = \"on\">On</option>\n <option value = \"off\" selected>Off</option>\n </select>\n\t\t\t\t\n </div>\n\n <div data-role = \"footer\">\n <h1>Tutorials point</h1>\n </div>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 4332,
"s": 4293,
"text": "This should produce following result −"
},
{
"code": null,
"e": 4342,
"s": 4332,
"text": "Text link"
},
{
"code": null,
"e": 4356,
"s": 4342,
"text": "A List View −"
},
{
"code": null,
"e": 4358,
"s": 4356,
"text": "A"
},
{
"code": null,
"e": 4367,
"s": 4358,
"text": "Android "
},
{
"code": null,
"e": 4369,
"s": 4367,
"text": "I"
},
{
"code": null,
"e": 4373,
"s": 4369,
"text": "IOS"
},
{
"code": null,
"e": 4420,
"s": 4373,
"text": "A Simple of B theming Example as shown below −"
},
{
"code": null,
"e": 6120,
"s": 4420,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" \n href = \"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css\">\n <script src = \"https://code.jquery.com/jquery-1.11.3.min.js\">\n </script>\n <script src = \"https://code.jquery.com/jquery-1.11.3.min.js\">\n </script>\n <script \n src = \"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js\">\n </script>\n </head>\n\t\n <body>\n <div data-role = \"page\" id = \"pageone\" data-theme = \"b\">\n <div data-role = \"header\">\n <h1>Tutorials Point</h1>\n </div>\n\n <div data-role = \"main\" class = \"ui-content\">\n <p>Text link</p>\n <a href = \"#\">A Standard Text Link</a>\n <a href = \"#\" class = \"ui-btn\">Link Button</a>\n <p>A List View:</p>\n\t\t\t\t\n <ul data-role = \"listview\" data-autodividers = \"true\" data-inset = \"true\">\n <li><a href = \"#\">Android </a></li>\n <li><a href = \"#\">IOS</a></li>\n </ul>\n\t\t\t\t\n <label for = \"fullname\">Input Field:</label>\n <input type = \"text\" name = \"fullname\" id = \"fullname\" \n placeholder = \"Name..\"> \n <label for = \"switch\">Toggle Switch:</label>\n\t\t\t\t\n <select name = \"switch\" id = \"switch\" data-role = \"slider\">\n <option value = \"on\">On</option>\n <option value = \"off\" selected>Off</option>\n </select>\n\t\t\t\t\n </div>\n\n <div data-role = \"footer\">\n <h1>Tutorials point</h1>\n </div>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 6159,
"s": 6120,
"text": "This should produce following result −"
},
{
"code": null,
"e": 6169,
"s": 6159,
"text": "Text link"
},
{
"code": null,
"e": 6183,
"s": 6169,
"text": "A List View −"
},
{
"code": null,
"e": 6185,
"s": 6183,
"text": "A"
},
{
"code": null,
"e": 6194,
"s": 6185,
"text": "Android "
},
{
"code": null,
"e": 6196,
"s": 6194,
"text": "I"
},
{
"code": null,
"e": 6200,
"s": 6196,
"text": "IOS"
},
{
"code": null,
"e": 6233,
"s": 6200,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6247,
"s": 6233,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 6282,
"s": 6247,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6296,
"s": 6282,
"text": " Pratik Singh"
},
{
"code": null,
"e": 6331,
"s": 6296,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6348,
"s": 6331,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6381,
"s": 6348,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6409,
"s": 6381,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6442,
"s": 6409,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6463,
"s": 6442,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 6495,
"s": 6463,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 6512,
"s": 6495,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 6519,
"s": 6512,
"text": " Print"
},
{
"code": null,
"e": 6530,
"s": 6519,
"text": " Add Notes"
}
]
|
Assign value to unique number in list in Python | Many times we need to identify the elements in a list uniquely. For that we need to assign unique IDs to each element in the list. This can be achieved by the following two approaches using different inbuilt functions available in Python.
The enumerate function assigns unique ids to each element. But if the list already as duplicate elements then we need to create a dictionary of key value pairs form the list and assign unique values using the set function.
Live Demo
# Given List
Alist = [5,3,3,12]
print("The given list : ",Alist)
# Assigning ids to values
enum_dict = {v: k for k, v in enumerate(set(Alist))}
list_ids = [enum_dict[n] for n in Alist]
# Print ids of the dictionary
print("The list of unique ids is: ",list_ids)
Running the above code gives us the following result −
The given list : [5, 3, 3, 12]
The list of unique ids is: [2, 0, 0, 1]
The map() function applies the same function again and again to the different parameters passed to it. But the count method returns the number of elements with the specified value. So we combine these two get the list of unique IDs for the elements of a given list in the below program.
from itertools import count
# Given List
Alist = [5,3,3,12]
print("The given list : ",Alist)
# Assign unique value to list elements
dict_ids = list(map({}.setdefault, Alist, count()))
# The result
print("The list of unique ids is: ",dict_ids)
Running the above code gives us the following result −
The given list : [5, 3, 3, 12]
The list of unique ids is: [0, 1, 1, 3] | [
{
"code": null,
"e": 1301,
"s": 1062,
"text": "Many times we need to identify the elements in a list uniquely. For that we need to assign unique IDs to each element in the list. This can be achieved by the following two approaches using different inbuilt functions available in Python."
},
{
"code": null,
"e": 1524,
"s": 1301,
"text": "The enumerate function assigns unique ids to each element. But if the list already as duplicate elements then we need to create a dictionary of key value pairs form the list and assign unique values using the set function."
},
{
"code": null,
"e": 1535,
"s": 1524,
"text": " Live Demo"
},
{
"code": null,
"e": 1798,
"s": 1535,
"text": "# Given List\nAlist = [5,3,3,12]\nprint(\"The given list : \",Alist)\n\n# Assigning ids to values\nenum_dict = {v: k for k, v in enumerate(set(Alist))}\nlist_ids = [enum_dict[n] for n in Alist]\n\n# Print ids of the dictionary\nprint(\"The list of unique ids is: \",list_ids)"
},
{
"code": null,
"e": 1853,
"s": 1798,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1924,
"s": 1853,
"text": "The given list : [5, 3, 3, 12]\nThe list of unique ids is: [2, 0, 0, 1]"
},
{
"code": null,
"e": 2211,
"s": 1924,
"text": "The map() function applies the same function again and again to the different parameters passed to it. But the count method returns the number of elements with the specified value. So we combine these two get the list of unique IDs for the elements of a given list in the below program."
},
{
"code": null,
"e": 2457,
"s": 2211,
"text": "from itertools import count\n\n# Given List\nAlist = [5,3,3,12]\nprint(\"The given list : \",Alist)\n\n# Assign unique value to list elements\ndict_ids = list(map({}.setdefault, Alist, count()))\n\n# The result\nprint(\"The list of unique ids is: \",dict_ids)"
},
{
"code": null,
"e": 2512,
"s": 2457,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2583,
"s": 2512,
"text": "The given list : [5, 3, 3, 12]\nThe list of unique ids is: [0, 1, 1, 3]"
}
]
|
Commonly used String functions in C/C++ with Examples - GeeksforGeeks | 29 Aug, 2021
Strings in C: Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’. Some of the most commonly used String functions are:
strcat: The strcat() function will append a copy of the source string to the end of destination string. The strcat() function takes two arguments: 1) dest 2) src It will append copy of the source string in the destination string. The terminating character at the end of dest is replaced by the first character of src . Return value: The strcat() function returns dest, the pointer to the destination string.
CPP
// CPP program to demonstrate// strcat#include <cstring>#include <iostream>using namespace std;int main(){ char dest[50] = "This is an"; char src[50] = " example"; strcat(dest, src); cout << dest; return 0;}
This is an example
strrchr: In C/C++, strrchr() is a predefined function used for string handling. cstring is the header file required for string functions.This function Returns a pointer to the last occurrence of a character in a string. The character whose last occurrence we want to find in passed as the second argument to the function and the string in which we have to find the character is passed as the first argument to the function. Syntax
char *strrchr(const char *str, int c)
Here, str is the string and c is the character to be located. It is passed as its int promotion, but it is internally converted back to char.Example:
C++
C
// C++ code to demonstrate the working of// strrchr()#include <cstring>#include <iostream>using namespace std; // Driver functionint main(){ // initializing variables char st[] = "GeeksforGeeks"; char ch = 'e'; char* val; // Use of strrchr() // returns "ks" val = strrchr(st, ch); cout <<"String after last " << ch << " is : " << val << endl; char ch2 = 'm'; // Use of strrchr() // returns null // test for null val = strrchr(st, ch2); cout <<"String after last " << ch2 << " is : " << val << endl; return (0);} // This code is contributed by shivanisinghss2110
// C code to demonstrate the working of// strrchr() #include <stdio.h>#include <string.h> // Driver functionint main(){ // initializing variables char st[] = "GeeksforGeeks"; char ch = 'e'; char* val; // Use of strrchr() // returns "ks" val = strrchr(st, ch); printf("String after last %c is : %s \n", ch, val); char ch2 = 'm'; // Use of strrchr() // returns null // test for null val = strrchr(st, ch2); printf("String after last %c is : %s ", ch2, val); return (0);}
String after last e is : eks
String after last m is : (null)
strcmp: strcmp() is a built-in library function and is declared in <string.h> header file. This function takes two strings as arguments and compare these two strings lexicographically.Syntax::
int strcmp(const char *leftStr, const char *rightStr );
In the above prototype, function srtcmp takes two strings as parameters and returns an integer value based on the comparison of strings. strcmp() compares the two strings lexicographically means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered.If first character in both strings are equal, then this function will check the second character, if this is also equal then it will check the third and so onThis process will be continued until a character in either string is NULL or the characters are unequal.
strcmp() compares the two strings lexicographically means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered.
If first character in both strings are equal, then this function will check the second character, if this is also equal then it will check the third and so on
This process will be continued until a character in either string is NULL or the characters are unequal.
strcpy: strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in string.h header file and in C++ it is present in cstring header file. Syntax:
char* strcpy(char* dest, const char* src);
Parameters: This method accepts following parameters: dest: Pointer to the destination array where the content is to be copied. src: string which will be copied.
dest: Pointer to the destination array where the content is to be copied.
src: string which will be copied.
strlen: The strlen() function calculates the length of a given string.The strlen() function is defined in string.h header file. It doesn’t count null character ‘\0’.Syntax:
int strlen(const char *str);
Parameter: str: It represents the string variable whose length we have to find.
str: It represents the string variable whose length we have to find.
strncat: In C/C++, strncat() is a predefined function used for string handling. string.h is the header file required for string functions.This function appends not more than n characters from the string pointed to by src to the end of the string pointed to by dest plus a terminating Null-character. The initial character of string(src) overwrites the Null-character present at the end of string(dest). Thus, length of the string(dest) becomes strlen(dest)+n. But, if the length of the string(src) is less than n, only the content up to the terminating null-character is copied and length of the string(dest) becomes strlen(src) + strlen(dest).The behavior is undefined if the strings overlap.the dest array is not large enough to append the contents of src.dest: the string where we want to append.src: the string from which ‘n’ characters are going to append.n: represents maximum number of character to be appended. size_t is an unsigned integral type.
the strings overlap.
the dest array is not large enough to append the contents of src.
dest: the string where we want to append.
src: the string from which ‘n’ characters are going to append.
n: represents maximum number of character to be appended. size_t is an unsigned integral type.
strncmp: std::strncmp() function lexicographically compares not more than count characters from the two null-terminated strings and returns an integer based on the outcome. This function takes two strings and a number num as arguments and compare at most first num bytes of both the strings.num should be at most equal to the length of the longest string. If num is defined greater than the string length than comparison is done till the null-character(‘\0’) of either string.This function compares the two strings lexicographically. It starts comparison from the first character of each string. If they are equal to each other, it continues and compare the next character of each string and so on.This process of comparison stops until a terminating null-character of either string is reached or num characters of both the strings matches.
This function takes two strings and a number num as arguments and compare at most first num bytes of both the strings.
num should be at most equal to the length of the longest string. If num is defined greater than the string length than comparison is done till the null-character(‘\0’) of either string.
This function compares the two strings lexicographically. It starts comparison from the first character of each string. If they are equal to each other, it continues and compare the next character of each string and so on.
This process of comparison stops until a terminating null-character of either string is reached or num characters of both the strings matches.
strncpy: The strncpy() function is similar to strcpy() function, except that at most n bytes of src are copied. If there is no NULL character among the first n character of src, the string placed in dest will not be NULL-terminated. If the length of src is less than n, strncpy() writes additional NULL character to dest to ensure that a total of n character are written.Syntax:
char *strncpy( char *dest, const char *src, size_t n )
Parameters: This function accepts two parameters as mentioned above and described below: src: The string which will be copied.dest: Pointer to the destination array where the content is to be copied.n: The first n character copied from src to dest.
src: The string which will be copied.
dest: Pointer to the destination array where the content is to be copied.
n: The first n character copied from src to dest.
strrchr: The strrchr() function in C/C++ locates the last occurrence of a character in a string. It returns a pointer to the last occurrence in the string. The terminating null character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string. It is defined in cstring header file. Syntax :
const char* strrchr( const char* str, int ch )
or
char* strrchr( char* str, int ch )
Parameter :The function takes two mandatory parameters which are described below: str : specifies the pointer to the null terminated string to be searched for.ch: specifies the character to be search for.
str : specifies the pointer to the null terminated string to be searched for.
ch: specifies the character to be search for.
APURVBAJAJ1
shivanisinghss2110
simmytarika5
C-Functions
C-String
CPP-Functions
cpp-string
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Core Dump (Segmentation fault) in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Operator Overloading in C++
Constructors in C++ | [
{
"code": null,
"e": 24352,
"s": 24324,
"text": "\n29 Aug, 2021"
},
{
"code": null,
"e": 24579,
"s": 24352,
"text": "Strings in C: Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\\0’. Some of the most commonly used String functions are:"
},
{
"code": null,
"e": 24988,
"s": 24579,
"text": "strcat: The strcat() function will append a copy of the source string to the end of destination string. The strcat() function takes two arguments: 1) dest 2) src It will append copy of the source string in the destination string. The terminating character at the end of dest is replaced by the first character of src . Return value: The strcat() function returns dest, the pointer to the destination string. "
},
{
"code": null,
"e": 24992,
"s": 24988,
"text": "CPP"
},
{
"code": "// CPP program to demonstrate// strcat#include <cstring>#include <iostream>using namespace std;int main(){ char dest[50] = \"This is an\"; char src[50] = \" example\"; strcat(dest, src); cout << dest; return 0;}",
"e": 25216,
"s": 24992,
"text": null
},
{
"code": null,
"e": 25235,
"s": 25216,
"text": "This is an example"
},
{
"code": null,
"e": 25669,
"s": 25237,
"text": "strrchr: In C/C++, strrchr() is a predefined function used for string handling. cstring is the header file required for string functions.This function Returns a pointer to the last occurrence of a character in a string. The character whose last occurrence we want to find in passed as the second argument to the function and the string in which we have to find the character is passed as the first argument to the function. Syntax "
},
{
"code": null,
"e": 25708,
"s": 25669,
"text": "char *strrchr(const char *str, int c) "
},
{
"code": null,
"e": 25859,
"s": 25708,
"text": "Here, str is the string and c is the character to be located. It is passed as its int promotion, but it is internally converted back to char.Example: "
},
{
"code": null,
"e": 25863,
"s": 25859,
"text": "C++"
},
{
"code": null,
"e": 25865,
"s": 25863,
"text": "C"
},
{
"code": "// C++ code to demonstrate the working of// strrchr()#include <cstring>#include <iostream>using namespace std; // Driver functionint main(){ // initializing variables char st[] = \"GeeksforGeeks\"; char ch = 'e'; char* val; // Use of strrchr() // returns \"ks\" val = strrchr(st, ch); cout <<\"String after last \" << ch << \" is : \" << val << endl; char ch2 = 'm'; // Use of strrchr() // returns null // test for null val = strrchr(st, ch2); cout <<\"String after last \" << ch2 << \" is : \" << val << endl; return (0);} // This code is contributed by shivanisinghss2110",
"e": 26481,
"s": 25865,
"text": null
},
{
"code": "// C code to demonstrate the working of// strrchr() #include <stdio.h>#include <string.h> // Driver functionint main(){ // initializing variables char st[] = \"GeeksforGeeks\"; char ch = 'e'; char* val; // Use of strrchr() // returns \"ks\" val = strrchr(st, ch); printf(\"String after last %c is : %s \\n\", ch, val); char ch2 = 'm'; // Use of strrchr() // returns null // test for null val = strrchr(st, ch2); printf(\"String after last %c is : %s \", ch2, val); return (0);}",
"e": 27024,
"s": 26481,
"text": null
},
{
"code": null,
"e": 27088,
"s": 27024,
"text": "String after last e is : eks \nString after last m is : (null)"
},
{
"code": null,
"e": 27284,
"s": 27090,
"text": "strcmp: strcmp() is a built-in library function and is declared in <string.h> header file. This function takes two strings as arguments and compare these two strings lexicographically.Syntax:: "
},
{
"code": null,
"e": 27340,
"s": 27284,
"text": "int strcmp(const char *leftStr, const char *rightStr );"
},
{
"code": null,
"e": 27958,
"s": 27340,
"text": "In the above prototype, function srtcmp takes two strings as parameters and returns an integer value based on the comparison of strings. strcmp() compares the two strings lexicographically means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered.If first character in both strings are equal, then this function will check the second character, if this is also equal then it will check the third and so onThis process will be continued until a character in either string is NULL or the characters are unequal."
},
{
"code": null,
"e": 28177,
"s": 27958,
"text": "strcmp() compares the two strings lexicographically means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered."
},
{
"code": null,
"e": 28336,
"s": 28177,
"text": "If first character in both strings are equal, then this function will check the second character, if this is also equal then it will check the third and so on"
},
{
"code": null,
"e": 28441,
"s": 28336,
"text": "This process will be continued until a character in either string is NULL or the characters are unequal."
},
{
"code": null,
"e": 28642,
"s": 28441,
"text": "strcpy: strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in string.h header file and in C++ it is present in cstring header file. Syntax: "
},
{
"code": null,
"e": 28685,
"s": 28642,
"text": "char* strcpy(char* dest, const char* src);"
},
{
"code": null,
"e": 28850,
"s": 28685,
"text": "Parameters: This method accepts following parameters: dest: Pointer to the destination array where the content is to be copied. src: string which will be copied. "
},
{
"code": null,
"e": 28926,
"s": 28850,
"text": "dest: Pointer to the destination array where the content is to be copied. "
},
{
"code": null,
"e": 28962,
"s": 28926,
"text": "src: string which will be copied. "
},
{
"code": null,
"e": 29136,
"s": 28962,
"text": "strlen: The strlen() function calculates the length of a given string.The strlen() function is defined in string.h header file. It doesn’t count null character ‘\\0’.Syntax: "
},
{
"code": null,
"e": 29165,
"s": 29136,
"text": "int strlen(const char *str);"
},
{
"code": null,
"e": 29245,
"s": 29165,
"text": "Parameter: str: It represents the string variable whose length we have to find."
},
{
"code": null,
"e": 29314,
"s": 29245,
"text": "str: It represents the string variable whose length we have to find."
},
{
"code": null,
"e": 30270,
"s": 29314,
"text": "strncat: In C/C++, strncat() is a predefined function used for string handling. string.h is the header file required for string functions.This function appends not more than n characters from the string pointed to by src to the end of the string pointed to by dest plus a terminating Null-character. The initial character of string(src) overwrites the Null-character present at the end of string(dest). Thus, length of the string(dest) becomes strlen(dest)+n. But, if the length of the string(src) is less than n, only the content up to the terminating null-character is copied and length of the string(dest) becomes strlen(src) + strlen(dest).The behavior is undefined if the strings overlap.the dest array is not large enough to append the contents of src.dest: the string where we want to append.src: the string from which ‘n’ characters are going to append.n: represents maximum number of character to be appended. size_t is an unsigned integral type."
},
{
"code": null,
"e": 30291,
"s": 30270,
"text": "the strings overlap."
},
{
"code": null,
"e": 30357,
"s": 30291,
"text": "the dest array is not large enough to append the contents of src."
},
{
"code": null,
"e": 30399,
"s": 30357,
"text": "dest: the string where we want to append."
},
{
"code": null,
"e": 30462,
"s": 30399,
"text": "src: the string from which ‘n’ characters are going to append."
},
{
"code": null,
"e": 30557,
"s": 30462,
"text": "n: represents maximum number of character to be appended. size_t is an unsigned integral type."
},
{
"code": null,
"e": 31398,
"s": 30557,
"text": "strncmp: std::strncmp() function lexicographically compares not more than count characters from the two null-terminated strings and returns an integer based on the outcome. This function takes two strings and a number num as arguments and compare at most first num bytes of both the strings.num should be at most equal to the length of the longest string. If num is defined greater than the string length than comparison is done till the null-character(‘\\0’) of either string.This function compares the two strings lexicographically. It starts comparison from the first character of each string. If they are equal to each other, it continues and compare the next character of each string and so on.This process of comparison stops until a terminating null-character of either string is reached or num characters of both the strings matches."
},
{
"code": null,
"e": 31517,
"s": 31398,
"text": "This function takes two strings and a number num as arguments and compare at most first num bytes of both the strings."
},
{
"code": null,
"e": 31703,
"s": 31517,
"text": "num should be at most equal to the length of the longest string. If num is defined greater than the string length than comparison is done till the null-character(‘\\0’) of either string."
},
{
"code": null,
"e": 31926,
"s": 31703,
"text": "This function compares the two strings lexicographically. It starts comparison from the first character of each string. If they are equal to each other, it continues and compare the next character of each string and so on."
},
{
"code": null,
"e": 32069,
"s": 31926,
"text": "This process of comparison stops until a terminating null-character of either string is reached or num characters of both the strings matches."
},
{
"code": null,
"e": 32449,
"s": 32069,
"text": "strncpy: The strncpy() function is similar to strcpy() function, except that at most n bytes of src are copied. If there is no NULL character among the first n character of src, the string placed in dest will not be NULL-terminated. If the length of src is less than n, strncpy() writes additional NULL character to dest to ensure that a total of n character are written.Syntax: "
},
{
"code": null,
"e": 32504,
"s": 32449,
"text": "char *strncpy( char *dest, const char *src, size_t n )"
},
{
"code": null,
"e": 32753,
"s": 32504,
"text": "Parameters: This function accepts two parameters as mentioned above and described below: src: The string which will be copied.dest: Pointer to the destination array where the content is to be copied.n: The first n character copied from src to dest."
},
{
"code": null,
"e": 32791,
"s": 32753,
"text": "src: The string which will be copied."
},
{
"code": null,
"e": 32865,
"s": 32791,
"text": "dest: Pointer to the destination array where the content is to be copied."
},
{
"code": null,
"e": 32915,
"s": 32865,
"text": "n: The first n character copied from src to dest."
},
{
"code": null,
"e": 33266,
"s": 32915,
"text": "strrchr: The strrchr() function in C/C++ locates the last occurrence of a character in a string. It returns a pointer to the last occurrence in the string. The terminating null character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string. It is defined in cstring header file. Syntax : "
},
{
"code": null,
"e": 33363,
"s": 33266,
"text": "const char* strrchr( const char* str, int ch )\n or\nchar* strrchr( char* str, int ch )"
},
{
"code": null,
"e": 33568,
"s": 33363,
"text": "Parameter :The function takes two mandatory parameters which are described below: str : specifies the pointer to the null terminated string to be searched for.ch: specifies the character to be search for."
},
{
"code": null,
"e": 33646,
"s": 33568,
"text": "str : specifies the pointer to the null terminated string to be searched for."
},
{
"code": null,
"e": 33692,
"s": 33646,
"text": "ch: specifies the character to be search for."
},
{
"code": null,
"e": 33704,
"s": 33692,
"text": "APURVBAJAJ1"
},
{
"code": null,
"e": 33723,
"s": 33704,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 33736,
"s": 33723,
"text": "simmytarika5"
},
{
"code": null,
"e": 33748,
"s": 33736,
"text": "C-Functions"
},
{
"code": null,
"e": 33757,
"s": 33748,
"text": "C-String"
},
{
"code": null,
"e": 33771,
"s": 33757,
"text": "CPP-Functions"
},
{
"code": null,
"e": 33782,
"s": 33771,
"text": "cpp-string"
},
{
"code": null,
"e": 33793,
"s": 33782,
"text": "C Language"
},
{
"code": null,
"e": 33797,
"s": 33793,
"text": "C++"
},
{
"code": null,
"e": 33801,
"s": 33797,
"text": "CPP"
},
{
"code": null,
"e": 33899,
"s": 33801,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33934,
"s": 33899,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 33962,
"s": 33934,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 34002,
"s": 33962,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 34048,
"s": 34002,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 34060,
"s": 34048,
"text": "fork() in C"
},
{
"code": null,
"e": 34078,
"s": 34060,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 34124,
"s": 34078,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 34167,
"s": 34124,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 34195,
"s": 34167,
"text": "Operator Overloading in C++"
}
]
|
Python program to check if the string is pangram | In this tutorial, we are going to write a program that checks whether a string is a pangram or not. Let's start the tutorial by talking about the pangram.
If a string contains all the alphabets whether small or caps then, the string is called panagram.
We can achieve the goal in different ways. Let's see two of them in this tutorial.
Try to write the program using the following steps.
1. Import the string module.
2. Initialize a variable with ascii_lowercase string. string.ascii_lowercase Contains all the
alphabets as a string.
3. Initialize the string which we have to check for pangram.
4. Define a function called is_anagram(string, alphabets).
4.1. Loop over the alphabets.
4.1.1. If the character from alphabets is not in the string.
4.1.1.1. Return False
4.2. Return True
5. Print pangram if the returned value is true else print not pangram.
## importing string module
import string
## function to check for the panagram
def is_panagram(string, alphabets):
## looping over the alphabets
for char in alphabets:
## if char is not present in string
if char not in string.lower():
## returning false
return False
return True
## initializing alphabets variable
alphabets = string.ascii_lowercase
## initializing strings
string_one = "The Quick Brown Fox Jumps Over The Lazy Dog"
string_two = "TutorialsPoint TutorialsPoint"
print("Panagram") if is_panagram(string_one, alphabets) else print("Not Panagram")
print("Panagram") if is_panagram(string_two, alphabets) else print("Not Panagram")
If you run the above program, you will get the following results.
Panagram
Not Panagram
Let's see how to get the same results using sets data structure. See the steps below to get an idea.
1. Import the string module.
2. Initialize a variable with ascii_lowercase string. string.ascii_lowercase contains all the alphabets as a string.
3. Initialize the string which we have to check for pangram.
4. Convert both alphabets and string(lower) to sets.
5. Print pangram if string set is greater than or equal to alphabets set else print not pangram.
Let's write the code.
Live Demo
## importing string module
import string
## initializing alphabets variable
alphabets = string.ascii_lowercase
## initializing strings
string_one = "The Quick Brown Fox Jumps Over The Lazy Dog"
string_two = "TutorialsPoint TutorialsPoint"
print("Panagram") if set(string_one.lower()) >= set(alphabets) else print("Not Pana gram")
print("Panagram") if set(string_two.lower()) >= set(alphabets) else print("Not Pana gram")
If you run the above program, you will get the following results.
Panagram
Not Panagram
If you have any doubts regarding the tutorial, please do mention them in the comment section. | [
{
"code": null,
"e": 1217,
"s": 1062,
"text": "In this tutorial, we are going to write a program that checks whether a string is a pangram or not. Let's start the tutorial by talking about the pangram."
},
{
"code": null,
"e": 1315,
"s": 1217,
"text": "If a string contains all the alphabets whether small or caps then, the string is called panagram."
},
{
"code": null,
"e": 1398,
"s": 1315,
"text": "We can achieve the goal in different ways. Let's see two of them in this tutorial."
},
{
"code": null,
"e": 1450,
"s": 1398,
"text": "Try to write the program using the following steps."
},
{
"code": null,
"e": 1938,
"s": 1450,
"text": "1. Import the string module.\n2. Initialize a variable with ascii_lowercase string. string.ascii_lowercase Contains all the\nalphabets as a string.\n3. Initialize the string which we have to check for pangram.\n4. Define a function called is_anagram(string, alphabets).\n 4.1. Loop over the alphabets.\n 4.1.1. If the character from alphabets is not in the string.\n 4.1.1.1. Return False\n 4.2. Return True\n5. Print pangram if the returned value is true else print not pangram."
},
{
"code": null,
"e": 2620,
"s": 1938,
"text": "## importing string module\nimport string\n## function to check for the panagram\ndef is_panagram(string, alphabets):\n ## looping over the alphabets\n for char in alphabets:\n ## if char is not present in string\n if char not in string.lower():\n ## returning false\n return False\n return True\n## initializing alphabets variable\nalphabets = string.ascii_lowercase\n## initializing strings\nstring_one = \"The Quick Brown Fox Jumps Over The Lazy Dog\"\nstring_two = \"TutorialsPoint TutorialsPoint\"\nprint(\"Panagram\") if is_panagram(string_one, alphabets) else print(\"Not Panagram\")\nprint(\"Panagram\") if is_panagram(string_two, alphabets) else print(\"Not Panagram\")"
},
{
"code": null,
"e": 2686,
"s": 2620,
"text": "If you run the above program, you will get the following results."
},
{
"code": null,
"e": 2708,
"s": 2686,
"text": "Panagram\nNot Panagram"
},
{
"code": null,
"e": 2809,
"s": 2708,
"text": "Let's see how to get the same results using sets data structure. See the steps below to get an idea."
},
{
"code": null,
"e": 3166,
"s": 2809,
"text": "1. Import the string module.\n2. Initialize a variable with ascii_lowercase string. string.ascii_lowercase contains all the alphabets as a string.\n3. Initialize the string which we have to check for pangram.\n4. Convert both alphabets and string(lower) to sets.\n5. Print pangram if string set is greater than or equal to alphabets set else print not pangram."
},
{
"code": null,
"e": 3188,
"s": 3166,
"text": "Let's write the code."
},
{
"code": null,
"e": 3199,
"s": 3188,
"text": " Live Demo"
},
{
"code": null,
"e": 3620,
"s": 3199,
"text": "## importing string module\nimport string\n## initializing alphabets variable\nalphabets = string.ascii_lowercase\n## initializing strings\nstring_one = \"The Quick Brown Fox Jumps Over The Lazy Dog\"\nstring_two = \"TutorialsPoint TutorialsPoint\"\nprint(\"Panagram\") if set(string_one.lower()) >= set(alphabets) else print(\"Not Pana gram\")\nprint(\"Panagram\") if set(string_two.lower()) >= set(alphabets) else print(\"Not Pana gram\")"
},
{
"code": null,
"e": 3686,
"s": 3620,
"text": "If you run the above program, you will get the following results."
},
{
"code": null,
"e": 3708,
"s": 3686,
"text": "Panagram\nNot Panagram"
},
{
"code": null,
"e": 3802,
"s": 3708,
"text": "If you have any doubts regarding the tutorial, please do mention them in the comment section."
}
]
|
What is NgStyle in Angular 10 ? - GeeksforGeeks | 30 Apr, 2021
In this article, we are going to see what is NgStyle in Angular 10 and how to use it.
NgStyle is used to add some style to an HTML element
Syntax:
<element [ngStyle] = "typescript_property">
Approach:
Create the Angular app to be used
In app.component.html make an element and sets its class using ngStyle directive
Serve the angular app using ng serve to see the output
Example 1:
app.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { }
app.component.html
<div [ngStyle] ="{'background-color':'green'}"> GeeksforGeeks</div> <div [ngStyle] ="{'color':'GREEN'}"> GeeksforGeeks</div>
Output:
Angular10
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 25195,
"s": 25109,
"text": "In this article, we are going to see what is NgStyle in Angular 10 and how to use it."
},
{
"code": null,
"e": 25248,
"s": 25195,
"text": "NgStyle is used to add some style to an HTML element"
},
{
"code": null,
"e": 25256,
"s": 25248,
"text": "Syntax:"
},
{
"code": null,
"e": 25300,
"s": 25256,
"text": "<element [ngStyle] = \"typescript_property\">"
},
{
"code": null,
"e": 25311,
"s": 25300,
"text": "Approach: "
},
{
"code": null,
"e": 25345,
"s": 25311,
"text": "Create the Angular app to be used"
},
{
"code": null,
"e": 25426,
"s": 25345,
"text": "In app.component.html make an element and sets its class using ngStyle directive"
},
{
"code": null,
"e": 25481,
"s": 25426,
"text": "Serve the angular app using ng serve to see the output"
},
{
"code": null,
"e": 25492,
"s": 25481,
"text": "Example 1:"
},
{
"code": null,
"e": 25509,
"s": 25492,
"text": "app.component.ts"
},
{
"code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { }",
"e": 25672,
"s": 25509,
"text": null
},
{
"code": null,
"e": 25691,
"s": 25672,
"text": "app.component.html"
},
{
"code": "<div [ngStyle] =\"{'background-color':'green'}\"> GeeksforGeeks</div> <div [ngStyle] =\"{'color':'GREEN'}\"> GeeksforGeeks</div>",
"e": 25819,
"s": 25691,
"text": null
},
{
"code": null,
"e": 25827,
"s": 25819,
"text": "Output:"
},
{
"code": null,
"e": 25837,
"s": 25827,
"text": "Angular10"
},
{
"code": null,
"e": 25847,
"s": 25837,
"text": "AngularJS"
},
{
"code": null,
"e": 25864,
"s": 25847,
"text": "Web Technologies"
},
{
"code": null,
"e": 25962,
"s": 25864,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25971,
"s": 25962,
"text": "Comments"
},
{
"code": null,
"e": 25984,
"s": 25971,
"text": "Old Comments"
},
{
"code": null,
"e": 26028,
"s": 25984,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 26092,
"s": 26028,
"text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?"
},
{
"code": null,
"e": 26145,
"s": 26092,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 26169,
"s": 26145,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 26204,
"s": 26169,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 26246,
"s": 26204,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26279,
"s": 26246,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26322,
"s": 26279,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26384,
"s": 26322,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
Android App Development Fundamentals for Beginners - GeeksforGeeks | 25 May, 2021
Android is an operating system that is built basically for Mobile phones. It is based on the Linux Kernel and other open-source software and is developed by Google. It is used for touchscreen mobile devices such as smartphones and tablets. But nowadays these are used in Android Auto cars, TV, watches, camera, etc. It has been one of the best-selling OS for smartphones. Android OS was developed by Android Inc. which Google bought in 2005. Various applications (apps) like games, music player, camera, etc. are built for these smartphones for running on Android. Google Play store features more than 3.3 million apps. The app is developed on an application known as Android Studio. These executable apps are installed through a bundle or package called APK(Android Package Kit).
1. Android Programming Languages
In Android, basically, programming is done in two languages JAVA or C++ and XML(Extension Markup Language). Nowadays KOTLIN is also preferred. The XML file deals with the design, presentation, layouts, blueprint, etc (as a front-end) while the JAVA or KOTLIN deals with the working of buttons, variables, storing, etc (as a back-end).
2. Android Components
The App components are the building blocks of Android. Each component has its own role and life cycles i.e from launching of an app till the end. Some of these components depend upon others also. Each component has a definite purpose. The four major app components are:
Activities
Services
Broadcast Receivers:
Content Provider:
Activities: It deals with the UI and the user interactions to the screen. In other words, it is a User Interface that contains activities. These can be one or more depending upon the App. It starts when the application is launched. At least one activity is always present which is known as MainActivity. The activity is implemented through the following.
Syntax:
public class MainActivity extends Activity{
// processes
}
To know more Activities please refer to this article: Introduction to Activities in Android
Services: Services are the background actions performed by the app, these might be long-running operations like a user playing music while surfing the Internet. A service might need other sub-services so as to perform specific tasks. The main purpose of the Services is to provide non-stop working of the app without breaking any interaction with the user.
Syntax:
public class MyServices extends Services{
// code for the services
}
To know more Services please refer to this article: Services in Android with Example
Broadcast Receivers: A Broadcast is used to respond to messages from other applications or from the System. For example, when the battery of the phone is low, then the Android OS fires a Broadcasting message to launch the Battery Saver function or app, after receiving the message the appropriate action is taken by the app. Broadcast Receiver is the subclass of BroadcastReceiver class and each object is represented by Intent objects.
Syntax:
public class MyReceiver extends BroadcastReceiver{
public void onReceive(context,intent){
}
To know more Broadcast Receivers please refer to this article: Broadcast Receiver in Android With Example
Content Provider: Content Provider is used to transferring the data from one application to the others at the request of the other application. These are handled by the class ContentResolver class. This class implements a set of APIs(Application Programming Interface) that enables the other applications to perform the transactions. Any Content Provider must implement the Parent Class of ContentProvider class.
Syntax:
public class MyContentProvider extends ContentProvider{
public void onCreate()
{}
}
To know more Content Provider please refer to this article: Content Providers in Android with Example
3. Structural Layout Of Android Studio
The basic structural layout of Android Studio is given below:
The above figure represents the various structure of an app.
Manifest Folder: Android Manifest is an XML file that is the root of the project source set. It describes the essential information about the app and the Android build tools, the Android Operating System, and Google Play. It contains the permission that an app might need in order to perform a specific task. It also contains the Hardware and the Software features of the app, which determines the compatibility of an app on the Play Store. It also includes special activities like services, broadcast receiver, content providers, package name, etc.
Java Folder: The JAVA folder consists of the java files that are required to perform the background task of the app. It consists of the functionality of the buttons, calculation, storing, variables, toast(small popup message), programming function, etc. The number of these files depends upon the type of activities created.
Resource Folder: The res or Resource folder consists of the various resources that are used in the app. This consists of sub-folders like drawable, layout, mipmap, raw, and values. The drawable consists of the images. The layout consists of the XML files that define the user interface layout. These are stored in res.layout and are accessed as R.layout class. The raw consists of the Resources files like audio files or music files, etc. These are accessed through R.raw.filename. values are used to store the hardcoded strings(considered safe to store string values) values, integers, and colors. It consists of various other directories like:
R.array :arrays.xml for resource arrays
R.integer : integers.xml for resource integers
R.bool : bools.xml for resource boolean
R.color :colors.xml for color values
R.string : strings.xml for string values
R.dimen : dimens.xml for dimension values
R.style : styles.xml for styles
Gradle Files: Gradle is an advanced toolkit, which is used to manage the build process, that allows defining the flexible custom build configurations. Each build configuration can define its own set of code and resources while reusing the parts common to all versions of your app. The Android plugin for Gradle works with the build toolkit to provide processes and configurable settings that are specific to building and testing Android applications. Gradle and the Android plugin run independently of Android Studio. This means that you can build your Android apps from within Android Studio. The flexibility of the Android build system enables you to perform custom build configurations without modifying your app’s core source files.
Basic Layout Can be defined in a tree structure as:
Project/
app/
manifest/
AndroidManifest.xml
java/
MyActivity.java
res/
drawable/
icon.png
background.png
drawable-hdpi/
icon.png
background.png
layout/
activity_main.xml
info.xml
values/
strings.xml
4. Lifecycle of Activity in Android App
The Lifecycle of Activity in Android App can be shown through this diagram:
States of Android Lifecycle:
OnCreate: This is called when activity is first created.OnStart: This is called when the activity becomes visible to the user.OnResume: This is called when the activity starts to interact with the user.OnPause: This is called when activity is not visible to the user.OnStop: This is called when activity is no longer visible.OnRestart: This is called when activity is stopped, and restarted again.OnDestroy: This is called when activity is to be closed or destroyed.
OnCreate: This is called when activity is first created.
OnStart: This is called when the activity becomes visible to the user.
OnResume: This is called when the activity starts to interact with the user.
OnPause: This is called when activity is not visible to the user.
OnStop: This is called when activity is no longer visible.
OnRestart: This is called when activity is stopped, and restarted again.
OnDestroy: This is called when activity is to be closed or destroyed.
To know more about Activity Lifecycle in Android Please refer to this article: Activity Lifecycle in Android with Demo App
To begin your journey in Android you may refer to these tutorials:
Android Tutorial
Kotlin Android Tutorial
Android Studio Tutorial
Android Projects – From Basic to Advanced Level
AmiyaRanjanRout
android
Picked
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
Top 10 Angular Libraries For Web Developers
Top 10 System Design Interview Questions and Answers
A Freshers Guide To Programming
Supervised and Unsupervised learning
XML parsing in Python
Working with PDF files in Python
Top 10 Programming Languages to Learn in 2022
ML | Underfitting and Overfitting | [
{
"code": null,
"e": 25138,
"s": 25110,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 25920,
"s": 25138,
"text": "Android is an operating system that is built basically for Mobile phones. It is based on the Linux Kernel and other open-source software and is developed by Google. It is used for touchscreen mobile devices such as smartphones and tablets. But nowadays these are used in Android Auto cars, TV, watches, camera, etc. It has been one of the best-selling OS for smartphones. Android OS was developed by Android Inc. which Google bought in 2005. Various applications (apps) like games, music player, camera, etc. are built for these smartphones for running on Android. Google Play store features more than 3.3 million apps. The app is developed on an application known as Android Studio. These executable apps are installed through a bundle or package called APK(Android Package Kit). "
},
{
"code": null,
"e": 25953,
"s": 25920,
"text": "1. Android Programming Languages"
},
{
"code": null,
"e": 26288,
"s": 25953,
"text": "In Android, basically, programming is done in two languages JAVA or C++ and XML(Extension Markup Language). Nowadays KOTLIN is also preferred. The XML file deals with the design, presentation, layouts, blueprint, etc (as a front-end) while the JAVA or KOTLIN deals with the working of buttons, variables, storing, etc (as a back-end)."
},
{
"code": null,
"e": 26310,
"s": 26288,
"text": "2. Android Components"
},
{
"code": null,
"e": 26581,
"s": 26310,
"text": "The App components are the building blocks of Android. Each component has its own role and life cycles i.e from launching of an app till the end. Some of these components depend upon others also. Each component has a definite purpose. The four major app components are: "
},
{
"code": null,
"e": 26592,
"s": 26581,
"text": "Activities"
},
{
"code": null,
"e": 26601,
"s": 26592,
"text": "Services"
},
{
"code": null,
"e": 26622,
"s": 26601,
"text": "Broadcast Receivers:"
},
{
"code": null,
"e": 26640,
"s": 26622,
"text": "Content Provider:"
},
{
"code": null,
"e": 26997,
"s": 26640,
"text": "Activities: It deals with the UI and the user interactions to the screen. In other words, it is a User Interface that contains activities. These can be one or more depending upon the App. It starts when the application is launched. At least one activity is always present which is known as MainActivity. The activity is implemented through the following. "
},
{
"code": null,
"e": 27005,
"s": 26997,
"text": "Syntax:"
},
{
"code": null,
"e": 27066,
"s": 27005,
"text": "public class MainActivity extends Activity{\n // processes\n}"
},
{
"code": null,
"e": 27158,
"s": 27066,
"text": "To know more Activities please refer to this article: Introduction to Activities in Android"
},
{
"code": null,
"e": 27516,
"s": 27158,
"text": "Services: Services are the background actions performed by the app, these might be long-running operations like a user playing music while surfing the Internet. A service might need other sub-services so as to perform specific tasks. The main purpose of the Services is to provide non-stop working of the app without breaking any interaction with the user. "
},
{
"code": null,
"e": 27524,
"s": 27516,
"text": "Syntax:"
},
{
"code": null,
"e": 27595,
"s": 27524,
"text": "public class MyServices extends Services{\n // code for the services\n}"
},
{
"code": null,
"e": 27680,
"s": 27595,
"text": "To know more Services please refer to this article: Services in Android with Example"
},
{
"code": null,
"e": 28118,
"s": 27680,
"text": "Broadcast Receivers: A Broadcast is used to respond to messages from other applications or from the System. For example, when the battery of the phone is low, then the Android OS fires a Broadcasting message to launch the Battery Saver function or app, after receiving the message the appropriate action is taken by the app. Broadcast Receiver is the subclass of BroadcastReceiver class and each object is represented by Intent objects. "
},
{
"code": null,
"e": 28128,
"s": 28118,
"text": "Syntax: "
},
{
"code": null,
"e": 28224,
"s": 28128,
"text": "public class MyReceiver extends BroadcastReceiver{\n public void onReceive(context,intent){\n }"
},
{
"code": null,
"e": 28330,
"s": 28224,
"text": "To know more Broadcast Receivers please refer to this article: Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 28744,
"s": 28330,
"text": "Content Provider: Content Provider is used to transferring the data from one application to the others at the request of the other application. These are handled by the class ContentResolver class. This class implements a set of APIs(Application Programming Interface) that enables the other applications to perform the transactions. Any Content Provider must implement the Parent Class of ContentProvider class. "
},
{
"code": null,
"e": 28754,
"s": 28744,
"text": "Syntax: "
},
{
"code": null,
"e": 28844,
"s": 28754,
"text": "public class MyContentProvider extends ContentProvider{\n public void onCreate()\n {}\n}"
},
{
"code": null,
"e": 28946,
"s": 28844,
"text": "To know more Content Provider please refer to this article: Content Providers in Android with Example"
},
{
"code": null,
"e": 28985,
"s": 28946,
"text": "3. Structural Layout Of Android Studio"
},
{
"code": null,
"e": 29047,
"s": 28985,
"text": "The basic structural layout of Android Studio is given below:"
},
{
"code": null,
"e": 29109,
"s": 29047,
"text": "The above figure represents the various structure of an app. "
},
{
"code": null,
"e": 29659,
"s": 29109,
"text": "Manifest Folder: Android Manifest is an XML file that is the root of the project source set. It describes the essential information about the app and the Android build tools, the Android Operating System, and Google Play. It contains the permission that an app might need in order to perform a specific task. It also contains the Hardware and the Software features of the app, which determines the compatibility of an app on the Play Store. It also includes special activities like services, broadcast receiver, content providers, package name, etc."
},
{
"code": null,
"e": 29984,
"s": 29659,
"text": "Java Folder: The JAVA folder consists of the java files that are required to perform the background task of the app. It consists of the functionality of the buttons, calculation, storing, variables, toast(small popup message), programming function, etc. The number of these files depends upon the type of activities created."
},
{
"code": null,
"e": 30630,
"s": 29984,
"text": "Resource Folder: The res or Resource folder consists of the various resources that are used in the app. This consists of sub-folders like drawable, layout, mipmap, raw, and values. The drawable consists of the images. The layout consists of the XML files that define the user interface layout. These are stored in res.layout and are accessed as R.layout class. The raw consists of the Resources files like audio files or music files, etc. These are accessed through R.raw.filename. values are used to store the hardcoded strings(considered safe to store string values) values, integers, and colors. It consists of various other directories like:"
},
{
"code": null,
"e": 30670,
"s": 30630,
"text": "R.array :arrays.xml for resource arrays"
},
{
"code": null,
"e": 30717,
"s": 30670,
"text": "R.integer : integers.xml for resource integers"
},
{
"code": null,
"e": 30757,
"s": 30717,
"text": "R.bool : bools.xml for resource boolean"
},
{
"code": null,
"e": 30794,
"s": 30757,
"text": "R.color :colors.xml for color values"
},
{
"code": null,
"e": 30835,
"s": 30794,
"text": "R.string : strings.xml for string values"
},
{
"code": null,
"e": 30877,
"s": 30835,
"text": "R.dimen : dimens.xml for dimension values"
},
{
"code": null,
"e": 30909,
"s": 30877,
"text": "R.style : styles.xml for styles"
},
{
"code": null,
"e": 31647,
"s": 30909,
"text": "Gradle Files: Gradle is an advanced toolkit, which is used to manage the build process, that allows defining the flexible custom build configurations. Each build configuration can define its own set of code and resources while reusing the parts common to all versions of your app. The Android plugin for Gradle works with the build toolkit to provide processes and configurable settings that are specific to building and testing Android applications. Gradle and the Android plugin run independently of Android Studio. This means that you can build your Android apps from within Android Studio. The flexibility of the Android build system enables you to perform custom build configurations without modifying your app’s core source files. "
},
{
"code": null,
"e": 31700,
"s": 31647,
"text": "Basic Layout Can be defined in a tree structure as: "
},
{
"code": null,
"e": 32066,
"s": 31700,
"text": "Project/\n app/\n manifest/\n AndroidManifest.xml\n java/\n MyActivity.java \n res/\n drawable/ \n icon.png\n background.png\n drawable-hdpi/ \n icon.png\n background.png \n layout/ \n activity_main.xml\n info.xml\n values/ \n strings.xml "
},
{
"code": null,
"e": 32107,
"s": 32066,
"text": "4. Lifecycle of Activity in Android App "
},
{
"code": null,
"e": 32184,
"s": 32107,
"text": "The Lifecycle of Activity in Android App can be shown through this diagram: "
},
{
"code": null,
"e": 32213,
"s": 32184,
"text": "States of Android Lifecycle:"
},
{
"code": null,
"e": 32680,
"s": 32213,
"text": "OnCreate: This is called when activity is first created.OnStart: This is called when the activity becomes visible to the user.OnResume: This is called when the activity starts to interact with the user.OnPause: This is called when activity is not visible to the user.OnStop: This is called when activity is no longer visible.OnRestart: This is called when activity is stopped, and restarted again.OnDestroy: This is called when activity is to be closed or destroyed."
},
{
"code": null,
"e": 32737,
"s": 32680,
"text": "OnCreate: This is called when activity is first created."
},
{
"code": null,
"e": 32808,
"s": 32737,
"text": "OnStart: This is called when the activity becomes visible to the user."
},
{
"code": null,
"e": 32885,
"s": 32808,
"text": "OnResume: This is called when the activity starts to interact with the user."
},
{
"code": null,
"e": 32951,
"s": 32885,
"text": "OnPause: This is called when activity is not visible to the user."
},
{
"code": null,
"e": 33010,
"s": 32951,
"text": "OnStop: This is called when activity is no longer visible."
},
{
"code": null,
"e": 33083,
"s": 33010,
"text": "OnRestart: This is called when activity is stopped, and restarted again."
},
{
"code": null,
"e": 33153,
"s": 33083,
"text": "OnDestroy: This is called when activity is to be closed or destroyed."
},
{
"code": null,
"e": 33276,
"s": 33153,
"text": "To know more about Activity Lifecycle in Android Please refer to this article: Activity Lifecycle in Android with Demo App"
},
{
"code": null,
"e": 33343,
"s": 33276,
"text": "To begin your journey in Android you may refer to these tutorials:"
},
{
"code": null,
"e": 33360,
"s": 33343,
"text": "Android Tutorial"
},
{
"code": null,
"e": 33384,
"s": 33360,
"text": "Kotlin Android Tutorial"
},
{
"code": null,
"e": 33408,
"s": 33384,
"text": "Android Studio Tutorial"
},
{
"code": null,
"e": 33456,
"s": 33408,
"text": "Android Projects – From Basic to Advanced Level"
},
{
"code": null,
"e": 33472,
"s": 33456,
"text": "AmiyaRanjanRout"
},
{
"code": null,
"e": 33480,
"s": 33472,
"text": "android"
},
{
"code": null,
"e": 33487,
"s": 33480,
"text": "Picked"
},
{
"code": null,
"e": 33493,
"s": 33487,
"text": "GBlog"
},
{
"code": null,
"e": 33591,
"s": 33493,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33600,
"s": 33591,
"text": "Comments"
},
{
"code": null,
"e": 33613,
"s": 33600,
"text": "Old Comments"
},
{
"code": null,
"e": 33655,
"s": 33613,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 33680,
"s": 33655,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33724,
"s": 33680,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 33777,
"s": 33724,
"text": "Top 10 System Design Interview Questions and Answers"
},
{
"code": null,
"e": 33809,
"s": 33777,
"text": "A Freshers Guide To Programming"
},
{
"code": null,
"e": 33846,
"s": 33809,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 33868,
"s": 33846,
"text": "XML parsing in Python"
},
{
"code": null,
"e": 33901,
"s": 33868,
"text": "Working with PDF files in Python"
},
{
"code": null,
"e": 33947,
"s": 33901,
"text": "Top 10 Programming Languages to Learn in 2022"
}
]
|
C++ String Library - insert | It inserts additional characters into the string right before the character indicated by pos.
Following is the declaration for std::string::insert.
string& insert (size_t pos, const string& str);
string& insert (size_t pos, const string& str);
string& insert (size_t pos, const string& str);
pos − It is an insertion point.
pos − It is an insertion point.
str − It is a string object.
str − It is a string object.
It returns *this.
if an exception is thrown, there are no changes in the string.
In below example for std::string::insert.
#include <cassert>
#include <iterator>
#include <string>
using namespace std::literals;
int main() {
std::string s = "xmplr";
s.insert(0, 1, 'E');
assert("Exmplr" == s);
s.insert(2, "e");
assert("Exemplr" == s);
s.insert(6, "a"s);
assert("Exemplar" == s);
s.insert(8, " is an example string."s, 0, 14);
assert("Exemplar is an example" == s);
s.insert(s.cbegin() + s.find_first_of('n') + 1, ':');
assert("Exemplar is an: example" == s);
s.insert(s.cbegin() + s.find_first_of(':') + 1, 2, '=');
assert("Exemplar is an:== example" == s);
{
std::string seq = " string";
s.insert(s.begin() + s.find_last_of('e') + 1,
std::begin(seq), std::end(seq));
assert("Exemplar is an:== example string" == s);
}
s.insert(s.cbegin() + s.find_first_of('g') + 1, { '.' });
assert("Exemplar is an:== example string." == s);
}
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2697,
"s": 2603,
"text": "It inserts additional characters into the string right before the character indicated by pos."
},
{
"code": null,
"e": 2751,
"s": 2697,
"text": "Following is the declaration for std::string::insert."
},
{
"code": null,
"e": 2799,
"s": 2751,
"text": "string& insert (size_t pos, const string& str);"
},
{
"code": null,
"e": 2847,
"s": 2799,
"text": "string& insert (size_t pos, const string& str);"
},
{
"code": null,
"e": 2895,
"s": 2847,
"text": "string& insert (size_t pos, const string& str);"
},
{
"code": null,
"e": 2927,
"s": 2895,
"text": "pos − It is an insertion point."
},
{
"code": null,
"e": 2959,
"s": 2927,
"text": "pos − It is an insertion point."
},
{
"code": null,
"e": 2988,
"s": 2959,
"text": "str − It is a string object."
},
{
"code": null,
"e": 3017,
"s": 2988,
"text": "str − It is a string object."
},
{
"code": null,
"e": 3035,
"s": 3017,
"text": "It returns *this."
},
{
"code": null,
"e": 3098,
"s": 3035,
"text": "if an exception is thrown, there are no changes in the string."
},
{
"code": null,
"e": 3140,
"s": 3098,
"text": "In below example for std::string::insert."
},
{
"code": null,
"e": 4029,
"s": 3140,
"text": "#include <cassert>\n#include <iterator>\n#include <string>\nusing namespace std::literals;\nint main() {\n std::string s = \"xmplr\";\n\n s.insert(0, 1, 'E');\n assert(\"Exmplr\" == s);\n\n s.insert(2, \"e\");\n assert(\"Exemplr\" == s);\n\n s.insert(6, \"a\"s);\n assert(\"Exemplar\" == s);\n\n s.insert(8, \" is an example string.\"s, 0, 14);\n assert(\"Exemplar is an example\" == s);\n\n s.insert(s.cbegin() + s.find_first_of('n') + 1, ':');\n assert(\"Exemplar is an: example\" == s);\n \n s.insert(s.cbegin() + s.find_first_of(':') + 1, 2, '=');\n assert(\"Exemplar is an:== example\" == s);\n {\n std::string seq = \" string\";\n s.insert(s.begin() + s.find_last_of('e') + 1,\n std::begin(seq), std::end(seq));\n assert(\"Exemplar is an:== example string\" == s);\n }\n\n s.insert(s.cbegin() + s.find_first_of('g') + 1, { '.' });\n assert(\"Exemplar is an:== example string.\" == s);\n}"
},
{
"code": null,
"e": 4036,
"s": 4029,
"text": " Print"
},
{
"code": null,
"e": 4047,
"s": 4036,
"text": " Add Notes"
}
]
|
Mastering the Bar Plot in Python. In this tutorial, let us learn the “Bar... | by Tanu N Prabhu | Towards Data Science | The data visualization is one of the most important fundamental toolkits of a data scientist. A good visualization is very hard to produce. Often during a presentation, people don’t understand well enough the data, or the statistics involved but showing them a good visualization will help them understand the story we are trying to convey them. Therefore, they say a picture is worth a thousand words.
I believe that visualization is one of the most powerful means of achieving personal goals. — Harvey Mackay
The whole code for this tutorial can be found on my GitHub repository given below. Go check it out:
github.com
One of the best and the most commonly used library used for visualization is called matplotlib. This library produces publishable quality plots. Throughout the tutorial, we will use the pyplot module. If you are using a jupyter notebook then you can directly import the library otherwise, you can use the below command to install it manually:
The current new version of matplotlib is 3.2.1. You can refer to the official installation docs here.
pip install matplotlib
If you are using a jupyter notebook then you might want to add a “!” at the beginning of the command. This is just informing the kernel that the command is being entered.
!pip install matplotlib
A bar plot or bar graph is a plot/graph that represents the value of categorical data with rectangle bars. The rectangle bars can be horizontal or vertical. Categorical data here can be the name of the movies, countries, football players, etc. Correspondingly the values can be the count of the movies that won Oscar, GDP of a country, players who scored most goals, etc.
Below is the general syntax of the bar plot:
bar(x, height, width, bottom, *, align)
x = The ‘x’ coordinate of the bars.
bottom = The ‘y’ coordinate of the bars. The default value is 0.
height = The ‘height’ of the bars.
width = The ‘width’ of the bars. The default value is 0.8.
align = The alignment of the bars based on the ‘x’ coordinate. The default value is “center” which centers the base on the ‘x’ position. Similarly, the alternate value is “edge” which align the left edges of the bar with respect to the ‘x’ coordinates.
The ‘*’ represents alternative parameters, I will mention only the most used parameter such as:
color = The color of the bar plot. The values must be either ‘r’, ‘g’, ‘b’, and any combination of all three. Also, colors such as ‘red’, ‘cyan’, etc are also valid.
orientation = The orientation of the bars. The values are ‘horizontal’ and ‘vertical’, their working is pretty much self-explanatory.
The bar function returns all the containers in the form of bars (horizontal or vertical).
Now, from here on I will explain the concepts via examples so that you will clearly understand its usage.
Here to plot the bar plot, I will use the data from worldometer, which is coronavirus total death counts from the top 6 countries. The data was taken on 8–6–20, at 10:18 AM (CST).
# Importing the matplotlib libraryimport matplotlib.pyplot as plt# Categorical data: Country namescountries = ['USA', 'Brazil', 'Russia', 'Spain', 'UK', 'India']# Integer value interms of death countstotalDeaths = [112596, 37312, 5971, 27136, 40597, 7449]# Passing the parameters to the bar function, this is the main function which creates the bar plotplt.bar(countries, totalDeaths)# Displaying the bar plotplt.show()
On executing this code on your notebook environment, you will get an amazing bar plot, with minimum details:
In the below plot, let us add some spices to the plot, spices in the sense of adding some more parameters and making the plot look better and more informative. Also, there are some attributes that we can use to make the bar plot more informative. Below are some things that I would add:
figsize = (12,7): Helps in setting the height and width of the plot. But one twist is the order is interchanged which is (width, height) or (y, x).
width= 0.9: It helps in setting the width of the bars.
color = ‘cyan’: It helps in setting the color of the bars.
edgecolor = ‘red’: It helps in setting the edge color of the bars.
annotate = (‘text’, (x, y)): Helps for annotation the bars, include the text or the string along with the desired location as x and y coordinates.
legend(labels = [‘Text’]): It helps for setting up a label for the bar plot.
title(‘Text’): Helps in providing a title for the bar plot
xlabel(‘Text’), ylabel(‘Text’): Helps in providing the name for the x and y-axis of the plot.
savefig(‘Path’): It helps in saving the plot to your local machine or anywhere. You can save in different formats such as “PNG”, “JPEG”, etc.
The ‘Text’ here can be replaced by the string of your choice, and the ‘Path’ represents the path where you want to store the plot.
# Importing the matplotlib libraryimport matplotlib.pyplot as plt# Declaring the figure or the plot (y, x) or (width, height)plt.figure(figsize = (12,7))# Categorical data: Country namescountries = ['USA', 'Brazil', 'Russia', 'Spain', 'UK', 'India']# Integer value interms of death countstotalDeaths = [112596, 37312, 5971, 27136, 40597, 7449]# Passing the parameters to the bar function, this is the main function which creates the bar plotplt.bar(countries, totalDeaths, width= 0.9, align='center',color='cyan', edgecolor = 'red')# This is the location for the annotated texti = 1.0j = 2000# Annotating the bar plot with the values (total death count)for i in range(len(countries)): plt.annotate(totalDeaths[i], (-0.1 + i, totalDeaths[i] + j))# Creating the legend of the bars in the plotplt.legend(labels = ['Total Deaths'])# Giving the tilte for the plotplt.title("Bar plot representing the total deaths by top 6 countries due to coronavirus")# Namimg the x and y axisplt.xlabel('Countries')plt.ylabel('Deaths')# Saving the plot as a 'png'plt.savefig('1BarPlot.png')# Displaying the bar plotplt.show()
Yes, you read it right. By adding one extra character ‘h’, we can align the bars horizontally. Also, we can represent the bars in two or more different colors, this will increase the readability of the plots. Show below is the code with the modifications.
# Importing the matplotlib libraryimport matplotlib.pyplot as plt# Declaring the figure or the plot (y, x) or (width, height)plt.figure(figsize=[14, 10])# Passing the parameters to the bar function, this is the main function which creates the bar plot# For creating the horizontal make sure that you append 'h' to the bar function nameplt.barh(['USA', 'Brazil', 'Russia', 'Spain', 'UK'], [2026493, 710887, 476658, 288797, 287399], label = "Danger zone", color = 'r')plt.barh(['India', 'Italy', 'Peru', 'Germany', 'Iran'], [265928, 235278, 199696, 186205, 173832], label = "Not safe zone", color = 'g')# Creating the legend of the bars in the plotplt.legend()# Namimg the x and y axisplt.xlabel('Total cases')plt.ylabel('Countries')# Giving the tilte for the plotplt.title('Top ten countries most affected by\n coronavirus')# Saving the plot as a 'png'plt.savefig('2BarPlot.png')# Displaying the bar plotplt.show()
At times you might want to stack two or more bar plots on top of each other. With the help of this, you can differentiate two separate quantities visually. To do this just follow.
# Importing the matplotlib libraryimport matplotlib.pyplot as plt# Declaring the figure or the plot (y, x) or (width, height)plt.figure(figsize=[15, 5])# Categorical data: Country namescountries = ['USA', 'Brazil', 'Russia', 'Spain', 'UK', 'India']# Integer value interms of death countstotalCases = (2026493, 710887, 476658, 288797, 287399, 265928)# Integer value interms of total casestotalDeaths = (113055, 37312, 5971, 27136, 40597, 7473)# Plotting both the total death and the total cases in a single plot. Formula total cases - total deathsfor i in range(len(countries)): plt.bar(countries[i], totalDeaths[i], bottom = totalCases[i] - totalDeaths[i], color='black') plt.bar(countries[i], totalCases[i] - totalDeaths[i], color='red')# Creating the legend of the bars in the plotplt.legend(labels = ['Total Deaths','Total Cases'])# Giving the tilte for the plotplt.title("Bar plot representing the total deaths and total cases country wise")# Namimg the x and y axisplt.xlabel('Countries')plt.ylabel('Cases')# Saving the plot as a 'png'plt.savefig('3BarPlot.png')# Displaying the bar plotplt.show()
In the above plot, we can see two different variations of the data being plotted which are the total deaths and the total cases.
Often many-a-times you might want to group two or more plots just to represent two or more different quantities or whatever. Also in the below code, you can learn to override the name of the x-axis with the name of your choice.
# Importing the matplotlib libraryimport numpy as npimport matplotlib.pyplot as plt# Declaring the figure or the plot (y, x) or (width, height)plt.figure(figsize=[15, 10])# Data to be plottedtotalDeath = [113055, 37312, 5971, 7473, 33964]totalRecovery = [773480, 325602, 230688, 129095, 166584]activeCases = [1139958, 347973, 239999, 129360, 34730]# Using numpy to group 3 different data with barsX = np.arange(len(totalDeath))# Passing the parameters to the bar function, this is the main function which creates the bar plot# Using X now to align the bars side by sideplt.bar(X, totalDeath, color = 'black', width = 0.25)plt.bar(X + 0.25, totalRecovery, color = 'g', width = 0.25)plt.bar(X + 0.5, activeCases, color = 'b', width = 0.25)# Creating the legend of the bars in the plotplt.legend(['Total Deaths', 'Total Recovery', 'Active Cases'])# Overiding the x axis with the country namesplt.xticks([i + 0.25 for i in range(5)], ['USA', 'Brazil', 'Russia', 'India', 'Italy'])# Giving the tilte for the plotplt.title("Bar plot representing the total deaths, total recovered cases and active cases country wise")# Namimg the x and y axisplt.xlabel('Countries')plt.ylabel('Cases')# Saving the plot as a 'png'plt.savefig('4BarPlot.png')# Displaying the bar plotplt.show()
In the above plot, we can easily visualize which country is doing well in terms of recovery or active cases, etc.
The bar plot is one of the most simple and interesting plots available in the matplotlib library. It’s fun to learn, I hope you guys have completely understood the in and out of the bar plot. Below is the brief table of contents I covered in the above part of the tutorial. Go take a look and make things clear in your head and come back to me if not.
The general syntax of the bar plot
Simple bar plot with no tricks involved
Learning how to use special parameters
Plotting a bar plot horizontally
Stacking two bar plot on top of another
Plotting three-bar plots next to another (Grouping)
Overriding the x-axis, learning what magic can xticks do.
Lastly, saving a plot as an image (png).
Thank you guys that’s it for this tutorial “Mastering the Bar Plot in Python”. Hope you have learned something new today, feel free to explore more create cool bar plots. See you stay tuned for more updates until then stay safe. | [
{
"code": null,
"e": 575,
"s": 172,
"text": "The data visualization is one of the most important fundamental toolkits of a data scientist. A good visualization is very hard to produce. Often during a presentation, people don’t understand well enough the data, or the statistics involved but showing them a good visualization will help them understand the story we are trying to convey them. Therefore, they say a picture is worth a thousand words."
},
{
"code": null,
"e": 683,
"s": 575,
"text": "I believe that visualization is one of the most powerful means of achieving personal goals. — Harvey Mackay"
},
{
"code": null,
"e": 783,
"s": 683,
"text": "The whole code for this tutorial can be found on my GitHub repository given below. Go check it out:"
},
{
"code": null,
"e": 794,
"s": 783,
"text": "github.com"
},
{
"code": null,
"e": 1137,
"s": 794,
"text": "One of the best and the most commonly used library used for visualization is called matplotlib. This library produces publishable quality plots. Throughout the tutorial, we will use the pyplot module. If you are using a jupyter notebook then you can directly import the library otherwise, you can use the below command to install it manually:"
},
{
"code": null,
"e": 1239,
"s": 1137,
"text": "The current new version of matplotlib is 3.2.1. You can refer to the official installation docs here."
},
{
"code": null,
"e": 1262,
"s": 1239,
"text": "pip install matplotlib"
},
{
"code": null,
"e": 1433,
"s": 1262,
"text": "If you are using a jupyter notebook then you might want to add a “!” at the beginning of the command. This is just informing the kernel that the command is being entered."
},
{
"code": null,
"e": 1457,
"s": 1433,
"text": "!pip install matplotlib"
},
{
"code": null,
"e": 1829,
"s": 1457,
"text": "A bar plot or bar graph is a plot/graph that represents the value of categorical data with rectangle bars. The rectangle bars can be horizontal or vertical. Categorical data here can be the name of the movies, countries, football players, etc. Correspondingly the values can be the count of the movies that won Oscar, GDP of a country, players who scored most goals, etc."
},
{
"code": null,
"e": 1874,
"s": 1829,
"text": "Below is the general syntax of the bar plot:"
},
{
"code": null,
"e": 1915,
"s": 1874,
"text": "bar(x, height, width, bottom, *, align) "
},
{
"code": null,
"e": 1951,
"s": 1915,
"text": "x = The ‘x’ coordinate of the bars."
},
{
"code": null,
"e": 2016,
"s": 1951,
"text": "bottom = The ‘y’ coordinate of the bars. The default value is 0."
},
{
"code": null,
"e": 2051,
"s": 2016,
"text": "height = The ‘height’ of the bars."
},
{
"code": null,
"e": 2110,
"s": 2051,
"text": "width = The ‘width’ of the bars. The default value is 0.8."
},
{
"code": null,
"e": 2363,
"s": 2110,
"text": "align = The alignment of the bars based on the ‘x’ coordinate. The default value is “center” which centers the base on the ‘x’ position. Similarly, the alternate value is “edge” which align the left edges of the bar with respect to the ‘x’ coordinates."
},
{
"code": null,
"e": 2459,
"s": 2363,
"text": "The ‘*’ represents alternative parameters, I will mention only the most used parameter such as:"
},
{
"code": null,
"e": 2625,
"s": 2459,
"text": "color = The color of the bar plot. The values must be either ‘r’, ‘g’, ‘b’, and any combination of all three. Also, colors such as ‘red’, ‘cyan’, etc are also valid."
},
{
"code": null,
"e": 2759,
"s": 2625,
"text": "orientation = The orientation of the bars. The values are ‘horizontal’ and ‘vertical’, their working is pretty much self-explanatory."
},
{
"code": null,
"e": 2849,
"s": 2759,
"text": "The bar function returns all the containers in the form of bars (horizontal or vertical)."
},
{
"code": null,
"e": 2955,
"s": 2849,
"text": "Now, from here on I will explain the concepts via examples so that you will clearly understand its usage."
},
{
"code": null,
"e": 3135,
"s": 2955,
"text": "Here to plot the bar plot, I will use the data from worldometer, which is coronavirus total death counts from the top 6 countries. The data was taken on 8–6–20, at 10:18 AM (CST)."
},
{
"code": null,
"e": 3555,
"s": 3135,
"text": "# Importing the matplotlib libraryimport matplotlib.pyplot as plt# Categorical data: Country namescountries = ['USA', 'Brazil', 'Russia', 'Spain', 'UK', 'India']# Integer value interms of death countstotalDeaths = [112596, 37312, 5971, 27136, 40597, 7449]# Passing the parameters to the bar function, this is the main function which creates the bar plotplt.bar(countries, totalDeaths)# Displaying the bar plotplt.show()"
},
{
"code": null,
"e": 3664,
"s": 3555,
"text": "On executing this code on your notebook environment, you will get an amazing bar plot, with minimum details:"
},
{
"code": null,
"e": 3951,
"s": 3664,
"text": "In the below plot, let us add some spices to the plot, spices in the sense of adding some more parameters and making the plot look better and more informative. Also, there are some attributes that we can use to make the bar plot more informative. Below are some things that I would add:"
},
{
"code": null,
"e": 4099,
"s": 3951,
"text": "figsize = (12,7): Helps in setting the height and width of the plot. But one twist is the order is interchanged which is (width, height) or (y, x)."
},
{
"code": null,
"e": 4154,
"s": 4099,
"text": "width= 0.9: It helps in setting the width of the bars."
},
{
"code": null,
"e": 4213,
"s": 4154,
"text": "color = ‘cyan’: It helps in setting the color of the bars."
},
{
"code": null,
"e": 4280,
"s": 4213,
"text": "edgecolor = ‘red’: It helps in setting the edge color of the bars."
},
{
"code": null,
"e": 4427,
"s": 4280,
"text": "annotate = (‘text’, (x, y)): Helps for annotation the bars, include the text or the string along with the desired location as x and y coordinates."
},
{
"code": null,
"e": 4504,
"s": 4427,
"text": "legend(labels = [‘Text’]): It helps for setting up a label for the bar plot."
},
{
"code": null,
"e": 4563,
"s": 4504,
"text": "title(‘Text’): Helps in providing a title for the bar plot"
},
{
"code": null,
"e": 4657,
"s": 4563,
"text": "xlabel(‘Text’), ylabel(‘Text’): Helps in providing the name for the x and y-axis of the plot."
},
{
"code": null,
"e": 4799,
"s": 4657,
"text": "savefig(‘Path’): It helps in saving the plot to your local machine or anywhere. You can save in different formats such as “PNG”, “JPEG”, etc."
},
{
"code": null,
"e": 4930,
"s": 4799,
"text": "The ‘Text’ here can be replaced by the string of your choice, and the ‘Path’ represents the path where you want to store the plot."
},
{
"code": null,
"e": 6039,
"s": 4930,
"text": "# Importing the matplotlib libraryimport matplotlib.pyplot as plt# Declaring the figure or the plot (y, x) or (width, height)plt.figure(figsize = (12,7))# Categorical data: Country namescountries = ['USA', 'Brazil', 'Russia', 'Spain', 'UK', 'India']# Integer value interms of death countstotalDeaths = [112596, 37312, 5971, 27136, 40597, 7449]# Passing the parameters to the bar function, this is the main function which creates the bar plotplt.bar(countries, totalDeaths, width= 0.9, align='center',color='cyan', edgecolor = 'red')# This is the location for the annotated texti = 1.0j = 2000# Annotating the bar plot with the values (total death count)for i in range(len(countries)): plt.annotate(totalDeaths[i], (-0.1 + i, totalDeaths[i] + j))# Creating the legend of the bars in the plotplt.legend(labels = ['Total Deaths'])# Giving the tilte for the plotplt.title(\"Bar plot representing the total deaths by top 6 countries due to coronavirus\")# Namimg the x and y axisplt.xlabel('Countries')plt.ylabel('Deaths')# Saving the plot as a 'png'plt.savefig('1BarPlot.png')# Displaying the bar plotplt.show()"
},
{
"code": null,
"e": 6295,
"s": 6039,
"text": "Yes, you read it right. By adding one extra character ‘h’, we can align the bars horizontally. Also, we can represent the bars in two or more different colors, this will increase the readability of the plots. Show below is the code with the modifications."
},
{
"code": null,
"e": 7209,
"s": 6295,
"text": "# Importing the matplotlib libraryimport matplotlib.pyplot as plt# Declaring the figure or the plot (y, x) or (width, height)plt.figure(figsize=[14, 10])# Passing the parameters to the bar function, this is the main function which creates the bar plot# For creating the horizontal make sure that you append 'h' to the bar function nameplt.barh(['USA', 'Brazil', 'Russia', 'Spain', 'UK'], [2026493, 710887, 476658, 288797, 287399], label = \"Danger zone\", color = 'r')plt.barh(['India', 'Italy', 'Peru', 'Germany', 'Iran'], [265928, 235278, 199696, 186205, 173832], label = \"Not safe zone\", color = 'g')# Creating the legend of the bars in the plotplt.legend()# Namimg the x and y axisplt.xlabel('Total cases')plt.ylabel('Countries')# Giving the tilte for the plotplt.title('Top ten countries most affected by\\n coronavirus')# Saving the plot as a 'png'plt.savefig('2BarPlot.png')# Displaying the bar plotplt.show()"
},
{
"code": null,
"e": 7389,
"s": 7209,
"text": "At times you might want to stack two or more bar plots on top of each other. With the help of this, you can differentiate two separate quantities visually. To do this just follow."
},
{
"code": null,
"e": 8499,
"s": 7389,
"text": "# Importing the matplotlib libraryimport matplotlib.pyplot as plt# Declaring the figure or the plot (y, x) or (width, height)plt.figure(figsize=[15, 5])# Categorical data: Country namescountries = ['USA', 'Brazil', 'Russia', 'Spain', 'UK', 'India']# Integer value interms of death countstotalCases = (2026493, 710887, 476658, 288797, 287399, 265928)# Integer value interms of total casestotalDeaths = (113055, 37312, 5971, 27136, 40597, 7473)# Plotting both the total death and the total cases in a single plot. Formula total cases - total deathsfor i in range(len(countries)): plt.bar(countries[i], totalDeaths[i], bottom = totalCases[i] - totalDeaths[i], color='black') plt.bar(countries[i], totalCases[i] - totalDeaths[i], color='red')# Creating the legend of the bars in the plotplt.legend(labels = ['Total Deaths','Total Cases'])# Giving the tilte for the plotplt.title(\"Bar plot representing the total deaths and total cases country wise\")# Namimg the x and y axisplt.xlabel('Countries')plt.ylabel('Cases')# Saving the plot as a 'png'plt.savefig('3BarPlot.png')# Displaying the bar plotplt.show()"
},
{
"code": null,
"e": 8628,
"s": 8499,
"text": "In the above plot, we can see two different variations of the data being plotted which are the total deaths and the total cases."
},
{
"code": null,
"e": 8856,
"s": 8628,
"text": "Often many-a-times you might want to group two or more plots just to represent two or more different quantities or whatever. Also in the below code, you can learn to override the name of the x-axis with the name of your choice."
},
{
"code": null,
"e": 10125,
"s": 8856,
"text": "# Importing the matplotlib libraryimport numpy as npimport matplotlib.pyplot as plt# Declaring the figure or the plot (y, x) or (width, height)plt.figure(figsize=[15, 10])# Data to be plottedtotalDeath = [113055, 37312, 5971, 7473, 33964]totalRecovery = [773480, 325602, 230688, 129095, 166584]activeCases = [1139958, 347973, 239999, 129360, 34730]# Using numpy to group 3 different data with barsX = np.arange(len(totalDeath))# Passing the parameters to the bar function, this is the main function which creates the bar plot# Using X now to align the bars side by sideplt.bar(X, totalDeath, color = 'black', width = 0.25)plt.bar(X + 0.25, totalRecovery, color = 'g', width = 0.25)plt.bar(X + 0.5, activeCases, color = 'b', width = 0.25)# Creating the legend of the bars in the plotplt.legend(['Total Deaths', 'Total Recovery', 'Active Cases'])# Overiding the x axis with the country namesplt.xticks([i + 0.25 for i in range(5)], ['USA', 'Brazil', 'Russia', 'India', 'Italy'])# Giving the tilte for the plotplt.title(\"Bar plot representing the total deaths, total recovered cases and active cases country wise\")# Namimg the x and y axisplt.xlabel('Countries')plt.ylabel('Cases')# Saving the plot as a 'png'plt.savefig('4BarPlot.png')# Displaying the bar plotplt.show()"
},
{
"code": null,
"e": 10239,
"s": 10125,
"text": "In the above plot, we can easily visualize which country is doing well in terms of recovery or active cases, etc."
},
{
"code": null,
"e": 10591,
"s": 10239,
"text": "The bar plot is one of the most simple and interesting plots available in the matplotlib library. It’s fun to learn, I hope you guys have completely understood the in and out of the bar plot. Below is the brief table of contents I covered in the above part of the tutorial. Go take a look and make things clear in your head and come back to me if not."
},
{
"code": null,
"e": 10626,
"s": 10591,
"text": "The general syntax of the bar plot"
},
{
"code": null,
"e": 10666,
"s": 10626,
"text": "Simple bar plot with no tricks involved"
},
{
"code": null,
"e": 10705,
"s": 10666,
"text": "Learning how to use special parameters"
},
{
"code": null,
"e": 10738,
"s": 10705,
"text": "Plotting a bar plot horizontally"
},
{
"code": null,
"e": 10778,
"s": 10738,
"text": "Stacking two bar plot on top of another"
},
{
"code": null,
"e": 10830,
"s": 10778,
"text": "Plotting three-bar plots next to another (Grouping)"
},
{
"code": null,
"e": 10888,
"s": 10830,
"text": "Overriding the x-axis, learning what magic can xticks do."
},
{
"code": null,
"e": 10929,
"s": 10888,
"text": "Lastly, saving a plot as an image (png)."
}
]
|
Python Program to get number of consecutive repeated substring - GeeksforGeeks | 06 Jun, 2021
Given a substring K, the task is to write a Python Program to find the repetition of K string in each consecutive occurrence of K.
Example
Input : test_str = ‘geeksgeeks are geeksgeeksgeeks for all geeks’, K = “geeks”
Output : [2, 3, 1]
Explanation : First consecution of ‘geeks’ is 2.
Input : test_str = ‘geeksgeeks are geeksgeeksgeeksgeeks for all geeks’, K = “geeks”
Output : [2, 4, 1]
Explanation : First consecution of ‘geeks’ is 2, next comes with 4 consecution of geeks.
Method 1: Using split() + count() + list comprehension
Works only for specific cases in which consecution is separated by spaces. In this, each word is splitted using split(), and each segment is evaluated for repetition count using count().
Python3
# Python3 code to demonstrate working of# Number of repeated substrings in consecution# Using split() + count() + list comprehension # initializing stringtest_str = 'geeksgeeks are geeksgeeksgeeks for all geeks' # printing original stringprint("The original string is : " + str(test_str)) # initializing K K = "geeks" # count() counts repetitionres = [sub.count(K) for sub in test_str.split(' ') if sub.count(K) != 0] # printing resultprint("String repetitions : " + str(res))
Output:
The original string is : geeksgeeks are geeksgeeksgeeks for all geeks
String repetitions : [2, 3, 1]
Method 2: Using findall() + regex + len()
In this, all the runs are computed for repetition of substring, and then division of length by substring length gives the measure of repetition number.
Python3
# Python3 code to demonstrate working of# Number of repeated substrings in consecution# Using findall() + regex + len()import re # initializing stringtest_str = 'geeksgeeksaregeeksgeeksgeeksforallgeeks' # printing original stringprint("The original string is : " + str(test_str)) # initializing K K = 'geeks'n = len(K) # getting regexregx = re.compile(f'((?:{K})+)') # getting repeats counts# findall finding all substring joined repetitionsres = [len(occ) // n for occ in regx.findall(test_str)] # printing resultprint("String repetitions : " + str(res))
Output:
The original string is : geeksgeeks are geeksgeeksgeeks for all geeks
String repetitions : [2, 3, 1]
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 24423,
"s": 24292,
"text": "Given a substring K, the task is to write a Python Program to find the repetition of K string in each consecutive occurrence of K."
},
{
"code": null,
"e": 24431,
"s": 24423,
"text": "Example"
},
{
"code": null,
"e": 24510,
"s": 24431,
"text": "Input : test_str = ‘geeksgeeks are geeksgeeksgeeks for all geeks’, K = “geeks”"
},
{
"code": null,
"e": 24529,
"s": 24510,
"text": "Output : [2, 3, 1]"
},
{
"code": null,
"e": 24579,
"s": 24529,
"text": "Explanation : First consecution of ‘geeks’ is 2. "
},
{
"code": null,
"e": 24663,
"s": 24579,
"text": "Input : test_str = ‘geeksgeeks are geeksgeeksgeeksgeeks for all geeks’, K = “geeks”"
},
{
"code": null,
"e": 24682,
"s": 24663,
"text": "Output : [2, 4, 1]"
},
{
"code": null,
"e": 24771,
"s": 24682,
"text": "Explanation : First consecution of ‘geeks’ is 2, next comes with 4 consecution of geeks."
},
{
"code": null,
"e": 24826,
"s": 24771,
"text": "Method 1: Using split() + count() + list comprehension"
},
{
"code": null,
"e": 25013,
"s": 24826,
"text": "Works only for specific cases in which consecution is separated by spaces. In this, each word is splitted using split(), and each segment is evaluated for repetition count using count()."
},
{
"code": null,
"e": 25021,
"s": 25013,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Number of repeated substrings in consecution# Using split() + count() + list comprehension # initializing stringtest_str = 'geeksgeeks are geeksgeeksgeeks for all geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing K K = \"geeks\" # count() counts repetitionres = [sub.count(K) for sub in test_str.split(' ') if sub.count(K) != 0] # printing resultprint(\"String repetitions : \" + str(res))",
"e": 25503,
"s": 25021,
"text": null
},
{
"code": null,
"e": 25511,
"s": 25503,
"text": "Output:"
},
{
"code": null,
"e": 25581,
"s": 25511,
"text": "The original string is : geeksgeeks are geeksgeeksgeeks for all geeks"
},
{
"code": null,
"e": 25612,
"s": 25581,
"text": "String repetitions : [2, 3, 1]"
},
{
"code": null,
"e": 25654,
"s": 25612,
"text": "Method 2: Using findall() + regex + len()"
},
{
"code": null,
"e": 25808,
"s": 25654,
"text": "In this, all the runs are computed for repetition of substring, and then division of length by substring length gives the measure of repetition number. "
},
{
"code": null,
"e": 25816,
"s": 25808,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Number of repeated substrings in consecution# Using findall() + regex + len()import re # initializing stringtest_str = 'geeksgeeksaregeeksgeeksgeeksforallgeeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing K K = 'geeks'n = len(K) # getting regexregx = re.compile(f'((?:{K})+)') # getting repeats counts# findall finding all substring joined repetitionsres = [len(occ) // n for occ in regx.findall(test_str)] # printing resultprint(\"String repetitions : \" + str(res))",
"e": 26378,
"s": 25816,
"text": null
},
{
"code": null,
"e": 26386,
"s": 26378,
"text": "Output:"
},
{
"code": null,
"e": 26456,
"s": 26386,
"text": "The original string is : geeksgeeks are geeksgeeksgeeks for all geeks"
},
{
"code": null,
"e": 26487,
"s": 26456,
"text": "String repetitions : [2, 3, 1]"
},
{
"code": null,
"e": 26510,
"s": 26487,
"text": "Python string-programs"
},
{
"code": null,
"e": 26517,
"s": 26510,
"text": "Python"
},
{
"code": null,
"e": 26533,
"s": 26517,
"text": "Python Programs"
},
{
"code": null,
"e": 26631,
"s": 26533,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26640,
"s": 26631,
"text": "Comments"
},
{
"code": null,
"e": 26653,
"s": 26640,
"text": "Old Comments"
},
{
"code": null,
"e": 26685,
"s": 26653,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26741,
"s": 26685,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26796,
"s": 26741,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26838,
"s": 26796,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26880,
"s": 26838,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26902,
"s": 26880,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26948,
"s": 26902,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26987,
"s": 26948,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27025,
"s": 26987,
"text": "Python | Convert a list to dictionary"
}
]
|
Construct Pushdown Automata for given languages | 22 Nov, 2021
Prerequisite – Pushdown Automata, Pushdown Automata Acceptance by Final State A push down automata is similar to deterministic finite automata except that it has a few more properties than a DFA.The data structure used for implementing a PDA is stack. A PDA has an output associated with every input. All the inputs are either pushed into a stack or just ignored. User can perform the basic push and pop operations on the stack which is use for PDA. One of the problems associated with DFAs was that could not make a count of number of characters which were given input to the machine. This problem is avoided by PDA as it uses a stack which provides us this facility also.
A Pushdown Automata (PDA) can be defined as – M = (Q, Σ, Γ, δ, q0, Ζ, F) where
Q is a finite set of states
Σ is a finite set which is called the input alphabet
Γ is a finite set which is called the stack alphabet
δ is a finite subset of Q X ( Σ ∪ {ε} X Γ X Q X Γ*) the transition relation.
q0 ∈ Q is the start state
Ζ ∈ Γ is the initial stack symbol
F ⊆ Q is the set of accepting states
Representation of State Transition –
Representation of Push in a PDA –
Representation of Pop in a PDA –
Representation of Ignore in a PDA –
Approach used in this PDA – First 0’s are pushed into stack. Then 1’s are pushed into stack. Then for every 2 as input a 1 is popped out of stack. If some 2’s are still left and top of stack is a 0 then string is not accepted by the PDA. Thereafter if 2’s are finished and top of stack is a 0 then for every 3 as input equal number of 0’s are popped out of stack. If string is finished and stack is empty then string is accepted by the PDA otherwise not accepted.
Step-1: On receiving 0 push it onto stack. On receiving 1, push it onto stack and goto next state
Step-2: On receiving 1 push it onto stack. On receiving 2, pop 1 from stack and goto next state
Step-3: On receiving 2 pop 1 from stack. If all the 1’s have been popped out of stack and now receive 3 then pop a 0 from stack and goto next state
Step-4: On receiving 3 pop 0 from stack. If input is finished and stack is empty then goto last state and string is accepted
Examples:
Input : 0 0 1 1 1 2 2 2 3 3
Result : ACCEPTED
Input : 0 0 0 1 1 2 2 2 3 3
Result : NOT ACCEPTED
Approach used in this PDA – First 0’s are pushed into stack.When 0’s are finished, two 1’s are ignored. Thereafter for every 1 as input a 0 is popped out of stack. When stack is empty and still some 1’s are left then all of them are ignored.
Step-1: On receiving 0 push it onto stack. On receiving 1, ignore it and goto next state
Step-2: On receiving 1, ignore it and goto next state
Step-3: On receiving 1, pop a 0 from top of stack and go to next state
Step-4: On receiving 1, pop a 0 from top of stack. If stack is empty, on receiving 1 ignore it and goto next state
Step-5: On receiving 1 ignore it. If input is finished then goto last state
Examples:
Input : 0 0 0 1 1 1 1 1 1
Result : ACCEPTED
Input : 0 0 0 0 1 1 1 1
Result : NOT ACCEPTED
kashishsoda
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 729,
"s": 54,
"text": "Prerequisite – Pushdown Automata, Pushdown Automata Acceptance by Final State A push down automata is similar to deterministic finite automata except that it has a few more properties than a DFA.The data structure used for implementing a PDA is stack. A PDA has an output associated with every input. All the inputs are either pushed into a stack or just ignored. User can perform the basic push and pop operations on the stack which is use for PDA. One of the problems associated with DFAs was that could not make a count of number of characters which were given input to the machine. This problem is avoided by PDA as it uses a stack which provides us this facility also. "
},
{
"code": null,
"e": 810,
"s": 729,
"text": "A Pushdown Automata (PDA) can be defined as – M = (Q, Σ, Γ, δ, q0, Ζ, F) where "
},
{
"code": null,
"e": 838,
"s": 810,
"text": "Q is a finite set of states"
},
{
"code": null,
"e": 891,
"s": 838,
"text": "Σ is a finite set which is called the input alphabet"
},
{
"code": null,
"e": 944,
"s": 891,
"text": "Γ is a finite set which is called the stack alphabet"
},
{
"code": null,
"e": 1021,
"s": 944,
"text": "δ is a finite subset of Q X ( Σ ∪ {ε} X Γ X Q X Γ*) the transition relation."
},
{
"code": null,
"e": 1047,
"s": 1021,
"text": "q0 ∈ Q is the start state"
},
{
"code": null,
"e": 1081,
"s": 1047,
"text": "Ζ ∈ Γ is the initial stack symbol"
},
{
"code": null,
"e": 1118,
"s": 1081,
"text": "F ⊆ Q is the set of accepting states"
},
{
"code": null,
"e": 1156,
"s": 1118,
"text": "Representation of State Transition – "
},
{
"code": null,
"e": 1190,
"s": 1156,
"text": "Representation of Push in a PDA –"
},
{
"code": null,
"e": 1224,
"s": 1190,
"text": "Representation of Pop in a PDA – "
},
{
"code": null,
"e": 1261,
"s": 1224,
"text": "Representation of Ignore in a PDA – "
},
{
"code": null,
"e": 1725,
"s": 1261,
"text": "Approach used in this PDA – First 0’s are pushed into stack. Then 1’s are pushed into stack. Then for every 2 as input a 1 is popped out of stack. If some 2’s are still left and top of stack is a 0 then string is not accepted by the PDA. Thereafter if 2’s are finished and top of stack is a 0 then for every 3 as input equal number of 0’s are popped out of stack. If string is finished and stack is empty then string is accepted by the PDA otherwise not accepted."
},
{
"code": null,
"e": 1823,
"s": 1725,
"text": "Step-1: On receiving 0 push it onto stack. On receiving 1, push it onto stack and goto next state"
},
{
"code": null,
"e": 1919,
"s": 1823,
"text": "Step-2: On receiving 1 push it onto stack. On receiving 2, pop 1 from stack and goto next state"
},
{
"code": null,
"e": 2067,
"s": 1919,
"text": "Step-3: On receiving 2 pop 1 from stack. If all the 1’s have been popped out of stack and now receive 3 then pop a 0 from stack and goto next state"
},
{
"code": null,
"e": 2192,
"s": 2067,
"text": "Step-4: On receiving 3 pop 0 from stack. If input is finished and stack is empty then goto last state and string is accepted"
},
{
"code": null,
"e": 2203,
"s": 2192,
"text": "Examples: "
},
{
"code": null,
"e": 2304,
"s": 2203,
"text": "Input : 0 0 1 1 1 2 2 2 3 3\nResult : ACCEPTED\n\nInput : 0 0 0 1 1 2 2 2 3 3 \nResult : NOT ACCEPTED "
},
{
"code": null,
"e": 2547,
"s": 2304,
"text": "Approach used in this PDA – First 0’s are pushed into stack.When 0’s are finished, two 1’s are ignored. Thereafter for every 1 as input a 0 is popped out of stack. When stack is empty and still some 1’s are left then all of them are ignored. "
},
{
"code": null,
"e": 2636,
"s": 2547,
"text": "Step-1: On receiving 0 push it onto stack. On receiving 1, ignore it and goto next state"
},
{
"code": null,
"e": 2690,
"s": 2636,
"text": "Step-2: On receiving 1, ignore it and goto next state"
},
{
"code": null,
"e": 2761,
"s": 2690,
"text": "Step-3: On receiving 1, pop a 0 from top of stack and go to next state"
},
{
"code": null,
"e": 2876,
"s": 2761,
"text": "Step-4: On receiving 1, pop a 0 from top of stack. If stack is empty, on receiving 1 ignore it and goto next state"
},
{
"code": null,
"e": 2952,
"s": 2876,
"text": "Step-5: On receiving 1 ignore it. If input is finished then goto last state"
},
{
"code": null,
"e": 2963,
"s": 2952,
"text": "Examples: "
},
{
"code": null,
"e": 3056,
"s": 2963,
"text": "Input : 0 0 0 1 1 1 1 1 1\nResult : ACCEPTED\n\nInput : 0 0 0 0 1 1 1 1\nResult : NOT ACCEPTED"
},
{
"code": null,
"e": 3068,
"s": 3056,
"text": "kashishsoda"
},
{
"code": null,
"e": 3076,
"s": 3068,
"text": "GATE CS"
},
{
"code": null,
"e": 3109,
"s": 3076,
"text": "Theory of Computation & Automata"
}
]
|
Lexicographically next string | 09 Jun, 2022
Given a string, find lexicographically next string.Examples:
Input : geeks
Output : geekt
The last character 's' is changed to 't'.
Input : raavz
Output : raawz
Since we can't increase last character,
we increment previous character.
Input : zzz
Output : zzza
If string is empty, we return ‘a’. If string contains all characters as ‘z’, we append ‘a’ at the end. Otherwise we find first character from end which is not z and increment it.
C++
Java
Python3
C#
Javascript
// C++ program to find lexicographically next// string#include <bits/stdc++.h>using namespace std; string nextWord(string s){ // If string is empty. if (s == "") return "a"; // Find first character from right // which is not z. int i = s.length() - 1; while (s[i] == 'z' && i >= 0) i--; // If all characters are 'z', append // an 'a' at the end. if (i == -1) s = s + 'a'; // If there are some non-z characters else s[i]++; return s;} // Driver codeint main(){ string str = "samez"; cout << nextWord(str); return 0;}
// Java program to find// lexicographically next stringimport java.util.*; class GFG{public static String nextWord(String str){ // if string is empty if (str == "") return "a"; // Find first character from // right which is not z. int i = str.length() - 1; while (str.charAt(i) == 'z' && i >= 0) i--; // If all characters are 'z', // append an 'a' at the end. if (i == -1) str = str + 'a'; // If there are some// non-z characterselse str = str.substring(0, i) + (char)((int)(str.charAt(i)) + 1) + str.substring(i + 1);return str;} // Driver Codepublic static void main (String[] args){ String str = "samez"; System.out.print(nextWord(str));}} // This code is contributed// by Kirti_Mangal
# Python 3 program to find lexicographically# next string def nextWord(s): # If string is empty. if (s == " "): return "a" # Find first character from right # which is not z. i = len(s) - 1 while (s[i] == 'z' and i >= 0): i -= 1 # If all characters are 'z', append # an 'a' at the end. if (i == -1): s = s + 'a' # If there are some non-z characters else: s = s.replace(s[i], chr(ord(s[i]) + 1), 1) return s # Driver codeif __name__ == '__main__': str = "samez" print(nextWord(str)) # This code is contributed by# Sanjit_Prasad
// C# program to find// lexicographically next stringusing System; class GFG{public static string nextWord(string str){ // if string is empty if (str == "") { return "a"; } // Find first character from // right which is not z. int i = str.Length - 1; while (str[i] == 'z' && i >= 0) { i--; } // If all characters are 'z', // append an 'a' at the end. if (i == -1) { str = str + 'a'; } // If there are some // non-z characters else { str = str.Substring(0, i) + (char)((int)(str[i]) + 1) + str.Substring(i + 1); } return str;} // Driver Codepublic static void Main(string[] args){ string str = "samez"; Console.Write(nextWord(str));}} // This code is contributed by Shrikant13
<script> // Javascript program to find lexicographically next// string function nextWord(s){ // If string is empty. if (s == "") return "a"; // Find first character from right // which is not z. var i = s.length - 1; while (s[i] == 'z' && i >= 0) i--; // If all characters are 'z', append // an 'a' at the end. if (i == -1) s = s + 'a'; // If there are some non-z characters else s[i] = String.fromCharCode(s[i].charCodeAt(0)+1); return s.join('');} // Driver codevar str = "samez".split('');document.write( nextWord(str)); // This code is contributed by noob2000.</script>
samfz
Time Complexity: O(n)
Auxiliary Space: O(1)This article is contributed by Pawan Asipu. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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.
Kirti_Mangal
shrikanth13
Sanjit_Prasad
noob2000
hasani
lexicographic-ordering
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Python program to check if a string is palindrome or not
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
Different Methods to Reverse a String in C++
Length of the longest substring without repeating characters
Top 50 String Coding Problems for Interviews | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 115,
"s": 52,
"text": "Given a string, find lexicographically next string.Examples: "
},
{
"code": null,
"e": 318,
"s": 115,
"text": "Input : geeks\nOutput : geekt\nThe last character 's' is changed to 't'.\n\nInput : raavz\nOutput : raawz\nSince we can't increase last character, \nwe increment previous character.\n\nInput : zzz\nOutput : zzza"
},
{
"code": null,
"e": 500,
"s": 320,
"text": "If string is empty, we return ‘a’. If string contains all characters as ‘z’, we append ‘a’ at the end. Otherwise we find first character from end which is not z and increment it. "
},
{
"code": null,
"e": 504,
"s": 500,
"text": "C++"
},
{
"code": null,
"e": 509,
"s": 504,
"text": "Java"
},
{
"code": null,
"e": 517,
"s": 509,
"text": "Python3"
},
{
"code": null,
"e": 520,
"s": 517,
"text": "C#"
},
{
"code": null,
"e": 531,
"s": 520,
"text": "Javascript"
},
{
"code": "// C++ program to find lexicographically next// string#include <bits/stdc++.h>using namespace std; string nextWord(string s){ // If string is empty. if (s == \"\") return \"a\"; // Find first character from right // which is not z. int i = s.length() - 1; while (s[i] == 'z' && i >= 0) i--; // If all characters are 'z', append // an 'a' at the end. if (i == -1) s = s + 'a'; // If there are some non-z characters else s[i]++; return s;} // Driver codeint main(){ string str = \"samez\"; cout << nextWord(str); return 0;}",
"e": 1129,
"s": 531,
"text": null
},
{
"code": "// Java program to find// lexicographically next stringimport java.util.*; class GFG{public static String nextWord(String str){ // if string is empty if (str == \"\") return \"a\"; // Find first character from // right which is not z. int i = str.length() - 1; while (str.charAt(i) == 'z' && i >= 0) i--; // If all characters are 'z', // append an 'a' at the end. if (i == -1) str = str + 'a'; // If there are some// non-z characterselse str = str.substring(0, i) + (char)((int)(str.charAt(i)) + 1) + str.substring(i + 1);return str;} // Driver Codepublic static void main (String[] args){ String str = \"samez\"; System.out.print(nextWord(str));}} // This code is contributed// by Kirti_Mangal",
"e": 1919,
"s": 1129,
"text": null
},
{
"code": "# Python 3 program to find lexicographically# next string def nextWord(s): # If string is empty. if (s == \" \"): return \"a\" # Find first character from right # which is not z. i = len(s) - 1 while (s[i] == 'z' and i >= 0): i -= 1 # If all characters are 'z', append # an 'a' at the end. if (i == -1): s = s + 'a' # If there are some non-z characters else: s = s.replace(s[i], chr(ord(s[i]) + 1), 1) return s # Driver codeif __name__ == '__main__': str = \"samez\" print(nextWord(str)) # This code is contributed by# Sanjit_Prasad",
"e": 2529,
"s": 1919,
"text": null
},
{
"code": "// C# program to find// lexicographically next stringusing System; class GFG{public static string nextWord(string str){ // if string is empty if (str == \"\") { return \"a\"; } // Find first character from // right which is not z. int i = str.Length - 1; while (str[i] == 'z' && i >= 0) { i--; } // If all characters are 'z', // append an 'a' at the end. if (i == -1) { str = str + 'a'; } // If there are some // non-z characters else { str = str.Substring(0, i) + (char)((int)(str[i]) + 1) + str.Substring(i + 1); } return str;} // Driver Codepublic static void Main(string[] args){ string str = \"samez\"; Console.Write(nextWord(str));}} // This code is contributed by Shrikant13",
"e": 3327,
"s": 2529,
"text": null
},
{
"code": "<script> // Javascript program to find lexicographically next// string function nextWord(s){ // If string is empty. if (s == \"\") return \"a\"; // Find first character from right // which is not z. var i = s.length - 1; while (s[i] == 'z' && i >= 0) i--; // If all characters are 'z', append // an 'a' at the end. if (i == -1) s = s + 'a'; // If there are some non-z characters else s[i] = String.fromCharCode(s[i].charCodeAt(0)+1); return s.join('');} // Driver codevar str = \"samez\".split('');document.write( nextWord(str)); // This code is contributed by noob2000.</script>",
"e": 3974,
"s": 3327,
"text": null
},
{
"code": null,
"e": 3980,
"s": 3974,
"text": "samfz"
},
{
"code": null,
"e": 4002,
"s": 3980,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 4443,
"s": 4002,
"text": "Auxiliary Space: O(1)This article is contributed by Pawan Asipu. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. "
},
{
"code": null,
"e": 4456,
"s": 4443,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 4468,
"s": 4456,
"text": "shrikanth13"
},
{
"code": null,
"e": 4482,
"s": 4468,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 4491,
"s": 4482,
"text": "noob2000"
},
{
"code": null,
"e": 4498,
"s": 4491,
"text": "hasani"
},
{
"code": null,
"e": 4521,
"s": 4498,
"text": "lexicographic-ordering"
},
{
"code": null,
"e": 4529,
"s": 4521,
"text": "Strings"
},
{
"code": null,
"e": 4537,
"s": 4529,
"text": "Strings"
},
{
"code": null,
"e": 4635,
"s": 4537,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4681,
"s": 4635,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 4706,
"s": 4681,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4766,
"s": 4706,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 4781,
"s": 4766,
"text": "C++ Data Types"
},
{
"code": null,
"e": 4838,
"s": 4781,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 4872,
"s": 4838,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 4947,
"s": 4872,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 4992,
"s": 4947,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 5053,
"s": 4992,
"text": "Length of the longest substring without repeating characters"
}
]
|
Shell Script to Perform Operations on a File | 12 Dec, 2021
Most of the time, we use shell scripting to interact with the files. Shell scripting offers some operators as well as some commands to check and perform different properties and functionalities associated with the file.
For our convenience, we create a file named ‘geeks.txt’ and another .sh file (or simply run on the command line) to execute different functions or operations on that file. Operations may be reading the contents of the file or testing the file type. These are being discussed below with proper examples:
File reading is an interesting task in a programmer’s life. Shell scripting offers some functionalities for reading the file, reversing the contents, counting words, lines, etc.
Reading line by line: First, we take input using the read command then run the while loop which runs line after line.
Script:
#!/bin/bash
read -p "Enter file name : " filename
while read line
do
echo $line
done < $filename
Counting characters, words & lines in the file: We take three variables, one for counting characters, words, and lines respectively. We use ‘wc’ command, which stands for word count and counts the number of characters and words as well. For counting lines, we pass ‘grep ‘ which keeps count of the lines that match a pattern. Then we print out each variable.
Script:
#! /bin/bash
echo Enter the filename
read file
c=`cat $file | wc -c`
w=`cat $file | wc -w`
l=`grep -c "." $file`
echo Number of characters in $file is $c
echo Number of words in $file is $w
echo Number of lines in $file is $l
Display file contents in reverse: To print the contents of any file in reverse, we use tac or nl, sort, cut commands. Tac is simply the reverse of a cat and simply prints the file in reverse order. Whereas nl commands numbers, the file contents sort the numbered file in the reverse order, and the cut command removes the number and prints the file contents.
Script:
$ nl geeks.txt | sort -nr | cut -f 2-
Frequency of a particular word in the file: To count the frequency of each word in a file, we use certain commands. These are xargs which applies print to every line in the output, the sort which sorts, current buffer piped to it, uniq -c displays the counts of each line in the buffer and, lastly awk, prints the 2nd column and then the 1st column based on the problem requirement.
Script:
cat geeks.txt | xargs printf “%s\n” | sort | uniq -c | sort -nr | awk ‘{print $2,$1}’
-b file: This operator checks if the file is a block special file or not and returns true or false subsequently. It is [-b $file] syntactically.
Script:
#! /bin/bash
echo -e "Enter the name of the file : \c"
read file_name
if [ -b $file_name ]
then
echo "$file_name is a block special file"
else
echo "$file_name is not a block special file"
fi
Output:
-d file: The operator looks over if the file is present as a directory. If Yes, it returns true else false. It is [-d $file] syntactically.
Script:
#! /bin/bash
echo -e "Enter the name of the file : \c"
read file_name
if [ -d $file_name ]
then
echo "$file_name is a directory"
else
echo "$file_name is not a directory"
fi
Output:
-e file: The operator inspects if the file exists or not. Even if a directory is passed, it returns true if the directory exists. It is [-e $file] syntactically.
Script:
#! /bin/bash
echo -e "Enter the name of the file : \c"
read file_name
if [ -e $file_name ]
then
echo "$file_name exist"
else
echo "$file_name not exist"
fi
Output:
-f file: If the file is an ordinary file or special file, then it returns true else false. It is [-f $file] syntactically.
Script:
#! /bin/bash
echo -e "Enter the name of the file : \c"
read file_name
if [ -f $file_name ]
then
echo "$file_name is file"
else
echo "$file_name is not file"
fi
Output:
-r file: This checks if the file is readable. If found yes, then return true else false. It is [-r $file] syntactically.
Script:
#! /bin/bash
echo -e "Enter the name of the file : \c"
read file_name
if [ -r $file_name ]
then
echo "$file_name is readable"
else
echo "$file_name is not readable"
fi
Output:
-s file: This operator checks if the file has a size greater than zero or not, which returns true or false subsequently. It is [-s $file] syntactically.
Script:
#! /bin/bash
echo -e "Enter the name of the file : \c"
read file_name
if [ -s $file_name ]
then
echo "$file_name has size>0"
else
echo "$file_name has size= 0"
fi
Output:
-w file: If wringing is allowed over the file, then the operator returns true, and if not then false. It is [-w $file] syntactically.
Script:
#! /bin/bash
echo -e "Enter the name of the file : \c"
read file_name
if [ -w $file_name ]
then
echo "$file_name is writable"
else
echo "$file_name is not writable"
fi
Output:
-x file: The operator looks over if the file is executable or not, and returns true and false subsequently. It is [-x $file] syntactically.
Script:
#! /bin/bash
echo -e "Enter the name of the file : \c"
read file_name
if [ -x $file_name ]
then
echo "$file_name is executable"
else
echo "$file_name is not executable"
fi
Output:
Rename & delete file: To rename the file, we use the ‘mv’ command which changes the name of the file and ‘rm’ to delete the file.
As we can see below the command line, breakingBad file (after renaming ) and deleting it with ‘rm’ command, it is no longer there.
simmytarika5
sagar0719kumar
Linux-Shell-Commands
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Dec, 2021"
},
{
"code": null,
"e": 274,
"s": 54,
"text": "Most of the time, we use shell scripting to interact with the files. Shell scripting offers some operators as well as some commands to check and perform different properties and functionalities associated with the file."
},
{
"code": null,
"e": 578,
"s": 274,
"text": "For our convenience, we create a file named ‘geeks.txt’ and another .sh file (or simply run on the command line) to execute different functions or operations on that file. Operations may be reading the contents of the file or testing the file type. These are being discussed below with proper examples:"
},
{
"code": null,
"e": 756,
"s": 578,
"text": "File reading is an interesting task in a programmer’s life. Shell scripting offers some functionalities for reading the file, reversing the contents, counting words, lines, etc."
},
{
"code": null,
"e": 874,
"s": 756,
"text": "Reading line by line: First, we take input using the read command then run the while loop which runs line after line."
},
{
"code": null,
"e": 882,
"s": 874,
"text": "Script:"
},
{
"code": null,
"e": 980,
"s": 882,
"text": "#!/bin/bash\nread -p \"Enter file name : \" filename\nwhile read line\ndo \necho $line\ndone < $filename"
},
{
"code": null,
"e": 1339,
"s": 980,
"text": "Counting characters, words & lines in the file: We take three variables, one for counting characters, words, and lines respectively. We use ‘wc’ command, which stands for word count and counts the number of characters and words as well. For counting lines, we pass ‘grep ‘ which keeps count of the lines that match a pattern. Then we print out each variable."
},
{
"code": null,
"e": 1348,
"s": 1339,
"text": " Script:"
},
{
"code": null,
"e": 1575,
"s": 1348,
"text": "#! /bin/bash\n\necho Enter the filename\nread file\nc=`cat $file | wc -c`\nw=`cat $file | wc -w`\nl=`grep -c \".\" $file`\necho Number of characters in $file is $c\necho Number of words in $file is $w\necho Number of lines in $file is $l"
},
{
"code": null,
"e": 1935,
"s": 1575,
"text": "Display file contents in reverse: To print the contents of any file in reverse, we use tac or nl, sort, cut commands. Tac is simply the reverse of a cat and simply prints the file in reverse order. Whereas nl commands numbers, the file contents sort the numbered file in the reverse order, and the cut command removes the number and prints the file contents."
},
{
"code": null,
"e": 1944,
"s": 1935,
"text": " Script:"
},
{
"code": null,
"e": 1982,
"s": 1944,
"text": "$ nl geeks.txt | sort -nr | cut -f 2-"
},
{
"code": null,
"e": 2365,
"s": 1982,
"text": "Frequency of a particular word in the file: To count the frequency of each word in a file, we use certain commands. These are xargs which applies print to every line in the output, the sort which sorts, current buffer piped to it, uniq -c displays the counts of each line in the buffer and, lastly awk, prints the 2nd column and then the 1st column based on the problem requirement."
},
{
"code": null,
"e": 2379,
"s": 2365,
"text": " Script:"
},
{
"code": null,
"e": 2465,
"s": 2379,
"text": "cat geeks.txt | xargs printf “%s\\n” | sort | uniq -c | sort -nr | awk ‘{print $2,$1}’"
},
{
"code": null,
"e": 2610,
"s": 2465,
"text": "-b file: This operator checks if the file is a block special file or not and returns true or false subsequently. It is [-b $file] syntactically."
},
{
"code": null,
"e": 2618,
"s": 2610,
"text": "Script:"
},
{
"code": null,
"e": 2817,
"s": 2618,
"text": "#! /bin/bash\necho -e \"Enter the name of the file : \\c\"\nread file_name\n\nif [ -b $file_name ]\nthen\n echo \"$file_name is a block special file\"\nelse\n echo \"$file_name is not a block special file\"\nfi"
},
{
"code": null,
"e": 2825,
"s": 2817,
"text": "Output:"
},
{
"code": null,
"e": 2965,
"s": 2825,
"text": "-d file: The operator looks over if the file is present as a directory. If Yes, it returns true else false. It is [-d $file] syntactically."
},
{
"code": null,
"e": 2973,
"s": 2965,
"text": "Script:"
},
{
"code": null,
"e": 3154,
"s": 2973,
"text": "#! /bin/bash\necho -e \"Enter the name of the file : \\c\"\nread file_name\n\nif [ -d $file_name ]\nthen\n echo \"$file_name is a directory\"\nelse\n echo \"$file_name is not a directory\"\nfi"
},
{
"code": null,
"e": 3162,
"s": 3154,
"text": "Output:"
},
{
"code": null,
"e": 3324,
"s": 3162,
"text": "-e file: The operator inspects if the file exists or not. Even if a directory is passed, it returns true if the directory exists. It is [-e $file] syntactically."
},
{
"code": null,
"e": 3332,
"s": 3324,
"text": "Script:"
},
{
"code": null,
"e": 3495,
"s": 3332,
"text": "#! /bin/bash\necho -e \"Enter the name of the file : \\c\"\nread file_name\n\nif [ -e $file_name ]\nthen\n echo \"$file_name exist\"\nelse\n echo \"$file_name not exist\"\nfi"
},
{
"code": null,
"e": 3503,
"s": 3495,
"text": "Output:"
},
{
"code": null,
"e": 3626,
"s": 3503,
"text": "-f file: If the file is an ordinary file or special file, then it returns true else false. It is [-f $file] syntactically."
},
{
"code": null,
"e": 3634,
"s": 3626,
"text": "Script:"
},
{
"code": null,
"e": 3801,
"s": 3634,
"text": "#! /bin/bash\necho -e \"Enter the name of the file : \\c\"\nread file_name\n\nif [ -f $file_name ]\nthen\n echo \"$file_name is file\"\nelse\n echo \"$file_name is not file\"\nfi"
},
{
"code": null,
"e": 3809,
"s": 3801,
"text": "Output:"
},
{
"code": null,
"e": 3930,
"s": 3809,
"text": "-r file: This checks if the file is readable. If found yes, then return true else false. It is [-r $file] syntactically."
},
{
"code": null,
"e": 3938,
"s": 3930,
"text": "Script:"
},
{
"code": null,
"e": 4113,
"s": 3938,
"text": "#! /bin/bash\necho -e \"Enter the name of the file : \\c\"\nread file_name\n\nif [ -r $file_name ]\nthen\n echo \"$file_name is readable\"\nelse\n echo \"$file_name is not readable\"\nfi"
},
{
"code": null,
"e": 4121,
"s": 4113,
"text": "Output:"
},
{
"code": null,
"e": 4275,
"s": 4121,
"text": "-s file: This operator checks if the file has a size greater than zero or not, which returns true or false subsequently. It is [-s $file] syntactically."
},
{
"code": null,
"e": 4283,
"s": 4275,
"text": "Script:"
},
{
"code": null,
"e": 4454,
"s": 4283,
"text": " #! /bin/bash\necho -e \"Enter the name of the file : \\c\"\nread file_name\n\nif [ -s $file_name ]\nthen\n echo \"$file_name has size>0\"\nelse\n echo \"$file_name has size= 0\"\nfi"
},
{
"code": null,
"e": 4462,
"s": 4454,
"text": "Output:"
},
{
"code": null,
"e": 4597,
"s": 4462,
"text": "-w file: If wringing is allowed over the file, then the operator returns true, and if not then false. It is [-w $file] syntactically."
},
{
"code": null,
"e": 4605,
"s": 4597,
"text": "Script:"
},
{
"code": null,
"e": 4783,
"s": 4605,
"text": "#! /bin/bash\necho -e \"Enter the name of the file : \\c\"\nread file_name\n\nif [ -w $file_name ]\nthen\n echo \"$file_name is writable\"\nelse\n echo \"$file_name is not writable\"\nfi "
},
{
"code": null,
"e": 4792,
"s": 4783,
"text": "Output: "
},
{
"code": null,
"e": 4933,
"s": 4792,
"text": "-x file: The operator looks over if the file is executable or not, and returns true and false subsequently. It is [-x $file] syntactically."
},
{
"code": null,
"e": 4941,
"s": 4933,
"text": "Script:"
},
{
"code": null,
"e": 5123,
"s": 4941,
"text": "#! /bin/bash\necho -e \"Enter the name of the file : \\c\"\nread file_name\n\nif [ -x $file_name ]\nthen\n echo \"$file_name is executable\"\nelse\n echo \"$file_name is not executable\"\nfi "
},
{
"code": null,
"e": 5131,
"s": 5123,
"text": "Output:"
},
{
"code": null,
"e": 5261,
"s": 5131,
"text": "Rename & delete file: To rename the file, we use the ‘mv’ command which changes the name of the file and ‘rm’ to delete the file."
},
{
"code": null,
"e": 5393,
"s": 5261,
"text": "As we can see below the command line, breakingBad file (after renaming ) and deleting it with ‘rm’ command, it is no longer there."
},
{
"code": null,
"e": 5406,
"s": 5393,
"text": "simmytarika5"
},
{
"code": null,
"e": 5421,
"s": 5406,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 5442,
"s": 5421,
"text": "Linux-Shell-Commands"
},
{
"code": null,
"e": 5449,
"s": 5442,
"text": "Picked"
},
{
"code": null,
"e": 5462,
"s": 5449,
"text": "Shell Script"
},
{
"code": null,
"e": 5473,
"s": 5462,
"text": "Linux-Unix"
}
]
|
Python | Remove all values from a list present in other list | 20 Aug, 2020
Sometimes we need to perform the operation of removing all the items from the lists that are present in another list, i.e we are given some of the invalid numbers in one list which needs to be get ridden from the original list. Let’s discuss various ways in which this can be performed.Method #1: Using list comprehension The list comprehension can be used to perform the naive method in just one line and hence gives an easy method to perform this particular task.
Python3
# Python 3 code to demonstrate# to remove elements present in other list# using list comprehension # initializing listtest_list = [1, 3, 4, 6, 7] # initializing remove listremove_list = [3, 6] # printing original listprint ("The original list is : " + str(test_list)) # printing remove listprint ("The original list is : " + str(remove_list)) # using list comprehension to perform taskres = [i for i in test_list if i not in remove_list] # printing resultprint ("The list after performing remove operation is : " + str(res))
Output :
The original list is : [1, 3, 4, 6, 7]
The original list is : [3, 6]
The list after performing remove operation is : [1, 4, 7]
Method #2 : Using filter() + lambda The filter function can be used along with lambda to perform this task and creating a new filtered list of all the elements that are not present in the remove element list.
Python3
# Python 3 code to demonstrate# to remove elements present in other list# using filter() + lambda # initializing listtest_list = [1, 3, 4, 6, 7] # initializing remove listremove_list = [3, 6] # printing original listprint ("The original list is : " + str(test_list)) # printing remove listprint ("The original list is : " + str(remove_list)) # using filter() + lambda to perform taskres = filter(lambda i: i not in remove_list, test_list) # printing resultprint ("The list after performing remove operation is : " + str(res))
Output :
The original list is : [1, 3, 4, 6, 7]
The original list is : [3, 6]
The list after performing remove operation is : [1, 4, 7]
Method #3 : Using remove() remove() can also perform this task but only if the exception of not getting specific elements is handled properly. One can iterate for all the elements of the removed list and remove those elements from the original list.
Python3
# Python 3 code to demonstrate# to remove elements present in other list# using remove() # initializing listtest_list = [1, 3, 4, 6, 7] # initializing remove listremove_list = [3, 6] # printing original listprint ("The original list is : " + str(test_list)) # printing remove listprint ("The original list is : " + str(remove_list)) # using remove() to perform task# handled exceptions.for i in remove_list: try: test_list.remove(i) except ValueError: pass # printing resultprint ("The list after performing remove operation is : " + str(test_list))
Output :
The original list is : [1, 3, 4, 6, 7]
The original list is : [3, 6]
The list after performing remove operation is : [1, 4, 7]
Method #4: Using set() set() can be used to perform this task and creating a new filtered list of all the elements that are not present in the remove element list.
Python3
# Python 3 code to demonstrate# to remove elements present in other list# using set() # initializing listtest_list = [1, 3, 4, 6, 7] # initializing remove listremove_list = [3, 6] # printing original listprint ("The original list is : " + str(test_list)) # printing remove listprint ("The original list is : " + str(remove_list)) # using set() to perform taskset1 = set(test_list)set2 = set(remove_list)res = list(set1 - set2) # printing resultprint ("The list after performing remove operation is : " + str(res))
Output :
The original list is : [1, 3, 4, 6, 7]
The original list is : [3, 6]
The list after performing remove operation is : [1, 4, 7]
ritesh_nehru
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 495,
"s": 28,
"text": "Sometimes we need to perform the operation of removing all the items from the lists that are present in another list, i.e we are given some of the invalid numbers in one list which needs to be get ridden from the original list. Let’s discuss various ways in which this can be performed.Method #1: Using list comprehension The list comprehension can be used to perform the naive method in just one line and hence gives an easy method to perform this particular task. "
},
{
"code": null,
"e": 503,
"s": 495,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# to remove elements present in other list# using list comprehension # initializing listtest_list = [1, 3, 4, 6, 7] # initializing remove listremove_list = [3, 6] # printing original listprint (\"The original list is : \" + str(test_list)) # printing remove listprint (\"The original list is : \" + str(remove_list)) # using list comprehension to perform taskres = [i for i in test_list if i not in remove_list] # printing resultprint (\"The list after performing remove operation is : \" + str(res))",
"e": 1028,
"s": 503,
"text": null
},
{
"code": null,
"e": 1039,
"s": 1028,
"text": "Output : "
},
{
"code": null,
"e": 1168,
"s": 1039,
"text": "The original list is : [1, 3, 4, 6, 7]\nThe original list is : [3, 6]\nThe list after performing remove operation is : [1, 4, 7]\n\n"
},
{
"code": null,
"e": 1378,
"s": 1168,
"text": "Method #2 : Using filter() + lambda The filter function can be used along with lambda to perform this task and creating a new filtered list of all the elements that are not present in the remove element list. "
},
{
"code": null,
"e": 1386,
"s": 1378,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# to remove elements present in other list# using filter() + lambda # initializing listtest_list = [1, 3, 4, 6, 7] # initializing remove listremove_list = [3, 6] # printing original listprint (\"The original list is : \" + str(test_list)) # printing remove listprint (\"The original list is : \" + str(remove_list)) # using filter() + lambda to perform taskres = filter(lambda i: i not in remove_list, test_list) # printing resultprint (\"The list after performing remove operation is : \" + str(res))",
"e": 1912,
"s": 1386,
"text": null
},
{
"code": null,
"e": 1923,
"s": 1912,
"text": "Output : "
},
{
"code": null,
"e": 2052,
"s": 1923,
"text": "The original list is : [1, 3, 4, 6, 7]\nThe original list is : [3, 6]\nThe list after performing remove operation is : [1, 4, 7]\n\n"
},
{
"code": null,
"e": 2303,
"s": 2052,
"text": "Method #3 : Using remove() remove() can also perform this task but only if the exception of not getting specific elements is handled properly. One can iterate for all the elements of the removed list and remove those elements from the original list. "
},
{
"code": null,
"e": 2311,
"s": 2303,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# to remove elements present in other list# using remove() # initializing listtest_list = [1, 3, 4, 6, 7] # initializing remove listremove_list = [3, 6] # printing original listprint (\"The original list is : \" + str(test_list)) # printing remove listprint (\"The original list is : \" + str(remove_list)) # using remove() to perform task# handled exceptions.for i in remove_list: try: test_list.remove(i) except ValueError: pass # printing resultprint (\"The list after performing remove operation is : \" + str(test_list))",
"e": 2881,
"s": 2311,
"text": null
},
{
"code": null,
"e": 2892,
"s": 2881,
"text": "Output : "
},
{
"code": null,
"e": 3021,
"s": 2892,
"text": "The original list is : [1, 3, 4, 6, 7]\nThe original list is : [3, 6]\nThe list after performing remove operation is : [1, 4, 7]\n\n"
},
{
"code": null,
"e": 3186,
"s": 3021,
"text": "Method #4: Using set() set() can be used to perform this task and creating a new filtered list of all the elements that are not present in the remove element list. "
},
{
"code": null,
"e": 3194,
"s": 3186,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# to remove elements present in other list# using set() # initializing listtest_list = [1, 3, 4, 6, 7] # initializing remove listremove_list = [3, 6] # printing original listprint (\"The original list is : \" + str(test_list)) # printing remove listprint (\"The original list is : \" + str(remove_list)) # using set() to perform taskset1 = set(test_list)set2 = set(remove_list)res = list(set1 - set2) # printing resultprint (\"The list after performing remove operation is : \" + str(res))",
"e": 3708,
"s": 3194,
"text": null
},
{
"code": null,
"e": 3719,
"s": 3708,
"text": "Output : "
},
{
"code": null,
"e": 3848,
"s": 3719,
"text": "The original list is : [1, 3, 4, 6, 7]\nThe original list is : [3, 6]\nThe list after performing remove operation is : [1, 4, 7]\n\n"
},
{
"code": null,
"e": 3863,
"s": 3850,
"text": "ritesh_nehru"
},
{
"code": null,
"e": 3884,
"s": 3863,
"text": "Python list-programs"
},
{
"code": null,
"e": 3896,
"s": 3884,
"text": "python-list"
},
{
"code": null,
"e": 3903,
"s": 3896,
"text": "Python"
},
{
"code": null,
"e": 3915,
"s": 3903,
"text": "python-list"
}
]
|
std::string::clear in C++ | 06 Jul, 2017
The string content is set to an empty string, erasing any previous content and thus leaving its size at 0 characters.Parameters: noneReturn Value: none
void string ::clear ()
- Removes all characters (makes string empty)
- Doesn't throw any error
- Receives no parameters and returns nothing
// CPP code to illustrate// clear() function #include <iostream>#include <string>using namespace std; // Function to demo clear()void clearDemo(string str){ // Deletes all characters in string str.clear(); cout << "After clear : "; cout << str;} // Driver codeint main(){ string str("Hello World!"); cout << "Before clear : "; cout << str << endl; clearDemo(str); return 0;}
Output:
Before clear : Hello World!
After clear :
Related Article: std::string::eraseThis article is contributed by Sakshi Tiwari. If you like GeeksforGeeks (We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. 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.
cpp-strings-library
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": "\n06 Jul, 2017"
},
{
"code": null,
"e": 205,
"s": 53,
"text": "The string content is set to an empty string, erasing any previous content and thus leaving its size at 0 characters.Parameters: noneReturn Value: none"
},
{
"code": null,
"e": 345,
"s": 205,
"text": "void string ::clear ()\n- Removes all characters (makes string empty)\n- Doesn't throw any error\n- Receives no parameters and returns nothing"
},
{
"code": "// CPP code to illustrate// clear() function #include <iostream>#include <string>using namespace std; // Function to demo clear()void clearDemo(string str){ // Deletes all characters in string str.clear(); cout << \"After clear : \"; cout << str;} // Driver codeint main(){ string str(\"Hello World!\"); cout << \"Before clear : \"; cout << str << endl; clearDemo(str); return 0;}",
"e": 756,
"s": 345,
"text": null
},
{
"code": null,
"e": 764,
"s": 756,
"text": "Output:"
},
{
"code": null,
"e": 808,
"s": 764,
"text": "Before clear : Hello World!\nAfter clear : \n"
},
{
"code": null,
"e": 1162,
"s": 808,
"text": "Related Article: std::string::eraseThis article is contributed by Sakshi Tiwari. If you like GeeksforGeeks (We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 1287,
"s": 1162,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1307,
"s": 1287,
"text": "cpp-strings-library"
},
{
"code": null,
"e": 1311,
"s": 1307,
"text": "STL"
},
{
"code": null,
"e": 1315,
"s": 1311,
"text": "C++"
},
{
"code": null,
"e": 1319,
"s": 1315,
"text": "STL"
},
{
"code": null,
"e": 1323,
"s": 1319,
"text": "CPP"
}
]
|
How addEventListener works for keydown on HTML 5 Canvas ? | 30 Jan, 2020
The addEventListener() method is an inbuilt function in JavaScript which takes the event to listen for. The second argument to be called whenever the described event gets fired means the keydown event is fired whenever a key is pressed. This article explains the working of a keydown event listener on a canvas.
The canvas needs to be in focus on to catch key events. It is not possible to assign the keydown event to canvas because it is not possible to focus the canvas with the cursor. So, a workaround for this problem is to bring the canvas to focus.
Below example illustrates the working approach of addEventListner for keydown on canvas:
Example:
<!DOCTYPE html> <html> <head> <title> Working of addeventlistener for keydown on a canvas </title> <style> body { display: block; margin-top: 8%; } h1 { color:green; text-align:center; } /* Canvas decoration */ canvas { display: block; margin: 0 auto; background: green; border: 2px solid black; height: 300px; width: 300px; } </style></head> <body> <h1>GeeksforGeeks</h1> <canvas id="canvas"></canvas> <script> var lastDownTarget, canvas; window.onload = function() { canvas = document.getElementById('canvas'); /* For mouse event */ document.addEventListener('mousedown', function(event) { lastDownTarget = event.target; alert('Mousedown Event'); }, false); /* For keyboard event */ document.addEventListener('keydown', function(event) { if(lastDownTarget == canvas) { alert('Keydown event! Key pressed: ' + event.key); } }, false); } </script></body> </html>
Output: First, the canvas is brought to focus on using the mousedown event. After the canvas is brought to focus, the keydown event is fired.
CSS-Misc
HTML-Canvas
HTML-Misc
JavaScript-Misc
Picked
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 340,
"s": 28,
"text": "The addEventListener() method is an inbuilt function in JavaScript which takes the event to listen for. The second argument to be called whenever the described event gets fired means the keydown event is fired whenever a key is pressed. This article explains the working of a keydown event listener on a canvas."
},
{
"code": null,
"e": 584,
"s": 340,
"text": "The canvas needs to be in focus on to catch key events. It is not possible to assign the keydown event to canvas because it is not possible to focus the canvas with the cursor. So, a workaround for this problem is to bring the canvas to focus."
},
{
"code": null,
"e": 673,
"s": 584,
"text": "Below example illustrates the working approach of addEventListner for keydown on canvas:"
},
{
"code": null,
"e": 682,
"s": 673,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> Working of addeventlistener for keydown on a canvas </title> <style> body { display: block; margin-top: 8%; } h1 { color:green; text-align:center; } /* Canvas decoration */ canvas { display: block; margin: 0 auto; background: green; border: 2px solid black; height: 300px; width: 300px; } </style></head> <body> <h1>GeeksforGeeks</h1> <canvas id=\"canvas\"></canvas> <script> var lastDownTarget, canvas; window.onload = function() { canvas = document.getElementById('canvas'); /* For mouse event */ document.addEventListener('mousedown', function(event) { lastDownTarget = event.target; alert('Mousedown Event'); }, false); /* For keyboard event */ document.addEventListener('keydown', function(event) { if(lastDownTarget == canvas) { alert('Keydown event! Key pressed: ' + event.key); } }, false); } </script></body> </html>",
"e": 2090,
"s": 682,
"text": null
},
{
"code": null,
"e": 2232,
"s": 2090,
"text": "Output: First, the canvas is brought to focus on using the mousedown event. After the canvas is brought to focus, the keydown event is fired."
},
{
"code": null,
"e": 2241,
"s": 2232,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2253,
"s": 2241,
"text": "HTML-Canvas"
},
{
"code": null,
"e": 2263,
"s": 2253,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2279,
"s": 2263,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2286,
"s": 2279,
"text": "Picked"
},
{
"code": null,
"e": 2291,
"s": 2286,
"text": "HTML"
},
{
"code": null,
"e": 2302,
"s": 2291,
"text": "JavaScript"
},
{
"code": null,
"e": 2319,
"s": 2302,
"text": "Web Technologies"
},
{
"code": null,
"e": 2346,
"s": 2319,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2351,
"s": 2346,
"text": "HTML"
},
{
"code": null,
"e": 2449,
"s": 2351,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2473,
"s": 2449,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2512,
"s": 2473,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2551,
"s": 2512,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2571,
"s": 2551,
"text": "Angular File Upload"
},
{
"code": null,
"e": 2600,
"s": 2571,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2661,
"s": 2600,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2733,
"s": 2661,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2773,
"s": 2733,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2815,
"s": 2773,
"text": "Roadmap to Learn JavaScript For Beginners"
}
]
|
JavaScript While Loop | 15 Nov, 2021
A While Loop in Javascript is a control flow statement that allows the code to be executed repeatedly based on the given boolean condition. The while loop can be thought of as a repeating if statement.
The loop can be used to execute the specific block of code multiple times until it failed to match the condition.
There are mainly two types of loops:
Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop body. For Loop and While Loop are entry-controlled loops.
Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. the do-while loop is exit controlled loop.
Syntax:
while (condition) {
// Statements
}
Example: This example illustrates the use of a while loop.
HTML
<!DOCTYPE html><html> <head> <title>JavaScript While loop</title></head> <body style="text-align:center;"> <div> <h1>GeeksForGeeks</h1> <h2>JavaScript While Loop</h2> </div> <p id="GFG"></p> <!-- Script to use while loop --> <script> var print = ""; var val = 1; while(val < 6) { print += "Geeks " + val; print += "<br>" val += 1; } document.getElementById("GFG").innerHTML = print; </script></body> </html>
Output:
while loop
Do-While loop: A do-while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block or not depending on a given boolean condition at the end of the block.
Syntax:
do {
// Statements
}
while (condition);
Example: This example illustrates the use of the do-while loop.
HTML
<!DOCTYPE html><html> <head> <title>JavaScript While loop</title></head> <body style="text-align:center;"> <div> <h1>GeeksforGeeks</h1> <h2>JavaScript Do-while Loop</h2> </div> <p id="GFG"></p> <!-- Script to use do-while loop --> <script> var print = "" var val = 0; do { print += "Geeks " + val; print += "<br>"; val += 1; } while (val < 6); document.getElementById("GFG").innerHTML = print; </script></body> </html>
Output:
Do-while Loop
Comparison between while and do-while loop: The do-while loop executes the content of the loop once before checking the condition of the while loop. While the while loop will check the condition first before executing the content.
While Loop
Do-While Loop
It is an entry condition looping structure.
It is an exit condition looping structure.
The number of iterations depends on the condition mentioned in the while block.
Irrespective of the condition mentioned in the do-while block, there will a minimum of 1 iteration.
The block control condition is available at the starting point of the loop.
The block control condition is available at the endpoint of the loop.
Example: This example illustrates both while and do-while loops.
HTML
<!DOCTYPE html><html> <head> <title>JavaScript loop</title></head> <body style="text-align:center;"> <div> <h1 style="color:green;"> GeeksforGeeks </h1> <h2>JavaScript Loop</h2> </div> <h3>While Loop</h3> <p id="GFG"></p> <!-- Script to use while loop --> <script> var text = ""; var i = 1; while(i < 6) { text += "Geeks " + i + "<br>"; i++; } document.getElementById("GFG").innerHTML = text; </script> <h3>Do While Loop</h3> <p id="GFG1"></p> <!-- Script to use do-while loop --> <script> var text = "" var i = 1; do { text += "Geeks " + i + "<br>"; i++; } while (i < 6); document.getElementById("GFG1").innerHTML = text; </script></body> </html>
Output:
Javascript Loop
bhaskargeeksforgeeks
javascript-basics
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Differences between Functional Components and Class Components in React
Hide or show elements in HTML using display property
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 230,
"s": 28,
"text": "A While Loop in Javascript is a control flow statement that allows the code to be executed repeatedly based on the given boolean condition. The while loop can be thought of as a repeating if statement."
},
{
"code": null,
"e": 344,
"s": 230,
"text": "The loop can be used to execute the specific block of code multiple times until it failed to match the condition."
},
{
"code": null,
"e": 381,
"s": 344,
"text": "There are mainly two types of loops:"
},
{
"code": null,
"e": 539,
"s": 381,
"text": "Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop body. For Loop and While Loop are entry-controlled loops."
},
{
"code": null,
"e": 811,
"s": 539,
"text": "Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. the do-while loop is exit controlled loop."
},
{
"code": null,
"e": 819,
"s": 811,
"text": "Syntax:"
},
{
"code": null,
"e": 859,
"s": 819,
"text": "while (condition) {\n // Statements\n}"
},
{
"code": null,
"e": 918,
"s": 859,
"text": "Example: This example illustrates the use of a while loop."
},
{
"code": null,
"e": 923,
"s": 918,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>JavaScript While loop</title></head> <body style=\"text-align:center;\"> <div> <h1>GeeksForGeeks</h1> <h2>JavaScript While Loop</h2> </div> <p id=\"GFG\"></p> <!-- Script to use while loop --> <script> var print = \"\"; var val = 1; while(val < 6) { print += \"Geeks \" + val; print += \"<br>\" val += 1; } document.getElementById(\"GFG\").innerHTML = print; </script></body> </html>",
"e": 1408,
"s": 923,
"text": null
},
{
"code": null,
"e": 1416,
"s": 1408,
"text": "Output:"
},
{
"code": null,
"e": 1427,
"s": 1416,
"text": "while loop"
},
{
"code": null,
"e": 1641,
"s": 1427,
"text": "Do-While loop: A do-while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block or not depending on a given boolean condition at the end of the block."
},
{
"code": null,
"e": 1649,
"s": 1641,
"text": "Syntax:"
},
{
"code": null,
"e": 1693,
"s": 1649,
"text": "do {\n // Statements\n}\nwhile (condition);"
},
{
"code": null,
"e": 1757,
"s": 1693,
"text": "Example: This example illustrates the use of the do-while loop."
},
{
"code": null,
"e": 1762,
"s": 1757,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>JavaScript While loop</title></head> <body style=\"text-align:center;\"> <div> <h1>GeeksforGeeks</h1> <h2>JavaScript Do-while Loop</h2> </div> <p id=\"GFG\"></p> <!-- Script to use do-while loop --> <script> var print = \"\" var val = 0; do { print += \"Geeks \" + val; print += \"<br>\"; val += 1; } while (val < 6); document.getElementById(\"GFG\").innerHTML = print; </script></body> </html>",
"e": 2258,
"s": 1762,
"text": null
},
{
"code": null,
"e": 2266,
"s": 2258,
"text": "Output:"
},
{
"code": null,
"e": 2280,
"s": 2266,
"text": "Do-while Loop"
},
{
"code": null,
"e": 2511,
"s": 2280,
"text": "Comparison between while and do-while loop: The do-while loop executes the content of the loop once before checking the condition of the while loop. While the while loop will check the condition first before executing the content."
},
{
"code": null,
"e": 2522,
"s": 2511,
"text": "While Loop"
},
{
"code": null,
"e": 2536,
"s": 2522,
"text": "Do-While Loop"
},
{
"code": null,
"e": 2580,
"s": 2536,
"text": "It is an entry condition looping structure."
},
{
"code": null,
"e": 2623,
"s": 2580,
"text": "It is an exit condition looping structure."
},
{
"code": null,
"e": 2703,
"s": 2623,
"text": "The number of iterations depends on the condition mentioned in the while block."
},
{
"code": null,
"e": 2803,
"s": 2703,
"text": "Irrespective of the condition mentioned in the do-while block, there will a minimum of 1 iteration."
},
{
"code": null,
"e": 2879,
"s": 2803,
"text": "The block control condition is available at the starting point of the loop."
},
{
"code": null,
"e": 2949,
"s": 2879,
"text": "The block control condition is available at the endpoint of the loop."
},
{
"code": null,
"e": 3014,
"s": 2949,
"text": "Example: This example illustrates both while and do-while loops."
},
{
"code": null,
"e": 3019,
"s": 3014,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>JavaScript loop</title></head> <body style=\"text-align:center;\"> <div> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2>JavaScript Loop</h2> </div> <h3>While Loop</h3> <p id=\"GFG\"></p> <!-- Script to use while loop --> <script> var text = \"\"; var i = 1; while(i < 6) { text += \"Geeks \" + i + \"<br>\"; i++; } document.getElementById(\"GFG\").innerHTML = text; </script> <h3>Do While Loop</h3> <p id=\"GFG1\"></p> <!-- Script to use do-while loop --> <script> var text = \"\" var i = 1; do { text += \"Geeks \" + i + \"<br>\"; i++; } while (i < 6); document.getElementById(\"GFG1\").innerHTML = text; </script></body> </html>",
"e": 3803,
"s": 3019,
"text": null
},
{
"code": null,
"e": 3811,
"s": 3803,
"text": "Output:"
},
{
"code": null,
"e": 3827,
"s": 3811,
"text": "Javascript Loop"
},
{
"code": null,
"e": 3848,
"s": 3827,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 3866,
"s": 3848,
"text": "javascript-basics"
},
{
"code": null,
"e": 3873,
"s": 3866,
"text": "Picked"
},
{
"code": null,
"e": 3884,
"s": 3873,
"text": "JavaScript"
},
{
"code": null,
"e": 3901,
"s": 3884,
"text": "Web Technologies"
},
{
"code": null,
"e": 3999,
"s": 3901,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4041,
"s": 3999,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4102,
"s": 4041,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4142,
"s": 4102,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4214,
"s": 4142,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4267,
"s": 4214,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 4329,
"s": 4267,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4362,
"s": 4329,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4404,
"s": 4362,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4465,
"s": 4404,
"text": "Difference between var, let and const keywords in JavaScript"
}
]
|
ReactJS Reactstrap Media Component | 28 Jul, 2021
Reactstrap is a bootstrap-based react UI library that is used to make good-looking webpages with its seamless and easy-to-use component.
In this article, we will see how to use the Media Component in Reactstrap. The media component is used to add some media to our project.
Properties:
Tag: In ReactStrap Media Component, Tag is a property that is used to set the tag in the component. It takes string and function values.
className: In ReactStrap Media Component className define the class name of the component. With the help of className, you can add the styling using CSS.
heading: In ReactStrap Media Component heading is the property in reactStrap is used to set the heading in the text. It takes a boolean value as the default argument.
middle: In the reactStrap, the middle property is used to set the middle alignment between the two objects. It takes a boolean value.
fluid: In ReactStrap Media Component fluid is applies .container-fluid class and if string then it applies .container-{breakpoint} class.
block: In ReactStrap Media Component block props are used to indicate whether the block should have a block style or not.
color: The color props in the reactStrap are used to set the color of the element in the component.
body: The body properties in the media component are used to set the body of the element. By default, it takes a boolean value.
bottom: The bottom properties are used to fix the position in the bottom of the components. It should be true or false, it takes a boolean value.
children: children properties are used to set the children of the element in components. It takes a node value.
heading: heading properties is used to set the heading of the element, by default it takes takes a boolean value.
left: left properties are used to set the alignment of the element on the left side of the component, it takes a boolean value .
<Media>
Content
</media>
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command.
cd foldername
Step 3: Install Reactstrap in your given directory.
npm install --save reactstrap react react-dom
Step 4: Import the element to be used in the project.
import {Media} from 'reactstrap'
Project Structure: It will look like the following.
Project Structure:
Step to Run Application: Run the application from the root directory of the project, using the following command.
npm start
Example 1: this is the basic example that shows how to use the media component.
App.js
import React from "react";import { Media } from "reactstrap";import "bootstrap/dist/css/bootstrap.min.css";export default function App() { return ( <div className="App"> <Media> <Media left href="#"> <Media object src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210728124621/geekslogo.png" alt="cat" /> </Media> <Media body> <br></br> <Media heading>GFG DSA Course</Media> <br></br> I Want to learn DSA but don't know where to start? Don't worry, this course is a complete package for you to learn all the concepts at your own pace. It's perfect for students and working professionals who know at least anyone coding language. </Media> </Media> </div> );}
Output:
Example 2: In this example, we will see how to use tag property in media.
App.js
Javascript
import React from 'react';import { Media } from 'reactstrap'; const gfg = (props) => { return ( <div id='gfg'> <br /> <Media tag='a' href= 'https://www.geeksforgeeks.org/'> <Media body> <Media heading> GeeksforGeeks </Media> Reactstrap is a bootstrap based react UI library that is used to make good looking webpages with its seamless and easy to use component. </Media> </Media> </div> );} export default gfg;
Output:
Reference: https://reactstrap.github.io/components/media
Reactstrap
JavaScript
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": "\n28 Jul, 2021"
},
{
"code": null,
"e": 165,
"s": 28,
"text": "Reactstrap is a bootstrap-based react UI library that is used to make good-looking webpages with its seamless and easy-to-use component."
},
{
"code": null,
"e": 302,
"s": 165,
"text": "In this article, we will see how to use the Media Component in Reactstrap. The media component is used to add some media to our project."
},
{
"code": null,
"e": 314,
"s": 302,
"text": "Properties:"
},
{
"code": null,
"e": 451,
"s": 314,
"text": "Tag: In ReactStrap Media Component, Tag is a property that is used to set the tag in the component. It takes string and function values."
},
{
"code": null,
"e": 605,
"s": 451,
"text": "className: In ReactStrap Media Component className define the class name of the component. With the help of className, you can add the styling using CSS."
},
{
"code": null,
"e": 772,
"s": 605,
"text": "heading: In ReactStrap Media Component heading is the property in reactStrap is used to set the heading in the text. It takes a boolean value as the default argument."
},
{
"code": null,
"e": 906,
"s": 772,
"text": "middle: In the reactStrap, the middle property is used to set the middle alignment between the two objects. It takes a boolean value."
},
{
"code": null,
"e": 1044,
"s": 906,
"text": "fluid: In ReactStrap Media Component fluid is applies .container-fluid class and if string then it applies .container-{breakpoint} class."
},
{
"code": null,
"e": 1166,
"s": 1044,
"text": "block: In ReactStrap Media Component block props are used to indicate whether the block should have a block style or not."
},
{
"code": null,
"e": 1266,
"s": 1166,
"text": "color: The color props in the reactStrap are used to set the color of the element in the component."
},
{
"code": null,
"e": 1394,
"s": 1266,
"text": "body: The body properties in the media component are used to set the body of the element. By default, it takes a boolean value."
},
{
"code": null,
"e": 1540,
"s": 1394,
"text": "bottom: The bottom properties are used to fix the position in the bottom of the components. It should be true or false, it takes a boolean value."
},
{
"code": null,
"e": 1652,
"s": 1540,
"text": "children: children properties are used to set the children of the element in components. It takes a node value."
},
{
"code": null,
"e": 1766,
"s": 1652,
"text": "heading: heading properties is used to set the heading of the element, by default it takes takes a boolean value."
},
{
"code": null,
"e": 1895,
"s": 1766,
"text": "left: left properties are used to set the alignment of the element on the left side of the component, it takes a boolean value ."
},
{
"code": null,
"e": 1922,
"s": 1895,
"text": "<Media>\n Content\n</media>"
},
{
"code": null,
"e": 1972,
"s": 1922,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 2036,
"s": 1972,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 2068,
"s": 2036,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 2169,
"s": 2068,
"text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command."
},
{
"code": null,
"e": 2183,
"s": 2169,
"text": "cd foldername"
},
{
"code": null,
"e": 2235,
"s": 2183,
"text": "Step 3: Install Reactstrap in your given directory."
},
{
"code": null,
"e": 2282,
"s": 2235,
"text": " npm install --save reactstrap react react-dom"
},
{
"code": null,
"e": 2336,
"s": 2282,
"text": "Step 4: Import the element to be used in the project."
},
{
"code": null,
"e": 2369,
"s": 2336,
"text": "import {Media} from 'reactstrap'"
},
{
"code": null,
"e": 2423,
"s": 2371,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 2442,
"s": 2423,
"text": "Project Structure:"
},
{
"code": null,
"e": 2556,
"s": 2442,
"text": "Step to Run Application: Run the application from the root directory of the project, using the following command."
},
{
"code": null,
"e": 2566,
"s": 2556,
"text": "npm start"
},
{
"code": null,
"e": 2646,
"s": 2566,
"text": "Example 1: this is the basic example that shows how to use the media component."
},
{
"code": null,
"e": 2653,
"s": 2646,
"text": "App.js"
},
{
"code": "import React from \"react\";import { Media } from \"reactstrap\";import \"bootstrap/dist/css/bootstrap.min.css\";export default function App() { return ( <div className=\"App\"> <Media> <Media left href=\"#\"> <Media object src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210728124621/geekslogo.png\" alt=\"cat\" /> </Media> <Media body> <br></br> <Media heading>GFG DSA Course</Media> <br></br> I Want to learn DSA but don't know where to start? Don't worry, this course is a complete package for you to learn all the concepts at your own pace. It's perfect for students and working professionals who know at least anyone coding language. </Media> </Media> </div> );}",
"e": 3707,
"s": 2653,
"text": null
},
{
"code": null,
"e": 3716,
"s": 3707,
"text": "Output: "
},
{
"code": null,
"e": 3790,
"s": 3716,
"text": "Example 2: In this example, we will see how to use tag property in media."
},
{
"code": null,
"e": 3797,
"s": 3790,
"text": "App.js"
},
{
"code": null,
"e": 3808,
"s": 3797,
"text": "Javascript"
},
{
"code": "import React from 'react';import { Media } from 'reactstrap'; const gfg = (props) => { return ( <div id='gfg'> <br /> <Media tag='a' href= 'https://www.geeksforgeeks.org/'> <Media body> <Media heading> GeeksforGeeks </Media> Reactstrap is a bootstrap based react UI library that is used to make good looking webpages with its seamless and easy to use component. </Media> </Media> </div> );} export default gfg;",
"e": 4476,
"s": 3808,
"text": null
},
{
"code": null,
"e": 4485,
"s": 4476,
"text": "Output: "
},
{
"code": null,
"e": 4542,
"s": 4485,
"text": "Reference: https://reactstrap.github.io/components/media"
},
{
"code": null,
"e": 4553,
"s": 4542,
"text": "Reactstrap"
},
{
"code": null,
"e": 4564,
"s": 4553,
"text": "JavaScript"
},
{
"code": null,
"e": 4572,
"s": 4564,
"text": "ReactJS"
},
{
"code": null,
"e": 4589,
"s": 4572,
"text": "Web Technologies"
}
]
|
Node.js URLsearchParams API | 10 Jul, 2020
Node.js is an open-source project widely used for the development of dynamic web applications. The URLSearchParams API in Node.js allows read and write operations on the URL query.
The URLSearchParams class is a global object and used with one of the four following constructors.
Constructors:
new URLSearchParams(): No argument constructor instantiates a new empty URLSearchParams object.new URLSearchParams(string): Accepts a string as an argument to instantiate a new URLSearchParams object.var params = new URLSearchParams('user=abc&q=xyz');console.log(params.get('user'));console.log(params.get('q'));Output:abc
xyznew URLSearchParams(obj): Accepts an object with a collection of key-value pairs to instantiate a new URLSearchParams object. The key-value pair of obj are always coerced to strings. Duplicate keys are not allowed.const params = new URLSearchParams({ user: 'ana', course: ['math', 'chem', 'phys']});console.log(params.toString());Output:user=ana&course=math%2Cchem%2Cphysnew URLSearchParams(iterable): Accepts an iterable object having a collection of key-value pairs to instantiate a new URLSearchParams object. Iterable can be any iterable object. Since URLSearchParams is iterable, an iterable object can be another URLSearchParams, where the constructor will create a clone of the provided URLSearchParams. Duplicate keys are allowed.// Using a Map object as it is iterableconst map = new Map();map.set('West Bengal', 'Kolkata');map.set('Karnataka', 'Bengaluru');params = new URLSearchParams(map);console.log(params.toString());Output:West+Bengal=Kolkata&Karnataka=Bengaluru
new URLSearchParams(): No argument constructor instantiates a new empty URLSearchParams object.
new URLSearchParams(string): Accepts a string as an argument to instantiate a new URLSearchParams object.var params = new URLSearchParams('user=abc&q=xyz');console.log(params.get('user'));console.log(params.get('q'));Output:abc
xyz
var params = new URLSearchParams('user=abc&q=xyz');console.log(params.get('user'));console.log(params.get('q'));
Output:
abc
xyz
new URLSearchParams(obj): Accepts an object with a collection of key-value pairs to instantiate a new URLSearchParams object. The key-value pair of obj are always coerced to strings. Duplicate keys are not allowed.const params = new URLSearchParams({ user: 'ana', course: ['math', 'chem', 'phys']});console.log(params.toString());Output:user=ana&course=math%2Cchem%2Cphys
const params = new URLSearchParams({ user: 'ana', course: ['math', 'chem', 'phys']});console.log(params.toString());
Output:
user=ana&course=math%2Cchem%2Cphys
new URLSearchParams(iterable): Accepts an iterable object having a collection of key-value pairs to instantiate a new URLSearchParams object. Iterable can be any iterable object. Since URLSearchParams is iterable, an iterable object can be another URLSearchParams, where the constructor will create a clone of the provided URLSearchParams. Duplicate keys are allowed.// Using a Map object as it is iterableconst map = new Map();map.set('West Bengal', 'Kolkata');map.set('Karnataka', 'Bengaluru');params = new URLSearchParams(map);console.log(params.toString());Output:West+Bengal=Kolkata&Karnataka=Bengaluru
// Using a Map object as it is iterableconst map = new Map();map.set('West Bengal', 'Kolkata');map.set('Karnataka', 'Bengaluru');params = new URLSearchParams(map);console.log(params.toString());
Output:
West+Bengal=Kolkata&Karnataka=Bengaluru
Accessing the URL query:
urlSearchParams.get(name): Returns the value of the first name-value pair that matches with the argument passed. If no such pair exists, null is returned.const myURL = new URL( 'https://example.org/?abc=123&abc=526'); console.log(myURL.searchParams.get('abc'));Output:123
const myURL = new URL( 'https://example.org/?abc=123&abc=526'); console.log(myURL.searchParams.get('abc'));
Output:
123
urlSearchParams.getAll(name): Returns all the value of the name-value pair that matches with the argument passed. If no such pair exists, null is returned.const myURL = new URL( 'https://example.org/?abc=123&abc=526');console.log(myURL.searchParams.getAll('abc'));Output:[ '123', '526' ]
const myURL = new URL( 'https://example.org/?abc=123&abc=526');console.log(myURL.searchParams.getAll('abc'));
Output:
[ '123', '526' ]
urlSearchParams.has(name): Returns true if the argument passed matches with any existing name of the name-value pair else returns false.const myURL = new URL( 'https://example.org/?abc=123&xyz=526');console.log(myURL.searchParams.has('abc'));console.log(myURL.searchParams.has('pqr'));Output:true
false
const myURL = new URL( 'https://example.org/?abc=123&xyz=526');console.log(myURL.searchParams.has('abc'));console.log(myURL.searchParams.has('pqr'));
Output:
true
false
Manipulating the URL query:
urlSearchParams.set(name, value): Sets the value in the URLSearchParams object associated with name to the specified value. If more than one name-value pairs exists, whose names are same as the ‘name’ argument, then the only value of first matching pair is changed, rest all are removed.const params = new URLSearchParams( 'abc=123&xyz=526&abc=258');console.log(params.toString());params.set('abc', 'opq');console.log(params.toString());Output:abc=123&xyz=526&abc=258
abc=opq&xyz=526
const params = new URLSearchParams( 'abc=123&xyz=526&abc=258');console.log(params.toString());params.set('abc', 'opq');console.log(params.toString());
Output:
abc=123&xyz=526&abc=258
abc=opq&xyz=526
urlSearchParams.append(name, value): Appends a new name-value pair to the existing URLSearchParams query.const params = new URLSearchParams('xyz=123');params.append('foo', '789');params.append('xyz', 'zoo');params.append('foo', 'def');console.log(params.toString());Output:xyz=123&foo=789&xyz=zoo&foo=def
const params = new URLSearchParams('xyz=123');params.append('foo', '789');params.append('xyz', 'zoo');params.append('foo', 'def');console.log(params.toString());
Output:
xyz=123&foo=789&xyz=zoo&foo=def
urlSearchParams.delete(name): Removes all name-value pairs whose name is same as ‘name’ argument.const params = new URLSearchParams( 'xyz=123&foo=789&xyz=zoo&foo=def');console.log(params.toString());params.delete('foo');console.log(params.toString());Output:xyz=123&foo=789&xyz=zoo&foo=def
xyz=123&xyz=zoo
const params = new URLSearchParams( 'xyz=123&foo=789&xyz=zoo&foo=def');console.log(params.toString());params.delete('foo');console.log(params.toString());
Output:
xyz=123&foo=789&xyz=zoo&foo=def
xyz=123&xyz=zoo
urlSearchParams.sort(): Sorts the existing name-value pairs in-place by their names using a stable sorting algorithm.const params = new URLSearchParams( 'query=node&type=search&abc=programs');params.sort();console.log(params.toString());Output:abc=programs&query=node&type=search
const params = new URLSearchParams( 'query=node&type=search&abc=programs');params.sort();console.log(params.toString());
Output:
abc=programs&query=node&type=search
urlSearchParams.toString(): Returns the URL search parameters as a string, with characters percent-encoded wherever necessary.const params = new URLSearchParams( 'query=node&type=search&passwd[]=3456');console.log(params.toString());Output:query=node&type=search&passwd%5B%5D=3456
const params = new URLSearchParams( 'query=node&type=search&passwd[]=3456');console.log(params.toString());
Output:
query=node&type=search&passwd%5B%5D=3456
Iterating the URL query:
urlSearchParams.entries(): Returns an iterator over the entry set of the param object.const params = new URLSearchParams( 'query=node&type=search&passwd=3456');for(var pair of params.entries()) { console.log(pair[0]+ '-->'+ pair[1]); }Output:query-->node
type-->search
passwd-->3456
const params = new URLSearchParams( 'query=node&type=search&passwd=3456');for(var pair of params.entries()) { console.log(pair[0]+ '-->'+ pair[1]); }
Output:
query-->node
type-->search
passwd-->3456
urlSearchParams.keys(): Returns an iterator over the key set of the param object.const params = new URLSearchParams( 'query=node&type=search&passwd=3456');for(var key of params.keys()) { console.log(key); }Output:query
type
passwd
const params = new URLSearchParams( 'query=node&type=search&passwd=3456');for(var key of params.keys()) { console.log(key); }
Output:
query
type
passwd
urlSearchParams.values(): Returns an iterator over the value set of the param object.const params = new URLSearchParams( 'query=node&type=search&passwd=3456');for(var value of params.values()) { console.log(value); }Output:node
search
3456
const params = new URLSearchParams( 'query=node&type=search&passwd=3456');for(var value of params.values()) { console.log(value); }
Output:
node
search
3456
urlSearchParams.forEach(fn[, arg]): fn is a function invoked for each name-value pair in the query and arg is an object to be used when ‘fn’ is called. It iterates over each name-value pair in the query and invokes the function.const myURL = new URL( 'https://example.com/?a=b&c=d&d=z');myURL.searchParams.forEach( (value, name, searchParams) => {console.log(name, value, myURL.searchParams === searchParams);});Output:a b true
c d true
d z true
const myURL = new URL( 'https://example.com/?a=b&c=d&d=z');myURL.searchParams.forEach( (value, name, searchParams) => {console.log(name, value, myURL.searchParams === searchParams);});
Output:
a b true
c d true
d z true
urlSearchParams[Symbol.iterator]():const params=new URLSearchParams( 'firstname=john&lastname=beck&gender=male');for (const [name, value] of params) { console.log(name, value);}Output:firstname john
lastname beck
gender male
const params=new URLSearchParams( 'firstname=john&lastname=beck&gender=male');for (const [name, value] of params) { console.log(name, value);}
Output:
firstname john
lastname beck
gender male
Node.js-Basics
Picked
Node.js
Web Technologies
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 ?
Node.js fs.readFileSync() Method
How to update NPM ?
Node.js fs.writeFile() Method
Difference between promise and async await in Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Roadmap to Learn JavaScript For Beginners | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 234,
"s": 53,
"text": "Node.js is an open-source project widely used for the development of dynamic web applications. The URLSearchParams API in Node.js allows read and write operations on the URL query."
},
{
"code": null,
"e": 333,
"s": 234,
"text": "The URLSearchParams class is a global object and used with one of the four following constructors."
},
{
"code": null,
"e": 347,
"s": 333,
"text": "Constructors:"
},
{
"code": null,
"e": 1654,
"s": 347,
"text": "new URLSearchParams(): No argument constructor instantiates a new empty URLSearchParams object.new URLSearchParams(string): Accepts a string as an argument to instantiate a new URLSearchParams object.var params = new URLSearchParams('user=abc&q=xyz');console.log(params.get('user'));console.log(params.get('q'));Output:abc\nxyznew URLSearchParams(obj): Accepts an object with a collection of key-value pairs to instantiate a new URLSearchParams object. The key-value pair of obj are always coerced to strings. Duplicate keys are not allowed.const params = new URLSearchParams({ user: 'ana', course: ['math', 'chem', 'phys']});console.log(params.toString());Output:user=ana&course=math%2Cchem%2Cphysnew URLSearchParams(iterable): Accepts an iterable object having a collection of key-value pairs to instantiate a new URLSearchParams object. Iterable can be any iterable object. Since URLSearchParams is iterable, an iterable object can be another URLSearchParams, where the constructor will create a clone of the provided URLSearchParams. Duplicate keys are allowed.// Using a Map object as it is iterableconst map = new Map();map.set('West Bengal', 'Kolkata');map.set('Karnataka', 'Bengaluru');params = new URLSearchParams(map);console.log(params.toString());Output:West+Bengal=Kolkata&Karnataka=Bengaluru"
},
{
"code": null,
"e": 1750,
"s": 1654,
"text": "new URLSearchParams(): No argument constructor instantiates a new empty URLSearchParams object."
},
{
"code": null,
"e": 1982,
"s": 1750,
"text": "new URLSearchParams(string): Accepts a string as an argument to instantiate a new URLSearchParams object.var params = new URLSearchParams('user=abc&q=xyz');console.log(params.get('user'));console.log(params.get('q'));Output:abc\nxyz"
},
{
"code": "var params = new URLSearchParams('user=abc&q=xyz');console.log(params.get('user'));console.log(params.get('q'));",
"e": 2095,
"s": 1982,
"text": null
},
{
"code": null,
"e": 2103,
"s": 2095,
"text": "Output:"
},
{
"code": null,
"e": 2111,
"s": 2103,
"text": "abc\nxyz"
},
{
"code": null,
"e": 2485,
"s": 2111,
"text": "new URLSearchParams(obj): Accepts an object with a collection of key-value pairs to instantiate a new URLSearchParams object. The key-value pair of obj are always coerced to strings. Duplicate keys are not allowed.const params = new URLSearchParams({ user: 'ana', course: ['math', 'chem', 'phys']});console.log(params.toString());Output:user=ana&course=math%2Cchem%2Cphys"
},
{
"code": "const params = new URLSearchParams({ user: 'ana', course: ['math', 'chem', 'phys']});console.log(params.toString());",
"e": 2604,
"s": 2485,
"text": null
},
{
"code": null,
"e": 2612,
"s": 2604,
"text": "Output:"
},
{
"code": null,
"e": 2647,
"s": 2612,
"text": "user=ana&course=math%2Cchem%2Cphys"
},
{
"code": null,
"e": 3255,
"s": 2647,
"text": "new URLSearchParams(iterable): Accepts an iterable object having a collection of key-value pairs to instantiate a new URLSearchParams object. Iterable can be any iterable object. Since URLSearchParams is iterable, an iterable object can be another URLSearchParams, where the constructor will create a clone of the provided URLSearchParams. Duplicate keys are allowed.// Using a Map object as it is iterableconst map = new Map();map.set('West Bengal', 'Kolkata');map.set('Karnataka', 'Bengaluru');params = new URLSearchParams(map);console.log(params.toString());Output:West+Bengal=Kolkata&Karnataka=Bengaluru"
},
{
"code": "// Using a Map object as it is iterableconst map = new Map();map.set('West Bengal', 'Kolkata');map.set('Karnataka', 'Bengaluru');params = new URLSearchParams(map);console.log(params.toString());",
"e": 3450,
"s": 3255,
"text": null
},
{
"code": null,
"e": 3458,
"s": 3450,
"text": "Output:"
},
{
"code": null,
"e": 3498,
"s": 3458,
"text": "West+Bengal=Kolkata&Karnataka=Bengaluru"
},
{
"code": null,
"e": 3523,
"s": 3498,
"text": "Accessing the URL query:"
},
{
"code": null,
"e": 3797,
"s": 3523,
"text": "urlSearchParams.get(name): Returns the value of the first name-value pair that matches with the argument passed. If no such pair exists, null is returned.const myURL = new URL( 'https://example.org/?abc=123&abc=526'); console.log(myURL.searchParams.get('abc'));Output:123"
},
{
"code": "const myURL = new URL( 'https://example.org/?abc=123&abc=526'); console.log(myURL.searchParams.get('abc'));",
"e": 3907,
"s": 3797,
"text": null
},
{
"code": null,
"e": 3915,
"s": 3907,
"text": "Output:"
},
{
"code": null,
"e": 3919,
"s": 3915,
"text": "123"
},
{
"code": null,
"e": 4208,
"s": 3919,
"text": "urlSearchParams.getAll(name): Returns all the value of the name-value pair that matches with the argument passed. If no such pair exists, null is returned.const myURL = new URL( 'https://example.org/?abc=123&abc=526');console.log(myURL.searchParams.getAll('abc'));Output:[ '123', '526' ]"
},
{
"code": "const myURL = new URL( 'https://example.org/?abc=123&abc=526');console.log(myURL.searchParams.getAll('abc'));",
"e": 4319,
"s": 4208,
"text": null
},
{
"code": null,
"e": 4327,
"s": 4319,
"text": "Output:"
},
{
"code": null,
"e": 4344,
"s": 4327,
"text": "[ '123', '526' ]"
},
{
"code": null,
"e": 4648,
"s": 4344,
"text": "urlSearchParams.has(name): Returns true if the argument passed matches with any existing name of the name-value pair else returns false.const myURL = new URL( 'https://example.org/?abc=123&xyz=526');console.log(myURL.searchParams.has('abc'));console.log(myURL.searchParams.has('pqr'));Output:true\nfalse"
},
{
"code": "const myURL = new URL( 'https://example.org/?abc=123&xyz=526');console.log(myURL.searchParams.has('abc'));console.log(myURL.searchParams.has('pqr'));",
"e": 4799,
"s": 4648,
"text": null
},
{
"code": null,
"e": 4807,
"s": 4799,
"text": "Output:"
},
{
"code": null,
"e": 4818,
"s": 4807,
"text": "true\nfalse"
},
{
"code": null,
"e": 4846,
"s": 4818,
"text": "Manipulating the URL query:"
},
{
"code": null,
"e": 5333,
"s": 4846,
"text": "urlSearchParams.set(name, value): Sets the value in the URLSearchParams object associated with name to the specified value. If more than one name-value pairs exists, whose names are same as the ‘name’ argument, then the only value of first matching pair is changed, rest all are removed.const params = new URLSearchParams( 'abc=123&xyz=526&abc=258');console.log(params.toString());params.set('abc', 'opq');console.log(params.toString());Output:abc=123&xyz=526&abc=258\nabc=opq&xyz=526"
},
{
"code": "const params = new URLSearchParams( 'abc=123&xyz=526&abc=258');console.log(params.toString());params.set('abc', 'opq');console.log(params.toString());",
"e": 5487,
"s": 5333,
"text": null
},
{
"code": null,
"e": 5495,
"s": 5487,
"text": "Output:"
},
{
"code": null,
"e": 5535,
"s": 5495,
"text": "abc=123&xyz=526&abc=258\nabc=opq&xyz=526"
},
{
"code": null,
"e": 5840,
"s": 5535,
"text": "urlSearchParams.append(name, value): Appends a new name-value pair to the existing URLSearchParams query.const params = new URLSearchParams('xyz=123');params.append('foo', '789');params.append('xyz', 'zoo');params.append('foo', 'def');console.log(params.toString());Output:xyz=123&foo=789&xyz=zoo&foo=def"
},
{
"code": "const params = new URLSearchParams('xyz=123');params.append('foo', '789');params.append('xyz', 'zoo');params.append('foo', 'def');console.log(params.toString());",
"e": 6002,
"s": 5840,
"text": null
},
{
"code": null,
"e": 6010,
"s": 6002,
"text": "Output:"
},
{
"code": null,
"e": 6042,
"s": 6010,
"text": "xyz=123&foo=789&xyz=zoo&foo=def"
},
{
"code": null,
"e": 6349,
"s": 6042,
"text": "urlSearchParams.delete(name): Removes all name-value pairs whose name is same as ‘name’ argument.const params = new URLSearchParams( 'xyz=123&foo=789&xyz=zoo&foo=def');console.log(params.toString());params.delete('foo');console.log(params.toString());Output:xyz=123&foo=789&xyz=zoo&foo=def\nxyz=123&xyz=zoo"
},
{
"code": "const params = new URLSearchParams( 'xyz=123&foo=789&xyz=zoo&foo=def');console.log(params.toString());params.delete('foo');console.log(params.toString());",
"e": 6505,
"s": 6349,
"text": null
},
{
"code": null,
"e": 6513,
"s": 6505,
"text": "Output:"
},
{
"code": null,
"e": 6561,
"s": 6513,
"text": "xyz=123&foo=789&xyz=zoo&foo=def\nxyz=123&xyz=zoo"
},
{
"code": null,
"e": 6842,
"s": 6561,
"text": "urlSearchParams.sort(): Sorts the existing name-value pairs in-place by their names using a stable sorting algorithm.const params = new URLSearchParams( 'query=node&type=search&abc=programs');params.sort();console.log(params.toString());Output:abc=programs&query=node&type=search"
},
{
"code": "const params = new URLSearchParams( 'query=node&type=search&abc=programs');params.sort();console.log(params.toString());",
"e": 6964,
"s": 6842,
"text": null
},
{
"code": null,
"e": 6972,
"s": 6964,
"text": "Output:"
},
{
"code": null,
"e": 7008,
"s": 6972,
"text": "abc=programs&query=node&type=search"
},
{
"code": null,
"e": 7290,
"s": 7008,
"text": "urlSearchParams.toString(): Returns the URL search parameters as a string, with characters percent-encoded wherever necessary.const params = new URLSearchParams( 'query=node&type=search&passwd[]=3456');console.log(params.toString());Output:query=node&type=search&passwd%5B%5D=3456"
},
{
"code": "const params = new URLSearchParams( 'query=node&type=search&passwd[]=3456');console.log(params.toString());",
"e": 7399,
"s": 7290,
"text": null
},
{
"code": null,
"e": 7407,
"s": 7399,
"text": "Output:"
},
{
"code": null,
"e": 7448,
"s": 7407,
"text": "query=node&type=search&passwd%5B%5D=3456"
},
{
"code": null,
"e": 7473,
"s": 7448,
"text": "Iterating the URL query:"
},
{
"code": null,
"e": 7761,
"s": 7473,
"text": "urlSearchParams.entries(): Returns an iterator over the entry set of the param object.const params = new URLSearchParams( 'query=node&type=search&passwd=3456');for(var pair of params.entries()) { console.log(pair[0]+ '-->'+ pair[1]); }Output:query-->node\ntype-->search\npasswd-->3456"
},
{
"code": "const params = new URLSearchParams( 'query=node&type=search&passwd=3456');for(var pair of params.entries()) { console.log(pair[0]+ '-->'+ pair[1]); }",
"e": 7916,
"s": 7761,
"text": null
},
{
"code": null,
"e": 7924,
"s": 7916,
"text": "Output:"
},
{
"code": null,
"e": 7965,
"s": 7924,
"text": "query-->node\ntype-->search\npasswd-->3456"
},
{
"code": null,
"e": 8201,
"s": 7965,
"text": "urlSearchParams.keys(): Returns an iterator over the key set of the param object.const params = new URLSearchParams( 'query=node&type=search&passwd=3456');for(var key of params.keys()) { console.log(key); }Output:query\ntype\npasswd"
},
{
"code": "const params = new URLSearchParams( 'query=node&type=search&passwd=3456');for(var key of params.keys()) { console.log(key); }",
"e": 8332,
"s": 8201,
"text": null
},
{
"code": null,
"e": 8340,
"s": 8332,
"text": "Output:"
},
{
"code": null,
"e": 8358,
"s": 8340,
"text": "query\ntype\npasswd"
},
{
"code": null,
"e": 8603,
"s": 8358,
"text": "urlSearchParams.values(): Returns an iterator over the value set of the param object.const params = new URLSearchParams( 'query=node&type=search&passwd=3456');for(var value of params.values()) { console.log(value); }Output:node\nsearch\n3456"
},
{
"code": "const params = new URLSearchParams( 'query=node&type=search&passwd=3456');for(var value of params.values()) { console.log(value); }",
"e": 8740,
"s": 8603,
"text": null
},
{
"code": null,
"e": 8748,
"s": 8740,
"text": "Output:"
},
{
"code": null,
"e": 8765,
"s": 8748,
"text": "node\nsearch\n3456"
},
{
"code": null,
"e": 9215,
"s": 8765,
"text": "urlSearchParams.forEach(fn[, arg]): fn is a function invoked for each name-value pair in the query and arg is an object to be used when ‘fn’ is called. It iterates over each name-value pair in the query and invokes the function.const myURL = new URL( 'https://example.com/?a=b&c=d&d=z');myURL.searchParams.forEach( (value, name, searchParams) => {console.log(name, value, myURL.searchParams === searchParams);});Output:a b true\nc d true\nd z true"
},
{
"code": "const myURL = new URL( 'https://example.com/?a=b&c=d&d=z');myURL.searchParams.forEach( (value, name, searchParams) => {console.log(name, value, myURL.searchParams === searchParams);});",
"e": 9404,
"s": 9215,
"text": null
},
{
"code": null,
"e": 9412,
"s": 9404,
"text": "Output:"
},
{
"code": null,
"e": 9439,
"s": 9412,
"text": "a b true\nc d true\nd z true"
},
{
"code": null,
"e": 9669,
"s": 9439,
"text": "urlSearchParams[Symbol.iterator]():const params=new URLSearchParams( 'firstname=john&lastname=beck&gender=male');for (const [name, value] of params) { console.log(name, value);}Output:firstname john\nlastname beck\ngender male\n"
},
{
"code": "const params=new URLSearchParams( 'firstname=john&lastname=beck&gender=male');for (const [name, value] of params) { console.log(name, value);}",
"e": 9816,
"s": 9669,
"text": null
},
{
"code": null,
"e": 9824,
"s": 9816,
"text": "Output:"
},
{
"code": null,
"e": 9866,
"s": 9824,
"text": "firstname john\nlastname beck\ngender male\n"
},
{
"code": null,
"e": 9881,
"s": 9866,
"text": "Node.js-Basics"
},
{
"code": null,
"e": 9888,
"s": 9881,
"text": "Picked"
},
{
"code": null,
"e": 9896,
"s": 9888,
"text": "Node.js"
},
{
"code": null,
"e": 9913,
"s": 9896,
"text": "Web Technologies"
},
{
"code": null,
"e": 10011,
"s": 9913,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10059,
"s": 10011,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 10092,
"s": 10059,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 10112,
"s": 10092,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 10142,
"s": 10112,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 10196,
"s": 10142,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 10258,
"s": 10196,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 10319,
"s": 10258,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 10362,
"s": 10319,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 10412,
"s": 10362,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Java Program To Merge K Sorted Linked Lists Using Min Heap - Set 2 - GeeksforGeeks | 10 Jan, 2022
Given k linked lists each of size n and each list is sorted in non-decreasing order, merge them into a single sorted (non-decreasing order) linked list and print the sorted linked list as output.Examples:
Input: k = 3, n = 4
list1 = 1->3->5->7->NULL
list2 = 2->4->6->8->NULL
list3 = 0->9->10->11->NULL
Output: 0->1->2->3->4->5->6->7->8->9->10->11
Merged lists in a sorted order
where every element is greater
than the previous element.
Input: k = 3, n = 3
list1 = 1->3->7->NULL
list2 = 2->4->8->NULL
list3 = 9->10->11->NULL
Output: 1->2->3->4->7->8->9->10->11
Merged lists in a sorted order
where every element is greater
than the previous element.
Source: Merge K sorted Linked Lists | Method 2
An efficient solution for the problem has been discussed in Method 3 of this post.
Approach: This solution is based on the MIN HEAP approach used to solve the problem ‘merge k sorted arrays’ which is discussed here.MinHeap: A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored at index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2.
Create a min-heap and insert the first element of all the ‘k’ linked lists.As long as the min-heap is not empty, perform the following steps:Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap.Return the head node address of the merged list.
Create a min-heap and insert the first element of all the ‘k’ linked lists.
As long as the min-heap is not empty, perform the following steps:Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap.
Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.
If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap.
Return the head node address of the merged list.
Below is the implementation of the above approach:
Java
// Java implementation to merge// k sorted linked lists// Using MIN HEAP methodimport java.util.PriorityQueue;import java.util.Comparator;public class MergeKLists { // Function to merge k sorted // linked lists public static Node mergeKSortedLists( Node arr[], int k) { Node head = null, last = null; // priority_queue 'pq' implemeted // as min heap with the // help of 'compare' function PriorityQueue<Node> pq = new PriorityQueue<>(new Comparator<Node>() { public int compare(Node a, Node b) { return a.data - b.data; } }); // Push the head nodes of all // the k lists in 'pq' for (int i = 0; i < k; i++) if (arr[i] != null) pq.add(arr[i]); // Loop till 'pq' is not empty while (!pq.isEmpty()) { // Get the top element of 'pq' Node top = pq.peek(); pq.remove(); // Check if there is a node // next to the 'top' node // in the list of which 'top' // node is a member if (top.next != null) // push the next node in 'pq' pq.add(top.next); // if final merged list is empty if (head == null) { head = top; // Points to the last node so far // of the final merged list last = top; } else { // Insert 'top' at the end of the // merged list so far last.next = top; // Update the 'last' pointer last = top; } } // Head node of the required merged list return head; } // Function to print the singly linked list public static void printList(Node head) { while (head != null) { System.out.print(head.data + " "); head = head.next; } } // Utility function to create // a new node public Node push(int data) { Node newNode = new Node(data); newNode.next = null; return newNode; } public static void main(String args[]) { // Number of linked lists int k = 3; // Number of elements in each list int n = 4; // An array of pointers storing the // head nodes of the linked lists Node arr[] = new Node[k]; arr[0] = new Node(1); arr[0].next = new Node(3); arr[0].next.next = new Node(5); arr[0].next.next.next = new Node(7); arr[1] = new Node(2); arr[1].next = new Node(4); arr[1].next.next = new Node(6); arr[1].next.next.next = new Node(8); arr[2] = new Node(0); arr[2].next = new Node(9); arr[2].next.next = new Node(10); arr[2].next.next.next = new Node(11); // Merge all lists Node head = mergeKSortedLists(arr, k); printList(head); }} class Node { int data; Node next; Node(int data) { this.data = data; next = null; }}// This code is contributed by Gaurav Tiwari
Output:
0 1 2 3 4 5 6 7 8 9 10 11
Complexity Analysis:
Time Complexity: O(N * log k) or O(n * k * log k), where, ‘N’ is the total number of elements among all the linked lists, ‘k’ is the total number of lists, and ‘n’ is the size of each linked list.Insertion and deletion operation will be performed in min-heap for all N nodes.Insertion and deletion in a min-heap require log k time.
Auxiliary Space: O(k). The priority queue will have atmost ‘k’ number of elements at any point of time, hence the additional space required for our algorithm is O(k).
Please refer complete article on Merge k sorted linked lists | Set 2 (Using Min Heap) for more details!
Amazon
VMWare
Heap
Java Programs
Linked List
VMWare
Amazon
Linked List
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Insertion and Deletion in Heaps
Building Heap from Array
Sliding Window Maximum (Maximum of all subarrays of size k)
Max Heap in Java
Time Complexity of building a heap
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 26447,
"s": 26419,
"text": "\n10 Jan, 2022"
},
{
"code": null,
"e": 26653,
"s": 26447,
"text": "Given k linked lists each of size n and each list is sorted in non-decreasing order, merge them into a single sorted (non-decreasing order) linked list and print the sorted linked list as output.Examples: "
},
{
"code": null,
"e": 27106,
"s": 26653,
"text": "Input: k = 3, n = 4\nlist1 = 1->3->5->7->NULL\nlist2 = 2->4->6->8->NULL\nlist3 = 0->9->10->11->NULL\n\nOutput: 0->1->2->3->4->5->6->7->8->9->10->11\nMerged lists in a sorted order \nwhere every element is greater \nthan the previous element.\n\nInput: k = 3, n = 3\nlist1 = 1->3->7->NULL\nlist2 = 2->4->8->NULL\nlist3 = 9->10->11->NULL\n\nOutput: 1->2->3->4->7->8->9->10->11\nMerged lists in a sorted order \nwhere every element is greater \nthan the previous element."
},
{
"code": null,
"e": 27153,
"s": 27106,
"text": "Source: Merge K sorted Linked Lists | Method 2"
},
{
"code": null,
"e": 27236,
"s": 27153,
"text": "An efficient solution for the problem has been discussed in Method 3 of this post."
},
{
"code": null,
"e": 27696,
"s": 27236,
"text": "Approach: This solution is based on the MIN HEAP approach used to solve the problem ‘merge k sorted arrays’ which is discussed here.MinHeap: A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored at index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2."
},
{
"code": null,
"e": 28155,
"s": 27696,
"text": "Create a min-heap and insert the first element of all the ‘k’ linked lists.As long as the min-heap is not empty, perform the following steps:Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap.Return the head node address of the merged list."
},
{
"code": null,
"e": 28231,
"s": 28155,
"text": "Create a min-heap and insert the first element of all the ‘k’ linked lists."
},
{
"code": null,
"e": 28567,
"s": 28231,
"text": "As long as the min-heap is not empty, perform the following steps:Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap."
},
{
"code": null,
"e": 28707,
"s": 28567,
"text": "Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list."
},
{
"code": null,
"e": 28838,
"s": 28707,
"text": "If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap."
},
{
"code": null,
"e": 28887,
"s": 28838,
"text": "Return the head node address of the merged list."
},
{
"code": null,
"e": 28938,
"s": 28887,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28943,
"s": 28938,
"text": "Java"
},
{
"code": "// Java implementation to merge// k sorted linked lists// Using MIN HEAP methodimport java.util.PriorityQueue;import java.util.Comparator;public class MergeKLists { // Function to merge k sorted // linked lists public static Node mergeKSortedLists( Node arr[], int k) { Node head = null, last = null; // priority_queue 'pq' implemeted // as min heap with the // help of 'compare' function PriorityQueue<Node> pq = new PriorityQueue<>(new Comparator<Node>() { public int compare(Node a, Node b) { return a.data - b.data; } }); // Push the head nodes of all // the k lists in 'pq' for (int i = 0; i < k; i++) if (arr[i] != null) pq.add(arr[i]); // Loop till 'pq' is not empty while (!pq.isEmpty()) { // Get the top element of 'pq' Node top = pq.peek(); pq.remove(); // Check if there is a node // next to the 'top' node // in the list of which 'top' // node is a member if (top.next != null) // push the next node in 'pq' pq.add(top.next); // if final merged list is empty if (head == null) { head = top; // Points to the last node so far // of the final merged list last = top; } else { // Insert 'top' at the end of the // merged list so far last.next = top; // Update the 'last' pointer last = top; } } // Head node of the required merged list return head; } // Function to print the singly linked list public static void printList(Node head) { while (head != null) { System.out.print(head.data + \" \"); head = head.next; } } // Utility function to create // a new node public Node push(int data) { Node newNode = new Node(data); newNode.next = null; return newNode; } public static void main(String args[]) { // Number of linked lists int k = 3; // Number of elements in each list int n = 4; // An array of pointers storing the // head nodes of the linked lists Node arr[] = new Node[k]; arr[0] = new Node(1); arr[0].next = new Node(3); arr[0].next.next = new Node(5); arr[0].next.next.next = new Node(7); arr[1] = new Node(2); arr[1].next = new Node(4); arr[1].next.next = new Node(6); arr[1].next.next.next = new Node(8); arr[2] = new Node(0); arr[2].next = new Node(9); arr[2].next.next = new Node(10); arr[2].next.next.next = new Node(11); // Merge all lists Node head = mergeKSortedLists(arr, k); printList(head); }} class Node { int data; Node next; Node(int data) { this.data = data; next = null; }}// This code is contributed by Gaurav Tiwari",
"e": 32196,
"s": 28943,
"text": null
},
{
"code": null,
"e": 32204,
"s": 32196,
"text": "Output:"
},
{
"code": null,
"e": 32231,
"s": 32204,
"text": "0 1 2 3 4 5 6 7 8 9 10 11 "
},
{
"code": null,
"e": 32253,
"s": 32231,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 32585,
"s": 32253,
"text": "Time Complexity: O(N * log k) or O(n * k * log k), where, ‘N’ is the total number of elements among all the linked lists, ‘k’ is the total number of lists, and ‘n’ is the size of each linked list.Insertion and deletion operation will be performed in min-heap for all N nodes.Insertion and deletion in a min-heap require log k time."
},
{
"code": null,
"e": 32752,
"s": 32585,
"text": "Auxiliary Space: O(k). The priority queue will have atmost ‘k’ number of elements at any point of time, hence the additional space required for our algorithm is O(k)."
},
{
"code": null,
"e": 32856,
"s": 32752,
"text": "Please refer complete article on Merge k sorted linked lists | Set 2 (Using Min Heap) for more details!"
},
{
"code": null,
"e": 32863,
"s": 32856,
"text": "Amazon"
},
{
"code": null,
"e": 32870,
"s": 32863,
"text": "VMWare"
},
{
"code": null,
"e": 32875,
"s": 32870,
"text": "Heap"
},
{
"code": null,
"e": 32889,
"s": 32875,
"text": "Java Programs"
},
{
"code": null,
"e": 32901,
"s": 32889,
"text": "Linked List"
},
{
"code": null,
"e": 32908,
"s": 32901,
"text": "VMWare"
},
{
"code": null,
"e": 32915,
"s": 32908,
"text": "Amazon"
},
{
"code": null,
"e": 32927,
"s": 32915,
"text": "Linked List"
},
{
"code": null,
"e": 32932,
"s": 32927,
"text": "Heap"
},
{
"code": null,
"e": 33030,
"s": 32932,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33062,
"s": 33030,
"text": "Insertion and Deletion in Heaps"
},
{
"code": null,
"e": 33087,
"s": 33062,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 33147,
"s": 33087,
"text": "Sliding Window Maximum (Maximum of all subarrays of size k)"
},
{
"code": null,
"e": 33164,
"s": 33147,
"text": "Max Heap in Java"
},
{
"code": null,
"e": 33199,
"s": 33164,
"text": "Time Complexity of building a heap"
},
{
"code": null,
"e": 33227,
"s": 33199,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 33271,
"s": 33227,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 33297,
"s": 33271,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 33331,
"s": 33297,
"text": "Convert Double to Integer in Java"
}
]
|
Difference between SHA1 and SHA256 - GeeksforGeeks | 28 Dec, 2020
1. SHA1 (Secure Hash Algorithm 1) :SHA1 refers to a cryptographic hash function that is proposed by United States National Security Agency. It takes an input and produces a output of 160 bits hash value. Furthermore the output produced by this function is converted into a 40 digits long hexadecimal number. It is known as U.S. Federal Information Processing Standard. It was first published in 1995. It is successor to SH0 published in 1993.
Example :
Data : Geeksforgeeks
SHA1 : bc7623b7a94ed3d8feaffaf7580df3eca4f5f5ca
2. SHA256 :SHA-256 is a more secure and newer cryptographic hash function that was launched in 2000 as a new version of SHA functions and was adopted as FIPS standard in 2002. It is allowed to use a hash generator tool to produce a SHA256 hash for any string or input value. Also, it generates 256 hash values, and the internal state size is 256 bit and the original message size is up to 264-1 bits.
Example :
Data : Geeksforgeeks
SHA256 : e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
Difference between SHA1 and SHA256 :
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Introduction and IPv4 Datagram Header
Intrusion Detection System (IDS)
Secure Socket Layer (SSL)
Cryptography and its Types
Difference between BFS and DFS
Class method vs Static method in Python
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Stack vs Heap Memory Allocation | [
{
"code": null,
"e": 25755,
"s": 25727,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 26198,
"s": 25755,
"text": "1. SHA1 (Secure Hash Algorithm 1) :SHA1 refers to a cryptographic hash function that is proposed by United States National Security Agency. It takes an input and produces a output of 160 bits hash value. Furthermore the output produced by this function is converted into a 40 digits long hexadecimal number. It is known as U.S. Federal Information Processing Standard. It was first published in 1995. It is successor to SH0 published in 1993."
},
{
"code": null,
"e": 26208,
"s": 26198,
"text": "Example :"
},
{
"code": null,
"e": 26278,
"s": 26208,
"text": "Data : Geeksforgeeks\nSHA1 : bc7623b7a94ed3d8feaffaf7580df3eca4f5f5ca\n"
},
{
"code": null,
"e": 26679,
"s": 26278,
"text": "2. SHA256 :SHA-256 is a more secure and newer cryptographic hash function that was launched in 2000 as a new version of SHA functions and was adopted as FIPS standard in 2002. It is allowed to use a hash generator tool to produce a SHA256 hash for any string or input value. Also, it generates 256 hash values, and the internal state size is 256 bit and the original message size is up to 264-1 bits."
},
{
"code": null,
"e": 26689,
"s": 26679,
"text": "Example :"
},
{
"code": null,
"e": 26784,
"s": 26689,
"text": "Data : Geeksforgeeks\nSHA256 : e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
{
"code": null,
"e": 26821,
"s": 26784,
"text": "Difference between SHA1 and SHA256 :"
},
{
"code": null,
"e": 26839,
"s": 26821,
"text": "Computer Networks"
},
{
"code": null,
"e": 26858,
"s": 26839,
"text": "Difference Between"
},
{
"code": null,
"e": 26876,
"s": 26858,
"text": "Computer Networks"
},
{
"code": null,
"e": 26974,
"s": 26876,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27009,
"s": 26974,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 27047,
"s": 27009,
"text": "Introduction and IPv4 Datagram Header"
},
{
"code": null,
"e": 27080,
"s": 27047,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 27106,
"s": 27080,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 27133,
"s": 27106,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 27164,
"s": 27133,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 27204,
"s": 27164,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 27265,
"s": 27204,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27333,
"s": 27265,
"text": "Difference Between Method Overloading and Method Overriding in Java"
}
]
|
Python program to find occurrence to each character in given string - GeeksforGeeks | 20 May, 2019
Given a string, the task is to write a program in Python which prints the number of occurrences of each character in a string.
There are multiple ways in Python, we can do this task. Let’s discuss a few of them.
Method #1: Using set() + count()
Iterate over the set converted string and get the count of each character in original string.
# Python3 code to program to find occurrence# to each character in given string # initializing string inp_str = "GeeksforGeeks" # using set() + count() to get count # of each element in string out = {x : inp_str.count(x) for x in set(inp_str )} # printing result print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(out))
Occurrence of all characters in GeeksforGeeks is :
{'o': 1, 'r': 1, 'e': 4, 's': 2, 'f': 1, 'G': 2, 'k': 2}
Method #2: Using dictionary
# Python3 code to program to find occurrence# to each character in given string # initializing string inp_str = "GeeksforGeeks" # frequency dictionaryfreq = {} for ele in inp_str: if ele in freq: freq[ele] += 1 else: freq[ele] = 1 # printing result print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(freq))
Occurrence of all characters in GeeksforGeeks is :
{'e': 4, 'r': 1, 'o': 1, 'f': 1, 'G': 2, 's': 2, 'k': 2}
Method #3: Using collections
# Python3 code to program to find occurrence# to each character in given stringfrom collections import Counter # initializing string in_str = "GeeksforGeeks" # using collections.Counter() to get # count of each element in string oup = Counter(in_str) # printing result print ("Occurrence of all characters in GeeksforGeeks is :\n "+ str(oup))
Occurrence of all characters in GeeksforGeeks is :
Counter({'e': 4, 's': 2, 'G': 2, 'k': 2, 'f': 1, 'r': 1, 'o': 1})
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25563,
"s": 25535,
"text": "\n20 May, 2019"
},
{
"code": null,
"e": 25690,
"s": 25563,
"text": "Given a string, the task is to write a program in Python which prints the number of occurrences of each character in a string."
},
{
"code": null,
"e": 25775,
"s": 25690,
"text": "There are multiple ways in Python, we can do this task. Let’s discuss a few of them."
},
{
"code": null,
"e": 25808,
"s": 25775,
"text": "Method #1: Using set() + count()"
},
{
"code": null,
"e": 25902,
"s": 25808,
"text": "Iterate over the set converted string and get the count of each character in original string."
},
{
"code": "# Python3 code to program to find occurrence# to each character in given string # initializing string inp_str = \"GeeksforGeeks\" # using set() + count() to get count # of each element in string out = {x : inp_str.count(x) for x in set(inp_str )} # printing result print (\"Occurrence of all characters in GeeksforGeeks is :\\n \"+ str(out)) ",
"e": 26244,
"s": 25902,
"text": null
},
{
"code": null,
"e": 26354,
"s": 26244,
"text": "Occurrence of all characters in GeeksforGeeks is :\n {'o': 1, 'r': 1, 'e': 4, 's': 2, 'f': 1, 'G': 2, 'k': 2}\n"
},
{
"code": null,
"e": 26383,
"s": 26354,
"text": " Method #2: Using dictionary"
},
{
"code": "# Python3 code to program to find occurrence# to each character in given string # initializing string inp_str = \"GeeksforGeeks\" # frequency dictionaryfreq = {} for ele in inp_str: if ele in freq: freq[ele] += 1 else: freq[ele] = 1 # printing result print (\"Occurrence of all characters in GeeksforGeeks is :\\n \"+ str(freq)) ",
"e": 26741,
"s": 26383,
"text": null
},
{
"code": null,
"e": 26851,
"s": 26741,
"text": "Occurrence of all characters in GeeksforGeeks is :\n {'e': 4, 'r': 1, 'o': 1, 'f': 1, 'G': 2, 's': 2, 'k': 2}\n"
},
{
"code": null,
"e": 26881,
"s": 26851,
"text": " Method #3: Using collections"
},
{
"code": "# Python3 code to program to find occurrence# to each character in given stringfrom collections import Counter # initializing string in_str = \"GeeksforGeeks\" # using collections.Counter() to get # count of each element in string oup = Counter(in_str) # printing result print (\"Occurrence of all characters in GeeksforGeeks is :\\n \"+ str(oup)) ",
"e": 27240,
"s": 26881,
"text": null
},
{
"code": null,
"e": 27359,
"s": 27240,
"text": "Occurrence of all characters in GeeksforGeeks is :\n Counter({'e': 4, 's': 2, 'G': 2, 'k': 2, 'f': 1, 'r': 1, 'o': 1})\n"
},
{
"code": null,
"e": 27380,
"s": 27359,
"text": "Python list-programs"
},
{
"code": null,
"e": 27387,
"s": 27380,
"text": "Python"
},
{
"code": null,
"e": 27403,
"s": 27387,
"text": "Python Programs"
},
{
"code": null,
"e": 27501,
"s": 27403,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27533,
"s": 27501,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27575,
"s": 27533,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27617,
"s": 27575,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27673,
"s": 27617,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27700,
"s": 27673,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27722,
"s": 27700,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27761,
"s": 27722,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27807,
"s": 27761,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27845,
"s": 27807,
"text": "Python | Convert a list to dictionary"
}
]
|
JvmStatic, JvmOverloads, and JvmField in Kotlin - GeeksforGeeks | 19 Sep, 2021
In this article, we’ll look at how to utilize Kotlin code in our current Java code using @JvmStatic, @JvmOverloads, and @JvmField in Kotlin. You may invoke Kotlin code from Java code and vice versa. This blog will concentrate on invoking Kotlin code from Java code.
Kotlin
Java
// Kotlin Classclass GeeksforGeeks// Calling from Kotlinval article = Article()
// Class in Java being calledArticle geeksforgeeks = new Article();
As you can see in the preceding code, calling the Kotlin code from the Java code is fairly straightforward, but there are times when it is not. In those instances, we utilize @JvmStatic, @JvmOverloads, and @JvmField in Kotlin to make it simple for someone calling the Kotlin code from Java.
Package-level functions are represented as static methods in Kotlin. You can also use the @JvmStatic annotation in Kotlin to create static methods for functions specified in a companion object or named object. As an example:
Kotlin
object GeeksforGeeks { fun useSomeLogic() { // your code goes here }}
Let’s call Kotlin now:
Kotlin
GeeksforGeeks.useSomeLogic()
You’ll need to make a call like this from Java.
Java
GeeksforGeeks.INSTANCE.useSomeLogic();
How can we make it function if we don’t use the INSTANCE?
JvmStatic is the answer.
Kotlin
object GeeksforGeeks { @JvmStatic fun useSomeLogic() { // logic goes here }}
Java
GeeksforGeeks.useSomeLogic();
If you do not supply a date in the argument, the current date will be used by default in the above code. So, if we call from Kotlin, the following code will execute without error:
Kotlin
val articleOne = Event("GeeksforGeeks")val articleTwo = Event("Android", Date())
However, if we call the same function from Java, we must supply all of the arguments, or we would receive the following error:
Java
Article articleOne = new Event("GeeksforGeeks");Article articleTwo = new Event("GeeksforGeeks", new Date());
We’ve passed both arguments. So, what’s the point of using the default value if we have to pass both values?
So, we can use the @JvmOverloads annotation to utilize the default value. Following the use of the annotation, the Kotlin code will be:
data class GeeksforGeeks @JvmOverloads constructor( val articleName: String, val date: Date = Date())
Let’s use the Event class from the previous section of the article as an example.
data class GeeksforGeeks ( val articleName: String, val date: Date = Date())
So, if you want a certain field to be utilized as a regular field rather than a getter or setter, you must instruct the compiler not to produce any getter or setter for it, which you can accomplish by using the @JvmField annotation. So, after applying the @JvmField annotation, the Kotlin code will be:
data class Article (@JvmField val geeksforgeeks: String, val date: Date = Date())
Now, in Java, you can access the class’s fields in the same manner as you can in Kotlin:
Java
Article newArticle = new Event("GeeksforGeeks", new Date());String articleName = newArticle.name;
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters | [
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n19 Sep, 2021"
},
{
"code": null,
"e": 26647,
"s": 26381,
"text": "In this article, we’ll look at how to utilize Kotlin code in our current Java code using @JvmStatic, @JvmOverloads, and @JvmField in Kotlin. You may invoke Kotlin code from Java code and vice versa. This blog will concentrate on invoking Kotlin code from Java code."
},
{
"code": null,
"e": 26654,
"s": 26647,
"text": "Kotlin"
},
{
"code": null,
"e": 26659,
"s": 26654,
"text": "Java"
},
{
"code": "// Kotlin Classclass GeeksforGeeks// Calling from Kotlinval article = Article()",
"e": 26739,
"s": 26659,
"text": null
},
{
"code": "// Class in Java being calledArticle geeksforgeeks = new Article();",
"e": 26807,
"s": 26739,
"text": null
},
{
"code": null,
"e": 27098,
"s": 26807,
"text": "As you can see in the preceding code, calling the Kotlin code from the Java code is fairly straightforward, but there are times when it is not. In those instances, we utilize @JvmStatic, @JvmOverloads, and @JvmField in Kotlin to make it simple for someone calling the Kotlin code from Java."
},
{
"code": null,
"e": 27323,
"s": 27098,
"text": "Package-level functions are represented as static methods in Kotlin. You can also use the @JvmStatic annotation in Kotlin to create static methods for functions specified in a companion object or named object. As an example:"
},
{
"code": null,
"e": 27330,
"s": 27323,
"text": "Kotlin"
},
{
"code": "object GeeksforGeeks { fun useSomeLogic() { // your code goes here }}",
"e": 27413,
"s": 27330,
"text": null
},
{
"code": null,
"e": 27436,
"s": 27413,
"text": "Let’s call Kotlin now:"
},
{
"code": null,
"e": 27443,
"s": 27436,
"text": "Kotlin"
},
{
"code": "GeeksforGeeks.useSomeLogic()",
"e": 27472,
"s": 27443,
"text": null
},
{
"code": null,
"e": 27520,
"s": 27472,
"text": "You’ll need to make a call like this from Java."
},
{
"code": null,
"e": 27525,
"s": 27520,
"text": "Java"
},
{
"code": "GeeksforGeeks.INSTANCE.useSomeLogic();",
"e": 27564,
"s": 27525,
"text": null
},
{
"code": null,
"e": 27622,
"s": 27564,
"text": "How can we make it function if we don’t use the INSTANCE?"
},
{
"code": null,
"e": 27647,
"s": 27622,
"text": "JvmStatic is the answer."
},
{
"code": null,
"e": 27654,
"s": 27647,
"text": "Kotlin"
},
{
"code": "object GeeksforGeeks { @JvmStatic fun useSomeLogic() { // logic goes here }}",
"e": 27747,
"s": 27654,
"text": null
},
{
"code": null,
"e": 27752,
"s": 27747,
"text": "Java"
},
{
"code": "GeeksforGeeks.useSomeLogic();",
"e": 27782,
"s": 27752,
"text": null
},
{
"code": null,
"e": 27962,
"s": 27782,
"text": "If you do not supply a date in the argument, the current date will be used by default in the above code. So, if we call from Kotlin, the following code will execute without error:"
},
{
"code": null,
"e": 27969,
"s": 27962,
"text": "Kotlin"
},
{
"code": "val articleOne = Event(\"GeeksforGeeks\")val articleTwo = Event(\"Android\", Date())",
"e": 28050,
"s": 27969,
"text": null
},
{
"code": null,
"e": 28177,
"s": 28050,
"text": "However, if we call the same function from Java, we must supply all of the arguments, or we would receive the following error:"
},
{
"code": null,
"e": 28182,
"s": 28177,
"text": "Java"
},
{
"code": "Article articleOne = new Event(\"GeeksforGeeks\");Article articleTwo = new Event(\"GeeksforGeeks\", new Date());",
"e": 28291,
"s": 28182,
"text": null
},
{
"code": null,
"e": 28400,
"s": 28291,
"text": "We’ve passed both arguments. So, what’s the point of using the default value if we have to pass both values?"
},
{
"code": null,
"e": 28536,
"s": 28400,
"text": "So, we can use the @JvmOverloads annotation to utilize the default value. Following the use of the annotation, the Kotlin code will be:"
},
{
"code": null,
"e": 28638,
"s": 28536,
"text": "data class GeeksforGeeks @JvmOverloads constructor( val articleName: String, val date: Date = Date())"
},
{
"code": null,
"e": 28720,
"s": 28638,
"text": "Let’s use the Event class from the previous section of the article as an example."
},
{
"code": null,
"e": 28797,
"s": 28720,
"text": "data class GeeksforGeeks ( val articleName: String, val date: Date = Date())"
},
{
"code": null,
"e": 29100,
"s": 28797,
"text": "So, if you want a certain field to be utilized as a regular field rather than a getter or setter, you must instruct the compiler not to produce any getter or setter for it, which you can accomplish by using the @JvmField annotation. So, after applying the @JvmField annotation, the Kotlin code will be:"
},
{
"code": null,
"e": 29182,
"s": 29100,
"text": "data class Article (@JvmField val geeksforgeeks: String, val date: Date = Date())"
},
{
"code": null,
"e": 29271,
"s": 29182,
"text": "Now, in Java, you can access the class’s fields in the same manner as you can in Kotlin:"
},
{
"code": null,
"e": 29276,
"s": 29271,
"text": "Java"
},
{
"code": "Article newArticle = new Event(\"GeeksforGeeks\", new Date());String articleName = newArticle.name;",
"e": 29374,
"s": 29276,
"text": null
},
{
"code": null,
"e": 29381,
"s": 29374,
"text": "Picked"
},
{
"code": null,
"e": 29389,
"s": 29381,
"text": "Android"
},
{
"code": null,
"e": 29396,
"s": 29389,
"text": "Kotlin"
},
{
"code": null,
"e": 29404,
"s": 29396,
"text": "Android"
},
{
"code": null,
"e": 29502,
"s": 29404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29540,
"s": 29502,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 29579,
"s": 29540,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29629,
"s": 29579,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 29671,
"s": 29629,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 29722,
"s": 29671,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 29741,
"s": 29722,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 29754,
"s": 29741,
"text": "Kotlin Array"
},
{
"code": null,
"e": 29796,
"s": 29754,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 29836,
"s": 29796,
"text": "How to Get Current Location in Android?"
}
]
|
How to use Fade Component in ReactJS ? - GeeksforGeeks | 22 Feb, 2021
Fade Component adds a fade animation to a child element or component. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Fade Component in ReactJS using the following approach.
Popper Transitions: The Transition component is used as an animated feature for the open/close state of the popper. This component should follow the following conditions.
Descendant should be a direct child of the popper.When enter transition starts call the onEnter callback prop.When the exit transition is completed call the onExited callback prop.
Descendant should be a direct child of the popper.
When enter transition starts call the onEnter callback prop.
When the exit transition is completed call the onExited callback prop.
Creating React Application And Installing Module:
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 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
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 FormControlLabel from '@material-ui/core/FormControlLabel';import Paper from '@material-ui/core/Paper';import Switch from '@material-ui/core/Switch';import Fade from '@material-ui/core/Fade'; export default function App() { const [isChecked, setIsChecked] = React.useState(false); return ( <div style={{ display: 'block', padding: 30 }}> <h4>How to use Fade Component in ReactJS?</h4> <FormControlLabel control={<Switch checked={isChecked} onChange={() => { setIsChecked((prev) => !prev); }} />} label="Toggle me to see Fade Effect" /> <div style={{ display: 'flex' }}> <Fade in={isChecked} style={{ transitionDelay:'100ms'}} > <Paper elevation={5} style={{ margin: 5 }} > <svg style={{ width: 100, height: 100 }}> <polygon points="0,50 40,0,50,90" style={{ fill: 'red', stroke: 'dimgrey', strokeWidth: 1, }} /> </svg> </Paper> </Fade> </div> </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://material-ui.com/components/popper/#transitions
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n22 Feb, 2021"
},
{
"code": null,
"e": 26305,
"s": 26071,
"text": "Fade Component adds a fade animation to a child element or component. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Fade Component in ReactJS using the following approach."
},
{
"code": null,
"e": 26476,
"s": 26305,
"text": "Popper Transitions: The Transition component is used as an animated feature for the open/close state of the popper. This component should follow the following conditions."
},
{
"code": null,
"e": 26657,
"s": 26476,
"text": "Descendant should be a direct child of the popper.When enter transition starts call the onEnter callback prop.When the exit transition is completed call the onExited callback prop."
},
{
"code": null,
"e": 26708,
"s": 26657,
"text": "Descendant should be a direct child of the popper."
},
{
"code": null,
"e": 26769,
"s": 26708,
"text": "When enter transition starts call the onEnter callback prop."
},
{
"code": null,
"e": 26840,
"s": 26769,
"text": "When the exit transition is completed call the onExited callback prop."
},
{
"code": null,
"e": 26890,
"s": 26840,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 26954,
"s": 26890,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 26986,
"s": 26954,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 27086,
"s": 26986,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 27100,
"s": 27086,
"text": "cd foldername"
},
{
"code": null,
"e": 27209,
"s": 27100,
"text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command."
},
{
"code": null,
"e": 27239,
"s": 27209,
"text": "npm install @material-ui/core"
},
{
"code": null,
"e": 27291,
"s": 27239,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 27309,
"s": 27291,
"text": "Project Structure"
},
{
"code": null,
"e": 27440,
"s": 27309,
"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": 27447,
"s": 27440,
"text": "App.js"
},
{
"code": "import React from 'react';import FormControlLabel from '@material-ui/core/FormControlLabel';import Paper from '@material-ui/core/Paper';import Switch from '@material-ui/core/Switch';import Fade from '@material-ui/core/Fade'; export default function App() { const [isChecked, setIsChecked] = React.useState(false); return ( <div style={{ display: 'block', padding: 30 }}> <h4>How to use Fade Component in ReactJS?</h4> <FormControlLabel control={<Switch checked={isChecked} onChange={() => { setIsChecked((prev) => !prev); }} />} label=\"Toggle me to see Fade Effect\" /> <div style={{ display: 'flex' }}> <Fade in={isChecked} style={{ transitionDelay:'100ms'}} > <Paper elevation={5} style={{ margin: 5 }} > <svg style={{ width: 100, height: 100 }}> <polygon points=\"0,50 40,0,50,90\" style={{ fill: 'red', stroke: 'dimgrey', strokeWidth: 1, }} /> </svg> </Paper> </Fade> </div> </div> );}",
"e": 28589,
"s": 27447,
"text": null
},
{
"code": null,
"e": 28702,
"s": 28589,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project."
},
{
"code": null,
"e": 28712,
"s": 28702,
"text": "npm start"
},
{
"code": null,
"e": 28811,
"s": 28712,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 28877,
"s": 28811,
"text": "Reference: https://material-ui.com/components/popper/#transitions"
},
{
"code": null,
"e": 28889,
"s": 28877,
"text": "Material-UI"
},
{
"code": null,
"e": 28905,
"s": 28889,
"text": "React-Questions"
},
{
"code": null,
"e": 28913,
"s": 28905,
"text": "ReactJS"
},
{
"code": null,
"e": 28930,
"s": 28913,
"text": "Web Technologies"
},
{
"code": null,
"e": 29028,
"s": 28930,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29055,
"s": 29028,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 29097,
"s": 29055,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 29135,
"s": 29097,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 29170,
"s": 29135,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 29228,
"s": 29170,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 29268,
"s": 29228,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29301,
"s": 29268,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29346,
"s": 29301,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29396,
"s": 29346,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
MIS - Quick Guide | Information can be defined as meaningfully interpreted data. If we give you a number 1-212-290-4700, it does not make any sense on its own. It is just a raw data. However if we say Tel: +1-212-290-4700, it starts making sense. It becomes a telephone number. If I gather some more data and record it meaningfully like −
Address: 350 Fifth Avenue, 34th floor
New York, NY 10118-3299 USA
Tel: +1-212-290-4700
Fax: +1-212-736-1300
It becomes a very useful information - the address of New York office of Human Rights Watch, a non-profit, non-governmental human rights organization.
So, from a system analyst's point of view, information is a sequence of symbols that can be construed to a useful message.
An Information System is a system that gathers data and disseminates information with the sole purpose of providing information to its users.
The main object of an information system is to provide information to its users. Information systems vary according to the type of users who use the system.
A Management Information System is an information system that evaluates, analyzes, and processes an organization's data to produce meaningful and useful information based on which the management can take right decisions to ensure future growth of the organization.
According to Wikipedia −
"Information can be recorded as signs, or transmitted as signals. Information is any kind of event that affects the state of a dynamic system that can interpret the information.
Conceptually, information is the message (utterance or expression) being conveyed. Therefore, in a general sense, information is "Knowledge communicated or received, concerning a particular fact or circumstance". Information cannot be predicted and resolves uncertainty."
Data can be described as unprocessed facts and figures. Plain collected data as raw facts cannot help in decision-making. However, data is the raw material that is organized, structured, and interpreted to create useful information systems.
Data is defined as 'groups of non-random symbols in the form of text, images, voice representing quantities, action and objects'.
Information is interpreted data; created from organized, structured, and processed data in a particular context.
According to Davis and Olson −
Professor Ray R. Larson of the School of Information at the University of California, Berkeley, provides an Information Hierarchy, which is −
Data − The raw material of information.
Data − The raw material of information.
Information − Data organized and presented by someone.
Information − Data organized and presented by someone.
Knowledge − Information read, heard, or seen, and understood.
Knowledge − Information read, heard, or seen, and understood.
Wisdom − Distilled and integrated knowledge and understanding.
Wisdom − Distilled and integrated knowledge and understanding.
Scott Andrews' explains Information Continuum as follows −
Data − A Fact or a piece of information, or a series thereof.
Data − A Fact or a piece of information, or a series thereof.
Information − Knowledge discerned from data.
Information − Knowledge discerned from data.
Business Intelligence − Information Management pertaining to an organization's policy or decision-making, particularly when tied to strategic or operational objectives.
Business Intelligence − Information Management pertaining to an organization's policy or decision-making, particularly when tied to strategic or operational objectives.
The most popular data collection techniques include −
Surveys − A questionnaires is prepared to collect the data from the field.
Surveys − A questionnaires is prepared to collect the data from the field.
Secondary data sources or archival data: Data is collected through old records, magazines, company website etc.
Secondary data sources or archival data: Data is collected through old records, magazines, company website etc.
Objective measures or tests − An experimental test is conducted on the subject and the data is collected.
Objective measures or tests − An experimental test is conducted on the subject and the data is collected.
Interviews − Data is collected by the system analyst by following a rigid procedure and collecting the answers to a set of pre-conceived questions through personal interviews.
Interviews − Data is collected by the system analyst by following a rigid procedure and collecting the answers to a set of pre-conceived questions through personal interviews.
Information can be classified in a number of ways and in this chapter, you will learn two of the most important ways to classify information.
Based on Anthony's classification of Management, information used in business for decision-making is generally categorized into three types −
Strategic Information − Strategic information is concerned with long term policy decisions that defines the objectives of a business and checks how well these objectives are met. For example, acquiring a new plant, a new product, diversification of business etc, comes under strategic information.
Strategic Information − Strategic information is concerned with long term policy decisions that defines the objectives of a business and checks how well these objectives are met. For example, acquiring a new plant, a new product, diversification of business etc, comes under strategic information.
Tactical Information − Tactical information is concerned with the information needed for exercising control over business resources, like budgeting, quality control, service level, inventory level, productivity level etc.
Tactical Information − Tactical information is concerned with the information needed for exercising control over business resources, like budgeting, quality control, service level, inventory level, productivity level etc.
Operational Information − Operational information is concerned with plant/business level information and is used to ensure proper conduction of specific operational tasks as planned/intended. Various operator specific, machine specific and shift specific jobs for quality control checks comes under this category.
Operational Information − Operational information is concerned with plant/business level information and is used to ensure proper conduction of specific operational tasks as planned/intended. Various operator specific, machine specific and shift specific jobs for quality control checks comes under this category.
In terms of applications, information can be categorized as −
Planning Information − These are the information needed for establishing standard norms and specifications in an organization. This information is used in strategic, tactical, and operation planning of any activity. Examples of such information are time standards, design standards.
Planning Information − These are the information needed for establishing standard norms and specifications in an organization. This information is used in strategic, tactical, and operation planning of any activity. Examples of such information are time standards, design standards.
Control Information − This information is needed for establishing control over all business activities through feedback mechanism. This information is used for controlling attainment, nature and utilization of important processes in a system. When such information reflects a deviation from the established standards, the system should induce a decision or an action leading to control.
Control Information − This information is needed for establishing control over all business activities through feedback mechanism. This information is used for controlling attainment, nature and utilization of important processes in a system. When such information reflects a deviation from the established standards, the system should induce a decision or an action leading to control.
Knowledge Information − Knowledge is defined as "information about information". Knowledge information is acquired through experience and learning, and collected from archival data and research studies.
Knowledge Information − Knowledge is defined as "information about information". Knowledge information is acquired through experience and learning, and collected from archival data and research studies.
Organizational Information − Organizational information deals with an organization's environment, culture in the light of its objectives. Karl Weick's Organizational Information Theory emphasizes that an organization reduces its equivocality or uncertainty by collecting, managing and using these information prudently. This information is used by everybody in the organization; examples of such information are employee and payroll information.
Organizational Information − Organizational information deals with an organization's environment, culture in the light of its objectives. Karl Weick's Organizational Information Theory emphasizes that an organization reduces its equivocality or uncertainty by collecting, managing and using these information prudently. This information is used by everybody in the organization; examples of such information are employee and payroll information.
Functional/Operational Information − This is operation specific information. For example, daily schedules in a manufacturing plant that refers to the detailed assignment of jobs to machines or machines to operators. In a service oriented business, it would be the duty roster of various personnel. This information is mostly internal to the organization.
Functional/Operational Information − This is operation specific information. For example, daily schedules in a manufacturing plant that refers to the detailed assignment of jobs to machines or machines to operators. In a service oriented business, it would be the duty roster of various personnel. This information is mostly internal to the organization.
Database Information − Database information construes large quantities of information that has multiple usage and application. Such information is stored, retrieved and managed to create databases. For example, material specification or supplier information is stored for multiple users.
Database Information − Database information construes large quantities of information that has multiple usage and application. Such information is stored, retrieved and managed to create databases. For example, material specification or supplier information is stored for multiple users.
Information is a vital resource for the success of any organization. Future of an organization lies in using and disseminating information wisely. Good quality information placed in right context in right time tells us about opportunities and problems well in advance.
Good quality information − Quality is a value that would vary according to the users and uses of the information.
According to Wang and Strong, following are the dimensions or elements of Information Quality −
Intrinsic − Accuracy, Objectivity, Believability, Reputation
Intrinsic − Accuracy, Objectivity, Believability, Reputation
Contextual − Relevancy, Value-Added, Timeliness, Completeness, Amount of information
Contextual − Relevancy, Value-Added, Timeliness, Completeness, Amount of information
Representational − Interpretability, Format, Coherence, Compatibility
Representational − Interpretability, Format, Coherence, Compatibility
Accessibility − Accessibility, Access security
Accessibility − Accessibility, Access security
Various authors propose various lists of metrics for assessing the quality of information. Let us generate a list of the most essential characteristic features for information quality −
Reliability − It should be verifiable and dependable.
Reliability − It should be verifiable and dependable.
Timely − It must be current and it must reach the users well in time, so that important decisions can be made in time.
Timely − It must be current and it must reach the users well in time, so that important decisions can be made in time.
Relevant − It should be current and valid information and it should reduce uncertainties.
Relevant − It should be current and valid information and it should reduce uncertainties.
Accurate − It should be free of errors and mistakes, true, and not deceptive.
Accurate − It should be free of errors and mistakes, true, and not deceptive.
Sufficient − It should be adequate in quantity, so that decisions can be made on its basis.
Sufficient − It should be adequate in quantity, so that decisions can be made on its basis.
Unambiguous − It should be expressed in clear terms. In other words, in should be comprehensive.
Unambiguous − It should be expressed in clear terms. In other words, in should be comprehensive.
Complete − It should meet all the needs in the current context.
Complete − It should meet all the needs in the current context.
Unbiased − It should be impartial, free from any bias. In other words, it should have integrity.
Unbiased − It should be impartial, free from any bias. In other words, it should have integrity.
Explicit − It should not need any further explanation.
Explicit − It should not need any further explanation.
Comparable − It should be of uniform collection, analysis, content, and format.
Comparable − It should be of uniform collection, analysis, content, and format.
Reproducible − It could be used by documented methods on the same data set to achieve a consistent result.
Reproducible − It could be used by documented methods on the same data set to achieve a consistent result.
Information processing beyond doubt is the dominant industry of the present century. Following factors states few common factors that reflect on the needs and objectives of the information processing −
Increasing impact of information processing for organizational decision making.
Increasing impact of information processing for organizational decision making.
Dependency of services sector including banking, financial organization, health care, entertainment, tourism and travel, education and numerous others on information.
Dependency of services sector including banking, financial organization, health care, entertainment, tourism and travel, education and numerous others on information.
Changing employment scene world over, shifting base from manual agricultural to machine-based manufacturing and other industry related jobs.
Changing employment scene world over, shifting base from manual agricultural to machine-based manufacturing and other industry related jobs.
Information revolution and the overall development scenario.
Information revolution and the overall development scenario.
Growth of IT industry and its strategic importance.
Growth of IT industry and its strategic importance.
Strong growth of information services fuelled by increasing competition and reduced product life cycle.
Strong growth of information services fuelled by increasing competition and reduced product life cycle.
Need for sustainable development and quality life.
Need for sustainable development and quality life.
Improvement in communication and transportation brought in by use of information processing.
Improvement in communication and transportation brought in by use of information processing.
Use of information processing in reduction of energy consumption, reduction in pollution and a better ecological balance in future.
Use of information processing in reduction of energy consumption, reduction in pollution and a better ecological balance in future.
Use of information processing in land record managements, legal delivery system, educational institutions, natural resource planning, customer relation management and so on.
Use of information processing in land record managements, legal delivery system, educational institutions, natural resource planning, customer relation management and so on.
In a nutshell −
Information is needed to survive in the modern competitive world.
Information is needed to survive in the modern competitive world.
Information is needed to create strong information systems and keep these systems up to date.
Information is needed to create strong information systems and keep these systems up to date.
Information processing has transformed our society in numerous ways. From a business perspective, there has been a huge shift towards increasingly automated business processes and communication. Access to information and capability of information processing has helped in achieving greater efficiency in accounting and other business processes.
A complete business information system, accomplishes the following functionalities −
Collection and storage of data.
Collection and storage of data.
Transform these data into business information useful for decision making.
Transform these data into business information useful for decision making.
Provide controls to safeguard data.
Provide controls to safeguard data.
Automate and streamline reporting.
Automate and streamline reporting.
The following list summarizes the five main uses of information by businesses and other organizations −
Planning − At the planning stage, information is the most important ingredient in decision making. Information at planning stage includes that of business resources, assets, liabilities, plants and machineries, properties, suppliers, customers, competitors, market and market dynamics, fiscal policy changes of the Government, emerging technologies, etc.
Planning − At the planning stage, information is the most important ingredient in decision making. Information at planning stage includes that of business resources, assets, liabilities, plants and machineries, properties, suppliers, customers, competitors, market and market dynamics, fiscal policy changes of the Government, emerging technologies, etc.
Recording − Business processing these days involves recording information about each transaction or event. This information collected, stored and updated regularly at the operational level.
Recording − Business processing these days involves recording information about each transaction or event. This information collected, stored and updated regularly at the operational level.
Controlling − A business need to set up an information filter, so that only filtered data is presented to the middle and top management. This ensures efficiency at the operational level and effectiveness at the tactical and strategic level.
Controlling − A business need to set up an information filter, so that only filtered data is presented to the middle and top management. This ensures efficiency at the operational level and effectiveness at the tactical and strategic level.
Measuring − A business measures its performance metrics by collecting and analyzing sales data, cost of manufacturing, and profit earned.
Measuring − A business measures its performance metrics by collecting and analyzing sales data, cost of manufacturing, and profit earned.
Decision-making − MIS is primarily concerned with managerial decision-making, theory of organizational behavior, and underlying human behavior in organizational context. Decision-making information includes the socio-economic impact of competition, globalization, democratization, and the effects of all these factors on an organizational structure.
Decision-making − MIS is primarily concerned with managerial decision-making, theory of organizational behavior, and underlying human behavior in organizational context. Decision-making information includes the socio-economic impact of competition, globalization, democratization, and the effects of all these factors on an organizational structure.
In short, this multi-dimensional information evolves from the following logical foundations −
Operations research and management science
Operations research and management science
Theory of organizational behavior
Theory of organizational behavior
Computer science −
Data and file structure
Data theory design and implementation
Computer networking
Expert systems and artificial intelligence
Computer science −
Data and file structure
Data and file structure
Data theory design and implementation
Data theory design and implementation
Computer networking
Computer networking
Expert systems and artificial intelligence
Expert systems and artificial intelligence
Information theory
Information theory
Following factors arising as an outcome of information processing help speed up of business events and achieves greater efficiency −
Directly and immediate linkage to the system
Directly and immediate linkage to the system
Faster communication of an order
Faster communication of an order
Electronic transfer of funds for faster payment
Electronic transfer of funds for faster payment
Electronically solicited pricing (helps in determining the best price)
Electronically solicited pricing (helps in determining the best price)
Managers make decisions. Decision-making generally takes a four-fold path −
Understanding the need for decision or the opportunity,
Understanding the need for decision or the opportunity,
Preparing alternative course of actions,
Preparing alternative course of actions,
Evaluating all alternative course of actions,
Evaluating all alternative course of actions,
Deciding the right path for implementation.
Deciding the right path for implementation.
MIS is an information system that provides information in the form of standardized reports and displays for the managers. MIS is a broad class of information systems designed to provide information needed for effective decision making.
Data and information created from an accounting information system and the reports generated thereon are used to provide accurate, timely and relevant information needed for effective decision making by managers.
Management information systems provide information to support management decision making, with the following goals −
Pre-specified and preplanned reporting to managers.
Pre-specified and preplanned reporting to managers.
Interactive and ad-hoc support for decision making.
Interactive and ad-hoc support for decision making.
Critical information for top management.
Critical information for top management.
MIS is of vital importance to any organization, because −
It emphasizes on the management decision making, not only processing of data generated by business operations.
It emphasizes on the management decision making, not only processing of data generated by business operations.
It emphasizes on the systems framework that should be used for organizing information systems applications.
It emphasizes on the systems framework that should be used for organizing information systems applications.
Enterprise applications are specifically designed for the sole purpose of promoting the needs and objectives of the organizations.
Enterprise applications provide business-oriented tools supporting electronic commerce, enterprise communication and collaboration, and web-enabled business processes both within a networked enterprise and with its customers and business partners.
Some of the services provided by an enterprise application includes −
Online shopping, billing and payment processing
Interactive product catalogue
Content management
Customer relationship management
Manufacturing and other business processes integration
IT services management
Enterprise resource management
Human resource management
Business intelligence management
Business collaboration and security
Form automation
Basically these applications intend to model the business processes, i.e., how the entire organization works. These tools work by displaying, manipulating and storing large amounts of data and automating the business processes with these data.
Multitude of applications comes under the definition of Enterprise Applications. In this section, let us briefly cover the following applications −
Management information system (MIS)
Management information system (MIS)
Enterprise Resource Planning (ERP)
Enterprise Resource Planning (ERP)
Customer Relationship Management (CRM)
Customer Relationship Management (CRM)
Decision Support System (DSS)
Decision Support System (DSS)
Knowledge Management Systems (KMS)
Knowledge Management Systems (KMS)
Content Management System (CMS)
Content Management System (CMS)
Executive Support System (ESS)
Executive Support System (ESS)
Business Intelligence System (BIS)
Business Intelligence System (BIS)
Enterprise Application Integration (EAI)
Enterprise Application Integration (EAI)
Business Continuity Planning (BCP)
Business Continuity Planning (BCP)
Supply Chain Management (SCM)
Supply Chain Management (SCM)
To the managers, Management Information System is an implementation of the organizational systems and procedures. To a programmer it is nothing but file structures and file processing. However, it involves much more complexity.
The three components of MIS provide a more complete and focused definition, where System suggests integration and holistic view, Information stands for processed data, and Management is the ultimate user, the decision makers.
Management information system can thus be analyzed as follows −
Management covers the planning, control, and administration of the operations of a concern. The top management handles planning; the middle management concentrates on controlling; and the lower management is concerned with actual administration.
Information, in MIS, means the processed data that helps the management in planning, controlling and operations. Data means all the facts arising out of the operations of the concern. Data is processed i.e. recorded, summarized, compared and finally presented to the management in the form of MIS report.
Data is processed into information with the help of a system. A system is made up of inputs, processing, output and feedback or control.
Thus MIS means a system for processing data in order to give proper information to the management for performing its functions.
The goals of an MIS are to implement the organizational structure and dynamics of the enterprise for the purpose of managing the organization in a better way and capturing the potential of the information system for competitive advantage.
Following are the basic objectives of an MIS −
Capturing Data − Capturing contextual data, or operational information that will contribute in decision making from various internal and external sources of organization.
Capturing Data − Capturing contextual data, or operational information that will contribute in decision making from various internal and external sources of organization.
Processing Data − The captured data is processed into information needed for planning, organizing, coordinating, directing and controlling functionalities at strategic, tactical and operational level. Processing data means −
making calculations with the data
sorting data
classifying data and
summarizing data
Processing Data − The captured data is processed into information needed for planning, organizing, coordinating, directing and controlling functionalities at strategic, tactical and operational level. Processing data means −
making calculations with the data
making calculations with the data
sorting data
sorting data
classifying data and
classifying data and
summarizing data
summarizing data
Information Storage − Information or processed data need to be stored for future use.
Information Storage − Information or processed data need to be stored for future use.
Information Retrieval − The system should be able to retrieve this information from the storage as and when required by various users.
Information Retrieval − The system should be able to retrieve this information from the storage as and when required by various users.
Information Propagation − Information or the finished product of the MIS should be circulated to its users periodically using the organizational network.
Information Propagation − Information or the finished product of the MIS should be circulated to its users periodically using the organizational network.
Following are the characteristics of an MIS −
It should be based on a long-term planning.
It should be based on a long-term planning.
It should provide a holistic view of the dynamics and the structure of the organization.
It should provide a holistic view of the dynamics and the structure of the organization.
It should work as a complete and comprehensive system covering all interconnecting sub-systems within the organization.
It should work as a complete and comprehensive system covering all interconnecting sub-systems within the organization.
It should be planned in a top-down way, as the decision makers or the management should actively take part and provide clear direction at the development stage of the MIS.
It should be planned in a top-down way, as the decision makers or the management should actively take part and provide clear direction at the development stage of the MIS.
It should be based on need of strategic, operational and tactical information of managers of an organization.
It should be based on need of strategic, operational and tactical information of managers of an organization.
It should also take care of exceptional situations by reporting such situations.
It should also take care of exceptional situations by reporting such situations.
It should be able to make forecasts and estimates, and generate advanced information, thus providing a competitive advantage. Decision makers can take actions on the basis of such predictions.
It should be able to make forecasts and estimates, and generate advanced information, thus providing a competitive advantage. Decision makers can take actions on the basis of such predictions.
It should create linkage between all sub-systems within the organization, so that the decision makers can take the right decision based on an integrated view.
It should create linkage between all sub-systems within the organization, so that the decision makers can take the right decision based on an integrated view.
It should allow easy flow of information through various sub-systems, thus avoiding redundancy and duplicity of data. It should simplify the operations with as much practicability as possible.
It should allow easy flow of information through various sub-systems, thus avoiding redundancy and duplicity of data. It should simplify the operations with as much practicability as possible.
Although the MIS is an integrated, complete system, it should be made in such a flexible way that it could be easily split into smaller sub-systems as and when required.
Although the MIS is an integrated, complete system, it should be made in such a flexible way that it could be easily split into smaller sub-systems as and when required.
A central database is the backbone of a well-built MIS.
A central database is the backbone of a well-built MIS.
Following are the characteristics of a well-designed computerized MIS −
It should be able to process data accurately and with high speed, using various techniques like operations research, simulation, heuristics, etc.
It should be able to process data accurately and with high speed, using various techniques like operations research, simulation, heuristics, etc.
It should be able to collect, organize, manipulate, and update large amount of raw data of both related and unrelated nature, coming from various internal and external sources at different periods of time.
It should be able to collect, organize, manipulate, and update large amount of raw data of both related and unrelated nature, coming from various internal and external sources at different periods of time.
It should provide real time information on ongoing events without any delay.
It should provide real time information on ongoing events without any delay.
It should support various output formats and follow latest rules and regulations in practice.
It should support various output formats and follow latest rules and regulations in practice.
It should provide organized and relevant information for all levels of management: strategic, operational, and tactical.
It should provide organized and relevant information for all levels of management: strategic, operational, and tactical.
It should aim at extreme flexibility in data storage and retrieval.
It should aim at extreme flexibility in data storage and retrieval.
The following diagram shows the nature and scope of MIS −
ERP is an integrated, real-time, cross-functional enterprise application, an enterprise-wide transaction framework that supports all the internal business processes of a company.
It supports all core business processes such as sales order processing, inventory management and control, production and distribution planning, and finance.
ERP is very helpful in the follwoing areas −
Business integration and automated data update
Business integration and automated data update
Linkage between all core business processes and easy flow of integration
Linkage between all core business processes and easy flow of integration
Flexibility in business operations and more agility to the company
Flexibility in business operations and more agility to the company
Better analysis and planning capabilities
Better analysis and planning capabilities
Critical decision-making
Critical decision-making
Competitive advantage
Competitive advantage
Use of latest technologies
Use of latest technologies
The following diagram illustrates the features of ERP −
Finance − Financial accounting, Managerial accounting, treasury management, asset management, budget control, costing, and enterprise control.
Finance − Financial accounting, Managerial accounting, treasury management, asset management, budget control, costing, and enterprise control.
Logistics − Production planning, material management, plant maintenance, project management, events management, etc.
Logistics − Production planning, material management, plant maintenance, project management, events management, etc.
Human resource − Personnel management, training and development, etc.
Human resource − Personnel management, training and development, etc.
Supply Chain − Inventory control, purchase and order control, supplier scheduling, planning, etc.
Supply Chain − Inventory control, purchase and order control, supplier scheduling, planning, etc.
Work flow − Integrate the entire organization with the flexible assignment of tasks and responsibility to locations, position, jobs, etc.
Work flow − Integrate the entire organization with the flexible assignment of tasks and responsibility to locations, position, jobs, etc.
Reduction of lead time
Reduction of cycle time
Better customer satisfaction
Increased flexibility, quality, and efficiency
Improved information accuracy and decision making capability
Onetime shipment
Improved resource utilization
Improve supplier performance
Reduced quality costs
Quick decision-making
Forecasting and optimization
Better transparency
Expense and time in implementation
Difficulty in integration with other system
Risk of implementation failure
Difficulty in implementation change
Risk in using one vendor
CRM is an enterprise application module that manages a company's interactions with current and future customers by organizing and coordinating, sales and marketing, and providing better customer services along with technical support.
Atul Parvatiyar and Jagdish N. Sheth provide an excellent definition for customer relationship management in their work titled - 'Customer Relationship Management: Emerging Practice, Process, and Discipline' −
To keep track of all present and future customers.
To keep track of all present and future customers.
To identify and target the best customers.
To identify and target the best customers.
To let the customers know about the existing as well as the new products and services.
To let the customers know about the existing as well as the new products and services.
To provide real-time and personalized services based on the needs and habits of the existing customers.
To provide real-time and personalized services based on the needs and habits of the existing customers.
To provide superior service and consistent customer experience.
To provide superior service and consistent customer experience.
To implement a feedback system.
To implement a feedback system.
Provides better customer service and increases customer revenues.
Provides better customer service and increases customer revenues.
Discovers new customers.
Discovers new customers.
Cross-sells and up-sells products more effectively.
Cross-sells and up-sells products more effectively.
Helps sales staff to close deals faster.
Helps sales staff to close deals faster.
Makes call centers more efficient.
Makes call centers more efficient.
Simplifies marketing and sales processes.
Simplifies marketing and sales processes.
Some times record loss is a major problem.
Some times record loss is a major problem.
Overhead costs.
Overhead costs.
Giving training to employees is an issue in small organizations.
Giving training to employees is an issue in small organizations.
Decision support systems (DSS) are interactive software-based systems intended to help managers in decision-making by accessing large volumes of information generated from various related information systems involved in organizational business processes, such as office automation system, transaction processing system, etc.
DSS uses the summary information, exceptions, patterns, and trends using the analytical models. A decision support system helps in decision-making but does not necessarily give a decision itself. The decision makers compile useful information from raw data, documents, personal knowledge, and/or business models to identify and solve problems and make decisions.
There are two types of decisions - programmed and non-programmed decisions.
Programmed decisions are basically automated processes, general routine work, where −
These decisions have been taken several times.
These decisions have been taken several times.
These decisions follow some guidelines or rules.
These decisions follow some guidelines or rules.
For example, selecting a reorder level for inventories, is a programmed decision.
Non-programmed decisions occur in unusual and non-addressed situations, so −
It would be a new decision.
It would be a new decision.
There will not be any rules to follow.
There will not be any rules to follow.
These decisions are made based on the available information.
These decisions are made based on the available information.
These decisions are based on the manger's discretion, instinct, perception and judgment.
These decisions are based on the manger's discretion, instinct, perception and judgment.
For example, investing in a new technology is a non-programmed decision.
Decision support systems generally involve non-programmed decisions. Therefore, there will be no exact report, content, or format for these systems. Reports are generated on the fly.
Adaptability and flexibility
High level of Interactivity
Ease of use
Efficiency and effectiveness
Complete control by decision-makers
Ease of development
Extendibility
Support for modeling and analysis
Support for data access
Standalone, integrated, and Web-based
Support for decision-makers in semi-structured and unstructured problems.
Support for decision-makers in semi-structured and unstructured problems.
Support for managers at various managerial levels, ranging from top executive to line managers.
Support for managers at various managerial levels, ranging from top executive to line managers.
Support for individuals and groups. Less structured problems often requires the involvement of several individuals from different departments and organization level.
Support for individuals and groups. Less structured problems often requires the involvement of several individuals from different departments and organization level.
Support for interdependent or sequential decisions.
Support for interdependent or sequential decisions.
Support for intelligence, design, choice, and implementation.
Support for intelligence, design, choice, and implementation.
Support for variety of decision processes and styles.
Support for variety of decision processes and styles.
DSSs are adaptive over time.
DSSs are adaptive over time.
Improves efficiency and speed of decision-making activities.
Improves efficiency and speed of decision-making activities.
Increases the control, competitiveness and capability of futuristic decision-making of the organization.
Increases the control, competitiveness and capability of futuristic decision-making of the organization.
Facilitates interpersonal communication.
Facilitates interpersonal communication.
Encourages learning or training.
Encourages learning or training.
Since it is mostly used in non-programmed decisions, it reveals new approaches and sets up new evidences for an unusual decision.
Since it is mostly used in non-programmed decisions, it reveals new approaches and sets up new evidences for an unusual decision.
Helps automate managerial processes.
Helps automate managerial processes.
Following are the components of the Decision Support System −
Database Management System (DBMS) − To solve a problem the necessary data may come from internal or external database. In an organization, internal data are generated by a system such as TPS and MIS. External data come from a variety of sources such as newspapers, online data services, databases (financial, marketing, human resources).
Database Management System (DBMS) − To solve a problem the necessary data may come from internal or external database. In an organization, internal data are generated by a system such as TPS and MIS. External data come from a variety of sources such as newspapers, online data services, databases (financial, marketing, human resources).
Model Management System − It stores and accesses models that managers use to make decisions. Such models are used for designing manufacturing facility, analyzing the financial health of an organization, forecasting demand of a product or service, etc.
Support Tools − Support tools like online help; pulls down menus, user interfaces, graphical analysis, error correction mechanism, facilitates the user interactions with the system.
Model Management System − It stores and accesses models that managers use to make decisions. Such models are used for designing manufacturing facility, analyzing the financial health of an organization, forecasting demand of a product or service, etc.
Support Tools − Support tools like online help; pulls down menus, user interfaces, graphical analysis, error correction mechanism, facilitates the user interactions with the system.
There are several ways to classify DSS. Hoi Apple and Whinstone classifies DSS as follows −
Text Oriented DSS − It contains textually represented information that could have a bearing on decision. It allows documents to be electronically created, revised and viewed as needed.
Text Oriented DSS − It contains textually represented information that could have a bearing on decision. It allows documents to be electronically created, revised and viewed as needed.
Database Oriented DSS − Database plays a major role here; it contains organized and highly structured data.
Database Oriented DSS − Database plays a major role here; it contains organized and highly structured data.
Spreadsheet Oriented DSS − It contains information in spread sheets that allows create, view, modify procedural knowledge and also instructs the system to execute self-contained instructions. The most popular tool is Excel and Lotus 1-2-3.
Spreadsheet Oriented DSS − It contains information in spread sheets that allows create, view, modify procedural knowledge and also instructs the system to execute self-contained instructions. The most popular tool is Excel and Lotus 1-2-3.
Solver Oriented DSS − It is based on a solver, which is an algorithm or procedure written for performing certain calculations and particular program type.
Solver Oriented DSS − It is based on a solver, which is an algorithm or procedure written for performing certain calculations and particular program type.
Rules Oriented DSS − It follows certain procedures adopted as rules.
Rules Oriented DSS − It follows certain procedures adopted as rules.
Rules Oriented DSS − Procedures are adopted in rules oriented DSS. Export system is the example.
Rules Oriented DSS − Procedures are adopted in rules oriented DSS. Export system is the example.
Compound DSS − It is built by using two or more of the five structures explained above.
Compound DSS − It is built by using two or more of the five structures explained above.
Following are some typical DSSs −
Status Inquiry System − It helps in taking operational, management level, or middle level management decisions, for example daily schedules of jobs to machines or machines to operators.
Status Inquiry System − It helps in taking operational, management level, or middle level management decisions, for example daily schedules of jobs to machines or machines to operators.
Data Analysis System − It needs comparative analysis and makes use of formula or an algorithm, for example cash flow analysis, inventory analysis etc.
Data Analysis System − It needs comparative analysis and makes use of formula or an algorithm, for example cash flow analysis, inventory analysis etc.
Information Analysis System − In this system data is analyzed and the information report is generated. For example, sales analysis, accounts receivable systems, market analysis etc.
Information Analysis System − In this system data is analyzed and the information report is generated. For example, sales analysis, accounts receivable systems, market analysis etc.
Accounting System − It keeps track of accounting and finance related information, for example, final account, accounts receivables, accounts payables, etc. that keep track of the major aspects of the business.
Accounting System − It keeps track of accounting and finance related information, for example, final account, accounts receivables, accounts payables, etc. that keep track of the major aspects of the business.
Model Based System − Simulation models or optimization models used for decision-making are used infrequently and creates general guidelines for operation or management.
Model Based System − Simulation models or optimization models used for decision-making are used infrequently and creates general guidelines for operation or management.
All the systems we are discussing here come under knowledge management category. A knowledge management system is not radically different from all these information systems, but it just extends the already existing systems by assimilating more information.
As we have seen, data is raw facts, information is processed and/or interpreted data, and knowledge is personalized information.
Personalized information
State of knowing and understanding
An object to be stored and manipulated
A process of applying expertise
A condition of access to information
Potential to influence action
Intranet
Data warehouses and knowledge repositories
Decision support tools
Groupware for supporting collaboration
Networks of knowledge workers
Internal expertise
Improved performance
Competitive advantage
Innovation
Sharing of knowledge
Integration
Continuous improvement by −
Driving strategy
Starting new lines of business
Solving problems faster
Developing professional skills
Recruit and retain talent
Start with the business problem and the business value to be delivered first.
Start with the business problem and the business value to be delivered first.
Identify what kind of strategy to pursue to deliver this value and address the KM problem.
Identify what kind of strategy to pursue to deliver this value and address the KM problem.
Think about the system required from a people and process point of view.
Think about the system required from a people and process point of view.
Finally, think about what kind of technical infrastructure are required to support the people and processes.
Finally, think about what kind of technical infrastructure are required to support the people and processes.
Implement system and processes with appropriate change management and iterative staged release.
Implement system and processes with appropriate change management and iterative staged release.
A Content Management System (CMS) allows publishing, editing, and modifying content as well as its maintenance by combining rules, processes and/or workflows, from a central interface, in a collaborative environment.
A CMS may serve as a central repository for content, which could be, textual data, documents, movies, pictures, phone numbers, and/or scientific data.
Creating content
Storing content
Indexing content
Searching content
Retrieving content
Publishing content
Archiving content
Revising content
Managing content end-to-end
Designing content template, for example web administrator designs webpage template for web content management.
Designing content template, for example web administrator designs webpage template for web content management.
Creating content blocks, for example, a web administrator adds empower CMS tags called "content blocks" to webpage template using CMS.
Creating content blocks, for example, a web administrator adds empower CMS tags called "content blocks" to webpage template using CMS.
Positioning content blocks on the document, for example, web administrator positions content blocks in webpage.
Positioning content blocks on the document, for example, web administrator positions content blocks in webpage.
Authoring content providers to search, retrieve, view and update content.
Authoring content providers to search, retrieve, view and update content.
Content management system helps to secure privacy and currency of the content and enhances performance by −
Ensuring integrity and accuracy of content by ensuring only one user modifies the content at a time.
Ensuring integrity and accuracy of content by ensuring only one user modifies the content at a time.
Implementing audit trails to monitor changes made in content over time.
Implementing audit trails to monitor changes made in content over time.
Providing secured user access to content.
Providing secured user access to content.
Organization of content into related groups and folders.
Organization of content into related groups and folders.
Allowing searching and retrieval of content.
Allowing searching and retrieval of content.
Recording information and meta-data related to the content, like author and title of content, version of content, date and time of creating the content etc.
Recording information and meta-data related to the content, like author and title of content, version of content, date and time of creating the content etc.
Workflow based routing of content from one user to another.
Workflow based routing of content from one user to another.
Converting paper-based content to digital format.
Converting paper-based content to digital format.
Organizing content into groups and distributing it to target audience.
Organizing content into groups and distributing it to target audience.
Executive support systems are intended to be used by the senior managers directly to provide support to non-programmed decisions in strategic management.
These information are often external, unstructured and even uncertain. Exact scope and context of such information is often not known beforehand.
This information is intelligence based −
Market intelligence
Investment intelligence
Technology intelligence
Following are some examples of intelligent information, which is often the source of an ESS −
External databases
Technology reports like patent records etc.
Technical reports from consultants
Market reports
Confidential information about competitors
Speculative information like market conditions
Government policies
Financial reports and information
Easy for upper level executive to use
Ability to analyze trends
Augmentation of managers' leadership capabilities
Enhance personal thinking and decision-making
Contribution to strategic control flexibility
Enhance organizational competitiveness in the market place
Instruments of change
Increased executive time horizons.
Better reporting system
Improved mental model of business executive
Help improve consensus building and communication
Improve office automation
Reduce time for finding information
Early identification of company performance
Detail examination of critical success factor
Better understanding
Time management
Increased communication capacity and quality
Functions are limited
Hard to quantify benefits
Executive may encounter information overload
System may become slow
Difficult to keep current data
May lead to less reliable and insecure data
Excessive cost for small company
The term 'Business Intelligence' has evolved from the decision support systems and gained strength with the technology and applications like data warehouses, Executive Information Systems and Online Analytical Processing (OLAP).
Business Intelligence System is basically a system used for finding patterns from existing data from operations.
It is created by procuring data and information for use in decision-making.
It is created by procuring data and information for use in decision-making.
It is a combination of skills, processes, technologies, applications and practices.
It is a combination of skills, processes, technologies, applications and practices.
It contains background data along with the reporting tools.
It contains background data along with the reporting tools.
It is a combination of a set of concepts and methods strengthened by fact-based support systems.
It is a combination of a set of concepts and methods strengthened by fact-based support systems.
It is an extension of Executive Support System or Executive Information System.
It is an extension of Executive Support System or Executive Information System.
It collects, integrates, stores, analyzes, and provides access to business information
It collects, integrates, stores, analyzes, and provides access to business information
It is an environment in which business users get reliable, secure, consistent, comprehensible, easily manipulated and timely information.
It is an environment in which business users get reliable, secure, consistent, comprehensible, easily manipulated and timely information.
It provides business insights that lead to better, faster, more relevant decisions.
It provides business insights that lead to better, faster, more relevant decisions.
Improved Management Processes.
Improved Management Processes.
Planning, controlling, measuring and/or applying changes that results in increased revenues and reduced costs.
Planning, controlling, measuring and/or applying changes that results in increased revenues and reduced costs.
Improved business operations.
Improved business operations.
Fraud detection, order processing, purchasing that results in increased revenues and reduced costs.
Fraud detection, order processing, purchasing that results in increased revenues and reduced costs.
Intelligent prediction of future.
Intelligent prediction of future.
For most companies, it is not possible to implement a proactive business intelligence system at one go. The following techniques and methodologies could be taken as approaches to BIS −
Improving reporting and analytical capabilities
Using scorecards and dashboards
Enterprise Reporting
On-line Analytical Processing (OLAP) Analysis
Advanced and Predictive Analysis
Alerts and Proactive Notification
Automated generation of reports with user subscriptions and "alerts" to problems and/or opportunities.
Data Storage and Management −
Data ware house
Ad hoc analysis
Data quality
Data mining
Information Delivery
Dashboard
Collaboration /search
Managed reporting
Visualization
Scorecard
Query, Reporting and Analysis
Ad hoc Analysis
Production reporting
OLAP analysis
An organization may use various information systems −
Supply Chain Management − For managing suppliers, inventory and shipping, etc.
Supply Chain Management − For managing suppliers, inventory and shipping, etc.
Human Resource Management − For managing personnel, training and recruiting talents;
Human Resource Management − For managing personnel, training and recruiting talents;
Employee Health Care − For managing medical records and insurance details of employees;
Employee Health Care − For managing medical records and insurance details of employees;
Customer Relationship Management − For managing current and potential customers;
Customer Relationship Management − For managing current and potential customers;
Business Intelligence Applications − For finding the patterns from existing data from business operations.
Business Intelligence Applications − For finding the patterns from existing data from business operations.
All these systems work as individual islands of automation. Most often these systems are standalone and do not communicate with each other due to incompatibility issues such as −
Operating systems they are residing on;
Operating systems they are residing on;
Database system used in the system;
Database system used in the system;
Legacy systems not supported anymore.
Legacy systems not supported anymore.
EAI is an integration framework, a middleware, made of a collection of technologies and services that allows smooth integration of all such systems and applications throughout the enterprise and enables data sharing and more automation of business processes.
EAI is defined as "the unrestricted sharing of data and business processes among any connected applications and data sources in the enterprise."
EAI is defined as "the unrestricted sharing of data and business processes among any connected applications and data sources in the enterprise."
EAI, when used effectively allows integration without any major changes to current infrastructure.
EAI, when used effectively allows integration without any major changes to current infrastructure.
Extends middleware capabilities to cope with application integration.
Extends middleware capabilities to cope with application integration.
Uses application logic layers of different middleware systems as building blocks.
Uses application logic layers of different middleware systems as building blocks.
Keeps track of information related to the operations of the enterprise e.g. Inventory, sales ledger and execute the core processes that create and manipulate this information.
Keeps track of information related to the operations of the enterprise e.g. Inventory, sales ledger and execute the core processes that create and manipulate this information.
Unrestricted sharing of data and business processes across an organization.
Unrestricted sharing of data and business processes across an organization.
Linkage between customers, suppliers and regulators.
Linkage between customers, suppliers and regulators.
The linking of data, business processes and applications to automate business processes.
The linking of data, business processes and applications to automate business processes.
Ensure consistent qualities of service (security, reliability etc.).
Ensure consistent qualities of service (security, reliability etc.).
Reduce the on-going cost of maintenance and reduce the cost of rolling out new systems.
Reduce the on-going cost of maintenance and reduce the cost of rolling out new systems.
Hub and spoke architecture concentrates all of the processing into a single server/cluster.
Hub and spoke architecture concentrates all of the processing into a single server/cluster.
Often became hard to maintain and evolve efficiently.
Often became hard to maintain and evolve efficiently.
Hard to extend to integrate 3rd parties on other technology platforms.
Hard to extend to integrate 3rd parties on other technology platforms.
The canonical data model introduces an intermediary step.
The canonical data model introduces an intermediary step.
Added complexity and additional processing effort.
Added complexity and additional processing effort.
EAI products typified.
EAI products typified.
Heavy customization required to implement the solution.
Heavy customization required to implement the solution.
Lock-In − Often built using proprietary technology and required specialist skills.
Lock-In − Often built using proprietary technology and required specialist skills.
Lack of flexibility − Hard to extend or to integrate with other EAI products!
Lack of flexibility − Hard to extend or to integrate with other EAI products!
Requires organization to be EAI ready.
Requires organization to be EAI ready.
Data Level − Process, techniques and technology of moving data between data stores.
Data Level − Process, techniques and technology of moving data between data stores.
Application Interface Level − Leveraging of interfaces exposed by custom or packaged applications.
Application Interface Level − Leveraging of interfaces exposed by custom or packaged applications.
Method Level − Sharing of the business logic.
Method Level − Sharing of the business logic.
User Interface Level − Packaging applications by using their user interface as a common point of integration.
User Interface Level − Packaging applications by using their user interface as a common point of integration.
Business Continuity Planning (BCP) or Business Continuity and Resiliency Planning (BCRP) creates a guideline for continuing business operations under adverse conditions such as a natural calamity, an interruption in regular business processes, loss or damage to critical infrastructure, or a crime done against the business.
It is defined as a plan that "identifies an organization's exposure to internal and external threats and synthesizes hard and soft assets to provide effective prevention and recovery for the organization, while maintaining competitive advantage and value system integrity."
Understandably, risk management and disaster management are major components in business continuity planning.
Following are the objectives of BCP −
Reducing the possibility of any interruption in regular business processes using proper risk management.
Reducing the possibility of any interruption in regular business processes using proper risk management.
Minimizing the impact of interruption, if any.
Minimizing the impact of interruption, if any.
Teaching the staff their roles and responsibilities in such a situation to safeguard their own security and other interests.
Teaching the staff their roles and responsibilities in such a situation to safeguard their own security and other interests.
Handling any potential failure in supply chain system, to maintain the natural flow of business.
Handling any potential failure in supply chain system, to maintain the natural flow of business.
Protecting the business from failure and negative publicity.
Protecting the business from failure and negative publicity.
Protecting customers and maintaining customer relationships.
Protecting customers and maintaining customer relationships.
Protecting the prevalent and prospective market and competitive advantage of the business.
Protecting the prevalent and prospective market and competitive advantage of the business.
Protecting profits, revenue and goodwill.
Protecting profits, revenue and goodwill.
Setting a recovery plan following a disruption to normal operating conditions.
Setting a recovery plan following a disruption to normal operating conditions.
Fulfilling legislative and regulatory requirements.
Fulfilling legislative and regulatory requirements.
Traditionally a business continuity plan would just protect the data center. With the advent of technologies, the scope of a BCP includes all distributed operations, personnel, networks, power and eventually all aspects of the IT environment.
The business continuity planning process involves recovery, continuation, and preservation of the entire business operation, not just its technology component. It should include contingency plans to protect all resources of the organization, e.g., human resource, financial resource and IT infrastructure, against any mishap.
It has the following phases −
Project management & initiation
Business Impact Analysis (BIA)
Recovery strategies
Plan design & development
Testing, maintenance, awareness, training
This phase has the following sub-phases −
Establish need (risk analysis)
Get management support
Establish team (functional, technical, BCC - Business Continuity Coordinator)
Create work plan (scope, goals, methods, timeline)
Initial report to management
Obtain management approval to proceed
This phase is used to obtain formal agreement with senior management for each time-critical business resource. This phase has the following sub-phases −
Deciding maximum tolerable downtime, also known as MAO (Maximum Allowable Outage)
Quantifying loss due to business outage (financial, extra cost of recovery, embarrassment), without estimating the probability of kinds of incidents, it only quantifies the consequences
Choosing information gathering methods (surveys, interviews, software tools)
Selecting interviewees
Customizing questionnaire
Analyzing information
Identifying time-critical business functions
Assigning MTDs
Ranking critical business functions by MTDs
Reporting recovery options
Obtaining management approval
This phase involves creating recovery strategies are based on MTDs, predefined and management-approved. These strategies should address recovery of −
Business operations
Facilities & supplies
Users (workers and end-users)
Network
Data center (technical)
Data (off-site backups of data and applications)
This phase involves creating detailed recovery plan that includes −
Business & service recovery plans
Maintenance plan
Awareness & training plan
Testing plan
The Sample Plan is divided into the following phases −
Initial disaster response
Resume critical business ops
Resume non-critical business ops
Restoration (return to primary site)
Interacting with external groups (customers, media, emergency responders)
The final phase is a continuously evolving process containing testing maintenance, and training.
The testing process generally follows procedures like structured walk-through, creating checklist, simulation, parallel and full interruptions.
Maintenance involves −
Fixing problems found in testing
Implementing change management
Auditing and addressing audit findings
Annual review of plan
Training is an ongoing process and it should be made a part of the corporate standards and the corporate culture.
In a traditional manufacturing environment, supply chain management meant managing movement and storage of raw materials, work-in-progress inventory, and finished goods from point of origin to point of consumption.
It involves managing the network of interconnected smaller business units, networks of channels that take part in producing a merchandise of a service package required by the end users or customers.
With businesses crossing the barriers of local markets and reaching out to a global scenario, SCM is now defined as −
SCM consists of −
operations management
operations management
logistics
logistics
procurement
procurement
information technology
information technology
integrated business operations
integrated business operations
To decrease inventory cost by more accurately predicting demand and scheduling production to match it.
To decrease inventory cost by more accurately predicting demand and scheduling production to match it.
To reduce overall production cost by streamlining production and by improving information flow.
To reduce overall production cost by streamlining production and by improving information flow.
To improve customer satisfaction.
To improve customer satisfaction.
Customer Relationship Management
Customer Service Management
Demand Management
Customer Order Fulfillment
Manufacturing Flow Management
Procurement Management
Product Development and Commercialization
Returns Management
SCM have multi-dimensional advantages −
To the suppliers −
Help in giving clear-cut instruction
Online data transfer reduce paper work
Inventory Economy −
Inventory Economy −
Low cost of handling inventory
Low cost of handling inventory
Low cost of stock outage by deciding optimum size of replenishment orders
Low cost of stock outage by deciding optimum size of replenishment orders
Achieve excellent logistical performance such as just in time
Achieve excellent logistical performance such as just in time
Distribution Point −
Distribution Point −
Satisfied distributor and whole seller ensure that the right products reach the right place at right time
Satisfied distributor and whole seller ensure that the right products reach the right place at right time
Clear business processes subject to fewer errors
Clear business processes subject to fewer errors
Easy accounting of stock and cost of stock
Easy accounting of stock and cost of stock
Channel Management −
Channel Management −
Reduce total number of transactions required to provide product assortment
Reduce total number of transactions required to provide product assortment
Organization is logically capable of performing customization requirements
Organization is logically capable of performing customization requirements
Financial management −
Low cost
Realistic analysis
Financial management −
Low cost
Realistic analysis
Operational performance −
Operational performance −
It involves delivery speed and consistency.
External customer −
External customer −
Conformance of product and services to their requirements
Competitive prices
Quality and reliability
Delivery
After sales services
To employees and internal customers −
To employees and internal customers −
Teamwork and cooperation
Efficient structure and system
Quality work
Delivery
Strategic planning for an organization involves long-term policy decisions, like location of a new plant, a new product, diversification etc.
Strategic planning is mostly influenced by −
Decision of diversification i.e., expansion or integration of business
Market dynamics, demand and supply
Technological changes
Competitive forces
Various other threats, challenges and opportunities
Strategic planning sets targets for the workings and references for taking such long-term policy decisions and transforms the business objectives into functional and operational units. Strategic planning generally follows one of the four-way paths −
Overall Company Strategy
Growth orientation
Product orientation
Market orientation
In this chapter, let us discuss the Strategic Business Objectives of MIS with regards to the following aspects of a business −
Operational Excellence
New Products, Services and Business Models
Services and Business Models
Customer and Supplier Intimacy
Improved Decision-making
Competitive Advantage, and Survival
This relates to achieving excellence in business in operations to achieve higher profitability. For example, a consumer goods manufacturer may decide upon using a wide distribution network to get maximum reach to the customers and exposure.
A manufacturing company may pursue a strategy of aggressive marketing and mass production.
This is part of growth strategy of an organization. A new product or a new service introduced, with a very fast growth potential provides a mean for steady growth business turnover.
With the help of information technology, a company might even opt for an entirely new business model, which will allow it to establish, consolidate and maintain a leadership in the existing market as well as provide a competitive edge in the industry.
For example, a company selling low priced detergent may opt for producing higher range detergents for washing machines, washing soaps, and bath soaps.
It involves market strategies also that includes planning for distribution, advertisement, market research and other related aspects.
When a Business really knows their Customers and serves them well, 'the way they want to be served', the Customers generally respond by returning and buying more from the firm. It raises revenues and profits.
Likewise with Suppliers, the more a Business engages its Suppliers, the better the Suppliers can provide vital information. This will lower the cost and bring huge improvements in the supply-chain management.
A very important pre-requisite of strategic planning is to provide the right information at the right time to the right person, for making an informed decision.
Well planned Information Systems and technologies make it possible for the decision makers to use real-time data from the marketplace when making informed decisions.
The following list illustrates some of the strategic planning that provides competitive advantage and survival −
Planning for an overall growth for the company.
Planning for an overall growth for the company.
Thorough market research to understand the market dynamics involving demand-supply.
Thorough market research to understand the market dynamics involving demand-supply.
Various policies that will dominate the course and movement of business.
Various policies that will dominate the course and movement of business.
Expansion and diversification to conquer new markets.
Expansion and diversification to conquer new markets.
Choosing a perfect product strategy that involves either expanding a family of products or an associated product.
Choosing a perfect product strategy that involves either expanding a family of products or an associated product.
Strategies for choosing the market, distribution, pricing, advertising, packing, and other market-oriented strategies.
Strategies for choosing the market, distribution, pricing, advertising, packing, and other market-oriented strategies.
Strategies driven by industry-level changes or Government regulations.
Strategies driven by industry-level changes or Government regulations.
Strategies for change management.
Strategies for change management.
Like any other product development, system development requires careful analysis and design before implementation. System development generally has the following phases −
The project planning part involves the following steps −
Reviewing various project requests
Prioritizing the project requests
Allocating the resources
Identifying the project development team
The techniques used in information system planning are −
Critical Success Factor
Business System Planning
End/Mean Analysis
The requirement analysis part involves understanding the goals, processes and the constraints of the system for which the information system is being designed.
It is basically an iterative process involving systematic investigation of the processes and requirements. The analyst creates a blueprint of the entire system in minute details, using various diagramming techniques like −
Data flow diagrams
Context diagrams
Requirement analysis has the following sub-processes −
Conducting preliminary investigation
Performing detailed analysis activities
Studying current system
Determining user requirements
Recommending a solution
The requirement analysis stage generally completes by creation of a 'Feasibility Report'. This report contains −
A preamble
A goal statement
A brief description of the present system
Proposed alternatives in details
The feasibility report and the proposed alternatives help in preparing the costs and benefits study.
Based on the costs and benefits, and considering all problems that may be encountered due to human, organizational or technological bottlenecks, the best alternative is chosen by the end-users of the system.
System design specifies how the system will accomplish this objective. System design consists of both logical design and physical design activity, which produces 'system specification' satisfying system requirements developed in the system analysis stage.
In this stage, the following documents are prepared −
Detailed specification
Hardware/software plan
The most creative and challenging phase of the system life cycle is system design, which refers to the technical specifications that will be applied in implementing the candidate system. It also includes the construction of programmers and program testing.
It has the following stages −
Acquiring hardware and software, if necessary
Database design
Developing system processes
Coding and testing each module
The final report prior to implementation phase includes procedural flowcharts, record layout, report layout and plan for implementing the candidate system. Information on personnel, money, hardware, facility and their estimated cost must also be available. At this point projected cost must be close to actual cost of implementation.
System testing requires a test plan that consists of several key activities and steps for programs, strings, system, and user acceptance testing. The system performance criteria deals with turnaround time,backup,file protection and the human factors.
Testing process focuses on both −
The internal logic of the system/software, ensuring that all statements have been tested;
The internal logic of the system/software, ensuring that all statements have been tested;
The external functions, by conducting tests to find errors and ensuring that the defined input will actually produce the required results.
The external functions, by conducting tests to find errors and ensuring that the defined input will actually produce the required results.
In some cases, a 'parallel run' of the new system is performed, where both the current and the proposed system are run in parallel for a specified time period and the current system is used to validate the proposed system.
At this stage, system is put into production to be used by the end users. Sometime, we put system into a Beta stage where users' feedback is received and based on the feedback, the system is corrected or improved before a final release or official release of the system.
Maintenance is necessary to eliminate the errors in the working system during its working life and to tune the system to any variation in its working environment. Often small system deficiencies are found, as system is brought into operation and changes are made to remove them. System planner must always plan for resources availability to carry on these maintenance functions.
In MIS, the information is recognized as a major resource like capital and time. If this resource has to be managed well, it calls upon the management to plan for it and control it, so that the information becomes a vital resource for the system.
The management information system needs good planning.
The management information system needs good planning.
This system should deal with the management information not with data processing alone.
This system should deal with the management information not with data processing alone.
It should provide support for the management planning, decision-making and action.
It should provide support for the management planning, decision-making and action.
It should provide support to the changing needs of business management.
It should provide support to the changing needs of business management.
Major challenges in MIS implementation are −
Quantity, content and context of information − how much information and exactly what should it describe.
Quantity, content and context of information − how much information and exactly what should it describe.
Nature of analysis and presentation − comprehensibility of information.
Nature of analysis and presentation − comprehensibility of information.
Availability of information − frequency, contemporariness, on-demand or routine, periodic or occasional, one-time info or repetitive in nature and so on
Availability of information − frequency, contemporariness, on-demand or routine, periodic or occasional, one-time info or repetitive in nature and so on
Accuracy of information.
Accuracy of information.
Reliability of information.
Reliability of information.
Security and Authentication of the system.
Security and Authentication of the system.
MIS design and development process has to address the following issues successfully −
There should be effective communication between the developers and users of the system.
There should be effective communication between the developers and users of the system.
There should be synchronization in understanding of management, processes and IT among the users as well as the developers.
There should be synchronization in understanding of management, processes and IT among the users as well as the developers.
Understanding of the information needs of managers from different functional areas and combining these needs into a single integrated system.
Understanding of the information needs of managers from different functional areas and combining these needs into a single integrated system.
Creating a unified MIS covering the entire organization will lead to a more economical, faster and more integrated system, however it will increase in design complexity manifold.
Creating a unified MIS covering the entire organization will lead to a more economical, faster and more integrated system, however it will increase in design complexity manifold.
The MIS has to be interacting with the complex environment comprising all other sub-systems in the overall information system of the organization. So, it is extremely necessary to understand and define the requirements of MIS in the context of the organization.
The MIS has to be interacting with the complex environment comprising all other sub-systems in the overall information system of the organization. So, it is extremely necessary to understand and define the requirements of MIS in the context of the organization.
It should keep pace with changes in environment, changing demands of the customers and growing competition.
It should keep pace with changes in environment, changing demands of the customers and growing competition.
It should utilize fast developing in IT capabilities in the best possible ways.
It should utilize fast developing in IT capabilities in the best possible ways.
Cost and time of installing such advanced IT-based systems is high, so there should not be a need for frequent and major modifications.
Cost and time of installing such advanced IT-based systems is high, so there should not be a need for frequent and major modifications.
It should take care of not only the users i.e., the managers but also other stakeholders like employees, customers and suppliers.
It should take care of not only the users i.e., the managers but also other stakeholders like employees, customers and suppliers.
Once the organizational planning stage is over, the designer of the system should take the following strategic decisions for the achievement of MIS goals and objectives −
Development Strategy − Example - an online, real-time batch.
Development Strategy − Example - an online, real-time batch.
System Development Strategy − Designer selects an approach to system development like operational verses functional, accounting verses analysis.
System Development Strategy − Designer selects an approach to system development like operational verses functional, accounting verses analysis.
Resources for the Development − Designer has to select resources. Resources can be in-house verses external, customized or use of package.
Resources for the Development − Designer has to select resources. Resources can be in-house verses external, customized or use of package.
Manpower Composition − The staffs should have analysts, and programmers.
Manpower Composition − The staffs should have analysts, and programmers.
Information system planning essentially involves −
Identification of the stage of information system in the organization.
Identification of the stage of information system in the organization.
Identification of the application of organizational IS.
Identification of the application of organizational IS.
Evolution of each of this application based on the established evolution criteria.
Evolution of each of this application based on the established evolution criteria.
Establishing a priority ranking for these applications.
Establishing a priority ranking for these applications.
Determining the optimum architecture of IS for serving the top priority applications.
Determining the optimum architecture of IS for serving the top priority applications.
The following diagram illustrates a brief sketch of the process of information requirement analysis −
The following three methodologies can be adopted to determine the requirements in developing a management information system for any organization −
Business Systems Planning (BSP) − this methodology is developed by IBM.
It identifies the IS priorities of the organization and focuses on the way data is maintained in the system.
It uses data architecture supporting multiple applications.
It defines data classes using different matrices to establish relationships among the organization, its processes and data requirements.
Business Systems Planning (BSP) − this methodology is developed by IBM.
It identifies the IS priorities of the organization and focuses on the way data is maintained in the system.
It identifies the IS priorities of the organization and focuses on the way data is maintained in the system.
It uses data architecture supporting multiple applications.
It uses data architecture supporting multiple applications.
It defines data classes using different matrices to establish relationships among the organization, its processes and data requirements.
It defines data classes using different matrices to establish relationships among the organization, its processes and data requirements.
Critical Success Factor (CSF) − this methodology is developed by John Rockart of MIT.
It identifies the key business goals and strategies of each manager as well as that of the business.
Next, it looks for the critical success factors underlying these goals.
Measure of CSF effectiveness becomes an input for defining the information system requirements.
Critical Success Factor (CSF) − this methodology is developed by John Rockart of MIT.
It identifies the key business goals and strategies of each manager as well as that of the business.
It identifies the key business goals and strategies of each manager as well as that of the business.
Next, it looks for the critical success factors underlying these goals.
Next, it looks for the critical success factors underlying these goals.
Measure of CSF effectiveness becomes an input for defining the information system requirements.
Measure of CSF effectiveness becomes an input for defining the information system requirements.
End/Means (E/M) analysis − this methodology is developed by Wetherbe and Davis at the University of Minnesota.
End/Means (E/M) analysis − this methodology is developed by Wetherbe and Davis at the University of Minnesota.
It determines the effectiveness criteria for outputs and efficiency criteria for the processes generating the outputs.
It determines the effectiveness criteria for outputs and efficiency criteria for the processes generating the outputs.
At first it identifies the outputs or services provided by the business processes.
At first it identifies the outputs or services provided by the business processes.
Then it describes the factors that make these outputs effective for the user.
Then it describes the factors that make these outputs effective for the user.
Finally it selects the information needed to evaluate the effectiveness of outputs
Finally it selects the information needed to evaluate the effectiveness of outputs
System analysis and design follows the typical System/Software Design Life Cycle (SDLC) as discussed in the previous chapter. It generally passes through the following phases −
Problem Definition
Feasibility Study
Systems Analysis
System Design
Detailed System Design
Implementation
Maintenance
In the analysis phase, the following techniques are commonly used −
Data flow diagrams (DFD)
Logic Modeling
Data Modeling
Rapid Application Development (RAD)
Object Oriented Analysis (OOA)
The technology requirement for an information system can be categorized as −
Devices
Devices
Data center systems − It is the environment that provides processing, storage, networking, management and the distribution of data within an enterprise.
Data center systems − It is the environment that provides processing, storage, networking, management and the distribution of data within an enterprise.
Enterprise software − These are software system like ERP, SCM, Human Resource Management, etc. that fulfill the needs and objectives of the organizations.
Enterprise software − These are software system like ERP, SCM, Human Resource Management, etc. that fulfill the needs and objectives of the organizations.
IT services − It refers to the implementation and management of quality IT services by IT service providers through people, process and information technology. It often includes various process improvement frameworks and methodologies like six sigma, TQM, and so on.
IT services − It refers to the implementation and management of quality IT services by IT service providers through people, process and information technology. It often includes various process improvement frameworks and methodologies like six sigma, TQM, and so on.
Telecom services
Telecom services
The system should be fully tested for errors before being fully operational.
The test plan should include for each test −
Purpose
Definition
test inputs
detailed specification of test procedure
details of expected outputs
Each sub-system and all their components should be tested using various test procedures and data to ensure that each component is working as it is intended.
The testing must include the users of the system to identify errors as well as get the feedback.
Before the system is in operation, the following issues should be taken care of −
Data security, backup and recovery;
Data security, backup and recovery;
Systems control;
Systems control;
Testing of the system to ensure that it works bug-free in all expected business situations;
Testing of the system to ensure that it works bug-free in all expected business situations;
The hardware and software used should be able to deliver the expected processing;
The hardware and software used should be able to deliver the expected processing;
The system capacity and expected response time should be maintained;
The system capacity and expected response time should be maintained;
The system should be well documented including;
The system should be well documented including;
A user guide for inexperienced users,
A user guide for inexperienced users,
A user reference or operations manual for advanced users,
A user reference or operations manual for advanced users,
A system reference manual describing system structures and architecture.
A system reference manual describing system structures and architecture.
Once the system is fully operational, it should be maintained throughout its working life to resolve any glitches or difficulties faced in operation and minor modifications might be made to overcome such situations.
MIS development projects are high-risk, high-return projects. Following could be stated as critical factors for success and failure in MIS development −
It should cater to a specific, well-perceived business.
It should cater to a specific, well-perceived business.
The top management should be completely convinced, able and willing to such a system. Ideally there should be a patron or a sponsor for the system in the top management.
The top management should be completely convinced, able and willing to such a system. Ideally there should be a patron or a sponsor for the system in the top management.
All users including managers and other employees should be made an integral part of the development, implementation, and use of the system.
All users including managers and other employees should be made an integral part of the development, implementation, and use of the system.
There should be an operational prototype of the system released as soon as possible, to create interest among the users.
There should be an operational prototype of the system released as soon as possible, to create interest among the users.
There should be good support staff with necessary technical, business, and interpersonal skills.
There should be good support staff with necessary technical, business, and interpersonal skills.
The system should be simple, easy to understand without adding much complexity. It is a best practice, not to add up an entity unless there is both a use and user for it.
The system should be simple, easy to understand without adding much complexity. It is a best practice, not to add up an entity unless there is both a use and user for it.
It should be easy to use and navigate with high response time.
It should be easy to use and navigate with high response time.
The implementation process should follow a definite goal and time.
The implementation process should follow a definite goal and time.
All the users including the top management should be given proper training, so that they have a good knowledge of the content and function of the system, and can use it fully for various managerial activities such as reporting, budgeting, controlling, planning, monitoring, etc.
All the users including the top management should be given proper training, so that they have a good knowledge of the content and function of the system, and can use it fully for various managerial activities such as reporting, budgeting, controlling, planning, monitoring, etc.
It must produce useful outputs to be used by all managers.
It must produce useful outputs to be used by all managers.
The system should be well integrated into the management processes of planning, decision-making, and monitoring.
The system should be well integrated into the management processes of planning, decision-making, and monitoring.
Decision-making is a cognitive process that results in the selection of a course of action among several alternative scenarios.
Decision-making is a daily activity for any human being. There is no exception about that. When it comes to business organizations, decision-making is a habit and a process as well.
Effective and successful decisions result in profits, while unsuccessful ones cause losses. Therefore, corporate decision-making is the most critical process in any organization.
In a decision-making process, we choose one course of action from a few possible alternatives. In the process of decision-making, we may use many tools, techniques, and perceptions.
In addition, we may make our own private decisions or may prefer a collective decision.
Usually, decision-making is hard. Majority of corporate decisions involve some level of dissatisfaction or conflict with another party.
Let's have a look at the decision-making process in detail.
Following are the important steps of the decision-making process. Each step may be supported by different tools and techniques.
In this step, the problem is thoroughly analyzed. There are a couple of questions one should ask when it comes to identifying the purpose of the decision.
What exactly is the problem?
Why the problem should be solved?
Who are the affected parties of the problem?
Does the problem have a deadline or a specific time-line?
A problem of an organization will have many stakeholders. In addition, there can be dozens of factors involved and affected by the problem.
In the process of solving the problem, you will have to gather as much as information related to the factors and stakeholders involved in the problem. For the process of information gathering, tools such as 'Check Sheets' can be effectively used.
In this step, the baseline criteria for judging the alternatives should be set up. When it comes to defining the criteria, organizational goals as well as the corporate culture should be taken into consideration.
As an example, profit is one of the main concerns in every decision making process. Companies usually do not make decisions that reduce profits, unless it is an exceptional case. Likewise, baseline principles should be identified related to the problem in hand.
For this step, brainstorming to list down all the ideas is the best option. Before the idea generation step, it is vital to understand the causes of the problem and prioritization of causes.
For this, you can make use of Cause-and-Effect diagrams and Pareto Chart tool. Cause-and-Effect diagram helps you to identify all possible causes of the problem and Pareto chart helps you to prioritize and identify the causes with the highest effect.
Then, you can move on generating all possible solutions (alternatives) for the problem in hand.
Use your judgment principles and decision-making criteria to evaluate each alternative. In this step, experience and effectiveness of the judgment principles come into play. You need to compare each alternative for their positives and negatives.
Once you go through from Step 1 to Step 5, this step is easy. In addition, the selection of the best alternative is an informed decision since you have already followed a methodology to derive and select the best alternative.
Convert your decision into a plan or a sequence of activities. Execute your plan by yourself or with the help of subordinates.
Evaluate the outcome of your decision. See whether there is anything you should learn and then correct in future decision making. This is one of the best practices that will improve your decision-making skills.
There are two basic models in decision-making −
Rational models
Normative model
The rational models are based on cognitive judgments and help in selecting the most logical and sensible alternative. Examples of such models include - decision matrix analysis, Pugh matrix, SWOT analysis, Pareto analysis and decision trees, selection matrix, etc.
A rational decision making model takes the following steps −
Identifying the problem,
Identifying the problem,
Identifying the important criteria for the process and the result,
Identifying the important criteria for the process and the result,
Considering all possible solutions,
Considering all possible solutions,
Calculating the consequences of all solutions and comparing the probability of satisfying the criteria,
Calculating the consequences of all solutions and comparing the probability of satisfying the criteria,
Selecting the best option.
Selecting the best option.
The normative model of decision-making considers constraints that may arise in making decisions, such as time, complexity, uncertainty, and inadequacy of resources.
According to this model, decision-making is characterized by −
Limited information processing - A person can manage only a limited amount of information.
Limited information processing - A person can manage only a limited amount of information.
Judgmental heuristics - A person may use shortcuts to simplify the decision making process.
Judgmental heuristics - A person may use shortcuts to simplify the decision making process.
Satisfying - A person may choose a solution that is just "good enough".
Satisfying - A person may choose a solution that is just "good enough".
Dynamic decision-making (DDM) is synergetic decision-making involving interdependent systems, in an environment that changes over time either due to the previous actions of the decision-maker or due to events that are outside of the control of the decision-maker.
These decision-makings are more complex and real-time.
Dynamic decision-making involves observing how people used their experience to control the system's dynamics and noting down the best decisions taken thereon.
Sensitivity analysis is a technique used for distributing the uncertainty in the output of a mathematical model or a system to different sources of uncertainty in its inputs.
From business decision perspective, the sensitivity analysis helps an analyst to identify cost drivers as well as other quantities to make an informed decision. If a particular quantity has no bearing on a decision or prediction, then the conditions relating to quantity could be eliminated, thus simplifying the decision making process.
Sensitivity analysis also helps in some other situations, like −
Resource optimization
Future data collections
Identifying critical assumptions
To optimize the tolerance of manufactured parts
Show the value of various attributes in a balanced system.
Show the value of various attributes in a balanced system.
Work best in static systems.
Work best in static systems.
Do not take into consideration the time-based variances.
Do not take into consideration the time-based variances.
Do not work well in real-time systems however, it may work in a dynamic system being in equilibrium
Do not work well in real-time systems however, it may work in a dynamic system being in equilibrium
Involve less data.
Involve less data.
Are easy to analyze.
Are easy to analyze.
Produce faster results.
Produce faster results.
Dynamic models −
Consider the change in data values over time.
Consider effect of system behavior over time.
Re-calculate equations as time changes.
Can be applied only in dynamic systems.
Simulation is a technique that imitates the operation of a real-world process or system over time. Simulation techniques can be used to assist management decision making, where analytical methods are either not available or cannot be applied.
Some of the typical business problem areas where simulation techniques are used are −
Inventory control
Queuing problem
Production planning
Operational Research (OR) includes a wide range of problem-solving techniques involving various advanced analytical models and methods applied. It helps in efficient and improved decision-making.
It encompasses techniques such as simulation, mathematical optimization, queuing theory, stochastic-process models, econometric methods, data envelopment analysis, neural networks, expert systems, decision analysis, and the analytic hierarchy process.
OR techniques describe a system by constructing its mathematical models.
Heuristic programming refers to a branch of artificial intelligence. It consists of programs that are self-learning in nature.
However, these programs are not optimal in nature, as they are experience-based techniques for problem solving.
Most basic heuristic programs would be based on pure 'trial-error' methods.
Heuristics take a 'guess' approach to problem solving, yielding a 'good enough' answer, rather than finding a 'best possible' solution.
In group decision-making, various individuals in a group take part in collaborative decision-making.
Group Decision Support System (GDSS) is a decision support system that provides support in decision making by a group of people. It facilitates the free flow and exchange of ideas and information among the group members. Decisions are made with a higher degree of consensus and agreement resulting in a dramatically higher likelihood of implementation.
Following are the available types of computer based GDSSs −
Decision Network − This type helps the participants to communicate with each other through a network or through a central database. Application software may use commonly shared models to provide support.
Decision Network − This type helps the participants to communicate with each other through a network or through a central database. Application software may use commonly shared models to provide support.
Decision Room − Participants are located at one place, i.e. the decision room. The purpose of this is to enhance participant's interactions and decision-making within a fixed period of time using a facilitator.
Decision Room − Participants are located at one place, i.e. the decision room. The purpose of this is to enhance participant's interactions and decision-making within a fixed period of time using a facilitator.
Teleconferencing − Groups are composed of members or sub groups that are geographically dispersed; teleconferencing provides interactive connection between two or more decision rooms. This interaction will involve transmission of computerized and audio visual information.
Teleconferencing − Groups are composed of members or sub groups that are geographically dispersed; teleconferencing provides interactive connection between two or more decision rooms. This interaction will involve transmission of computerized and audio visual information.
Information system security refers to the way the system is defended against unauthorized access, use, disclosure, disruption, modification, perusal, inspection, recording or destruction.
There are two major aspects of information system security −
Security of the information technology used − securing the system from malicious cyber-attacks that tend to break into the system and to access critical private information or gain control of the internal systems.
Security of the information technology used − securing the system from malicious cyber-attacks that tend to break into the system and to access critical private information or gain control of the internal systems.
Security of data − ensuring the integrity of data when critical issues, arise such as natural disasters, computer/server malfunction, physical theft etc. Generally an off-site backup of data is kept for such problems.
Security of data − ensuring the integrity of data when critical issues, arise such as natural disasters, computer/server malfunction, physical theft etc. Generally an off-site backup of data is kept for such problems.
Guaranteeing effective information security has the following key aspects −
Preventing the unauthorized individuals or systems from accessing the information.
Preventing the unauthorized individuals or systems from accessing the information.
Maintaining and assuring the accuracy and consistency of data over its entire life-cycle.
Maintaining and assuring the accuracy and consistency of data over its entire life-cycle.
Ensuring that the computing systems, the security controls used to protect it and the communication channels used to access it, functioning correctly all the time, thus making information available in all situations.
Ensuring that the computing systems, the security controls used to protect it and the communication channels used to access it, functioning correctly all the time, thus making information available in all situations.
Ensuring that the data, transactions, communications or documents are genuine.
Ensuring that the data, transactions, communications or documents are genuine.
Ensuring the integrity of a transaction by validating that both parties involved are genuine, by incorporating authentication features such as "digital signatures".
Ensuring the integrity of a transaction by validating that both parties involved are genuine, by incorporating authentication features such as "digital signatures".
Ensuring that once a transaction takes place, none of the parties can deny it, either having received a transaction, or having sent a transaction. This is called 'non-repudiation'.
Ensuring that once a transaction takes place, none of the parties can deny it, either having received a transaction, or having sent a transaction. This is called 'non-repudiation'.
Safeguarding data and communications stored and shared in network systems.
Safeguarding data and communications stored and shared in network systems.
Information systems bring about immense social changes, threatening the existing distributions of power, money, rights, and obligations. It also raises new kinds of crimes, like cyber-crimes.
Following organizations promote ethical issues −
The Association of Information Technology Professionals (AITP)
The Association of Information Technology Professionals (AITP)
The Association of Computing Machinery (ACM)
The Association of Computing Machinery (ACM)
The Institute of Electrical and Electronics Engineers (IEEE)
The Institute of Electrical and Electronics Engineers (IEEE)
Computer Professionals for Social Responsibility (CPSR)
Computer Professionals for Social Responsibility (CPSR)
Strive to achieve the highest quality, effectiveness, and dignity in both the process and products of professional work.
Strive to achieve the highest quality, effectiveness, and dignity in both the process and products of professional work.
Acquire and maintain professional competence.
Acquire and maintain professional competence.
Know and respect existing laws pertaining to professional work.
Know and respect existing laws pertaining to professional work.
Accept and provide appropriate professional review.
Accept and provide appropriate professional review.
Give comprehensive and thorough evaluations of computer systems and their impacts, including analysis and possible risks.
Give comprehensive and thorough evaluations of computer systems and their impacts, including analysis and possible risks.
Honor contracts, agreements, and assigned responsibilities.
Honor contracts, agreements, and assigned responsibilities.
Improve public understanding of computing and its consequences.
Improve public understanding of computing and its consequences.
Access computing and communication resources only when authorized to do so.
Access computing and communication resources only when authorized to do so.
IEEE code of ethics demands that every professional vouch to commit themselves to the highest ethical and professional conduct and agree −
To accept responsibility in making decisions consistent with the safety, health and welfare of the public, and to disclose promptly factors that might endanger the public or the environment;
To accept responsibility in making decisions consistent with the safety, health and welfare of the public, and to disclose promptly factors that might endanger the public or the environment;
To avoid real or perceived conflicts of interest whenever possible, and to disclose them to affected parties when they do exist;
To avoid real or perceived conflicts of interest whenever possible, and to disclose them to affected parties when they do exist;
To be honest and realistic in stating claims or estimates based on available data;
To be honest and realistic in stating claims or estimates based on available data;
To reject bribery in all its forms;
To reject bribery in all its forms;
To improve the understanding of technology, its appropriate application, and potential consequences;
To improve the understanding of technology, its appropriate application, and potential consequences;
To maintain and improve our technical competence and to undertake technological tasks for others only if qualified by training or experience, or after full disclosure of pertinent limitations;
To maintain and improve our technical competence and to undertake technological tasks for others only if qualified by training or experience, or after full disclosure of pertinent limitations;
To seek, accept, and offer honest criticism of technical work, to acknowledge and correct errors, and to credit properly the contributions of others;
To seek, accept, and offer honest criticism of technical work, to acknowledge and correct errors, and to credit properly the contributions of others;
To treat fairly all persons regardless of such factors as race, religion, gender, disability, age, or national origin;
To treat fairly all persons regardless of such factors as race, religion, gender, disability, age, or national origin;
To avoid injuring others, their property, reputation, or employment by false or malicious action;
To avoid injuring others, their property, reputation, or employment by false or malicious action;
To assist colleagues and co-workers in their professional development and to support them in following this code of ethics.
To assist colleagues and co-workers in their professional development and to support them in following this code of ethics.
An efficient information system creates an impact on the organization's function, performance, and productivity.
Nowadays, information system and information technology have become a vital part of any successful business and is regarded as a major functional area like any other functional areas such as marketing, finance, production and human resources, etc.
Thus, it is important to understand the functions of an information system just like any other functional area in business. A well maintained management information system supports the organization at different levels.
Many firms are using information system that cross the boundaries of traditional business functions in order to re-engineer and improve vital business processes all across the enterprise. This typical has involved installing −
Enterprise Resource Planning (ERP)
Supply Chain Management (SCM)
Customer Relationship Management (CRM)
Transaction Processing System (TPS)
Executive Information System (EIS)
Decision Support System (DSS)
Knowledge Management Systems (KMS)
Content Management Systems (CMS)
The strategic role of Management Information System involves using it to develop products, services, and capabilities that provides a company major advantages over competitive forces it faces in the global marketplace.
We need an MIS flexible enough to deal with changing information needs of the organization. The designing of such a system is a complex task. It can be achieved only if the MIS is planned. We understand this planning and implementation in management development process.
Decision support system is a major segment of organizational information system, because of its influential role in taking business decisions. It help all levels of managers to take various decisions.
20 Lectures
3.5 hours
Richa Maheshwari
15 Lectures
1 hours
Ajay
15 Lectures
1 hours
Ajay
12 Lectures
2 hours
Richa Maheshwari
12 Lectures
1.5 hours
Richa Maheshwari
15 Lectures
1 hours
Ajay
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2643,
"s": 2324,
"text": "Information can be defined as meaningfully interpreted data. If we give you a number 1-212-290-4700, it does not make any sense on its own. It is just a raw data. However if we say Tel: +1-212-290-4700, it starts making sense. It becomes a telephone number. If I gather some more data and record it meaningfully like −"
},
{
"code": null,
"e": 2752,
"s": 2643,
"text": "Address: 350 Fifth Avenue, 34th floor\nNew York, NY 10118-3299 USA\nTel: +1-212-290-4700\nFax: +1-212-736-1300\n"
},
{
"code": null,
"e": 2903,
"s": 2752,
"text": "It becomes a very useful information - the address of New York office of Human Rights Watch, a non-profit, non-governmental human rights organization."
},
{
"code": null,
"e": 3026,
"s": 2903,
"text": "So, from a system analyst's point of view, information is a sequence of symbols that can be construed to a useful message."
},
{
"code": null,
"e": 3168,
"s": 3026,
"text": "An Information System is a system that gathers data and disseminates information with the sole purpose of providing information to its users."
},
{
"code": null,
"e": 3326,
"s": 3168,
"text": "The main object of an information system is to provide information to its users. Information systems vary according to the type of users who use the system."
},
{
"code": null,
"e": 3591,
"s": 3326,
"text": "A Management Information System is an information system that evaluates, analyzes, and processes an organization's data to produce meaningful and useful information based on which the management can take right decisions to ensure future growth of the organization."
},
{
"code": null,
"e": 3616,
"s": 3591,
"text": "According to Wikipedia −"
},
{
"code": null,
"e": 3794,
"s": 3616,
"text": "\"Information can be recorded as signs, or transmitted as signals. Information is any kind of event that affects the state of a dynamic system that can interpret the information."
},
{
"code": null,
"e": 4066,
"s": 3794,
"text": "Conceptually, information is the message (utterance or expression) being conveyed. Therefore, in a general sense, information is \"Knowledge communicated or received, concerning a particular fact or circumstance\". Information cannot be predicted and resolves uncertainty.\""
},
{
"code": null,
"e": 4307,
"s": 4066,
"text": "Data can be described as unprocessed facts and figures. Plain collected data as raw facts cannot help in decision-making. However, data is the raw material that is organized, structured, and interpreted to create useful information systems."
},
{
"code": null,
"e": 4437,
"s": 4307,
"text": "Data is defined as 'groups of non-random symbols in the form of text, images, voice representing quantities, action and objects'."
},
{
"code": null,
"e": 4550,
"s": 4437,
"text": "Information is interpreted data; created from organized, structured, and processed data in a particular context."
},
{
"code": null,
"e": 4581,
"s": 4550,
"text": "According to Davis and Olson −"
},
{
"code": null,
"e": 4723,
"s": 4581,
"text": "Professor Ray R. Larson of the School of Information at the University of California, Berkeley, provides an Information Hierarchy, which is −"
},
{
"code": null,
"e": 4763,
"s": 4723,
"text": "Data − The raw material of information."
},
{
"code": null,
"e": 4803,
"s": 4763,
"text": "Data − The raw material of information."
},
{
"code": null,
"e": 4858,
"s": 4803,
"text": "Information − Data organized and presented by someone."
},
{
"code": null,
"e": 4913,
"s": 4858,
"text": "Information − Data organized and presented by someone."
},
{
"code": null,
"e": 4975,
"s": 4913,
"text": "Knowledge − Information read, heard, or seen, and understood."
},
{
"code": null,
"e": 5037,
"s": 4975,
"text": "Knowledge − Information read, heard, or seen, and understood."
},
{
"code": null,
"e": 5100,
"s": 5037,
"text": "Wisdom − Distilled and integrated knowledge and understanding."
},
{
"code": null,
"e": 5163,
"s": 5100,
"text": "Wisdom − Distilled and integrated knowledge and understanding."
},
{
"code": null,
"e": 5222,
"s": 5163,
"text": "Scott Andrews' explains Information Continuum as follows −"
},
{
"code": null,
"e": 5284,
"s": 5222,
"text": "Data − A Fact or a piece of information, or a series thereof."
},
{
"code": null,
"e": 5346,
"s": 5284,
"text": "Data − A Fact or a piece of information, or a series thereof."
},
{
"code": null,
"e": 5391,
"s": 5346,
"text": "Information − Knowledge discerned from data."
},
{
"code": null,
"e": 5436,
"s": 5391,
"text": "Information − Knowledge discerned from data."
},
{
"code": null,
"e": 5605,
"s": 5436,
"text": "Business Intelligence − Information Management pertaining to an organization's policy or decision-making, particularly when tied to strategic or operational objectives."
},
{
"code": null,
"e": 5774,
"s": 5605,
"text": "Business Intelligence − Information Management pertaining to an organization's policy or decision-making, particularly when tied to strategic or operational objectives."
},
{
"code": null,
"e": 5828,
"s": 5774,
"text": "The most popular data collection techniques include −"
},
{
"code": null,
"e": 5903,
"s": 5828,
"text": "Surveys − A questionnaires is prepared to collect the data from the field."
},
{
"code": null,
"e": 5978,
"s": 5903,
"text": "Surveys − A questionnaires is prepared to collect the data from the field."
},
{
"code": null,
"e": 6090,
"s": 5978,
"text": "Secondary data sources or archival data: Data is collected through old records, magazines, company website etc."
},
{
"code": null,
"e": 6202,
"s": 6090,
"text": "Secondary data sources or archival data: Data is collected through old records, magazines, company website etc."
},
{
"code": null,
"e": 6308,
"s": 6202,
"text": "Objective measures or tests − An experimental test is conducted on the subject and the data is collected."
},
{
"code": null,
"e": 6414,
"s": 6308,
"text": "Objective measures or tests − An experimental test is conducted on the subject and the data is collected."
},
{
"code": null,
"e": 6590,
"s": 6414,
"text": "Interviews − Data is collected by the system analyst by following a rigid procedure and collecting the answers to a set of pre-conceived questions through personal interviews."
},
{
"code": null,
"e": 6766,
"s": 6590,
"text": "Interviews − Data is collected by the system analyst by following a rigid procedure and collecting the answers to a set of pre-conceived questions through personal interviews."
},
{
"code": null,
"e": 6908,
"s": 6766,
"text": "Information can be classified in a number of ways and in this chapter, you will learn two of the most important ways to classify information."
},
{
"code": null,
"e": 7050,
"s": 6908,
"text": "Based on Anthony's classification of Management, information used in business for decision-making is generally categorized into three types −"
},
{
"code": null,
"e": 7348,
"s": 7050,
"text": "Strategic Information − Strategic information is concerned with long term policy decisions that defines the objectives of a business and checks how well these objectives are met. For example, acquiring a new plant, a new product, diversification of business etc, comes under strategic information."
},
{
"code": null,
"e": 7646,
"s": 7348,
"text": "Strategic Information − Strategic information is concerned with long term policy decisions that defines the objectives of a business and checks how well these objectives are met. For example, acquiring a new plant, a new product, diversification of business etc, comes under strategic information."
},
{
"code": null,
"e": 7868,
"s": 7646,
"text": "Tactical Information − Tactical information is concerned with the information needed for exercising control over business resources, like budgeting, quality control, service level, inventory level, productivity level etc."
},
{
"code": null,
"e": 8090,
"s": 7868,
"text": "Tactical Information − Tactical information is concerned with the information needed for exercising control over business resources, like budgeting, quality control, service level, inventory level, productivity level etc."
},
{
"code": null,
"e": 8404,
"s": 8090,
"text": "Operational Information − Operational information is concerned with plant/business level information and is used to ensure proper conduction of specific operational tasks as planned/intended. Various operator specific, machine specific and shift specific jobs for quality control checks comes under this category."
},
{
"code": null,
"e": 8718,
"s": 8404,
"text": "Operational Information − Operational information is concerned with plant/business level information and is used to ensure proper conduction of specific operational tasks as planned/intended. Various operator specific, machine specific and shift specific jobs for quality control checks comes under this category."
},
{
"code": null,
"e": 8780,
"s": 8718,
"text": "In terms of applications, information can be categorized as −"
},
{
"code": null,
"e": 9063,
"s": 8780,
"text": "Planning Information − These are the information needed for establishing standard norms and specifications in an organization. This information is used in strategic, tactical, and operation planning of any activity. Examples of such information are time standards, design standards."
},
{
"code": null,
"e": 9346,
"s": 9063,
"text": "Planning Information − These are the information needed for establishing standard norms and specifications in an organization. This information is used in strategic, tactical, and operation planning of any activity. Examples of such information are time standards, design standards."
},
{
"code": null,
"e": 9733,
"s": 9346,
"text": "Control Information − This information is needed for establishing control over all business activities through feedback mechanism. This information is used for controlling attainment, nature and utilization of important processes in a system. When such information reflects a deviation from the established standards, the system should induce a decision or an action leading to control."
},
{
"code": null,
"e": 10120,
"s": 9733,
"text": "Control Information − This information is needed for establishing control over all business activities through feedback mechanism. This information is used for controlling attainment, nature and utilization of important processes in a system. When such information reflects a deviation from the established standards, the system should induce a decision or an action leading to control."
},
{
"code": null,
"e": 10323,
"s": 10120,
"text": "Knowledge Information − Knowledge is defined as \"information about information\". Knowledge information is acquired through experience and learning, and collected from archival data and research studies."
},
{
"code": null,
"e": 10526,
"s": 10323,
"text": "Knowledge Information − Knowledge is defined as \"information about information\". Knowledge information is acquired through experience and learning, and collected from archival data and research studies."
},
{
"code": null,
"e": 10972,
"s": 10526,
"text": "Organizational Information − Organizational information deals with an organization's environment, culture in the light of its objectives. Karl Weick's Organizational Information Theory emphasizes that an organization reduces its equivocality or uncertainty by collecting, managing and using these information prudently. This information is used by everybody in the organization; examples of such information are employee and payroll information."
},
{
"code": null,
"e": 11418,
"s": 10972,
"text": "Organizational Information − Organizational information deals with an organization's environment, culture in the light of its objectives. Karl Weick's Organizational Information Theory emphasizes that an organization reduces its equivocality or uncertainty by collecting, managing and using these information prudently. This information is used by everybody in the organization; examples of such information are employee and payroll information."
},
{
"code": null,
"e": 11773,
"s": 11418,
"text": "Functional/Operational Information − This is operation specific information. For example, daily schedules in a manufacturing plant that refers to the detailed assignment of jobs to machines or machines to operators. In a service oriented business, it would be the duty roster of various personnel. This information is mostly internal to the organization."
},
{
"code": null,
"e": 12128,
"s": 11773,
"text": "Functional/Operational Information − This is operation specific information. For example, daily schedules in a manufacturing plant that refers to the detailed assignment of jobs to machines or machines to operators. In a service oriented business, it would be the duty roster of various personnel. This information is mostly internal to the organization."
},
{
"code": null,
"e": 12416,
"s": 12128,
"text": "Database Information − Database information construes large quantities of information that has multiple usage and application. Such information is stored, retrieved and managed to create databases. For example, material specification or supplier information is stored for multiple users."
},
{
"code": null,
"e": 12704,
"s": 12416,
"text": "Database Information − Database information construes large quantities of information that has multiple usage and application. Such information is stored, retrieved and managed to create databases. For example, material specification or supplier information is stored for multiple users."
},
{
"code": null,
"e": 12973,
"s": 12704,
"text": "Information is a vital resource for the success of any organization. Future of an organization lies in using and disseminating information wisely. Good quality information placed in right context in right time tells us about opportunities and problems well in advance."
},
{
"code": null,
"e": 13087,
"s": 12973,
"text": "Good quality information − Quality is a value that would vary according to the users and uses of the information."
},
{
"code": null,
"e": 13183,
"s": 13087,
"text": "According to Wang and Strong, following are the dimensions or elements of Information Quality −"
},
{
"code": null,
"e": 13244,
"s": 13183,
"text": "Intrinsic − Accuracy, Objectivity, Believability, Reputation"
},
{
"code": null,
"e": 13305,
"s": 13244,
"text": "Intrinsic − Accuracy, Objectivity, Believability, Reputation"
},
{
"code": null,
"e": 13390,
"s": 13305,
"text": "Contextual − Relevancy, Value-Added, Timeliness, Completeness, Amount of information"
},
{
"code": null,
"e": 13475,
"s": 13390,
"text": "Contextual − Relevancy, Value-Added, Timeliness, Completeness, Amount of information"
},
{
"code": null,
"e": 13545,
"s": 13475,
"text": "Representational − Interpretability, Format, Coherence, Compatibility"
},
{
"code": null,
"e": 13615,
"s": 13545,
"text": "Representational − Interpretability, Format, Coherence, Compatibility"
},
{
"code": null,
"e": 13662,
"s": 13615,
"text": "Accessibility − Accessibility, Access security"
},
{
"code": null,
"e": 13709,
"s": 13662,
"text": "Accessibility − Accessibility, Access security"
},
{
"code": null,
"e": 13895,
"s": 13709,
"text": "Various authors propose various lists of metrics for assessing the quality of information. Let us generate a list of the most essential characteristic features for information quality −"
},
{
"code": null,
"e": 13949,
"s": 13895,
"text": "Reliability − It should be verifiable and dependable."
},
{
"code": null,
"e": 14003,
"s": 13949,
"text": "Reliability − It should be verifiable and dependable."
},
{
"code": null,
"e": 14122,
"s": 14003,
"text": "Timely − It must be current and it must reach the users well in time, so that important decisions can be made in time."
},
{
"code": null,
"e": 14241,
"s": 14122,
"text": "Timely − It must be current and it must reach the users well in time, so that important decisions can be made in time."
},
{
"code": null,
"e": 14331,
"s": 14241,
"text": "Relevant − It should be current and valid information and it should reduce uncertainties."
},
{
"code": null,
"e": 14421,
"s": 14331,
"text": "Relevant − It should be current and valid information and it should reduce uncertainties."
},
{
"code": null,
"e": 14499,
"s": 14421,
"text": "Accurate − It should be free of errors and mistakes, true, and not deceptive."
},
{
"code": null,
"e": 14577,
"s": 14499,
"text": "Accurate − It should be free of errors and mistakes, true, and not deceptive."
},
{
"code": null,
"e": 14669,
"s": 14577,
"text": "Sufficient − It should be adequate in quantity, so that decisions can be made on its basis."
},
{
"code": null,
"e": 14761,
"s": 14669,
"text": "Sufficient − It should be adequate in quantity, so that decisions can be made on its basis."
},
{
"code": null,
"e": 14858,
"s": 14761,
"text": "Unambiguous − It should be expressed in clear terms. In other words, in should be comprehensive."
},
{
"code": null,
"e": 14955,
"s": 14858,
"text": "Unambiguous − It should be expressed in clear terms. In other words, in should be comprehensive."
},
{
"code": null,
"e": 15019,
"s": 14955,
"text": "Complete − It should meet all the needs in the current context."
},
{
"code": null,
"e": 15083,
"s": 15019,
"text": "Complete − It should meet all the needs in the current context."
},
{
"code": null,
"e": 15180,
"s": 15083,
"text": "Unbiased − It should be impartial, free from any bias. In other words, it should have integrity."
},
{
"code": null,
"e": 15277,
"s": 15180,
"text": "Unbiased − It should be impartial, free from any bias. In other words, it should have integrity."
},
{
"code": null,
"e": 15332,
"s": 15277,
"text": "Explicit − It should not need any further explanation."
},
{
"code": null,
"e": 15387,
"s": 15332,
"text": "Explicit − It should not need any further explanation."
},
{
"code": null,
"e": 15467,
"s": 15387,
"text": "Comparable − It should be of uniform collection, analysis, content, and format."
},
{
"code": null,
"e": 15547,
"s": 15467,
"text": "Comparable − It should be of uniform collection, analysis, content, and format."
},
{
"code": null,
"e": 15654,
"s": 15547,
"text": "Reproducible − It could be used by documented methods on the same data set to achieve a consistent result."
},
{
"code": null,
"e": 15761,
"s": 15654,
"text": "Reproducible − It could be used by documented methods on the same data set to achieve a consistent result."
},
{
"code": null,
"e": 15963,
"s": 15761,
"text": "Information processing beyond doubt is the dominant industry of the present century. Following factors states few common factors that reflect on the needs and objectives of the information processing −"
},
{
"code": null,
"e": 16043,
"s": 15963,
"text": "Increasing impact of information processing for organizational decision making."
},
{
"code": null,
"e": 16123,
"s": 16043,
"text": "Increasing impact of information processing for organizational decision making."
},
{
"code": null,
"e": 16290,
"s": 16123,
"text": "Dependency of services sector including banking, financial organization, health care, entertainment, tourism and travel, education and numerous others on information."
},
{
"code": null,
"e": 16457,
"s": 16290,
"text": "Dependency of services sector including banking, financial organization, health care, entertainment, tourism and travel, education and numerous others on information."
},
{
"code": null,
"e": 16598,
"s": 16457,
"text": "Changing employment scene world over, shifting base from manual agricultural to machine-based manufacturing and other industry related jobs."
},
{
"code": null,
"e": 16739,
"s": 16598,
"text": "Changing employment scene world over, shifting base from manual agricultural to machine-based manufacturing and other industry related jobs."
},
{
"code": null,
"e": 16800,
"s": 16739,
"text": "Information revolution and the overall development scenario."
},
{
"code": null,
"e": 16861,
"s": 16800,
"text": "Information revolution and the overall development scenario."
},
{
"code": null,
"e": 16913,
"s": 16861,
"text": "Growth of IT industry and its strategic importance."
},
{
"code": null,
"e": 16965,
"s": 16913,
"text": "Growth of IT industry and its strategic importance."
},
{
"code": null,
"e": 17069,
"s": 16965,
"text": "Strong growth of information services fuelled by increasing competition and reduced product life cycle."
},
{
"code": null,
"e": 17173,
"s": 17069,
"text": "Strong growth of information services fuelled by increasing competition and reduced product life cycle."
},
{
"code": null,
"e": 17224,
"s": 17173,
"text": "Need for sustainable development and quality life."
},
{
"code": null,
"e": 17275,
"s": 17224,
"text": "Need for sustainable development and quality life."
},
{
"code": null,
"e": 17368,
"s": 17275,
"text": "Improvement in communication and transportation brought in by use of information processing."
},
{
"code": null,
"e": 17461,
"s": 17368,
"text": "Improvement in communication and transportation brought in by use of information processing."
},
{
"code": null,
"e": 17593,
"s": 17461,
"text": "Use of information processing in reduction of energy consumption, reduction in pollution and a better ecological balance in future."
},
{
"code": null,
"e": 17725,
"s": 17593,
"text": "Use of information processing in reduction of energy consumption, reduction in pollution and a better ecological balance in future."
},
{
"code": null,
"e": 17899,
"s": 17725,
"text": "Use of information processing in land record managements, legal delivery system, educational institutions, natural resource planning, customer relation management and so on."
},
{
"code": null,
"e": 18073,
"s": 17899,
"text": "Use of information processing in land record managements, legal delivery system, educational institutions, natural resource planning, customer relation management and so on."
},
{
"code": null,
"e": 18089,
"s": 18073,
"text": "In a nutshell −"
},
{
"code": null,
"e": 18155,
"s": 18089,
"text": "Information is needed to survive in the modern competitive world."
},
{
"code": null,
"e": 18221,
"s": 18155,
"text": "Information is needed to survive in the modern competitive world."
},
{
"code": null,
"e": 18315,
"s": 18221,
"text": "Information is needed to create strong information systems and keep these systems up to date."
},
{
"code": null,
"e": 18409,
"s": 18315,
"text": "Information is needed to create strong information systems and keep these systems up to date."
},
{
"code": null,
"e": 18754,
"s": 18409,
"text": "Information processing has transformed our society in numerous ways. From a business perspective, there has been a huge shift towards increasingly automated business processes and communication. Access to information and capability of information processing has helped in achieving greater efficiency in accounting and other business processes."
},
{
"code": null,
"e": 18839,
"s": 18754,
"text": "A complete business information system, accomplishes the following functionalities −"
},
{
"code": null,
"e": 18871,
"s": 18839,
"text": "Collection and storage of data."
},
{
"code": null,
"e": 18903,
"s": 18871,
"text": "Collection and storage of data."
},
{
"code": null,
"e": 18978,
"s": 18903,
"text": "Transform these data into business information useful for decision making."
},
{
"code": null,
"e": 19053,
"s": 18978,
"text": "Transform these data into business information useful for decision making."
},
{
"code": null,
"e": 19089,
"s": 19053,
"text": "Provide controls to safeguard data."
},
{
"code": null,
"e": 19125,
"s": 19089,
"text": "Provide controls to safeguard data."
},
{
"code": null,
"e": 19160,
"s": 19125,
"text": "Automate and streamline reporting."
},
{
"code": null,
"e": 19195,
"s": 19160,
"text": "Automate and streamline reporting."
},
{
"code": null,
"e": 19299,
"s": 19195,
"text": "The following list summarizes the five main uses of information by businesses and other organizations −"
},
{
"code": null,
"e": 19654,
"s": 19299,
"text": "Planning − At the planning stage, information is the most important ingredient in decision making. Information at planning stage includes that of business resources, assets, liabilities, plants and machineries, properties, suppliers, customers, competitors, market and market dynamics, fiscal policy changes of the Government, emerging technologies, etc."
},
{
"code": null,
"e": 20009,
"s": 19654,
"text": "Planning − At the planning stage, information is the most important ingredient in decision making. Information at planning stage includes that of business resources, assets, liabilities, plants and machineries, properties, suppliers, customers, competitors, market and market dynamics, fiscal policy changes of the Government, emerging technologies, etc."
},
{
"code": null,
"e": 20199,
"s": 20009,
"text": "Recording − Business processing these days involves recording information about each transaction or event. This information collected, stored and updated regularly at the operational level."
},
{
"code": null,
"e": 20389,
"s": 20199,
"text": "Recording − Business processing these days involves recording information about each transaction or event. This information collected, stored and updated regularly at the operational level."
},
{
"code": null,
"e": 20630,
"s": 20389,
"text": "Controlling − A business need to set up an information filter, so that only filtered data is presented to the middle and top management. This ensures efficiency at the operational level and effectiveness at the tactical and strategic level."
},
{
"code": null,
"e": 20871,
"s": 20630,
"text": "Controlling − A business need to set up an information filter, so that only filtered data is presented to the middle and top management. This ensures efficiency at the operational level and effectiveness at the tactical and strategic level."
},
{
"code": null,
"e": 21009,
"s": 20871,
"text": "Measuring − A business measures its performance metrics by collecting and analyzing sales data, cost of manufacturing, and profit earned."
},
{
"code": null,
"e": 21147,
"s": 21009,
"text": "Measuring − A business measures its performance metrics by collecting and analyzing sales data, cost of manufacturing, and profit earned."
},
{
"code": null,
"e": 21497,
"s": 21147,
"text": "Decision-making − MIS is primarily concerned with managerial decision-making, theory of organizational behavior, and underlying human behavior in organizational context. Decision-making information includes the socio-economic impact of competition, globalization, democratization, and the effects of all these factors on an organizational structure."
},
{
"code": null,
"e": 21847,
"s": 21497,
"text": "Decision-making − MIS is primarily concerned with managerial decision-making, theory of organizational behavior, and underlying human behavior in organizational context. Decision-making information includes the socio-economic impact of competition, globalization, democratization, and the effects of all these factors on an organizational structure."
},
{
"code": null,
"e": 21941,
"s": 21847,
"text": "In short, this multi-dimensional information evolves from the following logical foundations −"
},
{
"code": null,
"e": 21984,
"s": 21941,
"text": "Operations research and management science"
},
{
"code": null,
"e": 22027,
"s": 21984,
"text": "Operations research and management science"
},
{
"code": null,
"e": 22061,
"s": 22027,
"text": "Theory of organizational behavior"
},
{
"code": null,
"e": 22095,
"s": 22061,
"text": "Theory of organizational behavior"
},
{
"code": null,
"e": 22242,
"s": 22095,
"text": "Computer science −\n\nData and file structure\nData theory design and implementation\nComputer networking\nExpert systems and artificial intelligence\n\n"
},
{
"code": null,
"e": 22261,
"s": 22242,
"text": "Computer science −"
},
{
"code": null,
"e": 22285,
"s": 22261,
"text": "Data and file structure"
},
{
"code": null,
"e": 22309,
"s": 22285,
"text": "Data and file structure"
},
{
"code": null,
"e": 22347,
"s": 22309,
"text": "Data theory design and implementation"
},
{
"code": null,
"e": 22385,
"s": 22347,
"text": "Data theory design and implementation"
},
{
"code": null,
"e": 22405,
"s": 22385,
"text": "Computer networking"
},
{
"code": null,
"e": 22425,
"s": 22405,
"text": "Computer networking"
},
{
"code": null,
"e": 22468,
"s": 22425,
"text": "Expert systems and artificial intelligence"
},
{
"code": null,
"e": 22511,
"s": 22468,
"text": "Expert systems and artificial intelligence"
},
{
"code": null,
"e": 22530,
"s": 22511,
"text": "Information theory"
},
{
"code": null,
"e": 22549,
"s": 22530,
"text": "Information theory"
},
{
"code": null,
"e": 22682,
"s": 22549,
"text": "Following factors arising as an outcome of information processing help speed up of business events and achieves greater efficiency −"
},
{
"code": null,
"e": 22727,
"s": 22682,
"text": "Directly and immediate linkage to the system"
},
{
"code": null,
"e": 22772,
"s": 22727,
"text": "Directly and immediate linkage to the system"
},
{
"code": null,
"e": 22805,
"s": 22772,
"text": "Faster communication of an order"
},
{
"code": null,
"e": 22838,
"s": 22805,
"text": "Faster communication of an order"
},
{
"code": null,
"e": 22886,
"s": 22838,
"text": "Electronic transfer of funds for faster payment"
},
{
"code": null,
"e": 22934,
"s": 22886,
"text": "Electronic transfer of funds for faster payment"
},
{
"code": null,
"e": 23005,
"s": 22934,
"text": "Electronically solicited pricing (helps in determining the best price)"
},
{
"code": null,
"e": 23076,
"s": 23005,
"text": "Electronically solicited pricing (helps in determining the best price)"
},
{
"code": null,
"e": 23152,
"s": 23076,
"text": "Managers make decisions. Decision-making generally takes a four-fold path −"
},
{
"code": null,
"e": 23208,
"s": 23152,
"text": "Understanding the need for decision or the opportunity,"
},
{
"code": null,
"e": 23264,
"s": 23208,
"text": "Understanding the need for decision or the opportunity,"
},
{
"code": null,
"e": 23305,
"s": 23264,
"text": "Preparing alternative course of actions,"
},
{
"code": null,
"e": 23346,
"s": 23305,
"text": "Preparing alternative course of actions,"
},
{
"code": null,
"e": 23392,
"s": 23346,
"text": "Evaluating all alternative course of actions,"
},
{
"code": null,
"e": 23438,
"s": 23392,
"text": "Evaluating all alternative course of actions,"
},
{
"code": null,
"e": 23482,
"s": 23438,
"text": "Deciding the right path for implementation."
},
{
"code": null,
"e": 23526,
"s": 23482,
"text": "Deciding the right path for implementation."
},
{
"code": null,
"e": 23762,
"s": 23526,
"text": "MIS is an information system that provides information in the form of standardized reports and displays for the managers. MIS is a broad class of information systems designed to provide information needed for effective decision making."
},
{
"code": null,
"e": 23975,
"s": 23762,
"text": "Data and information created from an accounting information system and the reports generated thereon are used to provide accurate, timely and relevant information needed for effective decision making by managers."
},
{
"code": null,
"e": 24092,
"s": 23975,
"text": "Management information systems provide information to support management decision making, with the following goals −"
},
{
"code": null,
"e": 24144,
"s": 24092,
"text": "Pre-specified and preplanned reporting to managers."
},
{
"code": null,
"e": 24196,
"s": 24144,
"text": "Pre-specified and preplanned reporting to managers."
},
{
"code": null,
"e": 24248,
"s": 24196,
"text": "Interactive and ad-hoc support for decision making."
},
{
"code": null,
"e": 24300,
"s": 24248,
"text": "Interactive and ad-hoc support for decision making."
},
{
"code": null,
"e": 24341,
"s": 24300,
"text": "Critical information for top management."
},
{
"code": null,
"e": 24382,
"s": 24341,
"text": "Critical information for top management."
},
{
"code": null,
"e": 24440,
"s": 24382,
"text": "MIS is of vital importance to any organization, because −"
},
{
"code": null,
"e": 24551,
"s": 24440,
"text": "It emphasizes on the management decision making, not only processing of data generated by business operations."
},
{
"code": null,
"e": 24662,
"s": 24551,
"text": "It emphasizes on the management decision making, not only processing of data generated by business operations."
},
{
"code": null,
"e": 24770,
"s": 24662,
"text": "It emphasizes on the systems framework that should be used for organizing information systems applications."
},
{
"code": null,
"e": 24878,
"s": 24770,
"text": "It emphasizes on the systems framework that should be used for organizing information systems applications."
},
{
"code": null,
"e": 25009,
"s": 24878,
"text": "Enterprise applications are specifically designed for the sole purpose of promoting the needs and objectives of the organizations."
},
{
"code": null,
"e": 25257,
"s": 25009,
"text": "Enterprise applications provide business-oriented tools supporting electronic commerce, enterprise communication and collaboration, and web-enabled business processes both within a networked enterprise and with its customers and business partners."
},
{
"code": null,
"e": 25327,
"s": 25257,
"text": "Some of the services provided by an enterprise application includes −"
},
{
"code": null,
"e": 25375,
"s": 25327,
"text": "Online shopping, billing and payment processing"
},
{
"code": null,
"e": 25405,
"s": 25375,
"text": "Interactive product catalogue"
},
{
"code": null,
"e": 25424,
"s": 25405,
"text": "Content management"
},
{
"code": null,
"e": 25457,
"s": 25424,
"text": "Customer relationship management"
},
{
"code": null,
"e": 25512,
"s": 25457,
"text": "Manufacturing and other business processes integration"
},
{
"code": null,
"e": 25535,
"s": 25512,
"text": "IT services management"
},
{
"code": null,
"e": 25566,
"s": 25535,
"text": "Enterprise resource management"
},
{
"code": null,
"e": 25592,
"s": 25566,
"text": "Human resource management"
},
{
"code": null,
"e": 25625,
"s": 25592,
"text": "Business intelligence management"
},
{
"code": null,
"e": 25661,
"s": 25625,
"text": "Business collaboration and security"
},
{
"code": null,
"e": 25677,
"s": 25661,
"text": "Form automation"
},
{
"code": null,
"e": 25921,
"s": 25677,
"text": "Basically these applications intend to model the business processes, i.e., how the entire organization works. These tools work by displaying, manipulating and storing large amounts of data and automating the business processes with these data."
},
{
"code": null,
"e": 26069,
"s": 25921,
"text": "Multitude of applications comes under the definition of Enterprise Applications. In this section, let us briefly cover the following applications −"
},
{
"code": null,
"e": 26105,
"s": 26069,
"text": "Management information system (MIS)"
},
{
"code": null,
"e": 26141,
"s": 26105,
"text": "Management information system (MIS)"
},
{
"code": null,
"e": 26176,
"s": 26141,
"text": "Enterprise Resource Planning (ERP)"
},
{
"code": null,
"e": 26211,
"s": 26176,
"text": "Enterprise Resource Planning (ERP)"
},
{
"code": null,
"e": 26250,
"s": 26211,
"text": "Customer Relationship Management (CRM)"
},
{
"code": null,
"e": 26289,
"s": 26250,
"text": "Customer Relationship Management (CRM)"
},
{
"code": null,
"e": 26319,
"s": 26289,
"text": "Decision Support System (DSS)"
},
{
"code": null,
"e": 26349,
"s": 26319,
"text": "Decision Support System (DSS)"
},
{
"code": null,
"e": 26384,
"s": 26349,
"text": "Knowledge Management Systems (KMS)"
},
{
"code": null,
"e": 26419,
"s": 26384,
"text": "Knowledge Management Systems (KMS)"
},
{
"code": null,
"e": 26451,
"s": 26419,
"text": "Content Management System (CMS)"
},
{
"code": null,
"e": 26483,
"s": 26451,
"text": "Content Management System (CMS)"
},
{
"code": null,
"e": 26514,
"s": 26483,
"text": "Executive Support System (ESS)"
},
{
"code": null,
"e": 26545,
"s": 26514,
"text": "Executive Support System (ESS)"
},
{
"code": null,
"e": 26580,
"s": 26545,
"text": "Business Intelligence System (BIS)"
},
{
"code": null,
"e": 26615,
"s": 26580,
"text": "Business Intelligence System (BIS)"
},
{
"code": null,
"e": 26656,
"s": 26615,
"text": "Enterprise Application Integration (EAI)"
},
{
"code": null,
"e": 26697,
"s": 26656,
"text": "Enterprise Application Integration (EAI)"
},
{
"code": null,
"e": 26732,
"s": 26697,
"text": "Business Continuity Planning (BCP)"
},
{
"code": null,
"e": 26767,
"s": 26732,
"text": "Business Continuity Planning (BCP)"
},
{
"code": null,
"e": 26797,
"s": 26767,
"text": "Supply Chain Management (SCM)"
},
{
"code": null,
"e": 26827,
"s": 26797,
"text": "Supply Chain Management (SCM)"
},
{
"code": null,
"e": 27055,
"s": 26827,
"text": "To the managers, Management Information System is an implementation of the organizational systems and procedures. To a programmer it is nothing but file structures and file processing. However, it involves much more complexity."
},
{
"code": null,
"e": 27281,
"s": 27055,
"text": "The three components of MIS provide a more complete and focused definition, where System suggests integration and holistic view, Information stands for processed data, and Management is the ultimate user, the decision makers."
},
{
"code": null,
"e": 27345,
"s": 27281,
"text": "Management information system can thus be analyzed as follows −"
},
{
"code": null,
"e": 27591,
"s": 27345,
"text": "Management covers the planning, control, and administration of the operations of a concern. The top management handles planning; the middle management concentrates on controlling; and the lower management is concerned with actual administration."
},
{
"code": null,
"e": 27896,
"s": 27591,
"text": "Information, in MIS, means the processed data that helps the management in planning, controlling and operations. Data means all the facts arising out of the operations of the concern. Data is processed i.e. recorded, summarized, compared and finally presented to the management in the form of MIS report."
},
{
"code": null,
"e": 28033,
"s": 27896,
"text": "Data is processed into information with the help of a system. A system is made up of inputs, processing, output and feedback or control."
},
{
"code": null,
"e": 28161,
"s": 28033,
"text": "Thus MIS means a system for processing data in order to give proper information to the management for performing its functions."
},
{
"code": null,
"e": 28400,
"s": 28161,
"text": "The goals of an MIS are to implement the organizational structure and dynamics of the enterprise for the purpose of managing the organization in a better way and capturing the potential of the information system for competitive advantage."
},
{
"code": null,
"e": 28447,
"s": 28400,
"text": "Following are the basic objectives of an MIS −"
},
{
"code": null,
"e": 28618,
"s": 28447,
"text": "Capturing Data − Capturing contextual data, or operational information that will contribute in decision making from various internal and external sources of organization."
},
{
"code": null,
"e": 28789,
"s": 28618,
"text": "Capturing Data − Capturing contextual data, or operational information that will contribute in decision making from various internal and external sources of organization."
},
{
"code": null,
"e": 29102,
"s": 28789,
"text": "Processing Data − The captured data is processed into information needed for planning, organizing, coordinating, directing and controlling functionalities at strategic, tactical and operational level. Processing data means −\n\nmaking calculations with the data\nsorting data\nclassifying data and\nsummarizing data\n\n"
},
{
"code": null,
"e": 29327,
"s": 29102,
"text": "Processing Data − The captured data is processed into information needed for planning, organizing, coordinating, directing and controlling functionalities at strategic, tactical and operational level. Processing data means −"
},
{
"code": null,
"e": 29361,
"s": 29327,
"text": "making calculations with the data"
},
{
"code": null,
"e": 29395,
"s": 29361,
"text": "making calculations with the data"
},
{
"code": null,
"e": 29408,
"s": 29395,
"text": "sorting data"
},
{
"code": null,
"e": 29421,
"s": 29408,
"text": "sorting data"
},
{
"code": null,
"e": 29442,
"s": 29421,
"text": "classifying data and"
},
{
"code": null,
"e": 29463,
"s": 29442,
"text": "classifying data and"
},
{
"code": null,
"e": 29480,
"s": 29463,
"text": "summarizing data"
},
{
"code": null,
"e": 29497,
"s": 29480,
"text": "summarizing data"
},
{
"code": null,
"e": 29583,
"s": 29497,
"text": "Information Storage − Information or processed data need to be stored for future use."
},
{
"code": null,
"e": 29669,
"s": 29583,
"text": "Information Storage − Information or processed data need to be stored for future use."
},
{
"code": null,
"e": 29804,
"s": 29669,
"text": "Information Retrieval − The system should be able to retrieve this information from the storage as and when required by various users."
},
{
"code": null,
"e": 29939,
"s": 29804,
"text": "Information Retrieval − The system should be able to retrieve this information from the storage as and when required by various users."
},
{
"code": null,
"e": 30093,
"s": 29939,
"text": "Information Propagation − Information or the finished product of the MIS should be circulated to its users periodically using the organizational network."
},
{
"code": null,
"e": 30247,
"s": 30093,
"text": "Information Propagation − Information or the finished product of the MIS should be circulated to its users periodically using the organizational network."
},
{
"code": null,
"e": 30293,
"s": 30247,
"text": "Following are the characteristics of an MIS −"
},
{
"code": null,
"e": 30337,
"s": 30293,
"text": "It should be based on a long-term planning."
},
{
"code": null,
"e": 30381,
"s": 30337,
"text": "It should be based on a long-term planning."
},
{
"code": null,
"e": 30470,
"s": 30381,
"text": "It should provide a holistic view of the dynamics and the structure of the organization."
},
{
"code": null,
"e": 30559,
"s": 30470,
"text": "It should provide a holistic view of the dynamics and the structure of the organization."
},
{
"code": null,
"e": 30679,
"s": 30559,
"text": "It should work as a complete and comprehensive system covering all interconnecting sub-systems within the organization."
},
{
"code": null,
"e": 30799,
"s": 30679,
"text": "It should work as a complete and comprehensive system covering all interconnecting sub-systems within the organization."
},
{
"code": null,
"e": 30971,
"s": 30799,
"text": "It should be planned in a top-down way, as the decision makers or the management should actively take part and provide clear direction at the development stage of the MIS."
},
{
"code": null,
"e": 31143,
"s": 30971,
"text": "It should be planned in a top-down way, as the decision makers or the management should actively take part and provide clear direction at the development stage of the MIS."
},
{
"code": null,
"e": 31253,
"s": 31143,
"text": "It should be based on need of strategic, operational and tactical information of managers of an organization."
},
{
"code": null,
"e": 31363,
"s": 31253,
"text": "It should be based on need of strategic, operational and tactical information of managers of an organization."
},
{
"code": null,
"e": 31444,
"s": 31363,
"text": "It should also take care of exceptional situations by reporting such situations."
},
{
"code": null,
"e": 31525,
"s": 31444,
"text": "It should also take care of exceptional situations by reporting such situations."
},
{
"code": null,
"e": 31718,
"s": 31525,
"text": "It should be able to make forecasts and estimates, and generate advanced information, thus providing a competitive advantage. Decision makers can take actions on the basis of such predictions."
},
{
"code": null,
"e": 31911,
"s": 31718,
"text": "It should be able to make forecasts and estimates, and generate advanced information, thus providing a competitive advantage. Decision makers can take actions on the basis of such predictions."
},
{
"code": null,
"e": 32070,
"s": 31911,
"text": "It should create linkage between all sub-systems within the organization, so that the decision makers can take the right decision based on an integrated view."
},
{
"code": null,
"e": 32229,
"s": 32070,
"text": "It should create linkage between all sub-systems within the organization, so that the decision makers can take the right decision based on an integrated view."
},
{
"code": null,
"e": 32422,
"s": 32229,
"text": "It should allow easy flow of information through various sub-systems, thus avoiding redundancy and duplicity of data. It should simplify the operations with as much practicability as possible."
},
{
"code": null,
"e": 32615,
"s": 32422,
"text": "It should allow easy flow of information through various sub-systems, thus avoiding redundancy and duplicity of data. It should simplify the operations with as much practicability as possible."
},
{
"code": null,
"e": 32785,
"s": 32615,
"text": "Although the MIS is an integrated, complete system, it should be made in such a flexible way that it could be easily split into smaller sub-systems as and when required."
},
{
"code": null,
"e": 32955,
"s": 32785,
"text": "Although the MIS is an integrated, complete system, it should be made in such a flexible way that it could be easily split into smaller sub-systems as and when required."
},
{
"code": null,
"e": 33011,
"s": 32955,
"text": "A central database is the backbone of a well-built MIS."
},
{
"code": null,
"e": 33067,
"s": 33011,
"text": "A central database is the backbone of a well-built MIS."
},
{
"code": null,
"e": 33139,
"s": 33067,
"text": "Following are the characteristics of a well-designed computerized MIS −"
},
{
"code": null,
"e": 33285,
"s": 33139,
"text": "It should be able to process data accurately and with high speed, using various techniques like operations research, simulation, heuristics, etc."
},
{
"code": null,
"e": 33431,
"s": 33285,
"text": "It should be able to process data accurately and with high speed, using various techniques like operations research, simulation, heuristics, etc."
},
{
"code": null,
"e": 33638,
"s": 33431,
"text": "It should be able to collect, organize, manipulate, and update large amount of raw data of both related and unrelated nature, coming from various internal and external sources at different periods of time."
},
{
"code": null,
"e": 33845,
"s": 33638,
"text": "It should be able to collect, organize, manipulate, and update large amount of raw data of both related and unrelated nature, coming from various internal and external sources at different periods of time."
},
{
"code": null,
"e": 33922,
"s": 33845,
"text": "It should provide real time information on ongoing events without any delay."
},
{
"code": null,
"e": 33999,
"s": 33922,
"text": "It should provide real time information on ongoing events without any delay."
},
{
"code": null,
"e": 34093,
"s": 33999,
"text": "It should support various output formats and follow latest rules and regulations in practice."
},
{
"code": null,
"e": 34187,
"s": 34093,
"text": "It should support various output formats and follow latest rules and regulations in practice."
},
{
"code": null,
"e": 34308,
"s": 34187,
"text": "It should provide organized and relevant information for all levels of management: strategic, operational, and tactical."
},
{
"code": null,
"e": 34429,
"s": 34308,
"text": "It should provide organized and relevant information for all levels of management: strategic, operational, and tactical."
},
{
"code": null,
"e": 34497,
"s": 34429,
"text": "It should aim at extreme flexibility in data storage and retrieval."
},
{
"code": null,
"e": 34565,
"s": 34497,
"text": "It should aim at extreme flexibility in data storage and retrieval."
},
{
"code": null,
"e": 34623,
"s": 34565,
"text": "The following diagram shows the nature and scope of MIS −"
},
{
"code": null,
"e": 34802,
"s": 34623,
"text": "ERP is an integrated, real-time, cross-functional enterprise application, an enterprise-wide transaction framework that supports all the internal business processes of a company."
},
{
"code": null,
"e": 34959,
"s": 34802,
"text": "It supports all core business processes such as sales order processing, inventory management and control, production and distribution planning, and finance."
},
{
"code": null,
"e": 35004,
"s": 34959,
"text": "ERP is very helpful in the follwoing areas −"
},
{
"code": null,
"e": 35051,
"s": 35004,
"text": "Business integration and automated data update"
},
{
"code": null,
"e": 35098,
"s": 35051,
"text": "Business integration and automated data update"
},
{
"code": null,
"e": 35171,
"s": 35098,
"text": "Linkage between all core business processes and easy flow of integration"
},
{
"code": null,
"e": 35244,
"s": 35171,
"text": "Linkage between all core business processes and easy flow of integration"
},
{
"code": null,
"e": 35311,
"s": 35244,
"text": "Flexibility in business operations and more agility to the company"
},
{
"code": null,
"e": 35378,
"s": 35311,
"text": "Flexibility in business operations and more agility to the company"
},
{
"code": null,
"e": 35420,
"s": 35378,
"text": "Better analysis and planning capabilities"
},
{
"code": null,
"e": 35462,
"s": 35420,
"text": "Better analysis and planning capabilities"
},
{
"code": null,
"e": 35487,
"s": 35462,
"text": "Critical decision-making"
},
{
"code": null,
"e": 35512,
"s": 35487,
"text": "Critical decision-making"
},
{
"code": null,
"e": 35534,
"s": 35512,
"text": "Competitive advantage"
},
{
"code": null,
"e": 35556,
"s": 35534,
"text": "Competitive advantage"
},
{
"code": null,
"e": 35583,
"s": 35556,
"text": "Use of latest technologies"
},
{
"code": null,
"e": 35610,
"s": 35583,
"text": "Use of latest technologies"
},
{
"code": null,
"e": 35666,
"s": 35610,
"text": "The following diagram illustrates the features of ERP −"
},
{
"code": null,
"e": 35809,
"s": 35666,
"text": "Finance − Financial accounting, Managerial accounting, treasury management, asset management, budget control, costing, and enterprise control."
},
{
"code": null,
"e": 35952,
"s": 35809,
"text": "Finance − Financial accounting, Managerial accounting, treasury management, asset management, budget control, costing, and enterprise control."
},
{
"code": null,
"e": 36069,
"s": 35952,
"text": "Logistics − Production planning, material management, plant maintenance, project management, events management, etc."
},
{
"code": null,
"e": 36186,
"s": 36069,
"text": "Logistics − Production planning, material management, plant maintenance, project management, events management, etc."
},
{
"code": null,
"e": 36256,
"s": 36186,
"text": "Human resource − Personnel management, training and development, etc."
},
{
"code": null,
"e": 36326,
"s": 36256,
"text": "Human resource − Personnel management, training and development, etc."
},
{
"code": null,
"e": 36424,
"s": 36326,
"text": "Supply Chain − Inventory control, purchase and order control, supplier scheduling, planning, etc."
},
{
"code": null,
"e": 36522,
"s": 36424,
"text": "Supply Chain − Inventory control, purchase and order control, supplier scheduling, planning, etc."
},
{
"code": null,
"e": 36660,
"s": 36522,
"text": "Work flow − Integrate the entire organization with the flexible assignment of tasks and responsibility to locations, position, jobs, etc."
},
{
"code": null,
"e": 36798,
"s": 36660,
"text": "Work flow − Integrate the entire organization with the flexible assignment of tasks and responsibility to locations, position, jobs, etc."
},
{
"code": null,
"e": 36821,
"s": 36798,
"text": "Reduction of lead time"
},
{
"code": null,
"e": 36845,
"s": 36821,
"text": "Reduction of cycle time"
},
{
"code": null,
"e": 36874,
"s": 36845,
"text": "Better customer satisfaction"
},
{
"code": null,
"e": 36921,
"s": 36874,
"text": "Increased flexibility, quality, and efficiency"
},
{
"code": null,
"e": 36982,
"s": 36921,
"text": "Improved information accuracy and decision making capability"
},
{
"code": null,
"e": 36999,
"s": 36982,
"text": "Onetime shipment"
},
{
"code": null,
"e": 37029,
"s": 36999,
"text": "Improved resource utilization"
},
{
"code": null,
"e": 37058,
"s": 37029,
"text": "Improve supplier performance"
},
{
"code": null,
"e": 37080,
"s": 37058,
"text": "Reduced quality costs"
},
{
"code": null,
"e": 37102,
"s": 37080,
"text": "Quick decision-making"
},
{
"code": null,
"e": 37131,
"s": 37102,
"text": "Forecasting and optimization"
},
{
"code": null,
"e": 37151,
"s": 37131,
"text": "Better transparency"
},
{
"code": null,
"e": 37186,
"s": 37151,
"text": "Expense and time in implementation"
},
{
"code": null,
"e": 37230,
"s": 37186,
"text": "Difficulty in integration with other system"
},
{
"code": null,
"e": 37261,
"s": 37230,
"text": "Risk of implementation failure"
},
{
"code": null,
"e": 37297,
"s": 37261,
"text": "Difficulty in implementation change"
},
{
"code": null,
"e": 37322,
"s": 37297,
"text": "Risk in using one vendor"
},
{
"code": null,
"e": 37556,
"s": 37322,
"text": "CRM is an enterprise application module that manages a company's interactions with current and future customers by organizing and coordinating, sales and marketing, and providing better customer services along with technical support."
},
{
"code": null,
"e": 37766,
"s": 37556,
"text": "Atul Parvatiyar and Jagdish N. Sheth provide an excellent definition for customer relationship management in their work titled - 'Customer Relationship Management: Emerging Practice, Process, and Discipline' −"
},
{
"code": null,
"e": 37817,
"s": 37766,
"text": "To keep track of all present and future customers."
},
{
"code": null,
"e": 37868,
"s": 37817,
"text": "To keep track of all present and future customers."
},
{
"code": null,
"e": 37911,
"s": 37868,
"text": "To identify and target the best customers."
},
{
"code": null,
"e": 37954,
"s": 37911,
"text": "To identify and target the best customers."
},
{
"code": null,
"e": 38041,
"s": 37954,
"text": "To let the customers know about the existing as well as the new products and services."
},
{
"code": null,
"e": 38128,
"s": 38041,
"text": "To let the customers know about the existing as well as the new products and services."
},
{
"code": null,
"e": 38232,
"s": 38128,
"text": "To provide real-time and personalized services based on the needs and habits of the existing customers."
},
{
"code": null,
"e": 38336,
"s": 38232,
"text": "To provide real-time and personalized services based on the needs and habits of the existing customers."
},
{
"code": null,
"e": 38400,
"s": 38336,
"text": "To provide superior service and consistent customer experience."
},
{
"code": null,
"e": 38464,
"s": 38400,
"text": "To provide superior service and consistent customer experience."
},
{
"code": null,
"e": 38496,
"s": 38464,
"text": "To implement a feedback system."
},
{
"code": null,
"e": 38528,
"s": 38496,
"text": "To implement a feedback system."
},
{
"code": null,
"e": 38594,
"s": 38528,
"text": "Provides better customer service and increases customer revenues."
},
{
"code": null,
"e": 38660,
"s": 38594,
"text": "Provides better customer service and increases customer revenues."
},
{
"code": null,
"e": 38685,
"s": 38660,
"text": "Discovers new customers."
},
{
"code": null,
"e": 38710,
"s": 38685,
"text": "Discovers new customers."
},
{
"code": null,
"e": 38762,
"s": 38710,
"text": "Cross-sells and up-sells products more effectively."
},
{
"code": null,
"e": 38814,
"s": 38762,
"text": "Cross-sells and up-sells products more effectively."
},
{
"code": null,
"e": 38855,
"s": 38814,
"text": "Helps sales staff to close deals faster."
},
{
"code": null,
"e": 38896,
"s": 38855,
"text": "Helps sales staff to close deals faster."
},
{
"code": null,
"e": 38931,
"s": 38896,
"text": "Makes call centers more efficient."
},
{
"code": null,
"e": 38966,
"s": 38931,
"text": "Makes call centers more efficient."
},
{
"code": null,
"e": 39008,
"s": 38966,
"text": "Simplifies marketing and sales processes."
},
{
"code": null,
"e": 39050,
"s": 39008,
"text": "Simplifies marketing and sales processes."
},
{
"code": null,
"e": 39093,
"s": 39050,
"text": "Some times record loss is a major problem."
},
{
"code": null,
"e": 39136,
"s": 39093,
"text": "Some times record loss is a major problem."
},
{
"code": null,
"e": 39152,
"s": 39136,
"text": "Overhead costs."
},
{
"code": null,
"e": 39168,
"s": 39152,
"text": "Overhead costs."
},
{
"code": null,
"e": 39233,
"s": 39168,
"text": "Giving training to employees is an issue in small organizations."
},
{
"code": null,
"e": 39298,
"s": 39233,
"text": "Giving training to employees is an issue in small organizations."
},
{
"code": null,
"e": 39623,
"s": 39298,
"text": "Decision support systems (DSS) are interactive software-based systems intended to help managers in decision-making by accessing large volumes of information generated from various related information systems involved in organizational business processes, such as office automation system, transaction processing system, etc."
},
{
"code": null,
"e": 39986,
"s": 39623,
"text": "DSS uses the summary information, exceptions, patterns, and trends using the analytical models. A decision support system helps in decision-making but does not necessarily give a decision itself. The decision makers compile useful information from raw data, documents, personal knowledge, and/or business models to identify and solve problems and make decisions."
},
{
"code": null,
"e": 40062,
"s": 39986,
"text": "There are two types of decisions - programmed and non-programmed decisions."
},
{
"code": null,
"e": 40148,
"s": 40062,
"text": "Programmed decisions are basically automated processes, general routine work, where −"
},
{
"code": null,
"e": 40195,
"s": 40148,
"text": "These decisions have been taken several times."
},
{
"code": null,
"e": 40242,
"s": 40195,
"text": "These decisions have been taken several times."
},
{
"code": null,
"e": 40291,
"s": 40242,
"text": "These decisions follow some guidelines or rules."
},
{
"code": null,
"e": 40340,
"s": 40291,
"text": "These decisions follow some guidelines or rules."
},
{
"code": null,
"e": 40424,
"s": 40340,
"text": "\nFor example, selecting a reorder level for inventories, is a programmed decision.\n"
},
{
"code": null,
"e": 40501,
"s": 40424,
"text": "Non-programmed decisions occur in unusual and non-addressed situations, so −"
},
{
"code": null,
"e": 40529,
"s": 40501,
"text": "It would be a new decision."
},
{
"code": null,
"e": 40557,
"s": 40529,
"text": "It would be a new decision."
},
{
"code": null,
"e": 40596,
"s": 40557,
"text": "There will not be any rules to follow."
},
{
"code": null,
"e": 40635,
"s": 40596,
"text": "There will not be any rules to follow."
},
{
"code": null,
"e": 40696,
"s": 40635,
"text": "These decisions are made based on the available information."
},
{
"code": null,
"e": 40757,
"s": 40696,
"text": "These decisions are made based on the available information."
},
{
"code": null,
"e": 40846,
"s": 40757,
"text": "These decisions are based on the manger's discretion, instinct, perception and judgment."
},
{
"code": null,
"e": 40935,
"s": 40846,
"text": "These decisions are based on the manger's discretion, instinct, perception and judgment."
},
{
"code": null,
"e": 41011,
"s": 40935,
"text": "\nFor example, investing in a new technology is a non-programmed decision. \n"
},
{
"code": null,
"e": 41194,
"s": 41011,
"text": "Decision support systems generally involve non-programmed decisions. Therefore, there will be no exact report, content, or format for these systems. Reports are generated on the fly."
},
{
"code": null,
"e": 41223,
"s": 41194,
"text": "Adaptability and flexibility"
},
{
"code": null,
"e": 41251,
"s": 41223,
"text": "High level of Interactivity"
},
{
"code": null,
"e": 41263,
"s": 41251,
"text": "Ease of use"
},
{
"code": null,
"e": 41292,
"s": 41263,
"text": "Efficiency and effectiveness"
},
{
"code": null,
"e": 41328,
"s": 41292,
"text": "Complete control by decision-makers"
},
{
"code": null,
"e": 41348,
"s": 41328,
"text": "Ease of development"
},
{
"code": null,
"e": 41362,
"s": 41348,
"text": "Extendibility"
},
{
"code": null,
"e": 41396,
"s": 41362,
"text": "Support for modeling and analysis"
},
{
"code": null,
"e": 41420,
"s": 41396,
"text": "Support for data access"
},
{
"code": null,
"e": 41458,
"s": 41420,
"text": "Standalone, integrated, and Web-based"
},
{
"code": null,
"e": 41532,
"s": 41458,
"text": "Support for decision-makers in semi-structured and unstructured problems."
},
{
"code": null,
"e": 41606,
"s": 41532,
"text": "Support for decision-makers in semi-structured and unstructured problems."
},
{
"code": null,
"e": 41702,
"s": 41606,
"text": "Support for managers at various managerial levels, ranging from top executive to line managers."
},
{
"code": null,
"e": 41798,
"s": 41702,
"text": "Support for managers at various managerial levels, ranging from top executive to line managers."
},
{
"code": null,
"e": 41964,
"s": 41798,
"text": "Support for individuals and groups. Less structured problems often requires the involvement of several individuals from different departments and organization level."
},
{
"code": null,
"e": 42130,
"s": 41964,
"text": "Support for individuals and groups. Less structured problems often requires the involvement of several individuals from different departments and organization level."
},
{
"code": null,
"e": 42182,
"s": 42130,
"text": "Support for interdependent or sequential decisions."
},
{
"code": null,
"e": 42234,
"s": 42182,
"text": "Support for interdependent or sequential decisions."
},
{
"code": null,
"e": 42296,
"s": 42234,
"text": "Support for intelligence, design, choice, and implementation."
},
{
"code": null,
"e": 42358,
"s": 42296,
"text": "Support for intelligence, design, choice, and implementation."
},
{
"code": null,
"e": 42412,
"s": 42358,
"text": "Support for variety of decision processes and styles."
},
{
"code": null,
"e": 42466,
"s": 42412,
"text": "Support for variety of decision processes and styles."
},
{
"code": null,
"e": 42495,
"s": 42466,
"text": "DSSs are adaptive over time."
},
{
"code": null,
"e": 42524,
"s": 42495,
"text": "DSSs are adaptive over time."
},
{
"code": null,
"e": 42585,
"s": 42524,
"text": "Improves efficiency and speed of decision-making activities."
},
{
"code": null,
"e": 42646,
"s": 42585,
"text": "Improves efficiency and speed of decision-making activities."
},
{
"code": null,
"e": 42751,
"s": 42646,
"text": "Increases the control, competitiveness and capability of futuristic decision-making of the organization."
},
{
"code": null,
"e": 42856,
"s": 42751,
"text": "Increases the control, competitiveness and capability of futuristic decision-making of the organization."
},
{
"code": null,
"e": 42897,
"s": 42856,
"text": "Facilitates interpersonal communication."
},
{
"code": null,
"e": 42938,
"s": 42897,
"text": "Facilitates interpersonal communication."
},
{
"code": null,
"e": 42971,
"s": 42938,
"text": "Encourages learning or training."
},
{
"code": null,
"e": 43004,
"s": 42971,
"text": "Encourages learning or training."
},
{
"code": null,
"e": 43134,
"s": 43004,
"text": "Since it is mostly used in non-programmed decisions, it reveals new approaches and sets up new evidences for an unusual decision."
},
{
"code": null,
"e": 43264,
"s": 43134,
"text": "Since it is mostly used in non-programmed decisions, it reveals new approaches and sets up new evidences for an unusual decision."
},
{
"code": null,
"e": 43301,
"s": 43264,
"text": "Helps automate managerial processes."
},
{
"code": null,
"e": 43338,
"s": 43301,
"text": "Helps automate managerial processes."
},
{
"code": null,
"e": 43400,
"s": 43338,
"text": "Following are the components of the Decision Support System −"
},
{
"code": null,
"e": 43738,
"s": 43400,
"text": "Database Management System (DBMS) − To solve a problem the necessary data may come from internal or external database. In an organization, internal data are generated by a system such as TPS and MIS. External data come from a variety of sources such as newspapers, online data services, databases (financial, marketing, human resources)."
},
{
"code": null,
"e": 44076,
"s": 43738,
"text": "Database Management System (DBMS) − To solve a problem the necessary data may come from internal or external database. In an organization, internal data are generated by a system such as TPS and MIS. External data come from a variety of sources such as newspapers, online data services, databases (financial, marketing, human resources)."
},
{
"code": null,
"e": 44510,
"s": 44076,
"text": "Model Management System − It stores and accesses models that managers use to make decisions. Such models are used for designing manufacturing facility, analyzing the financial health of an organization, forecasting demand of a product or service, etc.\nSupport Tools − Support tools like online help; pulls down menus, user interfaces, graphical analysis, error correction mechanism, facilitates the user interactions with the system."
},
{
"code": null,
"e": 44762,
"s": 44510,
"text": "Model Management System − It stores and accesses models that managers use to make decisions. Such models are used for designing manufacturing facility, analyzing the financial health of an organization, forecasting demand of a product or service, etc."
},
{
"code": null,
"e": 44944,
"s": 44762,
"text": "Support Tools − Support tools like online help; pulls down menus, user interfaces, graphical analysis, error correction mechanism, facilitates the user interactions with the system."
},
{
"code": null,
"e": 45037,
"s": 44944,
"text": "There are several ways to classify DSS. Hoi Apple and Whinstone classifies DSS as follows −"
},
{
"code": null,
"e": 45222,
"s": 45037,
"text": "Text Oriented DSS − It contains textually represented information that could have a bearing on decision. It allows documents to be electronically created, revised and viewed as needed."
},
{
"code": null,
"e": 45407,
"s": 45222,
"text": "Text Oriented DSS − It contains textually represented information that could have a bearing on decision. It allows documents to be electronically created, revised and viewed as needed."
},
{
"code": null,
"e": 45515,
"s": 45407,
"text": "Database Oriented DSS − Database plays a major role here; it contains organized and highly structured data."
},
{
"code": null,
"e": 45623,
"s": 45515,
"text": "Database Oriented DSS − Database plays a major role here; it contains organized and highly structured data."
},
{
"code": null,
"e": 45863,
"s": 45623,
"text": "Spreadsheet Oriented DSS − It contains information in spread sheets that allows create, view, modify procedural knowledge and also instructs the system to execute self-contained instructions. The most popular tool is Excel and Lotus 1-2-3."
},
{
"code": null,
"e": 46103,
"s": 45863,
"text": "Spreadsheet Oriented DSS − It contains information in spread sheets that allows create, view, modify procedural knowledge and also instructs the system to execute self-contained instructions. The most popular tool is Excel and Lotus 1-2-3."
},
{
"code": null,
"e": 46258,
"s": 46103,
"text": "Solver Oriented DSS − It is based on a solver, which is an algorithm or procedure written for performing certain calculations and particular program type."
},
{
"code": null,
"e": 46413,
"s": 46258,
"text": "Solver Oriented DSS − It is based on a solver, which is an algorithm or procedure written for performing certain calculations and particular program type."
},
{
"code": null,
"e": 46482,
"s": 46413,
"text": "Rules Oriented DSS − It follows certain procedures adopted as rules."
},
{
"code": null,
"e": 46551,
"s": 46482,
"text": "Rules Oriented DSS − It follows certain procedures adopted as rules."
},
{
"code": null,
"e": 46648,
"s": 46551,
"text": "Rules Oriented DSS − Procedures are adopted in rules oriented DSS. Export system is the example."
},
{
"code": null,
"e": 46745,
"s": 46648,
"text": "Rules Oriented DSS − Procedures are adopted in rules oriented DSS. Export system is the example."
},
{
"code": null,
"e": 46833,
"s": 46745,
"text": "Compound DSS − It is built by using two or more of the five structures explained above."
},
{
"code": null,
"e": 46921,
"s": 46833,
"text": "Compound DSS − It is built by using two or more of the five structures explained above."
},
{
"code": null,
"e": 46955,
"s": 46921,
"text": "Following are some typical DSSs −"
},
{
"code": null,
"e": 47141,
"s": 46955,
"text": "Status Inquiry System − It helps in taking operational, management level, or middle level management decisions, for example daily schedules of jobs to machines or machines to operators."
},
{
"code": null,
"e": 47327,
"s": 47141,
"text": "Status Inquiry System − It helps in taking operational, management level, or middle level management decisions, for example daily schedules of jobs to machines or machines to operators."
},
{
"code": null,
"e": 47478,
"s": 47327,
"text": "Data Analysis System − It needs comparative analysis and makes use of formula or an algorithm, for example cash flow analysis, inventory analysis etc."
},
{
"code": null,
"e": 47629,
"s": 47478,
"text": "Data Analysis System − It needs comparative analysis and makes use of formula or an algorithm, for example cash flow analysis, inventory analysis etc."
},
{
"code": null,
"e": 47811,
"s": 47629,
"text": "Information Analysis System − In this system data is analyzed and the information report is generated. For example, sales analysis, accounts receivable systems, market analysis etc."
},
{
"code": null,
"e": 47993,
"s": 47811,
"text": "Information Analysis System − In this system data is analyzed and the information report is generated. For example, sales analysis, accounts receivable systems, market analysis etc."
},
{
"code": null,
"e": 48203,
"s": 47993,
"text": "Accounting System − It keeps track of accounting and finance related information, for example, final account, accounts receivables, accounts payables, etc. that keep track of the major aspects of the business."
},
{
"code": null,
"e": 48413,
"s": 48203,
"text": "Accounting System − It keeps track of accounting and finance related information, for example, final account, accounts receivables, accounts payables, etc. that keep track of the major aspects of the business."
},
{
"code": null,
"e": 48582,
"s": 48413,
"text": "Model Based System − Simulation models or optimization models used for decision-making are used infrequently and creates general guidelines for operation or management."
},
{
"code": null,
"e": 48751,
"s": 48582,
"text": "Model Based System − Simulation models or optimization models used for decision-making are used infrequently and creates general guidelines for operation or management."
},
{
"code": null,
"e": 49008,
"s": 48751,
"text": "All the systems we are discussing here come under knowledge management category. A knowledge management system is not radically different from all these information systems, but it just extends the already existing systems by assimilating more information."
},
{
"code": null,
"e": 49137,
"s": 49008,
"text": "As we have seen, data is raw facts, information is processed and/or interpreted data, and knowledge is personalized information."
},
{
"code": null,
"e": 49162,
"s": 49137,
"text": "Personalized information"
},
{
"code": null,
"e": 49197,
"s": 49162,
"text": "State of knowing and understanding"
},
{
"code": null,
"e": 49236,
"s": 49197,
"text": "An object to be stored and manipulated"
},
{
"code": null,
"e": 49268,
"s": 49236,
"text": "A process of applying expertise"
},
{
"code": null,
"e": 49305,
"s": 49268,
"text": "A condition of access to information"
},
{
"code": null,
"e": 49335,
"s": 49305,
"text": "Potential to influence action"
},
{
"code": null,
"e": 49344,
"s": 49335,
"text": "Intranet"
},
{
"code": null,
"e": 49387,
"s": 49344,
"text": "Data warehouses and knowledge repositories"
},
{
"code": null,
"e": 49410,
"s": 49387,
"text": "Decision support tools"
},
{
"code": null,
"e": 49449,
"s": 49410,
"text": "Groupware for supporting collaboration"
},
{
"code": null,
"e": 49479,
"s": 49449,
"text": "Networks of knowledge workers"
},
{
"code": null,
"e": 49498,
"s": 49479,
"text": "Internal expertise"
},
{
"code": null,
"e": 49519,
"s": 49498,
"text": "Improved performance"
},
{
"code": null,
"e": 49541,
"s": 49519,
"text": "Competitive advantage"
},
{
"code": null,
"e": 49552,
"s": 49541,
"text": "Innovation"
},
{
"code": null,
"e": 49573,
"s": 49552,
"text": "Sharing of knowledge"
},
{
"code": null,
"e": 49585,
"s": 49573,
"text": "Integration"
},
{
"code": null,
"e": 49613,
"s": 49585,
"text": "Continuous improvement by −"
},
{
"code": null,
"e": 49630,
"s": 49613,
"text": "Driving strategy"
},
{
"code": null,
"e": 49661,
"s": 49630,
"text": "Starting new lines of business"
},
{
"code": null,
"e": 49685,
"s": 49661,
"text": "Solving problems faster"
},
{
"code": null,
"e": 49716,
"s": 49685,
"text": "Developing professional skills"
},
{
"code": null,
"e": 49742,
"s": 49716,
"text": "Recruit and retain talent"
},
{
"code": null,
"e": 49820,
"s": 49742,
"text": "Start with the business problem and the business value to be delivered first."
},
{
"code": null,
"e": 49898,
"s": 49820,
"text": "Start with the business problem and the business value to be delivered first."
},
{
"code": null,
"e": 49989,
"s": 49898,
"text": "Identify what kind of strategy to pursue to deliver this value and address the KM problem."
},
{
"code": null,
"e": 50080,
"s": 49989,
"text": "Identify what kind of strategy to pursue to deliver this value and address the KM problem."
},
{
"code": null,
"e": 50153,
"s": 50080,
"text": "Think about the system required from a people and process point of view."
},
{
"code": null,
"e": 50226,
"s": 50153,
"text": "Think about the system required from a people and process point of view."
},
{
"code": null,
"e": 50335,
"s": 50226,
"text": "Finally, think about what kind of technical infrastructure are required to support the people and processes."
},
{
"code": null,
"e": 50444,
"s": 50335,
"text": "Finally, think about what kind of technical infrastructure are required to support the people and processes."
},
{
"code": null,
"e": 50540,
"s": 50444,
"text": "Implement system and processes with appropriate change management and iterative staged release."
},
{
"code": null,
"e": 50636,
"s": 50540,
"text": "Implement system and processes with appropriate change management and iterative staged release."
},
{
"code": null,
"e": 50853,
"s": 50636,
"text": "A Content Management System (CMS) allows publishing, editing, and modifying content as well as its maintenance by combining rules, processes and/or workflows, from a central interface, in a collaborative environment."
},
{
"code": null,
"e": 51004,
"s": 50853,
"text": "A CMS may serve as a central repository for content, which could be, textual data, documents, movies, pictures, phone numbers, and/or scientific data."
},
{
"code": null,
"e": 51021,
"s": 51004,
"text": "Creating content"
},
{
"code": null,
"e": 51037,
"s": 51021,
"text": "Storing content"
},
{
"code": null,
"e": 51054,
"s": 51037,
"text": "Indexing content"
},
{
"code": null,
"e": 51072,
"s": 51054,
"text": "Searching content"
},
{
"code": null,
"e": 51091,
"s": 51072,
"text": "Retrieving content"
},
{
"code": null,
"e": 51110,
"s": 51091,
"text": "Publishing content"
},
{
"code": null,
"e": 51128,
"s": 51110,
"text": "Archiving content"
},
{
"code": null,
"e": 51145,
"s": 51128,
"text": "Revising content"
},
{
"code": null,
"e": 51173,
"s": 51145,
"text": "Managing content end-to-end"
},
{
"code": null,
"e": 51284,
"s": 51173,
"text": "Designing content template, for example web administrator designs webpage template for web content management."
},
{
"code": null,
"e": 51395,
"s": 51284,
"text": "Designing content template, for example web administrator designs webpage template for web content management."
},
{
"code": null,
"e": 51530,
"s": 51395,
"text": "Creating content blocks, for example, a web administrator adds empower CMS tags called \"content blocks\" to webpage template using CMS."
},
{
"code": null,
"e": 51665,
"s": 51530,
"text": "Creating content blocks, for example, a web administrator adds empower CMS tags called \"content blocks\" to webpage template using CMS."
},
{
"code": null,
"e": 51777,
"s": 51665,
"text": "Positioning content blocks on the document, for example, web administrator positions content blocks in webpage."
},
{
"code": null,
"e": 51889,
"s": 51777,
"text": "Positioning content blocks on the document, for example, web administrator positions content blocks in webpage."
},
{
"code": null,
"e": 51963,
"s": 51889,
"text": "Authoring content providers to search, retrieve, view and update content."
},
{
"code": null,
"e": 52037,
"s": 51963,
"text": "Authoring content providers to search, retrieve, view and update content."
},
{
"code": null,
"e": 52145,
"s": 52037,
"text": "Content management system helps to secure privacy and currency of the content and enhances performance by −"
},
{
"code": null,
"e": 52246,
"s": 52145,
"text": "Ensuring integrity and accuracy of content by ensuring only one user modifies the content at a time."
},
{
"code": null,
"e": 52347,
"s": 52246,
"text": "Ensuring integrity and accuracy of content by ensuring only one user modifies the content at a time."
},
{
"code": null,
"e": 52419,
"s": 52347,
"text": "Implementing audit trails to monitor changes made in content over time."
},
{
"code": null,
"e": 52491,
"s": 52419,
"text": "Implementing audit trails to monitor changes made in content over time."
},
{
"code": null,
"e": 52533,
"s": 52491,
"text": "Providing secured user access to content."
},
{
"code": null,
"e": 52575,
"s": 52533,
"text": "Providing secured user access to content."
},
{
"code": null,
"e": 52632,
"s": 52575,
"text": "Organization of content into related groups and folders."
},
{
"code": null,
"e": 52689,
"s": 52632,
"text": "Organization of content into related groups and folders."
},
{
"code": null,
"e": 52734,
"s": 52689,
"text": "Allowing searching and retrieval of content."
},
{
"code": null,
"e": 52779,
"s": 52734,
"text": "Allowing searching and retrieval of content."
},
{
"code": null,
"e": 52936,
"s": 52779,
"text": "Recording information and meta-data related to the content, like author and title of content, version of content, date and time of creating the content etc."
},
{
"code": null,
"e": 53093,
"s": 52936,
"text": "Recording information and meta-data related to the content, like author and title of content, version of content, date and time of creating the content etc."
},
{
"code": null,
"e": 53153,
"s": 53093,
"text": "Workflow based routing of content from one user to another."
},
{
"code": null,
"e": 53213,
"s": 53153,
"text": "Workflow based routing of content from one user to another."
},
{
"code": null,
"e": 53263,
"s": 53213,
"text": "Converting paper-based content to digital format."
},
{
"code": null,
"e": 53313,
"s": 53263,
"text": "Converting paper-based content to digital format."
},
{
"code": null,
"e": 53384,
"s": 53313,
"text": "Organizing content into groups and distributing it to target audience."
},
{
"code": null,
"e": 53455,
"s": 53384,
"text": "Organizing content into groups and distributing it to target audience."
},
{
"code": null,
"e": 53609,
"s": 53455,
"text": "Executive support systems are intended to be used by the senior managers directly to provide support to non-programmed decisions in strategic management."
},
{
"code": null,
"e": 53755,
"s": 53609,
"text": "These information are often external, unstructured and even uncertain. Exact scope and context of such information is often not known beforehand."
},
{
"code": null,
"e": 53796,
"s": 53755,
"text": "This information is intelligence based −"
},
{
"code": null,
"e": 53816,
"s": 53796,
"text": "Market intelligence"
},
{
"code": null,
"e": 53840,
"s": 53816,
"text": "Investment intelligence"
},
{
"code": null,
"e": 53864,
"s": 53840,
"text": "Technology intelligence"
},
{
"code": null,
"e": 53958,
"s": 53864,
"text": "Following are some examples of intelligent information, which is often the source of an ESS −"
},
{
"code": null,
"e": 53977,
"s": 53958,
"text": "External databases"
},
{
"code": null,
"e": 54021,
"s": 53977,
"text": "Technology reports like patent records etc."
},
{
"code": null,
"e": 54056,
"s": 54021,
"text": "Technical reports from consultants"
},
{
"code": null,
"e": 54071,
"s": 54056,
"text": "Market reports"
},
{
"code": null,
"e": 54114,
"s": 54071,
"text": "Confidential information about competitors"
},
{
"code": null,
"e": 54161,
"s": 54114,
"text": "Speculative information like market conditions"
},
{
"code": null,
"e": 54181,
"s": 54161,
"text": "Government policies"
},
{
"code": null,
"e": 54215,
"s": 54181,
"text": "Financial reports and information"
},
{
"code": null,
"e": 54253,
"s": 54215,
"text": "Easy for upper level executive to use"
},
{
"code": null,
"e": 54279,
"s": 54253,
"text": "Ability to analyze trends"
},
{
"code": null,
"e": 54329,
"s": 54279,
"text": "Augmentation of managers' leadership capabilities"
},
{
"code": null,
"e": 54375,
"s": 54329,
"text": "Enhance personal thinking and decision-making"
},
{
"code": null,
"e": 54421,
"s": 54375,
"text": "Contribution to strategic control flexibility"
},
{
"code": null,
"e": 54480,
"s": 54421,
"text": "Enhance organizational competitiveness in the market place"
},
{
"code": null,
"e": 54502,
"s": 54480,
"text": "Instruments of change"
},
{
"code": null,
"e": 54537,
"s": 54502,
"text": "Increased executive time horizons."
},
{
"code": null,
"e": 54561,
"s": 54537,
"text": "Better reporting system"
},
{
"code": null,
"e": 54605,
"s": 54561,
"text": "Improved mental model of business executive"
},
{
"code": null,
"e": 54655,
"s": 54605,
"text": "Help improve consensus building and communication"
},
{
"code": null,
"e": 54681,
"s": 54655,
"text": "Improve office automation"
},
{
"code": null,
"e": 54717,
"s": 54681,
"text": "Reduce time for finding information"
},
{
"code": null,
"e": 54762,
"s": 54717,
"text": "Early identification of company performance"
},
{
"code": null,
"e": 54808,
"s": 54762,
"text": "Detail examination of critical success factor"
},
{
"code": null,
"e": 54829,
"s": 54808,
"text": "Better understanding"
},
{
"code": null,
"e": 54845,
"s": 54829,
"text": "Time management"
},
{
"code": null,
"e": 54890,
"s": 54845,
"text": "Increased communication capacity and quality"
},
{
"code": null,
"e": 54912,
"s": 54890,
"text": "Functions are limited"
},
{
"code": null,
"e": 54938,
"s": 54912,
"text": "Hard to quantify benefits"
},
{
"code": null,
"e": 54983,
"s": 54938,
"text": "Executive may encounter information overload"
},
{
"code": null,
"e": 55006,
"s": 54983,
"text": "System may become slow"
},
{
"code": null,
"e": 55037,
"s": 55006,
"text": "Difficult to keep current data"
},
{
"code": null,
"e": 55081,
"s": 55037,
"text": "May lead to less reliable and insecure data"
},
{
"code": null,
"e": 55114,
"s": 55081,
"text": "Excessive cost for small company"
},
{
"code": null,
"e": 55343,
"s": 55114,
"text": "The term 'Business Intelligence' has evolved from the decision support systems and gained strength with the technology and applications like data warehouses, Executive Information Systems and Online Analytical Processing (OLAP)."
},
{
"code": null,
"e": 55456,
"s": 55343,
"text": "Business Intelligence System is basically a system used for finding patterns from existing data from operations."
},
{
"code": null,
"e": 55532,
"s": 55456,
"text": "It is created by procuring data and information for use in decision-making."
},
{
"code": null,
"e": 55608,
"s": 55532,
"text": "It is created by procuring data and information for use in decision-making."
},
{
"code": null,
"e": 55692,
"s": 55608,
"text": "It is a combination of skills, processes, technologies, applications and practices."
},
{
"code": null,
"e": 55776,
"s": 55692,
"text": "It is a combination of skills, processes, technologies, applications and practices."
},
{
"code": null,
"e": 55836,
"s": 55776,
"text": "It contains background data along with the reporting tools."
},
{
"code": null,
"e": 55896,
"s": 55836,
"text": "It contains background data along with the reporting tools."
},
{
"code": null,
"e": 55993,
"s": 55896,
"text": "It is a combination of a set of concepts and methods strengthened by fact-based support systems."
},
{
"code": null,
"e": 56090,
"s": 55993,
"text": "It is a combination of a set of concepts and methods strengthened by fact-based support systems."
},
{
"code": null,
"e": 56170,
"s": 56090,
"text": "It is an extension of Executive Support System or Executive Information System."
},
{
"code": null,
"e": 56250,
"s": 56170,
"text": "It is an extension of Executive Support System or Executive Information System."
},
{
"code": null,
"e": 56337,
"s": 56250,
"text": "It collects, integrates, stores, analyzes, and provides access to business information"
},
{
"code": null,
"e": 56424,
"s": 56337,
"text": "It collects, integrates, stores, analyzes, and provides access to business information"
},
{
"code": null,
"e": 56562,
"s": 56424,
"text": "It is an environment in which business users get reliable, secure, consistent, comprehensible, easily manipulated and timely information."
},
{
"code": null,
"e": 56700,
"s": 56562,
"text": "It is an environment in which business users get reliable, secure, consistent, comprehensible, easily manipulated and timely information."
},
{
"code": null,
"e": 56784,
"s": 56700,
"text": "It provides business insights that lead to better, faster, more relevant decisions."
},
{
"code": null,
"e": 56868,
"s": 56784,
"text": "It provides business insights that lead to better, faster, more relevant decisions."
},
{
"code": null,
"e": 56899,
"s": 56868,
"text": "Improved Management Processes."
},
{
"code": null,
"e": 56930,
"s": 56899,
"text": "Improved Management Processes."
},
{
"code": null,
"e": 57041,
"s": 56930,
"text": "Planning, controlling, measuring and/or applying changes that results in increased revenues and reduced costs."
},
{
"code": null,
"e": 57152,
"s": 57041,
"text": "Planning, controlling, measuring and/or applying changes that results in increased revenues and reduced costs."
},
{
"code": null,
"e": 57182,
"s": 57152,
"text": "Improved business operations."
},
{
"code": null,
"e": 57212,
"s": 57182,
"text": "Improved business operations."
},
{
"code": null,
"e": 57312,
"s": 57212,
"text": "Fraud detection, order processing, purchasing that results in increased revenues and reduced costs."
},
{
"code": null,
"e": 57412,
"s": 57312,
"text": "Fraud detection, order processing, purchasing that results in increased revenues and reduced costs."
},
{
"code": null,
"e": 57446,
"s": 57412,
"text": "Intelligent prediction of future."
},
{
"code": null,
"e": 57480,
"s": 57446,
"text": "Intelligent prediction of future."
},
{
"code": null,
"e": 57665,
"s": 57480,
"text": "For most companies, it is not possible to implement a proactive business intelligence system at one go. The following techniques and methodologies could be taken as approaches to BIS −"
},
{
"code": null,
"e": 57713,
"s": 57665,
"text": "Improving reporting and analytical capabilities"
},
{
"code": null,
"e": 57745,
"s": 57713,
"text": "Using scorecards and dashboards"
},
{
"code": null,
"e": 57766,
"s": 57745,
"text": "Enterprise Reporting"
},
{
"code": null,
"e": 57812,
"s": 57766,
"text": "On-line Analytical Processing (OLAP) Analysis"
},
{
"code": null,
"e": 57845,
"s": 57812,
"text": "Advanced and Predictive Analysis"
},
{
"code": null,
"e": 57879,
"s": 57845,
"text": "Alerts and Proactive Notification"
},
{
"code": null,
"e": 57982,
"s": 57879,
"text": "Automated generation of reports with user subscriptions and \"alerts\" to problems and/or opportunities."
},
{
"code": null,
"e": 58012,
"s": 57982,
"text": "Data Storage and Management −"
},
{
"code": null,
"e": 58028,
"s": 58012,
"text": "Data ware house"
},
{
"code": null,
"e": 58044,
"s": 58028,
"text": "Ad hoc analysis"
},
{
"code": null,
"e": 58057,
"s": 58044,
"text": "Data quality"
},
{
"code": null,
"e": 58069,
"s": 58057,
"text": "Data mining"
},
{
"code": null,
"e": 58090,
"s": 58069,
"text": "Information Delivery"
},
{
"code": null,
"e": 58100,
"s": 58090,
"text": "Dashboard"
},
{
"code": null,
"e": 58122,
"s": 58100,
"text": "Collaboration /search"
},
{
"code": null,
"e": 58140,
"s": 58122,
"text": "Managed reporting"
},
{
"code": null,
"e": 58154,
"s": 58140,
"text": "Visualization"
},
{
"code": null,
"e": 58164,
"s": 58154,
"text": "Scorecard"
},
{
"code": null,
"e": 58194,
"s": 58164,
"text": "Query, Reporting and Analysis"
},
{
"code": null,
"e": 58210,
"s": 58194,
"text": "Ad hoc Analysis"
},
{
"code": null,
"e": 58231,
"s": 58210,
"text": "Production reporting"
},
{
"code": null,
"e": 58245,
"s": 58231,
"text": "OLAP analysis"
},
{
"code": null,
"e": 58299,
"s": 58245,
"text": "An organization may use various information systems −"
},
{
"code": null,
"e": 58378,
"s": 58299,
"text": "Supply Chain Management − For managing suppliers, inventory and shipping, etc."
},
{
"code": null,
"e": 58457,
"s": 58378,
"text": "Supply Chain Management − For managing suppliers, inventory and shipping, etc."
},
{
"code": null,
"e": 58542,
"s": 58457,
"text": "Human Resource Management − For managing personnel, training and recruiting talents;"
},
{
"code": null,
"e": 58627,
"s": 58542,
"text": "Human Resource Management − For managing personnel, training and recruiting talents;"
},
{
"code": null,
"e": 58715,
"s": 58627,
"text": "Employee Health Care − For managing medical records and insurance details of employees;"
},
{
"code": null,
"e": 58803,
"s": 58715,
"text": "Employee Health Care − For managing medical records and insurance details of employees;"
},
{
"code": null,
"e": 58884,
"s": 58803,
"text": "Customer Relationship Management − For managing current and potential customers;"
},
{
"code": null,
"e": 58965,
"s": 58884,
"text": "Customer Relationship Management − For managing current and potential customers;"
},
{
"code": null,
"e": 59072,
"s": 58965,
"text": "Business Intelligence Applications − For finding the patterns from existing data from business operations."
},
{
"code": null,
"e": 59179,
"s": 59072,
"text": "Business Intelligence Applications − For finding the patterns from existing data from business operations."
},
{
"code": null,
"e": 59358,
"s": 59179,
"text": "All these systems work as individual islands of automation. Most often these systems are standalone and do not communicate with each other due to incompatibility issues such as −"
},
{
"code": null,
"e": 59398,
"s": 59358,
"text": "Operating systems they are residing on;"
},
{
"code": null,
"e": 59438,
"s": 59398,
"text": "Operating systems they are residing on;"
},
{
"code": null,
"e": 59474,
"s": 59438,
"text": "Database system used in the system;"
},
{
"code": null,
"e": 59510,
"s": 59474,
"text": "Database system used in the system;"
},
{
"code": null,
"e": 59548,
"s": 59510,
"text": "Legacy systems not supported anymore."
},
{
"code": null,
"e": 59586,
"s": 59548,
"text": "Legacy systems not supported anymore."
},
{
"code": null,
"e": 59845,
"s": 59586,
"text": "EAI is an integration framework, a middleware, made of a collection of technologies and services that allows smooth integration of all such systems and applications throughout the enterprise and enables data sharing and more automation of business processes."
},
{
"code": null,
"e": 59990,
"s": 59845,
"text": "EAI is defined as \"the unrestricted sharing of data and business processes among any connected applications and data sources in the enterprise.\""
},
{
"code": null,
"e": 60135,
"s": 59990,
"text": "EAI is defined as \"the unrestricted sharing of data and business processes among any connected applications and data sources in the enterprise.\""
},
{
"code": null,
"e": 60234,
"s": 60135,
"text": "EAI, when used effectively allows integration without any major changes to current infrastructure."
},
{
"code": null,
"e": 60333,
"s": 60234,
"text": "EAI, when used effectively allows integration without any major changes to current infrastructure."
},
{
"code": null,
"e": 60403,
"s": 60333,
"text": "Extends middleware capabilities to cope with application integration."
},
{
"code": null,
"e": 60473,
"s": 60403,
"text": "Extends middleware capabilities to cope with application integration."
},
{
"code": null,
"e": 60555,
"s": 60473,
"text": "Uses application logic layers of different middleware systems as building blocks."
},
{
"code": null,
"e": 60637,
"s": 60555,
"text": "Uses application logic layers of different middleware systems as building blocks."
},
{
"code": null,
"e": 60814,
"s": 60637,
"text": "Keeps track of information related to the operations of the enterprise e.g. Inventory, sales ledger and execute the core processes that create and manipulate this information."
},
{
"code": null,
"e": 60991,
"s": 60814,
"text": "Keeps track of information related to the operations of the enterprise e.g. Inventory, sales ledger and execute the core processes that create and manipulate this information."
},
{
"code": null,
"e": 61067,
"s": 60991,
"text": "Unrestricted sharing of data and business processes across an organization."
},
{
"code": null,
"e": 61143,
"s": 61067,
"text": "Unrestricted sharing of data and business processes across an organization."
},
{
"code": null,
"e": 61196,
"s": 61143,
"text": "Linkage between customers, suppliers and regulators."
},
{
"code": null,
"e": 61249,
"s": 61196,
"text": "Linkage between customers, suppliers and regulators."
},
{
"code": null,
"e": 61338,
"s": 61249,
"text": "The linking of data, business processes and applications to automate business processes."
},
{
"code": null,
"e": 61427,
"s": 61338,
"text": "The linking of data, business processes and applications to automate business processes."
},
{
"code": null,
"e": 61496,
"s": 61427,
"text": "Ensure consistent qualities of service (security, reliability etc.)."
},
{
"code": null,
"e": 61565,
"s": 61496,
"text": "Ensure consistent qualities of service (security, reliability etc.)."
},
{
"code": null,
"e": 61653,
"s": 61565,
"text": "Reduce the on-going cost of maintenance and reduce the cost of rolling out new systems."
},
{
"code": null,
"e": 61741,
"s": 61653,
"text": "Reduce the on-going cost of maintenance and reduce the cost of rolling out new systems."
},
{
"code": null,
"e": 61833,
"s": 61741,
"text": "Hub and spoke architecture concentrates all of the processing into a single server/cluster."
},
{
"code": null,
"e": 61925,
"s": 61833,
"text": "Hub and spoke architecture concentrates all of the processing into a single server/cluster."
},
{
"code": null,
"e": 61979,
"s": 61925,
"text": "Often became hard to maintain and evolve efficiently."
},
{
"code": null,
"e": 62033,
"s": 61979,
"text": "Often became hard to maintain and evolve efficiently."
},
{
"code": null,
"e": 62104,
"s": 62033,
"text": "Hard to extend to integrate 3rd parties on other technology platforms."
},
{
"code": null,
"e": 62175,
"s": 62104,
"text": "Hard to extend to integrate 3rd parties on other technology platforms."
},
{
"code": null,
"e": 62233,
"s": 62175,
"text": "The canonical data model introduces an intermediary step."
},
{
"code": null,
"e": 62291,
"s": 62233,
"text": "The canonical data model introduces an intermediary step."
},
{
"code": null,
"e": 62342,
"s": 62291,
"text": "Added complexity and additional processing effort."
},
{
"code": null,
"e": 62393,
"s": 62342,
"text": "Added complexity and additional processing effort."
},
{
"code": null,
"e": 62416,
"s": 62393,
"text": "EAI products typified."
},
{
"code": null,
"e": 62439,
"s": 62416,
"text": "EAI products typified."
},
{
"code": null,
"e": 62495,
"s": 62439,
"text": "Heavy customization required to implement the solution."
},
{
"code": null,
"e": 62551,
"s": 62495,
"text": "Heavy customization required to implement the solution."
},
{
"code": null,
"e": 62634,
"s": 62551,
"text": "Lock-In − Often built using proprietary technology and required specialist skills."
},
{
"code": null,
"e": 62717,
"s": 62634,
"text": "Lock-In − Often built using proprietary technology and required specialist skills."
},
{
"code": null,
"e": 62795,
"s": 62717,
"text": "Lack of flexibility − Hard to extend or to integrate with other EAI products!"
},
{
"code": null,
"e": 62873,
"s": 62795,
"text": "Lack of flexibility − Hard to extend or to integrate with other EAI products!"
},
{
"code": null,
"e": 62912,
"s": 62873,
"text": "Requires organization to be EAI ready."
},
{
"code": null,
"e": 62951,
"s": 62912,
"text": "Requires organization to be EAI ready."
},
{
"code": null,
"e": 63035,
"s": 62951,
"text": "Data Level − Process, techniques and technology of moving data between data stores."
},
{
"code": null,
"e": 63119,
"s": 63035,
"text": "Data Level − Process, techniques and technology of moving data between data stores."
},
{
"code": null,
"e": 63218,
"s": 63119,
"text": "Application Interface Level − Leveraging of interfaces exposed by custom or packaged applications."
},
{
"code": null,
"e": 63317,
"s": 63218,
"text": "Application Interface Level − Leveraging of interfaces exposed by custom or packaged applications."
},
{
"code": null,
"e": 63363,
"s": 63317,
"text": "Method Level − Sharing of the business logic."
},
{
"code": null,
"e": 63409,
"s": 63363,
"text": "Method Level − Sharing of the business logic."
},
{
"code": null,
"e": 63519,
"s": 63409,
"text": "User Interface Level − Packaging applications by using their user interface as a common point of integration."
},
{
"code": null,
"e": 63629,
"s": 63519,
"text": "User Interface Level − Packaging applications by using their user interface as a common point of integration."
},
{
"code": null,
"e": 63954,
"s": 63629,
"text": "Business Continuity Planning (BCP) or Business Continuity and Resiliency Planning (BCRP) creates a guideline for continuing business operations under adverse conditions such as a natural calamity, an interruption in regular business processes, loss or damage to critical infrastructure, or a crime done against the business."
},
{
"code": null,
"e": 64228,
"s": 63954,
"text": "It is defined as a plan that \"identifies an organization's exposure to internal and external threats and synthesizes hard and soft assets to provide effective prevention and recovery for the organization, while maintaining competitive advantage and value system integrity.\""
},
{
"code": null,
"e": 64338,
"s": 64228,
"text": "Understandably, risk management and disaster management are major components in business continuity planning."
},
{
"code": null,
"e": 64376,
"s": 64338,
"text": "Following are the objectives of BCP −"
},
{
"code": null,
"e": 64481,
"s": 64376,
"text": "Reducing the possibility of any interruption in regular business processes using proper risk management."
},
{
"code": null,
"e": 64586,
"s": 64481,
"text": "Reducing the possibility of any interruption in regular business processes using proper risk management."
},
{
"code": null,
"e": 64633,
"s": 64586,
"text": "Minimizing the impact of interruption, if any."
},
{
"code": null,
"e": 64680,
"s": 64633,
"text": "Minimizing the impact of interruption, if any."
},
{
"code": null,
"e": 64805,
"s": 64680,
"text": "Teaching the staff their roles and responsibilities in such a situation to safeguard their own security and other interests."
},
{
"code": null,
"e": 64930,
"s": 64805,
"text": "Teaching the staff their roles and responsibilities in such a situation to safeguard their own security and other interests."
},
{
"code": null,
"e": 65027,
"s": 64930,
"text": "Handling any potential failure in supply chain system, to maintain the natural flow of business."
},
{
"code": null,
"e": 65124,
"s": 65027,
"text": "Handling any potential failure in supply chain system, to maintain the natural flow of business."
},
{
"code": null,
"e": 65185,
"s": 65124,
"text": "Protecting the business from failure and negative publicity."
},
{
"code": null,
"e": 65246,
"s": 65185,
"text": "Protecting the business from failure and negative publicity."
},
{
"code": null,
"e": 65307,
"s": 65246,
"text": "Protecting customers and maintaining customer relationships."
},
{
"code": null,
"e": 65368,
"s": 65307,
"text": "Protecting customers and maintaining customer relationships."
},
{
"code": null,
"e": 65459,
"s": 65368,
"text": "Protecting the prevalent and prospective market and competitive advantage of the business."
},
{
"code": null,
"e": 65550,
"s": 65459,
"text": "Protecting the prevalent and prospective market and competitive advantage of the business."
},
{
"code": null,
"e": 65592,
"s": 65550,
"text": "Protecting profits, revenue and goodwill."
},
{
"code": null,
"e": 65634,
"s": 65592,
"text": "Protecting profits, revenue and goodwill."
},
{
"code": null,
"e": 65713,
"s": 65634,
"text": "Setting a recovery plan following a disruption to normal operating conditions."
},
{
"code": null,
"e": 65792,
"s": 65713,
"text": "Setting a recovery plan following a disruption to normal operating conditions."
},
{
"code": null,
"e": 65844,
"s": 65792,
"text": "Fulfilling legislative and regulatory requirements."
},
{
"code": null,
"e": 65896,
"s": 65844,
"text": "Fulfilling legislative and regulatory requirements."
},
{
"code": null,
"e": 66139,
"s": 65896,
"text": "Traditionally a business continuity plan would just protect the data center. With the advent of technologies, the scope of a BCP includes all distributed operations, personnel, networks, power and eventually all aspects of the IT environment."
},
{
"code": null,
"e": 66465,
"s": 66139,
"text": "The business continuity planning process involves recovery, continuation, and preservation of the entire business operation, not just its technology component. It should include contingency plans to protect all resources of the organization, e.g., human resource, financial resource and IT infrastructure, against any mishap."
},
{
"code": null,
"e": 66495,
"s": 66465,
"text": "It has the following phases −"
},
{
"code": null,
"e": 66527,
"s": 66495,
"text": "Project management & initiation"
},
{
"code": null,
"e": 66558,
"s": 66527,
"text": "Business Impact Analysis (BIA)"
},
{
"code": null,
"e": 66578,
"s": 66558,
"text": "Recovery strategies"
},
{
"code": null,
"e": 66604,
"s": 66578,
"text": "Plan design & development"
},
{
"code": null,
"e": 66646,
"s": 66604,
"text": "Testing, maintenance, awareness, training"
},
{
"code": null,
"e": 66688,
"s": 66646,
"text": "This phase has the following sub-phases −"
},
{
"code": null,
"e": 66719,
"s": 66688,
"text": "Establish need (risk analysis)"
},
{
"code": null,
"e": 66742,
"s": 66719,
"text": "Get management support"
},
{
"code": null,
"e": 66820,
"s": 66742,
"text": "Establish team (functional, technical, BCC - Business Continuity Coordinator)"
},
{
"code": null,
"e": 66871,
"s": 66820,
"text": "Create work plan (scope, goals, methods, timeline)"
},
{
"code": null,
"e": 66900,
"s": 66871,
"text": "Initial report to management"
},
{
"code": null,
"e": 66938,
"s": 66900,
"text": "Obtain management approval to proceed"
},
{
"code": null,
"e": 67091,
"s": 66938,
"text": "This phase is used to obtain formal agreement with senior management for each time-critical business resource. This phase has the following sub-phases −"
},
{
"code": null,
"e": 67173,
"s": 67091,
"text": "Deciding maximum tolerable downtime, also known as MAO (Maximum Allowable Outage)"
},
{
"code": null,
"e": 67359,
"s": 67173,
"text": "Quantifying loss due to business outage (financial, extra cost of recovery, embarrassment), without estimating the probability of kinds of incidents, it only quantifies the consequences"
},
{
"code": null,
"e": 67436,
"s": 67359,
"text": "Choosing information gathering methods (surveys, interviews, software tools)"
},
{
"code": null,
"e": 67459,
"s": 67436,
"text": "Selecting interviewees"
},
{
"code": null,
"e": 67485,
"s": 67459,
"text": "Customizing questionnaire"
},
{
"code": null,
"e": 67507,
"s": 67485,
"text": "Analyzing information"
},
{
"code": null,
"e": 67552,
"s": 67507,
"text": "Identifying time-critical business functions"
},
{
"code": null,
"e": 67567,
"s": 67552,
"text": "Assigning MTDs"
},
{
"code": null,
"e": 67611,
"s": 67567,
"text": "Ranking critical business functions by MTDs"
},
{
"code": null,
"e": 67638,
"s": 67611,
"text": "Reporting recovery options"
},
{
"code": null,
"e": 67668,
"s": 67638,
"text": "Obtaining management approval"
},
{
"code": null,
"e": 67818,
"s": 67668,
"text": "This phase involves creating recovery strategies are based on MTDs, predefined and management-approved. These strategies should address recovery of −"
},
{
"code": null,
"e": 67838,
"s": 67818,
"text": "Business operations"
},
{
"code": null,
"e": 67860,
"s": 67838,
"text": "Facilities & supplies"
},
{
"code": null,
"e": 67890,
"s": 67860,
"text": "Users (workers and end-users)"
},
{
"code": null,
"e": 67898,
"s": 67890,
"text": "Network"
},
{
"code": null,
"e": 67922,
"s": 67898,
"text": "Data center (technical)"
},
{
"code": null,
"e": 67971,
"s": 67922,
"text": "Data (off-site backups of data and applications)"
},
{
"code": null,
"e": 68039,
"s": 67971,
"text": "This phase involves creating detailed recovery plan that includes −"
},
{
"code": null,
"e": 68073,
"s": 68039,
"text": "Business & service recovery plans"
},
{
"code": null,
"e": 68090,
"s": 68073,
"text": "Maintenance plan"
},
{
"code": null,
"e": 68116,
"s": 68090,
"text": "Awareness & training plan"
},
{
"code": null,
"e": 68129,
"s": 68116,
"text": "Testing plan"
},
{
"code": null,
"e": 68184,
"s": 68129,
"text": "The Sample Plan is divided into the following phases −"
},
{
"code": null,
"e": 68210,
"s": 68184,
"text": "Initial disaster response"
},
{
"code": null,
"e": 68239,
"s": 68210,
"text": "Resume critical business ops"
},
{
"code": null,
"e": 68272,
"s": 68239,
"text": "Resume non-critical business ops"
},
{
"code": null,
"e": 68309,
"s": 68272,
"text": "Restoration (return to primary site)"
},
{
"code": null,
"e": 68383,
"s": 68309,
"text": "Interacting with external groups (customers, media, emergency responders)"
},
{
"code": null,
"e": 68480,
"s": 68383,
"text": "The final phase is a continuously evolving process containing testing maintenance, and training."
},
{
"code": null,
"e": 68624,
"s": 68480,
"text": "The testing process generally follows procedures like structured walk-through, creating checklist, simulation, parallel and full interruptions."
},
{
"code": null,
"e": 68647,
"s": 68624,
"text": "Maintenance involves −"
},
{
"code": null,
"e": 68680,
"s": 68647,
"text": "Fixing problems found in testing"
},
{
"code": null,
"e": 68711,
"s": 68680,
"text": "Implementing change management"
},
{
"code": null,
"e": 68750,
"s": 68711,
"text": "Auditing and addressing audit findings"
},
{
"code": null,
"e": 68772,
"s": 68750,
"text": "Annual review of plan"
},
{
"code": null,
"e": 68886,
"s": 68772,
"text": "Training is an ongoing process and it should be made a part of the corporate standards and the corporate culture."
},
{
"code": null,
"e": 69101,
"s": 68886,
"text": "In a traditional manufacturing environment, supply chain management meant managing movement and storage of raw materials, work-in-progress inventory, and finished goods from point of origin to point of consumption."
},
{
"code": null,
"e": 69300,
"s": 69101,
"text": "It involves managing the network of interconnected smaller business units, networks of channels that take part in producing a merchandise of a service package required by the end users or customers."
},
{
"code": null,
"e": 69418,
"s": 69300,
"text": "With businesses crossing the barriers of local markets and reaching out to a global scenario, SCM is now defined as −"
},
{
"code": null,
"e": 69436,
"s": 69418,
"text": "SCM consists of −"
},
{
"code": null,
"e": 69458,
"s": 69436,
"text": "operations management"
},
{
"code": null,
"e": 69480,
"s": 69458,
"text": "operations management"
},
{
"code": null,
"e": 69490,
"s": 69480,
"text": "logistics"
},
{
"code": null,
"e": 69500,
"s": 69490,
"text": "logistics"
},
{
"code": null,
"e": 69512,
"s": 69500,
"text": "procurement"
},
{
"code": null,
"e": 69524,
"s": 69512,
"text": "procurement"
},
{
"code": null,
"e": 69547,
"s": 69524,
"text": "information technology"
},
{
"code": null,
"e": 69570,
"s": 69547,
"text": "information technology"
},
{
"code": null,
"e": 69601,
"s": 69570,
"text": "integrated business operations"
},
{
"code": null,
"e": 69632,
"s": 69601,
"text": "integrated business operations"
},
{
"code": null,
"e": 69735,
"s": 69632,
"text": "To decrease inventory cost by more accurately predicting demand and scheduling production to match it."
},
{
"code": null,
"e": 69838,
"s": 69735,
"text": "To decrease inventory cost by more accurately predicting demand and scheduling production to match it."
},
{
"code": null,
"e": 69934,
"s": 69838,
"text": "To reduce overall production cost by streamlining production and by improving information flow."
},
{
"code": null,
"e": 70030,
"s": 69934,
"text": "To reduce overall production cost by streamlining production and by improving information flow."
},
{
"code": null,
"e": 70064,
"s": 70030,
"text": "To improve customer satisfaction."
},
{
"code": null,
"e": 70098,
"s": 70064,
"text": "To improve customer satisfaction."
},
{
"code": null,
"e": 70131,
"s": 70098,
"text": "Customer Relationship Management"
},
{
"code": null,
"e": 70159,
"s": 70131,
"text": "Customer Service Management"
},
{
"code": null,
"e": 70177,
"s": 70159,
"text": "Demand Management"
},
{
"code": null,
"e": 70204,
"s": 70177,
"text": "Customer Order Fulfillment"
},
{
"code": null,
"e": 70234,
"s": 70204,
"text": "Manufacturing Flow Management"
},
{
"code": null,
"e": 70257,
"s": 70234,
"text": "Procurement Management"
},
{
"code": null,
"e": 70299,
"s": 70257,
"text": "Product Development and Commercialization"
},
{
"code": null,
"e": 70318,
"s": 70299,
"text": "Returns Management"
},
{
"code": null,
"e": 70358,
"s": 70318,
"text": "SCM have multi-dimensional advantages −"
},
{
"code": null,
"e": 70377,
"s": 70358,
"text": "To the suppliers −"
},
{
"code": null,
"e": 70414,
"s": 70377,
"text": "Help in giving clear-cut instruction"
},
{
"code": null,
"e": 70453,
"s": 70414,
"text": "Online data transfer reduce paper work"
},
{
"code": null,
"e": 70473,
"s": 70453,
"text": "Inventory Economy −"
},
{
"code": null,
"e": 70493,
"s": 70473,
"text": "Inventory Economy −"
},
{
"code": null,
"e": 70524,
"s": 70493,
"text": "Low cost of handling inventory"
},
{
"code": null,
"e": 70555,
"s": 70524,
"text": "Low cost of handling inventory"
},
{
"code": null,
"e": 70629,
"s": 70555,
"text": "Low cost of stock outage by deciding optimum size of replenishment orders"
},
{
"code": null,
"e": 70703,
"s": 70629,
"text": "Low cost of stock outage by deciding optimum size of replenishment orders"
},
{
"code": null,
"e": 70765,
"s": 70703,
"text": "Achieve excellent logistical performance such as just in time"
},
{
"code": null,
"e": 70827,
"s": 70765,
"text": "Achieve excellent logistical performance such as just in time"
},
{
"code": null,
"e": 70848,
"s": 70827,
"text": "Distribution Point −"
},
{
"code": null,
"e": 70869,
"s": 70848,
"text": "Distribution Point −"
},
{
"code": null,
"e": 70975,
"s": 70869,
"text": "Satisfied distributor and whole seller ensure that the right products reach the right place at right time"
},
{
"code": null,
"e": 71081,
"s": 70975,
"text": "Satisfied distributor and whole seller ensure that the right products reach the right place at right time"
},
{
"code": null,
"e": 71130,
"s": 71081,
"text": "Clear business processes subject to fewer errors"
},
{
"code": null,
"e": 71179,
"s": 71130,
"text": "Clear business processes subject to fewer errors"
},
{
"code": null,
"e": 71222,
"s": 71179,
"text": "Easy accounting of stock and cost of stock"
},
{
"code": null,
"e": 71265,
"s": 71222,
"text": "Easy accounting of stock and cost of stock"
},
{
"code": null,
"e": 71286,
"s": 71265,
"text": "Channel Management −"
},
{
"code": null,
"e": 71307,
"s": 71286,
"text": "Channel Management −"
},
{
"code": null,
"e": 71382,
"s": 71307,
"text": "Reduce total number of transactions required to provide product assortment"
},
{
"code": null,
"e": 71457,
"s": 71382,
"text": "Reduce total number of transactions required to provide product assortment"
},
{
"code": null,
"e": 71532,
"s": 71457,
"text": "Organization is logically capable of performing customization requirements"
},
{
"code": null,
"e": 71607,
"s": 71532,
"text": "Organization is logically capable of performing customization requirements"
},
{
"code": null,
"e": 71661,
"s": 71607,
"text": "Financial management −\n\nLow cost\nRealistic analysis\n\n"
},
{
"code": null,
"e": 71684,
"s": 71661,
"text": "Financial management −"
},
{
"code": null,
"e": 71693,
"s": 71684,
"text": "Low cost"
},
{
"code": null,
"e": 71712,
"s": 71693,
"text": "Realistic analysis"
},
{
"code": null,
"e": 71738,
"s": 71712,
"text": "Operational performance −"
},
{
"code": null,
"e": 71764,
"s": 71738,
"text": "Operational performance −"
},
{
"code": null,
"e": 71808,
"s": 71764,
"text": "It involves delivery speed and consistency."
},
{
"code": null,
"e": 71828,
"s": 71808,
"text": "External customer −"
},
{
"code": null,
"e": 71848,
"s": 71828,
"text": "External customer −"
},
{
"code": null,
"e": 71906,
"s": 71848,
"text": "Conformance of product and services to their requirements"
},
{
"code": null,
"e": 71925,
"s": 71906,
"text": "Competitive prices"
},
{
"code": null,
"e": 71949,
"s": 71925,
"text": "Quality and reliability"
},
{
"code": null,
"e": 71958,
"s": 71949,
"text": "Delivery"
},
{
"code": null,
"e": 71979,
"s": 71958,
"text": "After sales services"
},
{
"code": null,
"e": 72017,
"s": 71979,
"text": "To employees and internal customers −"
},
{
"code": null,
"e": 72055,
"s": 72017,
"text": "To employees and internal customers −"
},
{
"code": null,
"e": 72080,
"s": 72055,
"text": "Teamwork and cooperation"
},
{
"code": null,
"e": 72111,
"s": 72080,
"text": "Efficient structure and system"
},
{
"code": null,
"e": 72124,
"s": 72111,
"text": "Quality work"
},
{
"code": null,
"e": 72133,
"s": 72124,
"text": "Delivery"
},
{
"code": null,
"e": 72275,
"s": 72133,
"text": "Strategic planning for an organization involves long-term policy decisions, like location of a new plant, a new product, diversification etc."
},
{
"code": null,
"e": 72320,
"s": 72275,
"text": "Strategic planning is mostly influenced by −"
},
{
"code": null,
"e": 72391,
"s": 72320,
"text": "Decision of diversification i.e., expansion or integration of business"
},
{
"code": null,
"e": 72426,
"s": 72391,
"text": "Market dynamics, demand and supply"
},
{
"code": null,
"e": 72448,
"s": 72426,
"text": "Technological changes"
},
{
"code": null,
"e": 72467,
"s": 72448,
"text": "Competitive forces"
},
{
"code": null,
"e": 72519,
"s": 72467,
"text": "Various other threats, challenges and opportunities"
},
{
"code": null,
"e": 72769,
"s": 72519,
"text": "Strategic planning sets targets for the workings and references for taking such long-term policy decisions and transforms the business objectives into functional and operational units. Strategic planning generally follows one of the four-way paths −"
},
{
"code": null,
"e": 72794,
"s": 72769,
"text": "Overall Company Strategy"
},
{
"code": null,
"e": 72813,
"s": 72794,
"text": "Growth orientation"
},
{
"code": null,
"e": 72833,
"s": 72813,
"text": "Product orientation"
},
{
"code": null,
"e": 72852,
"s": 72833,
"text": "Market orientation"
},
{
"code": null,
"e": 72979,
"s": 72852,
"text": "In this chapter, let us discuss the Strategic Business Objectives of MIS with regards to the following aspects of a business −"
},
{
"code": null,
"e": 73002,
"s": 72979,
"text": "Operational Excellence"
},
{
"code": null,
"e": 73045,
"s": 73002,
"text": "New Products, Services and Business Models"
},
{
"code": null,
"e": 73074,
"s": 73045,
"text": "Services and Business Models"
},
{
"code": null,
"e": 73105,
"s": 73074,
"text": "Customer and Supplier Intimacy"
},
{
"code": null,
"e": 73130,
"s": 73105,
"text": "Improved Decision-making"
},
{
"code": null,
"e": 73166,
"s": 73130,
"text": "Competitive Advantage, and Survival"
},
{
"code": null,
"e": 73407,
"s": 73166,
"text": "This relates to achieving excellence in business in operations to achieve higher profitability. For example, a consumer goods manufacturer may decide upon using a wide distribution network to get maximum reach to the customers and exposure."
},
{
"code": null,
"e": 73498,
"s": 73407,
"text": "A manufacturing company may pursue a strategy of aggressive marketing and mass production."
},
{
"code": null,
"e": 73680,
"s": 73498,
"text": "This is part of growth strategy of an organization. A new product or a new service introduced, with a very fast growth potential provides a mean for steady growth business turnover."
},
{
"code": null,
"e": 73932,
"s": 73680,
"text": "With the help of information technology, a company might even opt for an entirely new business model, which will allow it to establish, consolidate and maintain a leadership in the existing market as well as provide a competitive edge in the industry."
},
{
"code": null,
"e": 74083,
"s": 73932,
"text": "For example, a company selling low priced detergent may opt for producing higher range detergents for washing machines, washing soaps, and bath soaps."
},
{
"code": null,
"e": 74217,
"s": 74083,
"text": "It involves market strategies also that includes planning for distribution, advertisement, market research and other related aspects."
},
{
"code": null,
"e": 74426,
"s": 74217,
"text": "When a Business really knows their Customers and serves them well, 'the way they want to be served', the Customers generally respond by returning and buying more from the firm. It raises revenues and profits."
},
{
"code": null,
"e": 74635,
"s": 74426,
"text": "Likewise with Suppliers, the more a Business engages its Suppliers, the better the Suppliers can provide vital information. This will lower the cost and bring huge improvements in the supply-chain management."
},
{
"code": null,
"e": 74796,
"s": 74635,
"text": "A very important pre-requisite of strategic planning is to provide the right information at the right time to the right person, for making an informed decision."
},
{
"code": null,
"e": 74962,
"s": 74796,
"text": "Well planned Information Systems and technologies make it possible for the decision makers to use real-time data from the marketplace when making informed decisions."
},
{
"code": null,
"e": 75075,
"s": 74962,
"text": "The following list illustrates some of the strategic planning that provides competitive advantage and survival −"
},
{
"code": null,
"e": 75123,
"s": 75075,
"text": "Planning for an overall growth for the company."
},
{
"code": null,
"e": 75171,
"s": 75123,
"text": "Planning for an overall growth for the company."
},
{
"code": null,
"e": 75255,
"s": 75171,
"text": "Thorough market research to understand the market dynamics involving demand-supply."
},
{
"code": null,
"e": 75339,
"s": 75255,
"text": "Thorough market research to understand the market dynamics involving demand-supply."
},
{
"code": null,
"e": 75412,
"s": 75339,
"text": "Various policies that will dominate the course and movement of business."
},
{
"code": null,
"e": 75485,
"s": 75412,
"text": "Various policies that will dominate the course and movement of business."
},
{
"code": null,
"e": 75539,
"s": 75485,
"text": "Expansion and diversification to conquer new markets."
},
{
"code": null,
"e": 75593,
"s": 75539,
"text": "Expansion and diversification to conquer new markets."
},
{
"code": null,
"e": 75707,
"s": 75593,
"text": "Choosing a perfect product strategy that involves either expanding a family of products or an associated product."
},
{
"code": null,
"e": 75821,
"s": 75707,
"text": "Choosing a perfect product strategy that involves either expanding a family of products or an associated product."
},
{
"code": null,
"e": 75940,
"s": 75821,
"text": "Strategies for choosing the market, distribution, pricing, advertising, packing, and other market-oriented strategies."
},
{
"code": null,
"e": 76059,
"s": 75940,
"text": "Strategies for choosing the market, distribution, pricing, advertising, packing, and other market-oriented strategies."
},
{
"code": null,
"e": 76130,
"s": 76059,
"text": "Strategies driven by industry-level changes or Government regulations."
},
{
"code": null,
"e": 76201,
"s": 76130,
"text": "Strategies driven by industry-level changes or Government regulations."
},
{
"code": null,
"e": 76235,
"s": 76201,
"text": "Strategies for change management."
},
{
"code": null,
"e": 76269,
"s": 76235,
"text": "Strategies for change management."
},
{
"code": null,
"e": 76440,
"s": 76269,
"text": "Like any other product development, system development requires careful analysis and design before implementation. System development generally has the following phases −"
},
{
"code": null,
"e": 76497,
"s": 76440,
"text": "The project planning part involves the following steps −"
},
{
"code": null,
"e": 76532,
"s": 76497,
"text": "Reviewing various project requests"
},
{
"code": null,
"e": 76566,
"s": 76532,
"text": "Prioritizing the project requests"
},
{
"code": null,
"e": 76591,
"s": 76566,
"text": "Allocating the resources"
},
{
"code": null,
"e": 76632,
"s": 76591,
"text": "Identifying the project development team"
},
{
"code": null,
"e": 76689,
"s": 76632,
"text": "The techniques used in information system planning are −"
},
{
"code": null,
"e": 76713,
"s": 76689,
"text": "Critical Success Factor"
},
{
"code": null,
"e": 76738,
"s": 76713,
"text": "Business System Planning"
},
{
"code": null,
"e": 76756,
"s": 76738,
"text": "End/Mean Analysis"
},
{
"code": null,
"e": 76916,
"s": 76756,
"text": "The requirement analysis part involves understanding the goals, processes and the constraints of the system for which the information system is being designed."
},
{
"code": null,
"e": 77139,
"s": 76916,
"text": "It is basically an iterative process involving systematic investigation of the processes and requirements. The analyst creates a blueprint of the entire system in minute details, using various diagramming techniques like −"
},
{
"code": null,
"e": 77158,
"s": 77139,
"text": "Data flow diagrams"
},
{
"code": null,
"e": 77175,
"s": 77158,
"text": "Context diagrams"
},
{
"code": null,
"e": 77230,
"s": 77175,
"text": "Requirement analysis has the following sub-processes −"
},
{
"code": null,
"e": 77267,
"s": 77230,
"text": "Conducting preliminary investigation"
},
{
"code": null,
"e": 77307,
"s": 77267,
"text": "Performing detailed analysis activities"
},
{
"code": null,
"e": 77331,
"s": 77307,
"text": "Studying current system"
},
{
"code": null,
"e": 77361,
"s": 77331,
"text": "Determining user requirements"
},
{
"code": null,
"e": 77385,
"s": 77361,
"text": "Recommending a solution"
},
{
"code": null,
"e": 77498,
"s": 77385,
"text": "The requirement analysis stage generally completes by creation of a 'Feasibility Report'. This report contains −"
},
{
"code": null,
"e": 77509,
"s": 77498,
"text": "A preamble"
},
{
"code": null,
"e": 77526,
"s": 77509,
"text": "A goal statement"
},
{
"code": null,
"e": 77568,
"s": 77526,
"text": "A brief description of the present system"
},
{
"code": null,
"e": 77601,
"s": 77568,
"text": "Proposed alternatives in details"
},
{
"code": null,
"e": 77702,
"s": 77601,
"text": "The feasibility report and the proposed alternatives help in preparing the costs and benefits study."
},
{
"code": null,
"e": 77910,
"s": 77702,
"text": "Based on the costs and benefits, and considering all problems that may be encountered due to human, organizational or technological bottlenecks, the best alternative is chosen by the end-users of the system."
},
{
"code": null,
"e": 78166,
"s": 77910,
"text": "System design specifies how the system will accomplish this objective. System design consists of both logical design and physical design activity, which produces 'system specification' satisfying system requirements developed in the system analysis stage."
},
{
"code": null,
"e": 78220,
"s": 78166,
"text": "In this stage, the following documents are prepared −"
},
{
"code": null,
"e": 78243,
"s": 78220,
"text": "Detailed specification"
},
{
"code": null,
"e": 78266,
"s": 78243,
"text": "Hardware/software plan"
},
{
"code": null,
"e": 78523,
"s": 78266,
"text": "The most creative and challenging phase of the system life cycle is system design, which refers to the technical specifications that will be applied in implementing the candidate system. It also includes the construction of programmers and program testing."
},
{
"code": null,
"e": 78553,
"s": 78523,
"text": "It has the following stages −"
},
{
"code": null,
"e": 78599,
"s": 78553,
"text": "Acquiring hardware and software, if necessary"
},
{
"code": null,
"e": 78615,
"s": 78599,
"text": "Database design"
},
{
"code": null,
"e": 78643,
"s": 78615,
"text": "Developing system processes"
},
{
"code": null,
"e": 78674,
"s": 78643,
"text": "Coding and testing each module"
},
{
"code": null,
"e": 79010,
"s": 78674,
"text": "The final report prior to implementation phase includes procedural flowcharts, record layout, report layout and plan for implementing the candidate system. Information on personnel, money, hardware, facility and their estimated cost must also be available. At this point projected cost must be close to actual cost of implementation."
},
{
"code": null,
"e": 79261,
"s": 79010,
"text": "System testing requires a test plan that consists of several key activities and steps for programs, strings, system, and user acceptance testing. The system performance criteria deals with turnaround time,backup,file protection and the human factors."
},
{
"code": null,
"e": 79295,
"s": 79261,
"text": "Testing process focuses on both −"
},
{
"code": null,
"e": 79385,
"s": 79295,
"text": "The internal logic of the system/software, ensuring that all statements have been tested;"
},
{
"code": null,
"e": 79475,
"s": 79385,
"text": "The internal logic of the system/software, ensuring that all statements have been tested;"
},
{
"code": null,
"e": 79614,
"s": 79475,
"text": "The external functions, by conducting tests to find errors and ensuring that the defined input will actually produce the required results."
},
{
"code": null,
"e": 79753,
"s": 79614,
"text": "The external functions, by conducting tests to find errors and ensuring that the defined input will actually produce the required results."
},
{
"code": null,
"e": 79976,
"s": 79753,
"text": "In some cases, a 'parallel run' of the new system is performed, where both the current and the proposed system are run in parallel for a specified time period and the current system is used to validate the proposed system."
},
{
"code": null,
"e": 80247,
"s": 79976,
"text": "At this stage, system is put into production to be used by the end users. Sometime, we put system into a Beta stage where users' feedback is received and based on the feedback, the system is corrected or improved before a final release or official release of the system."
},
{
"code": null,
"e": 80627,
"s": 80247,
"text": "Maintenance is necessary to eliminate the errors in the working system during its working life and to tune the system to any variation in its working environment. Often small system deficiencies are found, as system is brought into operation and changes are made to remove them. System planner must always plan for resources availability to carry on these maintenance functions."
},
{
"code": null,
"e": 80874,
"s": 80627,
"text": "In MIS, the information is recognized as a major resource like capital and time. If this resource has to be managed well, it calls upon the management to plan for it and control it, so that the information becomes a vital resource for the system."
},
{
"code": null,
"e": 80929,
"s": 80874,
"text": "The management information system needs good planning."
},
{
"code": null,
"e": 80984,
"s": 80929,
"text": "The management information system needs good planning."
},
{
"code": null,
"e": 81072,
"s": 80984,
"text": "This system should deal with the management information not with data processing alone."
},
{
"code": null,
"e": 81160,
"s": 81072,
"text": "This system should deal with the management information not with data processing alone."
},
{
"code": null,
"e": 81243,
"s": 81160,
"text": "It should provide support for the management planning, decision-making and action."
},
{
"code": null,
"e": 81326,
"s": 81243,
"text": "It should provide support for the management planning, decision-making and action."
},
{
"code": null,
"e": 81398,
"s": 81326,
"text": "It should provide support to the changing needs of business management."
},
{
"code": null,
"e": 81470,
"s": 81398,
"text": "It should provide support to the changing needs of business management."
},
{
"code": null,
"e": 81515,
"s": 81470,
"text": "Major challenges in MIS implementation are −"
},
{
"code": null,
"e": 81620,
"s": 81515,
"text": "Quantity, content and context of information − how much information and exactly what should it describe."
},
{
"code": null,
"e": 81725,
"s": 81620,
"text": "Quantity, content and context of information − how much information and exactly what should it describe."
},
{
"code": null,
"e": 81797,
"s": 81725,
"text": "Nature of analysis and presentation − comprehensibility of information."
},
{
"code": null,
"e": 81869,
"s": 81797,
"text": "Nature of analysis and presentation − comprehensibility of information."
},
{
"code": null,
"e": 82022,
"s": 81869,
"text": "Availability of information − frequency, contemporariness, on-demand or routine, periodic or occasional, one-time info or repetitive in nature and so on"
},
{
"code": null,
"e": 82175,
"s": 82022,
"text": "Availability of information − frequency, contemporariness, on-demand or routine, periodic or occasional, one-time info or repetitive in nature and so on"
},
{
"code": null,
"e": 82200,
"s": 82175,
"text": "Accuracy of information."
},
{
"code": null,
"e": 82225,
"s": 82200,
"text": "Accuracy of information."
},
{
"code": null,
"e": 82253,
"s": 82225,
"text": "Reliability of information."
},
{
"code": null,
"e": 82281,
"s": 82253,
"text": "Reliability of information."
},
{
"code": null,
"e": 82324,
"s": 82281,
"text": "Security and Authentication of the system."
},
{
"code": null,
"e": 82367,
"s": 82324,
"text": "Security and Authentication of the system."
},
{
"code": null,
"e": 82453,
"s": 82367,
"text": "MIS design and development process has to address the following issues successfully −"
},
{
"code": null,
"e": 82541,
"s": 82453,
"text": "There should be effective communication between the developers and users of the system."
},
{
"code": null,
"e": 82629,
"s": 82541,
"text": "There should be effective communication between the developers and users of the system."
},
{
"code": null,
"e": 82753,
"s": 82629,
"text": "There should be synchronization in understanding of management, processes and IT among the users as well as the developers."
},
{
"code": null,
"e": 82877,
"s": 82753,
"text": "There should be synchronization in understanding of management, processes and IT among the users as well as the developers."
},
{
"code": null,
"e": 83019,
"s": 82877,
"text": "Understanding of the information needs of managers from different functional areas and combining these needs into a single integrated system."
},
{
"code": null,
"e": 83161,
"s": 83019,
"text": "Understanding of the information needs of managers from different functional areas and combining these needs into a single integrated system."
},
{
"code": null,
"e": 83340,
"s": 83161,
"text": "Creating a unified MIS covering the entire organization will lead to a more economical, faster and more integrated system, however it will increase in design complexity manifold."
},
{
"code": null,
"e": 83519,
"s": 83340,
"text": "Creating a unified MIS covering the entire organization will lead to a more economical, faster and more integrated system, however it will increase in design complexity manifold."
},
{
"code": null,
"e": 83781,
"s": 83519,
"text": "The MIS has to be interacting with the complex environment comprising all other sub-systems in the overall information system of the organization. So, it is extremely necessary to understand and define the requirements of MIS in the context of the organization."
},
{
"code": null,
"e": 84043,
"s": 83781,
"text": "The MIS has to be interacting with the complex environment comprising all other sub-systems in the overall information system of the organization. So, it is extremely necessary to understand and define the requirements of MIS in the context of the organization."
},
{
"code": null,
"e": 84151,
"s": 84043,
"text": "It should keep pace with changes in environment, changing demands of the customers and growing competition."
},
{
"code": null,
"e": 84259,
"s": 84151,
"text": "It should keep pace with changes in environment, changing demands of the customers and growing competition."
},
{
"code": null,
"e": 84339,
"s": 84259,
"text": "It should utilize fast developing in IT capabilities in the best possible ways."
},
{
"code": null,
"e": 84419,
"s": 84339,
"text": "It should utilize fast developing in IT capabilities in the best possible ways."
},
{
"code": null,
"e": 84555,
"s": 84419,
"text": "Cost and time of installing such advanced IT-based systems is high, so there should not be a need for frequent and major modifications."
},
{
"code": null,
"e": 84691,
"s": 84555,
"text": "Cost and time of installing such advanced IT-based systems is high, so there should not be a need for frequent and major modifications."
},
{
"code": null,
"e": 84821,
"s": 84691,
"text": "It should take care of not only the users i.e., the managers but also other stakeholders like employees, customers and suppliers."
},
{
"code": null,
"e": 84951,
"s": 84821,
"text": "It should take care of not only the users i.e., the managers but also other stakeholders like employees, customers and suppliers."
},
{
"code": null,
"e": 85122,
"s": 84951,
"text": "Once the organizational planning stage is over, the designer of the system should take the following strategic decisions for the achievement of MIS goals and objectives −"
},
{
"code": null,
"e": 85183,
"s": 85122,
"text": "Development Strategy − Example - an online, real-time batch."
},
{
"code": null,
"e": 85244,
"s": 85183,
"text": "Development Strategy − Example - an online, real-time batch."
},
{
"code": null,
"e": 85389,
"s": 85244,
"text": "System Development Strategy − Designer selects an approach to system development like operational verses functional, accounting verses analysis."
},
{
"code": null,
"e": 85534,
"s": 85389,
"text": "System Development Strategy − Designer selects an approach to system development like operational verses functional, accounting verses analysis."
},
{
"code": null,
"e": 85673,
"s": 85534,
"text": "Resources for the Development − Designer has to select resources. Resources can be in-house verses external, customized or use of package."
},
{
"code": null,
"e": 85812,
"s": 85673,
"text": "Resources for the Development − Designer has to select resources. Resources can be in-house verses external, customized or use of package."
},
{
"code": null,
"e": 85885,
"s": 85812,
"text": "Manpower Composition − The staffs should have analysts, and programmers."
},
{
"code": null,
"e": 85958,
"s": 85885,
"text": "Manpower Composition − The staffs should have analysts, and programmers."
},
{
"code": null,
"e": 86009,
"s": 85958,
"text": "Information system planning essentially involves −"
},
{
"code": null,
"e": 86080,
"s": 86009,
"text": "Identification of the stage of information system in the organization."
},
{
"code": null,
"e": 86151,
"s": 86080,
"text": "Identification of the stage of information system in the organization."
},
{
"code": null,
"e": 86207,
"s": 86151,
"text": "Identification of the application of organizational IS."
},
{
"code": null,
"e": 86263,
"s": 86207,
"text": "Identification of the application of organizational IS."
},
{
"code": null,
"e": 86346,
"s": 86263,
"text": "Evolution of each of this application based on the established evolution criteria."
},
{
"code": null,
"e": 86429,
"s": 86346,
"text": "Evolution of each of this application based on the established evolution criteria."
},
{
"code": null,
"e": 86485,
"s": 86429,
"text": "Establishing a priority ranking for these applications."
},
{
"code": null,
"e": 86541,
"s": 86485,
"text": "Establishing a priority ranking for these applications."
},
{
"code": null,
"e": 86627,
"s": 86541,
"text": "Determining the optimum architecture of IS for serving the top priority applications."
},
{
"code": null,
"e": 86713,
"s": 86627,
"text": "Determining the optimum architecture of IS for serving the top priority applications."
},
{
"code": null,
"e": 86815,
"s": 86713,
"text": "The following diagram illustrates a brief sketch of the process of information requirement analysis −"
},
{
"code": null,
"e": 86963,
"s": 86815,
"text": "The following three methodologies can be adopted to determine the requirements in developing a management information system for any organization −"
},
{
"code": null,
"e": 87344,
"s": 86963,
"text": "Business Systems Planning (BSP) − this methodology is developed by IBM.\n\nIt identifies the IS priorities of the organization and focuses on the way data is maintained in the system.\nIt uses data architecture supporting multiple applications.\nIt defines data classes using different matrices to establish relationships among the organization, its processes and data requirements.\n\n"
},
{
"code": null,
"e": 87416,
"s": 87344,
"text": "Business Systems Planning (BSP) − this methodology is developed by IBM."
},
{
"code": null,
"e": 87525,
"s": 87416,
"text": "It identifies the IS priorities of the organization and focuses on the way data is maintained in the system."
},
{
"code": null,
"e": 87634,
"s": 87525,
"text": "It identifies the IS priorities of the organization and focuses on the way data is maintained in the system."
},
{
"code": null,
"e": 87694,
"s": 87634,
"text": "It uses data architecture supporting multiple applications."
},
{
"code": null,
"e": 87754,
"s": 87694,
"text": "It uses data architecture supporting multiple applications."
},
{
"code": null,
"e": 87891,
"s": 87754,
"text": "It defines data classes using different matrices to establish relationships among the organization, its processes and data requirements."
},
{
"code": null,
"e": 88028,
"s": 87891,
"text": "It defines data classes using different matrices to establish relationships among the organization, its processes and data requirements."
},
{
"code": null,
"e": 88386,
"s": 88028,
"text": "Critical Success Factor (CSF) − this methodology is developed by John Rockart of MIT.\n\nIt identifies the key business goals and strategies of each manager as well as that of the business.\nNext, it looks for the critical success factors underlying these goals.\nMeasure of CSF effectiveness becomes an input for defining the information system requirements.\n\n"
},
{
"code": null,
"e": 88472,
"s": 88386,
"text": "Critical Success Factor (CSF) − this methodology is developed by John Rockart of MIT."
},
{
"code": null,
"e": 88573,
"s": 88472,
"text": "It identifies the key business goals and strategies of each manager as well as that of the business."
},
{
"code": null,
"e": 88674,
"s": 88573,
"text": "It identifies the key business goals and strategies of each manager as well as that of the business."
},
{
"code": null,
"e": 88746,
"s": 88674,
"text": "Next, it looks for the critical success factors underlying these goals."
},
{
"code": null,
"e": 88818,
"s": 88746,
"text": "Next, it looks for the critical success factors underlying these goals."
},
{
"code": null,
"e": 88914,
"s": 88818,
"text": "Measure of CSF effectiveness becomes an input for defining the information system requirements."
},
{
"code": null,
"e": 89010,
"s": 88914,
"text": "Measure of CSF effectiveness becomes an input for defining the information system requirements."
},
{
"code": null,
"e": 89121,
"s": 89010,
"text": "End/Means (E/M) analysis − this methodology is developed by Wetherbe and Davis at the University of Minnesota."
},
{
"code": null,
"e": 89232,
"s": 89121,
"text": "End/Means (E/M) analysis − this methodology is developed by Wetherbe and Davis at the University of Minnesota."
},
{
"code": null,
"e": 89351,
"s": 89232,
"text": "It determines the effectiveness criteria for outputs and efficiency criteria for the processes generating the outputs."
},
{
"code": null,
"e": 89470,
"s": 89351,
"text": "It determines the effectiveness criteria for outputs and efficiency criteria for the processes generating the outputs."
},
{
"code": null,
"e": 89553,
"s": 89470,
"text": "At first it identifies the outputs or services provided by the business processes."
},
{
"code": null,
"e": 89636,
"s": 89553,
"text": "At first it identifies the outputs or services provided by the business processes."
},
{
"code": null,
"e": 89714,
"s": 89636,
"text": "Then it describes the factors that make these outputs effective for the user."
},
{
"code": null,
"e": 89792,
"s": 89714,
"text": "Then it describes the factors that make these outputs effective for the user."
},
{
"code": null,
"e": 89875,
"s": 89792,
"text": "Finally it selects the information needed to evaluate the effectiveness of outputs"
},
{
"code": null,
"e": 89958,
"s": 89875,
"text": "Finally it selects the information needed to evaluate the effectiveness of outputs"
},
{
"code": null,
"e": 90135,
"s": 89958,
"text": "System analysis and design follows the typical System/Software Design Life Cycle (SDLC) as discussed in the previous chapter. It generally passes through the following phases −"
},
{
"code": null,
"e": 90154,
"s": 90135,
"text": "Problem Definition"
},
{
"code": null,
"e": 90172,
"s": 90154,
"text": "Feasibility Study"
},
{
"code": null,
"e": 90189,
"s": 90172,
"text": "Systems Analysis"
},
{
"code": null,
"e": 90203,
"s": 90189,
"text": "System Design"
},
{
"code": null,
"e": 90226,
"s": 90203,
"text": "Detailed System Design"
},
{
"code": null,
"e": 90241,
"s": 90226,
"text": "Implementation"
},
{
"code": null,
"e": 90253,
"s": 90241,
"text": "Maintenance"
},
{
"code": null,
"e": 90321,
"s": 90253,
"text": "In the analysis phase, the following techniques are commonly used −"
},
{
"code": null,
"e": 90346,
"s": 90321,
"text": "Data flow diagrams (DFD)"
},
{
"code": null,
"e": 90361,
"s": 90346,
"text": "Logic Modeling"
},
{
"code": null,
"e": 90375,
"s": 90361,
"text": "Data Modeling"
},
{
"code": null,
"e": 90411,
"s": 90375,
"text": "Rapid Application Development (RAD)"
},
{
"code": null,
"e": 90442,
"s": 90411,
"text": "Object Oriented Analysis (OOA)"
},
{
"code": null,
"e": 90519,
"s": 90442,
"text": "The technology requirement for an information system can be categorized as −"
},
{
"code": null,
"e": 90527,
"s": 90519,
"text": "Devices"
},
{
"code": null,
"e": 90535,
"s": 90527,
"text": "Devices"
},
{
"code": null,
"e": 90688,
"s": 90535,
"text": "Data center systems − It is the environment that provides processing, storage, networking, management and the distribution of data within an enterprise."
},
{
"code": null,
"e": 90841,
"s": 90688,
"text": "Data center systems − It is the environment that provides processing, storage, networking, management and the distribution of data within an enterprise."
},
{
"code": null,
"e": 90996,
"s": 90841,
"text": "Enterprise software − These are software system like ERP, SCM, Human Resource Management, etc. that fulfill the needs and objectives of the organizations."
},
{
"code": null,
"e": 91151,
"s": 90996,
"text": "Enterprise software − These are software system like ERP, SCM, Human Resource Management, etc. that fulfill the needs and objectives of the organizations."
},
{
"code": null,
"e": 91418,
"s": 91151,
"text": "IT services − It refers to the implementation and management of quality IT services by IT service providers through people, process and information technology. It often includes various process improvement frameworks and methodologies like six sigma, TQM, and so on."
},
{
"code": null,
"e": 91685,
"s": 91418,
"text": "IT services − It refers to the implementation and management of quality IT services by IT service providers through people, process and information technology. It often includes various process improvement frameworks and methodologies like six sigma, TQM, and so on."
},
{
"code": null,
"e": 91702,
"s": 91685,
"text": "Telecom services"
},
{
"code": null,
"e": 91719,
"s": 91702,
"text": "Telecom services"
},
{
"code": null,
"e": 91796,
"s": 91719,
"text": "The system should be fully tested for errors before being fully operational."
},
{
"code": null,
"e": 91841,
"s": 91796,
"text": "The test plan should include for each test −"
},
{
"code": null,
"e": 91849,
"s": 91841,
"text": "Purpose"
},
{
"code": null,
"e": 91860,
"s": 91849,
"text": "Definition"
},
{
"code": null,
"e": 91872,
"s": 91860,
"text": "test inputs"
},
{
"code": null,
"e": 91913,
"s": 91872,
"text": "detailed specification of test procedure"
},
{
"code": null,
"e": 91941,
"s": 91913,
"text": "details of expected outputs"
},
{
"code": null,
"e": 92098,
"s": 91941,
"text": "Each sub-system and all their components should be tested using various test procedures and data to ensure that each component is working as it is intended."
},
{
"code": null,
"e": 92195,
"s": 92098,
"text": "The testing must include the users of the system to identify errors as well as get the feedback."
},
{
"code": null,
"e": 92277,
"s": 92195,
"text": "Before the system is in operation, the following issues should be taken care of −"
},
{
"code": null,
"e": 92313,
"s": 92277,
"text": "Data security, backup and recovery;"
},
{
"code": null,
"e": 92349,
"s": 92313,
"text": "Data security, backup and recovery;"
},
{
"code": null,
"e": 92366,
"s": 92349,
"text": "Systems control;"
},
{
"code": null,
"e": 92383,
"s": 92366,
"text": "Systems control;"
},
{
"code": null,
"e": 92475,
"s": 92383,
"text": "Testing of the system to ensure that it works bug-free in all expected business situations;"
},
{
"code": null,
"e": 92567,
"s": 92475,
"text": "Testing of the system to ensure that it works bug-free in all expected business situations;"
},
{
"code": null,
"e": 92649,
"s": 92567,
"text": "The hardware and software used should be able to deliver the expected processing;"
},
{
"code": null,
"e": 92731,
"s": 92649,
"text": "The hardware and software used should be able to deliver the expected processing;"
},
{
"code": null,
"e": 92800,
"s": 92731,
"text": "The system capacity and expected response time should be maintained;"
},
{
"code": null,
"e": 92869,
"s": 92800,
"text": "The system capacity and expected response time should be maintained;"
},
{
"code": null,
"e": 92917,
"s": 92869,
"text": "The system should be well documented including;"
},
{
"code": null,
"e": 92965,
"s": 92917,
"text": "The system should be well documented including;"
},
{
"code": null,
"e": 93003,
"s": 92965,
"text": "A user guide for inexperienced users,"
},
{
"code": null,
"e": 93041,
"s": 93003,
"text": "A user guide for inexperienced users,"
},
{
"code": null,
"e": 93099,
"s": 93041,
"text": "A user reference or operations manual for advanced users,"
},
{
"code": null,
"e": 93157,
"s": 93099,
"text": "A user reference or operations manual for advanced users,"
},
{
"code": null,
"e": 93230,
"s": 93157,
"text": "A system reference manual describing system structures and architecture."
},
{
"code": null,
"e": 93303,
"s": 93230,
"text": "A system reference manual describing system structures and architecture."
},
{
"code": null,
"e": 93519,
"s": 93303,
"text": "Once the system is fully operational, it should be maintained throughout its working life to resolve any glitches or difficulties faced in operation and minor modifications might be made to overcome such situations."
},
{
"code": null,
"e": 93672,
"s": 93519,
"text": "MIS development projects are high-risk, high-return projects. Following could be stated as critical factors for success and failure in MIS development −"
},
{
"code": null,
"e": 93728,
"s": 93672,
"text": "It should cater to a specific, well-perceived business."
},
{
"code": null,
"e": 93784,
"s": 93728,
"text": "It should cater to a specific, well-perceived business."
},
{
"code": null,
"e": 93954,
"s": 93784,
"text": "The top management should be completely convinced, able and willing to such a system. Ideally there should be a patron or a sponsor for the system in the top management."
},
{
"code": null,
"e": 94124,
"s": 93954,
"text": "The top management should be completely convinced, able and willing to such a system. Ideally there should be a patron or a sponsor for the system in the top management."
},
{
"code": null,
"e": 94264,
"s": 94124,
"text": "All users including managers and other employees should be made an integral part of the development, implementation, and use of the system."
},
{
"code": null,
"e": 94404,
"s": 94264,
"text": "All users including managers and other employees should be made an integral part of the development, implementation, and use of the system."
},
{
"code": null,
"e": 94525,
"s": 94404,
"text": "There should be an operational prototype of the system released as soon as possible, to create interest among the users."
},
{
"code": null,
"e": 94646,
"s": 94525,
"text": "There should be an operational prototype of the system released as soon as possible, to create interest among the users."
},
{
"code": null,
"e": 94743,
"s": 94646,
"text": "There should be good support staff with necessary technical, business, and interpersonal skills."
},
{
"code": null,
"e": 94840,
"s": 94743,
"text": "There should be good support staff with necessary technical, business, and interpersonal skills."
},
{
"code": null,
"e": 95011,
"s": 94840,
"text": "The system should be simple, easy to understand without adding much complexity. It is a best practice, not to add up an entity unless there is both a use and user for it."
},
{
"code": null,
"e": 95182,
"s": 95011,
"text": "The system should be simple, easy to understand without adding much complexity. It is a best practice, not to add up an entity unless there is both a use and user for it."
},
{
"code": null,
"e": 95245,
"s": 95182,
"text": "It should be easy to use and navigate with high response time."
},
{
"code": null,
"e": 95308,
"s": 95245,
"text": "It should be easy to use and navigate with high response time."
},
{
"code": null,
"e": 95375,
"s": 95308,
"text": "The implementation process should follow a definite goal and time."
},
{
"code": null,
"e": 95442,
"s": 95375,
"text": "The implementation process should follow a definite goal and time."
},
{
"code": null,
"e": 95721,
"s": 95442,
"text": "All the users including the top management should be given proper training, so that they have a good knowledge of the content and function of the system, and can use it fully for various managerial activities such as reporting, budgeting, controlling, planning, monitoring, etc."
},
{
"code": null,
"e": 96000,
"s": 95721,
"text": "All the users including the top management should be given proper training, so that they have a good knowledge of the content and function of the system, and can use it fully for various managerial activities such as reporting, budgeting, controlling, planning, monitoring, etc."
},
{
"code": null,
"e": 96059,
"s": 96000,
"text": "It must produce useful outputs to be used by all managers."
},
{
"code": null,
"e": 96118,
"s": 96059,
"text": "It must produce useful outputs to be used by all managers."
},
{
"code": null,
"e": 96231,
"s": 96118,
"text": "The system should be well integrated into the management processes of planning, decision-making, and monitoring."
},
{
"code": null,
"e": 96344,
"s": 96231,
"text": "The system should be well integrated into the management processes of planning, decision-making, and monitoring."
},
{
"code": null,
"e": 96472,
"s": 96344,
"text": "Decision-making is a cognitive process that results in the selection of a course of action among several alternative scenarios."
},
{
"code": null,
"e": 96654,
"s": 96472,
"text": "Decision-making is a daily activity for any human being. There is no exception about that. When it comes to business organizations, decision-making is a habit and a process as well."
},
{
"code": null,
"e": 96833,
"s": 96654,
"text": "Effective and successful decisions result in profits, while unsuccessful ones cause losses. Therefore, corporate decision-making is the most critical process in any organization."
},
{
"code": null,
"e": 97015,
"s": 96833,
"text": "In a decision-making process, we choose one course of action from a few possible alternatives. In the process of decision-making, we may use many tools, techniques, and perceptions."
},
{
"code": null,
"e": 97103,
"s": 97015,
"text": "In addition, we may make our own private decisions or may prefer a collective decision."
},
{
"code": null,
"e": 97239,
"s": 97103,
"text": "Usually, decision-making is hard. Majority of corporate decisions involve some level of dissatisfaction or conflict with another party."
},
{
"code": null,
"e": 97299,
"s": 97239,
"text": "Let's have a look at the decision-making process in detail."
},
{
"code": null,
"e": 97427,
"s": 97299,
"text": "Following are the important steps of the decision-making process. Each step may be supported by different tools and techniques."
},
{
"code": null,
"e": 97582,
"s": 97427,
"text": "In this step, the problem is thoroughly analyzed. There are a couple of questions one should ask when it comes to identifying the purpose of the decision."
},
{
"code": null,
"e": 97611,
"s": 97582,
"text": "What exactly is the problem?"
},
{
"code": null,
"e": 97645,
"s": 97611,
"text": "Why the problem should be solved?"
},
{
"code": null,
"e": 97690,
"s": 97645,
"text": "Who are the affected parties of the problem?"
},
{
"code": null,
"e": 97748,
"s": 97690,
"text": "Does the problem have a deadline or a specific time-line?"
},
{
"code": null,
"e": 97888,
"s": 97748,
"text": "A problem of an organization will have many stakeholders. In addition, there can be dozens of factors involved and affected by the problem."
},
{
"code": null,
"e": 98135,
"s": 97888,
"text": "In the process of solving the problem, you will have to gather as much as information related to the factors and stakeholders involved in the problem. For the process of information gathering, tools such as 'Check Sheets' can be effectively used."
},
{
"code": null,
"e": 98348,
"s": 98135,
"text": "In this step, the baseline criteria for judging the alternatives should be set up. When it comes to defining the criteria, organizational goals as well as the corporate culture should be taken into consideration."
},
{
"code": null,
"e": 98610,
"s": 98348,
"text": "As an example, profit is one of the main concerns in every decision making process. Companies usually do not make decisions that reduce profits, unless it is an exceptional case. Likewise, baseline principles should be identified related to the problem in hand."
},
{
"code": null,
"e": 98801,
"s": 98610,
"text": "For this step, brainstorming to list down all the ideas is the best option. Before the idea generation step, it is vital to understand the causes of the problem and prioritization of causes."
},
{
"code": null,
"e": 99052,
"s": 98801,
"text": "For this, you can make use of Cause-and-Effect diagrams and Pareto Chart tool. Cause-and-Effect diagram helps you to identify all possible causes of the problem and Pareto chart helps you to prioritize and identify the causes with the highest effect."
},
{
"code": null,
"e": 99148,
"s": 99052,
"text": "Then, you can move on generating all possible solutions (alternatives) for the problem in hand."
},
{
"code": null,
"e": 99394,
"s": 99148,
"text": "Use your judgment principles and decision-making criteria to evaluate each alternative. In this step, experience and effectiveness of the judgment principles come into play. You need to compare each alternative for their positives and negatives."
},
{
"code": null,
"e": 99620,
"s": 99394,
"text": "Once you go through from Step 1 to Step 5, this step is easy. In addition, the selection of the best alternative is an informed decision since you have already followed a methodology to derive and select the best alternative."
},
{
"code": null,
"e": 99747,
"s": 99620,
"text": "Convert your decision into a plan or a sequence of activities. Execute your plan by yourself or with the help of subordinates."
},
{
"code": null,
"e": 99958,
"s": 99747,
"text": "Evaluate the outcome of your decision. See whether there is anything you should learn and then correct in future decision making. This is one of the best practices that will improve your decision-making skills."
},
{
"code": null,
"e": 100006,
"s": 99958,
"text": "There are two basic models in decision-making −"
},
{
"code": null,
"e": 100022,
"s": 100006,
"text": "Rational models"
},
{
"code": null,
"e": 100038,
"s": 100022,
"text": "Normative model"
},
{
"code": null,
"e": 100303,
"s": 100038,
"text": "The rational models are based on cognitive judgments and help in selecting the most logical and sensible alternative. Examples of such models include - decision matrix analysis, Pugh matrix, SWOT analysis, Pareto analysis and decision trees, selection matrix, etc."
},
{
"code": null,
"e": 100364,
"s": 100303,
"text": "A rational decision making model takes the following steps −"
},
{
"code": null,
"e": 100389,
"s": 100364,
"text": "Identifying the problem,"
},
{
"code": null,
"e": 100414,
"s": 100389,
"text": "Identifying the problem,"
},
{
"code": null,
"e": 100481,
"s": 100414,
"text": "Identifying the important criteria for the process and the result,"
},
{
"code": null,
"e": 100548,
"s": 100481,
"text": "Identifying the important criteria for the process and the result,"
},
{
"code": null,
"e": 100584,
"s": 100548,
"text": "Considering all possible solutions,"
},
{
"code": null,
"e": 100620,
"s": 100584,
"text": "Considering all possible solutions,"
},
{
"code": null,
"e": 100724,
"s": 100620,
"text": "Calculating the consequences of all solutions and comparing the probability of satisfying the criteria,"
},
{
"code": null,
"e": 100828,
"s": 100724,
"text": "Calculating the consequences of all solutions and comparing the probability of satisfying the criteria,"
},
{
"code": null,
"e": 100855,
"s": 100828,
"text": "Selecting the best option."
},
{
"code": null,
"e": 100882,
"s": 100855,
"text": "Selecting the best option."
},
{
"code": null,
"e": 101047,
"s": 100882,
"text": "The normative model of decision-making considers constraints that may arise in making decisions, such as time, complexity, uncertainty, and inadequacy of resources."
},
{
"code": null,
"e": 101110,
"s": 101047,
"text": "According to this model, decision-making is characterized by −"
},
{
"code": null,
"e": 101201,
"s": 101110,
"text": "Limited information processing - A person can manage only a limited amount of information."
},
{
"code": null,
"e": 101292,
"s": 101201,
"text": "Limited information processing - A person can manage only a limited amount of information."
},
{
"code": null,
"e": 101384,
"s": 101292,
"text": "Judgmental heuristics - A person may use shortcuts to simplify the decision making process."
},
{
"code": null,
"e": 101476,
"s": 101384,
"text": "Judgmental heuristics - A person may use shortcuts to simplify the decision making process."
},
{
"code": null,
"e": 101548,
"s": 101476,
"text": "Satisfying - A person may choose a solution that is just \"good enough\"."
},
{
"code": null,
"e": 101620,
"s": 101548,
"text": "Satisfying - A person may choose a solution that is just \"good enough\"."
},
{
"code": null,
"e": 101884,
"s": 101620,
"text": "Dynamic decision-making (DDM) is synergetic decision-making involving interdependent systems, in an environment that changes over time either due to the previous actions of the decision-maker or due to events that are outside of the control of the decision-maker."
},
{
"code": null,
"e": 101939,
"s": 101884,
"text": "These decision-makings are more complex and real-time."
},
{
"code": null,
"e": 102098,
"s": 101939,
"text": "Dynamic decision-making involves observing how people used their experience to control the system's dynamics and noting down the best decisions taken thereon."
},
{
"code": null,
"e": 102273,
"s": 102098,
"text": "Sensitivity analysis is a technique used for distributing the uncertainty in the output of a mathematical model or a system to different sources of uncertainty in its inputs."
},
{
"code": null,
"e": 102611,
"s": 102273,
"text": "From business decision perspective, the sensitivity analysis helps an analyst to identify cost drivers as well as other quantities to make an informed decision. If a particular quantity has no bearing on a decision or prediction, then the conditions relating to quantity could be eliminated, thus simplifying the decision making process."
},
{
"code": null,
"e": 102676,
"s": 102611,
"text": "Sensitivity analysis also helps in some other situations, like −"
},
{
"code": null,
"e": 102698,
"s": 102676,
"text": "Resource optimization"
},
{
"code": null,
"e": 102722,
"s": 102698,
"text": "Future data collections"
},
{
"code": null,
"e": 102755,
"s": 102722,
"text": "Identifying critical assumptions"
},
{
"code": null,
"e": 102803,
"s": 102755,
"text": "To optimize the tolerance of manufactured parts"
},
{
"code": null,
"e": 102862,
"s": 102803,
"text": "Show the value of various attributes in a balanced system."
},
{
"code": null,
"e": 102921,
"s": 102862,
"text": "Show the value of various attributes in a balanced system."
},
{
"code": null,
"e": 102950,
"s": 102921,
"text": "Work best in static systems."
},
{
"code": null,
"e": 102979,
"s": 102950,
"text": "Work best in static systems."
},
{
"code": null,
"e": 103036,
"s": 102979,
"text": "Do not take into consideration the time-based variances."
},
{
"code": null,
"e": 103093,
"s": 103036,
"text": "Do not take into consideration the time-based variances."
},
{
"code": null,
"e": 103193,
"s": 103093,
"text": "Do not work well in real-time systems however, it may work in a dynamic system being in equilibrium"
},
{
"code": null,
"e": 103293,
"s": 103193,
"text": "Do not work well in real-time systems however, it may work in a dynamic system being in equilibrium"
},
{
"code": null,
"e": 103312,
"s": 103293,
"text": "Involve less data."
},
{
"code": null,
"e": 103331,
"s": 103312,
"text": "Involve less data."
},
{
"code": null,
"e": 103352,
"s": 103331,
"text": "Are easy to analyze."
},
{
"code": null,
"e": 103373,
"s": 103352,
"text": "Are easy to analyze."
},
{
"code": null,
"e": 103397,
"s": 103373,
"text": "Produce faster results."
},
{
"code": null,
"e": 103421,
"s": 103397,
"text": "Produce faster results."
},
{
"code": null,
"e": 103438,
"s": 103421,
"text": "Dynamic models −"
},
{
"code": null,
"e": 103484,
"s": 103438,
"text": "Consider the change in data values over time."
},
{
"code": null,
"e": 103530,
"s": 103484,
"text": "Consider effect of system behavior over time."
},
{
"code": null,
"e": 103570,
"s": 103530,
"text": "Re-calculate equations as time changes."
},
{
"code": null,
"e": 103610,
"s": 103570,
"text": "Can be applied only in dynamic systems."
},
{
"code": null,
"e": 103853,
"s": 103610,
"text": "Simulation is a technique that imitates the operation of a real-world process or system over time. Simulation techniques can be used to assist management decision making, where analytical methods are either not available or cannot be applied."
},
{
"code": null,
"e": 103939,
"s": 103853,
"text": "Some of the typical business problem areas where simulation techniques are used are −"
},
{
"code": null,
"e": 103957,
"s": 103939,
"text": "Inventory control"
},
{
"code": null,
"e": 103973,
"s": 103957,
"text": "Queuing problem"
},
{
"code": null,
"e": 103993,
"s": 103973,
"text": "Production planning"
},
{
"code": null,
"e": 104189,
"s": 103993,
"text": "Operational Research (OR) includes a wide range of problem-solving techniques involving various advanced analytical models and methods applied. It helps in efficient and improved decision-making."
},
{
"code": null,
"e": 104441,
"s": 104189,
"text": "It encompasses techniques such as simulation, mathematical optimization, queuing theory, stochastic-process models, econometric methods, data envelopment analysis, neural networks, expert systems, decision analysis, and the analytic hierarchy process."
},
{
"code": null,
"e": 104514,
"s": 104441,
"text": "OR techniques describe a system by constructing its mathematical models."
},
{
"code": null,
"e": 104641,
"s": 104514,
"text": "Heuristic programming refers to a branch of artificial intelligence. It consists of programs that are self-learning in nature."
},
{
"code": null,
"e": 104753,
"s": 104641,
"text": "However, these programs are not optimal in nature, as they are experience-based techniques for problem solving."
},
{
"code": null,
"e": 104829,
"s": 104753,
"text": "Most basic heuristic programs would be based on pure 'trial-error' methods."
},
{
"code": null,
"e": 104965,
"s": 104829,
"text": "Heuristics take a 'guess' approach to problem solving, yielding a 'good enough' answer, rather than finding a 'best possible' solution."
},
{
"code": null,
"e": 105066,
"s": 104965,
"text": "In group decision-making, various individuals in a group take part in collaborative decision-making."
},
{
"code": null,
"e": 105420,
"s": 105066,
"text": "Group Decision Support System (GDSS) is a decision support system that provides support in decision making by a group of people. It facilitates the free flow and exchange of ideas and information among the group members. Decisions are made with a higher degree of consensus and agreement resulting in a dramatically higher likelihood of implementation."
},
{
"code": null,
"e": 105480,
"s": 105420,
"text": "Following are the available types of computer based GDSSs −"
},
{
"code": null,
"e": 105684,
"s": 105480,
"text": "Decision Network − This type helps the participants to communicate with each other through a network or through a central database. Application software may use commonly shared models to provide support."
},
{
"code": null,
"e": 105888,
"s": 105684,
"text": "Decision Network − This type helps the participants to communicate with each other through a network or through a central database. Application software may use commonly shared models to provide support."
},
{
"code": null,
"e": 106100,
"s": 105888,
"text": "Decision Room − Participants are located at one place, i.e. the decision room. The purpose of this is to enhance participant's interactions and decision-making within a fixed period of time using a facilitator."
},
{
"code": null,
"e": 106312,
"s": 106100,
"text": "Decision Room − Participants are located at one place, i.e. the decision room. The purpose of this is to enhance participant's interactions and decision-making within a fixed period of time using a facilitator."
},
{
"code": null,
"e": 106585,
"s": 106312,
"text": "Teleconferencing − Groups are composed of members or sub groups that are geographically dispersed; teleconferencing provides interactive connection between two or more decision rooms. This interaction will involve transmission of computerized and audio visual information."
},
{
"code": null,
"e": 106858,
"s": 106585,
"text": "Teleconferencing − Groups are composed of members or sub groups that are geographically dispersed; teleconferencing provides interactive connection between two or more decision rooms. This interaction will involve transmission of computerized and audio visual information."
},
{
"code": null,
"e": 107046,
"s": 106858,
"text": "Information system security refers to the way the system is defended against unauthorized access, use, disclosure, disruption, modification, perusal, inspection, recording or destruction."
},
{
"code": null,
"e": 107107,
"s": 107046,
"text": "There are two major aspects of information system security −"
},
{
"code": null,
"e": 107321,
"s": 107107,
"text": "Security of the information technology used − securing the system from malicious cyber-attacks that tend to break into the system and to access critical private information or gain control of the internal systems."
},
{
"code": null,
"e": 107535,
"s": 107321,
"text": "Security of the information technology used − securing the system from malicious cyber-attacks that tend to break into the system and to access critical private information or gain control of the internal systems."
},
{
"code": null,
"e": 107753,
"s": 107535,
"text": "Security of data − ensuring the integrity of data when critical issues, arise such as natural disasters, computer/server malfunction, physical theft etc. Generally an off-site backup of data is kept for such problems."
},
{
"code": null,
"e": 107971,
"s": 107753,
"text": "Security of data − ensuring the integrity of data when critical issues, arise such as natural disasters, computer/server malfunction, physical theft etc. Generally an off-site backup of data is kept for such problems."
},
{
"code": null,
"e": 108047,
"s": 107971,
"text": "Guaranteeing effective information security has the following key aspects −"
},
{
"code": null,
"e": 108130,
"s": 108047,
"text": "Preventing the unauthorized individuals or systems from accessing the information."
},
{
"code": null,
"e": 108213,
"s": 108130,
"text": "Preventing the unauthorized individuals or systems from accessing the information."
},
{
"code": null,
"e": 108303,
"s": 108213,
"text": "Maintaining and assuring the accuracy and consistency of data over its entire life-cycle."
},
{
"code": null,
"e": 108393,
"s": 108303,
"text": "Maintaining and assuring the accuracy and consistency of data over its entire life-cycle."
},
{
"code": null,
"e": 108610,
"s": 108393,
"text": "Ensuring that the computing systems, the security controls used to protect it and the communication channels used to access it, functioning correctly all the time, thus making information available in all situations."
},
{
"code": null,
"e": 108827,
"s": 108610,
"text": "Ensuring that the computing systems, the security controls used to protect it and the communication channels used to access it, functioning correctly all the time, thus making information available in all situations."
},
{
"code": null,
"e": 108906,
"s": 108827,
"text": "Ensuring that the data, transactions, communications or documents are genuine."
},
{
"code": null,
"e": 108985,
"s": 108906,
"text": "Ensuring that the data, transactions, communications or documents are genuine."
},
{
"code": null,
"e": 109150,
"s": 108985,
"text": "Ensuring the integrity of a transaction by validating that both parties involved are genuine, by incorporating authentication features such as \"digital signatures\"."
},
{
"code": null,
"e": 109315,
"s": 109150,
"text": "Ensuring the integrity of a transaction by validating that both parties involved are genuine, by incorporating authentication features such as \"digital signatures\"."
},
{
"code": null,
"e": 109496,
"s": 109315,
"text": "Ensuring that once a transaction takes place, none of the parties can deny it, either having received a transaction, or having sent a transaction. This is called 'non-repudiation'."
},
{
"code": null,
"e": 109677,
"s": 109496,
"text": "Ensuring that once a transaction takes place, none of the parties can deny it, either having received a transaction, or having sent a transaction. This is called 'non-repudiation'."
},
{
"code": null,
"e": 109752,
"s": 109677,
"text": "Safeguarding data and communications stored and shared in network systems."
},
{
"code": null,
"e": 109827,
"s": 109752,
"text": "Safeguarding data and communications stored and shared in network systems."
},
{
"code": null,
"e": 110019,
"s": 109827,
"text": "Information systems bring about immense social changes, threatening the existing distributions of power, money, rights, and obligations. It also raises new kinds of crimes, like cyber-crimes."
},
{
"code": null,
"e": 110068,
"s": 110019,
"text": "Following organizations promote ethical issues −"
},
{
"code": null,
"e": 110131,
"s": 110068,
"text": "The Association of Information Technology Professionals (AITP)"
},
{
"code": null,
"e": 110194,
"s": 110131,
"text": "The Association of Information Technology Professionals (AITP)"
},
{
"code": null,
"e": 110239,
"s": 110194,
"text": "The Association of Computing Machinery (ACM)"
},
{
"code": null,
"e": 110284,
"s": 110239,
"text": "The Association of Computing Machinery (ACM)"
},
{
"code": null,
"e": 110345,
"s": 110284,
"text": "The Institute of Electrical and Electronics Engineers (IEEE)"
},
{
"code": null,
"e": 110406,
"s": 110345,
"text": "The Institute of Electrical and Electronics Engineers (IEEE)"
},
{
"code": null,
"e": 110462,
"s": 110406,
"text": "Computer Professionals for Social Responsibility (CPSR)"
},
{
"code": null,
"e": 110518,
"s": 110462,
"text": "Computer Professionals for Social Responsibility (CPSR)"
},
{
"code": null,
"e": 110639,
"s": 110518,
"text": "Strive to achieve the highest quality, effectiveness, and dignity in both the process and products of professional work."
},
{
"code": null,
"e": 110760,
"s": 110639,
"text": "Strive to achieve the highest quality, effectiveness, and dignity in both the process and products of professional work."
},
{
"code": null,
"e": 110806,
"s": 110760,
"text": "Acquire and maintain professional competence."
},
{
"code": null,
"e": 110852,
"s": 110806,
"text": "Acquire and maintain professional competence."
},
{
"code": null,
"e": 110916,
"s": 110852,
"text": "Know and respect existing laws pertaining to professional work."
},
{
"code": null,
"e": 110980,
"s": 110916,
"text": "Know and respect existing laws pertaining to professional work."
},
{
"code": null,
"e": 111032,
"s": 110980,
"text": "Accept and provide appropriate professional review."
},
{
"code": null,
"e": 111084,
"s": 111032,
"text": "Accept and provide appropriate professional review."
},
{
"code": null,
"e": 111206,
"s": 111084,
"text": "Give comprehensive and thorough evaluations of computer systems and their impacts, including analysis and possible risks."
},
{
"code": null,
"e": 111328,
"s": 111206,
"text": "Give comprehensive and thorough evaluations of computer systems and their impacts, including analysis and possible risks."
},
{
"code": null,
"e": 111388,
"s": 111328,
"text": "Honor contracts, agreements, and assigned responsibilities."
},
{
"code": null,
"e": 111448,
"s": 111388,
"text": "Honor contracts, agreements, and assigned responsibilities."
},
{
"code": null,
"e": 111512,
"s": 111448,
"text": "Improve public understanding of computing and its consequences."
},
{
"code": null,
"e": 111576,
"s": 111512,
"text": "Improve public understanding of computing and its consequences."
},
{
"code": null,
"e": 111652,
"s": 111576,
"text": "Access computing and communication resources only when authorized to do so."
},
{
"code": null,
"e": 111728,
"s": 111652,
"text": "Access computing and communication resources only when authorized to do so."
},
{
"code": null,
"e": 111867,
"s": 111728,
"text": "IEEE code of ethics demands that every professional vouch to commit themselves to the highest ethical and professional conduct and agree −"
},
{
"code": null,
"e": 112058,
"s": 111867,
"text": "To accept responsibility in making decisions consistent with the safety, health and welfare of the public, and to disclose promptly factors that might endanger the public or the environment;"
},
{
"code": null,
"e": 112249,
"s": 112058,
"text": "To accept responsibility in making decisions consistent with the safety, health and welfare of the public, and to disclose promptly factors that might endanger the public or the environment;"
},
{
"code": null,
"e": 112378,
"s": 112249,
"text": "To avoid real or perceived conflicts of interest whenever possible, and to disclose them to affected parties when they do exist;"
},
{
"code": null,
"e": 112507,
"s": 112378,
"text": "To avoid real or perceived conflicts of interest whenever possible, and to disclose them to affected parties when they do exist;"
},
{
"code": null,
"e": 112590,
"s": 112507,
"text": "To be honest and realistic in stating claims or estimates based on available data;"
},
{
"code": null,
"e": 112673,
"s": 112590,
"text": "To be honest and realistic in stating claims or estimates based on available data;"
},
{
"code": null,
"e": 112709,
"s": 112673,
"text": "To reject bribery in all its forms;"
},
{
"code": null,
"e": 112745,
"s": 112709,
"text": "To reject bribery in all its forms;"
},
{
"code": null,
"e": 112846,
"s": 112745,
"text": "To improve the understanding of technology, its appropriate application, and potential consequences;"
},
{
"code": null,
"e": 112947,
"s": 112846,
"text": "To improve the understanding of technology, its appropriate application, and potential consequences;"
},
{
"code": null,
"e": 113140,
"s": 112947,
"text": "To maintain and improve our technical competence and to undertake technological tasks for others only if qualified by training or experience, or after full disclosure of pertinent limitations;"
},
{
"code": null,
"e": 113333,
"s": 113140,
"text": "To maintain and improve our technical competence and to undertake technological tasks for others only if qualified by training or experience, or after full disclosure of pertinent limitations;"
},
{
"code": null,
"e": 113483,
"s": 113333,
"text": "To seek, accept, and offer honest criticism of technical work, to acknowledge and correct errors, and to credit properly the contributions of others;"
},
{
"code": null,
"e": 113633,
"s": 113483,
"text": "To seek, accept, and offer honest criticism of technical work, to acknowledge and correct errors, and to credit properly the contributions of others;"
},
{
"code": null,
"e": 113752,
"s": 113633,
"text": "To treat fairly all persons regardless of such factors as race, religion, gender, disability, age, or national origin;"
},
{
"code": null,
"e": 113871,
"s": 113752,
"text": "To treat fairly all persons regardless of such factors as race, religion, gender, disability, age, or national origin;"
},
{
"code": null,
"e": 113969,
"s": 113871,
"text": "To avoid injuring others, their property, reputation, or employment by false or malicious action;"
},
{
"code": null,
"e": 114067,
"s": 113969,
"text": "To avoid injuring others, their property, reputation, or employment by false or malicious action;"
},
{
"code": null,
"e": 114191,
"s": 114067,
"text": "To assist colleagues and co-workers in their professional development and to support them in following this code of ethics."
},
{
"code": null,
"e": 114315,
"s": 114191,
"text": "To assist colleagues and co-workers in their professional development and to support them in following this code of ethics."
},
{
"code": null,
"e": 114428,
"s": 114315,
"text": "An efficient information system creates an impact on the organization's function, performance, and productivity."
},
{
"code": null,
"e": 114676,
"s": 114428,
"text": "Nowadays, information system and information technology have become a vital part of any successful business and is regarded as a major functional area like any other functional areas such as marketing, finance, production and human resources, etc."
},
{
"code": null,
"e": 114895,
"s": 114676,
"text": "Thus, it is important to understand the functions of an information system just like any other functional area in business. A well maintained management information system supports the organization at different levels."
},
{
"code": null,
"e": 115122,
"s": 114895,
"text": "Many firms are using information system that cross the boundaries of traditional business functions in order to re-engineer and improve vital business processes all across the enterprise. This typical has involved installing −"
},
{
"code": null,
"e": 115157,
"s": 115122,
"text": "Enterprise Resource Planning (ERP)"
},
{
"code": null,
"e": 115187,
"s": 115157,
"text": "Supply Chain Management (SCM)"
},
{
"code": null,
"e": 115226,
"s": 115187,
"text": "Customer Relationship Management (CRM)"
},
{
"code": null,
"e": 115262,
"s": 115226,
"text": "Transaction Processing System (TPS)"
},
{
"code": null,
"e": 115297,
"s": 115262,
"text": "Executive Information System (EIS)"
},
{
"code": null,
"e": 115327,
"s": 115297,
"text": "Decision Support System (DSS)"
},
{
"code": null,
"e": 115362,
"s": 115327,
"text": "Knowledge Management Systems (KMS)"
},
{
"code": null,
"e": 115395,
"s": 115362,
"text": "Content Management Systems (CMS)"
},
{
"code": null,
"e": 115614,
"s": 115395,
"text": "The strategic role of Management Information System involves using it to develop products, services, and capabilities that provides a company major advantages over competitive forces it faces in the global marketplace."
},
{
"code": null,
"e": 115885,
"s": 115614,
"text": "We need an MIS flexible enough to deal with changing information needs of the organization. The designing of such a system is a complex task. It can be achieved only if the MIS is planned. We understand this planning and implementation in management development process."
},
{
"code": null,
"e": 116086,
"s": 115885,
"text": "Decision support system is a major segment of organizational information system, because of its influential role in taking business decisions. It help all levels of managers to take various decisions."
},
{
"code": null,
"e": 116121,
"s": 116086,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 116139,
"s": 116121,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 116172,
"s": 116139,
"text": "\n 15 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 116178,
"s": 116172,
"text": " Ajay"
},
{
"code": null,
"e": 116211,
"s": 116178,
"text": "\n 15 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 116217,
"s": 116211,
"text": " Ajay"
},
{
"code": null,
"e": 116250,
"s": 116217,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 116268,
"s": 116250,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 116303,
"s": 116268,
"text": "\n 12 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 116321,
"s": 116303,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 116354,
"s": 116321,
"text": "\n 15 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 116360,
"s": 116354,
"text": " Ajay"
},
{
"code": null,
"e": 116367,
"s": 116360,
"text": " Print"
},
{
"code": null,
"e": 116378,
"s": 116367,
"text": " Add Notes"
}
]
|
Check given matrix is magic square or not in C++ | Here we will see, if a matrix is magic square or not, a magic square is a square matrix, where the sum of each row, each column, and each diagonal are same.
Suppose a matrix is like below −
This is a magic square, if we see, the sum of each row, column and diagonals are 15.
To check whether a matrix is magic square or not, we have to find the major diagonal sum and the secondary diagonal sum, if they are same, then that is magic square, otherwise not.
Live Demo
#include <iostream>
#define N 3
using namespace std;
bool isMagicSquare(int mat[][N]) {
int sum_diag = 0,sum_diag_second=0;
for (int i = 0; i < N; i++)
sum_diag = sum_diag + mat[i][i];
for (int i = 0; i < N; i++)
sum_diag_second = sum_diag_second + mat[i][N-1-i];
if(sum_diag!=sum_diag_second)
return false;
for (int i = 0; i < N; i++) {
int rowSum = 0;
for (int j = 0; j < N; j++)
rowSum += mat[i][j];
if (rowSum != sum_diag)
return false;
}
for (int i = 0; i < N; i++) {
int colSum = 0;
for (int j = 0; j < N; j++)
colSum += mat[j][i];
if (sum_diag != colSum)
return false;
}
return true;
}
int main() {
int mat[][N] = {{ 6, 1, 8 },
{ 7, 5, 3 },
{ 2, 9, 4 }};
if (isMagicSquare(mat))
cout << "It is Magic Square";
else
cout << "It is Not a magic Square";
}
It is Magic Square | [
{
"code": null,
"e": 1219,
"s": 1062,
"text": "Here we will see, if a matrix is magic square or not, a magic square is a square matrix, where the sum of each row, each column, and each diagonal are same."
},
{
"code": null,
"e": 1252,
"s": 1219,
"text": "Suppose a matrix is like below −"
},
{
"code": null,
"e": 1337,
"s": 1252,
"text": "This is a magic square, if we see, the sum of each row, column and diagonals are 15."
},
{
"code": null,
"e": 1518,
"s": 1337,
"text": "To check whether a matrix is magic square or not, we have to find the major diagonal sum and the secondary diagonal sum, if they are same, then that is magic square, otherwise not."
},
{
"code": null,
"e": 1529,
"s": 1518,
"text": " Live Demo"
},
{
"code": null,
"e": 2426,
"s": 1529,
"text": "#include <iostream>\n#define N 3\nusing namespace std;\nbool isMagicSquare(int mat[][N]) {\n int sum_diag = 0,sum_diag_second=0;\n for (int i = 0; i < N; i++)\n sum_diag = sum_diag + mat[i][i];\n for (int i = 0; i < N; i++)\n sum_diag_second = sum_diag_second + mat[i][N-1-i];\n if(sum_diag!=sum_diag_second)\n return false;\n for (int i = 0; i < N; i++) {\n int rowSum = 0;\n for (int j = 0; j < N; j++)\n rowSum += mat[i][j];\n if (rowSum != sum_diag)\n return false;\n }\n for (int i = 0; i < N; i++) {\n int colSum = 0;\n for (int j = 0; j < N; j++)\n colSum += mat[j][i];\n if (sum_diag != colSum)\n return false;\n }\n return true;\n}\nint main() {\n int mat[][N] = {{ 6, 1, 8 },\n { 7, 5, 3 },\n { 2, 9, 4 }};\n if (isMagicSquare(mat))\n cout << \"It is Magic Square\";\n else\n cout << \"It is Not a magic Square\";\n}"
},
{
"code": null,
"e": 2445,
"s": 2426,
"text": "It is Magic Square"
}
]
|
How to create a JMenuBar Component in Java? | To create a JMenuBar component, use the JMenuBar class −
JMenuBar menuBar = new JMenuBar();
Now, create menus inside the MenuBar −
JMenu fileMenu = new JMenu("File");
Add the above menu to the MenuBar −
menuBar.add(fileMenu);
The following is an example to create a JMenuBar Component in Java −
package my;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class SwingDemo {
public static void main(final String args[]) {
JFrame frame = new JFrame("MenuBar Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);
JMenuItem menuItem1 = new JMenuItem("New", KeyEvent.VK_N);
fileMenu.add(menuItem1);
JMenuItem menuItem2 = new JMenuItem("Open File", KeyEvent.VK_O);
fileMenu.add(menuItem2);
JMenu editMenu = new JMenu("Edit");
editMenu.setMnemonic(KeyEvent.VK_E);
menuBar.add(editMenu);
frame.setJMenuBar(menuBar);
frame.setSize(550, 350);
frame.setVisible(true);
}
} | [
{
"code": null,
"e": 1119,
"s": 1062,
"text": "To create a JMenuBar component, use the JMenuBar class −"
},
{
"code": null,
"e": 1154,
"s": 1119,
"text": "JMenuBar menuBar = new JMenuBar();"
},
{
"code": null,
"e": 1193,
"s": 1154,
"text": "Now, create menus inside the MenuBar −"
},
{
"code": null,
"e": 1229,
"s": 1193,
"text": "JMenu fileMenu = new JMenu(\"File\");"
},
{
"code": null,
"e": 1265,
"s": 1229,
"text": "Add the above menu to the MenuBar −"
},
{
"code": null,
"e": 1288,
"s": 1265,
"text": "menuBar.add(fileMenu);"
},
{
"code": null,
"e": 1357,
"s": 1288,
"text": "The following is an example to create a JMenuBar Component in Java −"
},
{
"code": null,
"e": 2266,
"s": 1357,
"text": "package my;\nimport java.awt.event.KeyEvent;\nimport javax.swing.JFrame;\nimport javax.swing.JMenu;\nimport javax.swing.JMenuBar;\nimport javax.swing.JMenuItem;\npublic class SwingDemo {\n public static void main(final String args[]) {\n JFrame frame = new JFrame(\"MenuBar Demo\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n JMenuBar menuBar = new JMenuBar();\n JMenu fileMenu = new JMenu(\"File\");\n fileMenu.setMnemonic(KeyEvent.VK_F);\n menuBar.add(fileMenu);\n JMenuItem menuItem1 = new JMenuItem(\"New\", KeyEvent.VK_N);\n fileMenu.add(menuItem1);\n JMenuItem menuItem2 = new JMenuItem(\"Open File\", KeyEvent.VK_O);\n fileMenu.add(menuItem2);\n JMenu editMenu = new JMenu(\"Edit\");\n editMenu.setMnemonic(KeyEvent.VK_E);\n menuBar.add(editMenu);\n frame.setJMenuBar(menuBar);\n frame.setSize(550, 350);\n frame.setVisible(true);\n }\n}"
}
]
|
I Used Code to Create Animation. Here’s How. | by Matt Przybyla | Towards Data Science | IntroductionProcessingCodingExampleSummaryReferences
Introduction
Processing
Coding
Example
Summary
References
From my article you will learn two main takeaways:
1. What the Processing software platform is.
2. How to execute code to create an entertaining and beautiful animation.
You do not need to be an expert coder or software developer to create awesome visualizations. In this tutorial and outline, there are several ways to show off what you can do with a little bit of code and a little bit of Processing magic. All of the principles from this article can be applied to visualizing data science initiatives as well. Ultimately, you will be able to present a moving animation; an infographic, a funny cartoon, or a story with powerful visuals. This tool can be used for explaining complex data science results to nontechnical uses through the use of easy to digest visualization and animation.
The example in this article is specifically displaying a sailboat going through a thunderstorm on the ocean. Charts, graphs, and maps, akin to Excel, Tableau, or Google Data Studio can be executed in Processing as well. To learn more about Processing read below, as well as further explanations of the code used, and resources for more code. Finally, if you would like to skip to the animation at the end, click on the video.
Processing [3] is a software that not many people have heard of but is extremely valuable, and of course, fun to use. It is considered a sketchbook for coding unique visualizations. These visuals can be considered art even, and because the code is written line by line by the user, the number of creations are endless. Mainly composed of Java code, the user creates programming classes and voids that inherit from one another, which will ultimately create shapes that move and become animated.
The great part about Processing and Java is that you do not need to be an expert data scientist or software engineer to use this tool.
Because it is open-source, meaning there is tons of available information and code out there to use, you can find templates, tutorials, and ideas, right on their site that allows you to make those same visualizations and animations. Once you get used to it, too, and learn from it, you can then add your own code and spin to create a personalized output to share.
If you are interested in the code itself, read here; if not, keep scrolling to see what the finished product looks like, as well as information on usable templates and examples.
Lightning Animation
I will outline one of the classes used in the final visualization of this article here. The lightning class is a yellow, animated shape that will hit the boat in this rainstorm. It is a class that includes the color, position, and shape coordinates of the object. As you can see, there are several vertexes, which are the positions of the X and Y coordinates, ultimately serving as the outline of the lightning shape. You fill the lighting outline with that same color so that it looks completely solid. The code [6] below, is what creates the lightning shape:
class Lightning {color c;float xpos;float ypos;Lightning(color tempc, float tempxpos, float tempypos) {c = tempc;xpos = tempxpos;ypos = tempypos;}void display(){beginShape();noStroke();fill(c);vertex(xpos+246, 0);vertex(xpos+145, ypos-285);vertex(xpos+172, ypos-269);vertex(xpos+54, ypos-184);vertex(xpos+89, ypos-178);vertex(xpos, ypos);vertex(xpos+112, ypos-187);vertex(xpos+94, ypos-191);vertex(xpos+210, ypos-278);vertex(xpos+189, ypos-291);vertex(xpos+300, 0);endShape(CLOSE);endShape(CLOSE);}}
The above code refers to a specific shape, however, there is a certain template or format that you can follow to develop your first, simple animation. The usual template of code is:
void setup() — the size of the shape
void draw() — the color of the background
There are several other parts of Processing that are unique, like mouse-clicked, which means when you click your mouse this X animation will occur.
To find an abundance of examples to practice with, OpenProcessing[5] compiles a unique list on their website.
This code [6] is some of the code used to create the animation in the video. It is quite comprehensive but is a beneficial way to learn how to include different colors, shapes, and animations.
The final product. Here is the animation [7]. After executing the code, or ‘hitting play’, the sailboat will start moving in the rainstorm, followed by some damage in the boat from the strike of the lightning, and will continue moving to the right on the water, also becoming closer to the moving windmill:
Processing can seem intimidating at first, but with the use of code samples, examples, and tutorials, you can learn to animate pretty much anything you want. Whether it is abstract art, a chart, a comic book-like animation, or a boat sailing through the water in a storm, Processing allows users to express their creativity. With tools like Tableau being the frontrunner of visualizations, this software proves to be a unique skill set you could employ as a part of your resume, education, or job, especially as a data scientist and even a software engineer. I hope you found this article interesting, thank you for reading! If you have any questions, feel free to comment below.
[1] Photo by KOBU Agency on Unsplash, (2018)
[2] M.Przybyla, Processing screenshot, (2020)
[3] Processing, (2020)
[4] Photo by Irvan Smith on Unsplash, (2018)
[5] OpenProcessing, (2020)
[6] M.Przybyla, gist, (2020)
[7] M.Przybyla, animation, (2020) | [
{
"code": null,
"e": 224,
"s": 171,
"text": "IntroductionProcessingCodingExampleSummaryReferences"
},
{
"code": null,
"e": 237,
"s": 224,
"text": "Introduction"
},
{
"code": null,
"e": 248,
"s": 237,
"text": "Processing"
},
{
"code": null,
"e": 255,
"s": 248,
"text": "Coding"
},
{
"code": null,
"e": 263,
"s": 255,
"text": "Example"
},
{
"code": null,
"e": 271,
"s": 263,
"text": "Summary"
},
{
"code": null,
"e": 282,
"s": 271,
"text": "References"
},
{
"code": null,
"e": 333,
"s": 282,
"text": "From my article you will learn two main takeaways:"
},
{
"code": null,
"e": 378,
"s": 333,
"text": "1. What the Processing software platform is."
},
{
"code": null,
"e": 452,
"s": 378,
"text": "2. How to execute code to create an entertaining and beautiful animation."
},
{
"code": null,
"e": 1072,
"s": 452,
"text": "You do not need to be an expert coder or software developer to create awesome visualizations. In this tutorial and outline, there are several ways to show off what you can do with a little bit of code and a little bit of Processing magic. All of the principles from this article can be applied to visualizing data science initiatives as well. Ultimately, you will be able to present a moving animation; an infographic, a funny cartoon, or a story with powerful visuals. This tool can be used for explaining complex data science results to nontechnical uses through the use of easy to digest visualization and animation."
},
{
"code": null,
"e": 1498,
"s": 1072,
"text": "The example in this article is specifically displaying a sailboat going through a thunderstorm on the ocean. Charts, graphs, and maps, akin to Excel, Tableau, or Google Data Studio can be executed in Processing as well. To learn more about Processing read below, as well as further explanations of the code used, and resources for more code. Finally, if you would like to skip to the animation at the end, click on the video."
},
{
"code": null,
"e": 1992,
"s": 1498,
"text": "Processing [3] is a software that not many people have heard of but is extremely valuable, and of course, fun to use. It is considered a sketchbook for coding unique visualizations. These visuals can be considered art even, and because the code is written line by line by the user, the number of creations are endless. Mainly composed of Java code, the user creates programming classes and voids that inherit from one another, which will ultimately create shapes that move and become animated."
},
{
"code": null,
"e": 2127,
"s": 1992,
"text": "The great part about Processing and Java is that you do not need to be an expert data scientist or software engineer to use this tool."
},
{
"code": null,
"e": 2491,
"s": 2127,
"text": "Because it is open-source, meaning there is tons of available information and code out there to use, you can find templates, tutorials, and ideas, right on their site that allows you to make those same visualizations and animations. Once you get used to it, too, and learn from it, you can then add your own code and spin to create a personalized output to share."
},
{
"code": null,
"e": 2669,
"s": 2491,
"text": "If you are interested in the code itself, read here; if not, keep scrolling to see what the finished product looks like, as well as information on usable templates and examples."
},
{
"code": null,
"e": 2689,
"s": 2669,
"text": "Lightning Animation"
},
{
"code": null,
"e": 3250,
"s": 2689,
"text": "I will outline one of the classes used in the final visualization of this article here. The lightning class is a yellow, animated shape that will hit the boat in this rainstorm. It is a class that includes the color, position, and shape coordinates of the object. As you can see, there are several vertexes, which are the positions of the X and Y coordinates, ultimately serving as the outline of the lightning shape. You fill the lighting outline with that same color so that it looks completely solid. The code [6] below, is what creates the lightning shape:"
},
{
"code": null,
"e": 3750,
"s": 3250,
"text": "class Lightning {color c;float xpos;float ypos;Lightning(color tempc, float tempxpos, float tempypos) {c = tempc;xpos = tempxpos;ypos = tempypos;}void display(){beginShape();noStroke();fill(c);vertex(xpos+246, 0);vertex(xpos+145, ypos-285);vertex(xpos+172, ypos-269);vertex(xpos+54, ypos-184);vertex(xpos+89, ypos-178);vertex(xpos, ypos);vertex(xpos+112, ypos-187);vertex(xpos+94, ypos-191);vertex(xpos+210, ypos-278);vertex(xpos+189, ypos-291);vertex(xpos+300, 0);endShape(CLOSE);endShape(CLOSE);}}"
},
{
"code": null,
"e": 3932,
"s": 3750,
"text": "The above code refers to a specific shape, however, there is a certain template or format that you can follow to develop your first, simple animation. The usual template of code is:"
},
{
"code": null,
"e": 3969,
"s": 3932,
"text": "void setup() — the size of the shape"
},
{
"code": null,
"e": 4011,
"s": 3969,
"text": "void draw() — the color of the background"
},
{
"code": null,
"e": 4159,
"s": 4011,
"text": "There are several other parts of Processing that are unique, like mouse-clicked, which means when you click your mouse this X animation will occur."
},
{
"code": null,
"e": 4269,
"s": 4159,
"text": "To find an abundance of examples to practice with, OpenProcessing[5] compiles a unique list on their website."
},
{
"code": null,
"e": 4462,
"s": 4269,
"text": "This code [6] is some of the code used to create the animation in the video. It is quite comprehensive but is a beneficial way to learn how to include different colors, shapes, and animations."
},
{
"code": null,
"e": 4769,
"s": 4462,
"text": "The final product. Here is the animation [7]. After executing the code, or ‘hitting play’, the sailboat will start moving in the rainstorm, followed by some damage in the boat from the strike of the lightning, and will continue moving to the right on the water, also becoming closer to the moving windmill:"
},
{
"code": null,
"e": 5449,
"s": 4769,
"text": "Processing can seem intimidating at first, but with the use of code samples, examples, and tutorials, you can learn to animate pretty much anything you want. Whether it is abstract art, a chart, a comic book-like animation, or a boat sailing through the water in a storm, Processing allows users to express their creativity. With tools like Tableau being the frontrunner of visualizations, this software proves to be a unique skill set you could employ as a part of your resume, education, or job, especially as a data scientist and even a software engineer. I hope you found this article interesting, thank you for reading! If you have any questions, feel free to comment below."
},
{
"code": null,
"e": 5494,
"s": 5449,
"text": "[1] Photo by KOBU Agency on Unsplash, (2018)"
},
{
"code": null,
"e": 5540,
"s": 5494,
"text": "[2] M.Przybyla, Processing screenshot, (2020)"
},
{
"code": null,
"e": 5563,
"s": 5540,
"text": "[3] Processing, (2020)"
},
{
"code": null,
"e": 5608,
"s": 5563,
"text": "[4] Photo by Irvan Smith on Unsplash, (2018)"
},
{
"code": null,
"e": 5635,
"s": 5608,
"text": "[5] OpenProcessing, (2020)"
},
{
"code": null,
"e": 5664,
"s": 5635,
"text": "[6] M.Przybyla, gist, (2020)"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.