title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
C/C++ Program to check whether it is possible to make a divisible by 3 number using all digits in an array - GeeksforGeeks
|
05 Dec, 2018
Given an array of integers, the task is to find whether it is possible to construct an integer using all the digits of these numbers such that it would be divisible by 3. If it is possible then print “Yes” and if not print “No”.
Examples:
Input : arr[] = {40, 50, 90}
Output : Yes
We can construct a number which is
divisible by 3, for example 945000.
So the answer is Yes.
Input : arr[] = {1, 4}
Output : No
The only possible numbers are 14 and 41,
but both of them are not divisible by 3,
so the answer is No.
// C++ program to find if it is possible// to make a number divisible by 3 using// all digits of given array#include <bits/stdc++.h>using namespace std; bool isPossibleToMakeDivisible(int arr[], int n){ // Find remainder of sum when divided by 3 int remainder = 0; for (int i = 0; i < n; i++) remainder = (remainder + arr[i]) % 3; // Return true if remainder is 0. return (remainder == 0);} // Driver codeint main(){ int arr[] = { 40, 50, 90 }; int n = sizeof(arr) / sizeof(arr[0]); if (isPossibleToMakeDivisible(arr, n)) printf("Yes\n"); else printf("No\n"); return 0;}
Yes
Time Complexity: O(n)
Please refer complete article on Possible to make a divisible by 3 number using all digits in an array for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Handling multiple clients on server with multithreading using Socket Programming in C/C++
Regular expressions in C
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Create n-child process from same parent process using fork() in C
Conditional wait and signal in multi-threading
Lamport's logical clock
|
[
{
"code": null,
"e": 26175,
"s": 26147,
"text": "\n05 Dec, 2018"
},
{
"code": null,
"e": 26404,
"s": 26175,
"text": "Given an array of integers, the task is to find whether it is possible to construct an integer using all the digits of these numbers such that it would be divisible by 3. If it is possible then print “Yes” and if not print “No”."
},
{
"code": null,
"e": 26414,
"s": 26404,
"text": "Examples:"
},
{
"code": null,
"e": 26692,
"s": 26414,
"text": "Input : arr[] = {40, 50, 90}\nOutput : Yes\nWe can construct a number which is\ndivisible by 3, for example 945000. \nSo the answer is Yes. \n\nInput : arr[] = {1, 4}\nOutput : No\nThe only possible numbers are 14 and 41,\nbut both of them are not divisible by 3, \nso the answer is No.\n"
},
{
"code": "// C++ program to find if it is possible// to make a number divisible by 3 using// all digits of given array#include <bits/stdc++.h>using namespace std; bool isPossibleToMakeDivisible(int arr[], int n){ // Find remainder of sum when divided by 3 int remainder = 0; for (int i = 0; i < n; i++) remainder = (remainder + arr[i]) % 3; // Return true if remainder is 0. return (remainder == 0);} // Driver codeint main(){ int arr[] = { 40, 50, 90 }; int n = sizeof(arr) / sizeof(arr[0]); if (isPossibleToMakeDivisible(arr, n)) printf(\"Yes\\n\"); else printf(\"No\\n\"); return 0;}",
"e": 27320,
"s": 26692,
"text": null
},
{
"code": null,
"e": 27325,
"s": 27320,
"text": "Yes\n"
},
{
"code": null,
"e": 27347,
"s": 27325,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 27468,
"s": 27347,
"text": "Please refer complete article on Possible to make a divisible by 3 number using all digits in an array for more details!"
},
{
"code": null,
"e": 27479,
"s": 27468,
"text": "C Programs"
},
{
"code": null,
"e": 27577,
"s": 27479,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27618,
"s": 27577,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 27649,
"s": 27618,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 27690,
"s": 27649,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 27724,
"s": 27690,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 27814,
"s": 27724,
"text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++"
},
{
"code": null,
"e": 27839,
"s": 27814,
"text": "Regular expressions in C"
},
{
"code": null,
"e": 27910,
"s": 27839,
"text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 27976,
"s": 27910,
"text": "Create n-child process from same parent process using fork() in C"
},
{
"code": null,
"e": 28023,
"s": 27976,
"text": "Conditional wait and signal in multi-threading"
}
] |
Understanding Code Reuse and Modularity in Python 3 - GeeksforGeeks
|
05 Jul, 2021
What is Object Oriented Programming(OOP)?
OOP is a programming paradigm based on the concept of “objects”, which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. Learn more here, or just Google “OOP”.Objects have characteristics and features, known as attributes, and can do various things, through their methods. The biggest feature of OOP is how well objects can be interacted with, and even molded in the future, which makes them very friendly to developers, scale, change over time, testing, and much more.
What is Modularity?
Modularity refers to the concept of making multiple modules first and then linking and combining them to form a complete system (i.e, the extent to which a software/Web application may be divided into smaller modules is called modularity). Modularity enables re-usability and will minimize duplication.
Flow of the Article
Aim: To learn object oriented programming – Modularity. How can we turn some portions of our code into a library so that it can be used by anyone for future reference. Making the code modular will enable re-usability and minimizes duplication.
Dependencies: pygame
Summary: We are going to make a small game(not really a game) but just an environment and some objects in it. We will try to make the environment static and the objects( blobs in our case) modular. We will make use of PyGame, since it gives us a simple way to actually visualize what we’re doing and building, so we can see our objects in action. What we’re going to do is build Blob World, which is a world that consists of actors, known as blobs. Different blobs have different properties, and the blobs need to otherwise function within their Blob World environment. With this example, we’ll be able to illustrate modularity.
We are dividing our learning process into two phases.
Creating the Environment and the BlobsUnderstanding Modularity
Creating the Environment and the Blobs
Understanding Modularity
Repository(Github): source
BLOB WORLD ( Python Code )
Python
import pygameimport random STARTING_BLUE_BLOBS = 10STARTING_RED_BLOBS = 3 WIDTH = 800HEIGHT = 600WHITE = (255, 255, 255)BLUE = (0, 0, 255)RED = (255, 0, 0) game_display = pygame.display.set_mode((WIDTH, HEIGHT))pygame.display.set_caption("Blob World")clock = pygame.time.Clock() class Blob: def __init__(self, color): self.x = random.randrange(0, WIDTH) self.y = random.randrange(0, HEIGHT) self.size = random.randrange(4,8) self.color = color def move(self): self.move_x = random.randrange(-1,2) self.move_y = random.randrange(-1,2) self.x += self.move_x self.y += self.move_y if self.x < 0: self.x = 0 elif self.x > WIDTH: self.x = WIDTH if self.y < 0: self.y = 0 elif self.y > HEIGHT: self.y = HEIGHT def draw_environment(blob_list): game_display.fill(WHITE) for blob_dict in blob_list: for blob_id in blob_dict: blob = blob_dict[blob_id] pygame.draw.circle(game_display, blob.color, [blob.x, blob.y], blob.size) blob.move() pygame.display.update() def main(): blue_blobs = dict(enumerate([Blob(BLUE) for i in range(STARTING_BLUE_BLOBS)])) red_blobs = dict(enumerate([Blob(RED) for i in range(STARTING_RED_BLOBS)])) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() draw_environment([blue_blobs,red_blobs]) clock.tick(60) if __name__ == '__main__': main()
Output:
PART(1/2): Blob World In this part, we are creating a simple game environment and some objects in it because visualizing what we have created is an exceptional way of learning programming. The explanation for the creation of the blob world ( i.e, its environment and its objects) using pygame is explained here. All we need to understand is how to make our code modular.
PART(2/2): Modularity In this second part, we are going to understand an essential feature of Object Oriented Programming, i.e Modularity. So far, we’ve not introduced anything that will make this (BLOB WORLD code) too hard to maintain or scale over time, at least within the scope of what we can do with PyGame. What about making it modular? There’s a really easy test for this, let’s try to import it!
To do this, let’s have two files. Let’s copy the Blob class and random, and make a new file: blob.py
import random
class Blob:
def __init__(self, color):
self.x = random.randrange(0, WIDTH)
self.y = random.randrange(0, HEIGHT)
self.size = random.randrange(4,8)
self.color = color
def move(self):
self.move_x = random.randrange(-1,2)
self.move_y = random.randrange(-1,2)
self.x += self.move_x
self.y += self.move_y
if self.x WIDTH: self.x = WIDTH
if self.y HEIGHT: self.y = HEIGHT
Back to our original file, let’s remove the Blob class, and then import Blob from blob.py.
import pygame
import random
from blob import Blob
STARTING_BLUE_BLOBS = 10
...
Immediately, we’re given an error in the blob.py file, regarding our Blob class, where we have some undefined variables. This is definitely a problem with writing classes, we should try to avoid using constants or variables outside of the class. Let’s add these values to the __init__ method, then modify all of the parts where we used the constants. So, here is our new Blob class file :blob.py
Next, within our original file, when we call the Blob class, it’s expecting some values for those arguments, so you’d add those in the main function:
def main():
blue_blobs = dict(enumerate([Blob(BLUE,WIDTH,HEIGHT) for i in range(STARTING_BLUE_BLOBS)]))
red_blobs = dict(enumerate([Blob(RED,WIDTH,HEIGHT) for i in range(STARTING_RED_BLOBS)]))
while True:
...
Great, so now our Blob class can at least be imported, so it’s modular by nature already! Another good idea is to attempt to give the developer that is using your code as much power as possible, and to make your class as generalize-able as possible. At least one example where we could definitely give more to the programmer using this class is in the definition of the blob’s size:
self.size = random.randrange(4,8)
Is there any reason why we wouldn’t want to give the programmer an easy way to change these? I don’t think so. Unlike x_boundary and y_boundary, however, we do not necessarily *need* the programmer to provide us a value for the size, since we can at least use a reasonable starting default. Thus, we can do something like:
class Blob:
def __init__(self, color, x_boundary, y_boundary, size_range=(4,8)):
self.x_boundary = x_boundary
self.y_boundary = y_boundary
self.x = random.randrange(0, self.x_boundary)
self.y = random.randrange(0, self.y_boundary)
self.size = random.randrange(size_range[0],size_range[1])
self.color = color
Now, if the programmer wants to change the size, they can, otherwise they don’t have to. We might also want to allow the programmer to modify the speed of the blob if they want to:
import random
class Blob:
def __init__(self, color, x_boundary, y_boundary, size_range=(4,8), movement_range=(-1,2)):
self.size = random.randrange(size_range[0],size_range[1])
self.color = color
self.x_boundary = x_boundary
self.y_boundary = y_boundary
self.x = random.randrange(0, self.x_boundary)
self.y = random.randrange(0, self.y_boundary)
self.movement_range = movement_range
def move(self):
self.move_x = random.randrange(self.movement_range[0],self.movement_range[1])
self.move_y = random.randrange(self.movement_range[0],self.movement_range[1])
self.x += self.move_x
self.y += self.move_y
if self.x self.x_boundary: self.x = self.x_boundary
if self.y self.y_boundary: self.y = self.y_boundary
Now we’ve opened up the class quite a bit. Does anything else jump out at us? Yes, the line where we force the blob to remain in-bounds. Might there be examples where we’d like the blobs to be able to roam freely out of view? Certainly! Is this bounding code useful though? Is it likely that programmers will want to make use of this quite often? Certainly! however, that it makes more sense to either not have the code at all, or to give it its own method, like so:
import random
class Blob:
def __init__(self, color, x_boundary, y_boundary, size_range=(4,8), movement_range=(-1,2)):
self.size = random.randrange(size_range[0],size_range[1])
self.color = color
self.x_boundary = x_boundary
self.y_boundary = y_boundary
self.x = random.randrange(0, self.x_boundary)
self.y = random.randrange(0, self.y_boundary)
self.movement_range = movement_range
def move(self):
self.move_x = random.randrange(self.movement_range[0],self.movement_range[1])
self.move_y = random.randrange(self.movement_range[0],self.movement_range[1])
self.x += self.move_x
self.y += self.move_y
def check_bounds(self):
if self.x self.x_boundary: self.x = self.x_boundary
if self.y self.y_boundary: self.y = self.y_boundary
Now, the programmer can decide to use it or not. You could also give some sort of argument in the move method, where, if True, then boundaries would be enforced. So we got a glimpse of how we can make our python code Modular.
Resources:
Original Video Series (by pythonprogramming.net)
pythonprogramming.net
Harrison Kinsley (Thank you H.Kinsley)
This article is contributed by Amartya Ranjan Saikia. 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.
sooda367
Project
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Banking Transaction System using Java
E-commerce Website using Django
Student record management system using linked list
How to write a good SRS for your Project
Handling Ajax request in Django
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 25721,
"s": 25693,
"text": "\n05 Jul, 2021"
},
{
"code": null,
"e": 25763,
"s": 25721,
"text": "What is Object Oriented Programming(OOP)?"
},
{
"code": null,
"e": 26313,
"s": 25763,
"text": "OOP is a programming paradigm based on the concept of “objects”, which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. Learn more here, or just Google “OOP”.Objects have characteristics and features, known as attributes, and can do various things, through their methods. The biggest feature of OOP is how well objects can be interacted with, and even molded in the future, which makes them very friendly to developers, scale, change over time, testing, and much more. "
},
{
"code": null,
"e": 26333,
"s": 26313,
"text": "What is Modularity?"
},
{
"code": null,
"e": 26637,
"s": 26333,
"text": "Modularity refers to the concept of making multiple modules first and then linking and combining them to form a complete system (i.e, the extent to which a software/Web application may be divided into smaller modules is called modularity). Modularity enables re-usability and will minimize duplication. "
},
{
"code": null,
"e": 26657,
"s": 26637,
"text": "Flow of the Article"
},
{
"code": null,
"e": 26901,
"s": 26657,
"text": "Aim: To learn object oriented programming – Modularity. How can we turn some portions of our code into a library so that it can be used by anyone for future reference. Making the code modular will enable re-usability and minimizes duplication."
},
{
"code": null,
"e": 26922,
"s": 26901,
"text": "Dependencies: pygame"
},
{
"code": null,
"e": 27552,
"s": 26922,
"text": "Summary: We are going to make a small game(not really a game) but just an environment and some objects in it. We will try to make the environment static and the objects( blobs in our case) modular. We will make use of PyGame, since it gives us a simple way to actually visualize what we’re doing and building, so we can see our objects in action. What we’re going to do is build Blob World, which is a world that consists of actors, known as blobs. Different blobs have different properties, and the blobs need to otherwise function within their Blob World environment. With this example, we’ll be able to illustrate modularity. "
},
{
"code": null,
"e": 27608,
"s": 27552,
"text": "We are dividing our learning process into two phases. "
},
{
"code": null,
"e": 27671,
"s": 27608,
"text": "Creating the Environment and the BlobsUnderstanding Modularity"
},
{
"code": null,
"e": 27710,
"s": 27671,
"text": "Creating the Environment and the Blobs"
},
{
"code": null,
"e": 27735,
"s": 27710,
"text": "Understanding Modularity"
},
{
"code": null,
"e": 27762,
"s": 27735,
"text": "Repository(Github): source"
},
{
"code": null,
"e": 27789,
"s": 27762,
"text": "BLOB WORLD ( Python Code )"
},
{
"code": null,
"e": 27796,
"s": 27789,
"text": "Python"
},
{
"code": "import pygameimport random STARTING_BLUE_BLOBS = 10STARTING_RED_BLOBS = 3 WIDTH = 800HEIGHT = 600WHITE = (255, 255, 255)BLUE = (0, 0, 255)RED = (255, 0, 0) game_display = pygame.display.set_mode((WIDTH, HEIGHT))pygame.display.set_caption(\"Blob World\")clock = pygame.time.Clock() class Blob: def __init__(self, color): self.x = random.randrange(0, WIDTH) self.y = random.randrange(0, HEIGHT) self.size = random.randrange(4,8) self.color = color def move(self): self.move_x = random.randrange(-1,2) self.move_y = random.randrange(-1,2) self.x += self.move_x self.y += self.move_y if self.x < 0: self.x = 0 elif self.x > WIDTH: self.x = WIDTH if self.y < 0: self.y = 0 elif self.y > HEIGHT: self.y = HEIGHT def draw_environment(blob_list): game_display.fill(WHITE) for blob_dict in blob_list: for blob_id in blob_dict: blob = blob_dict[blob_id] pygame.draw.circle(game_display, blob.color, [blob.x, blob.y], blob.size) blob.move() pygame.display.update() def main(): blue_blobs = dict(enumerate([Blob(BLUE) for i in range(STARTING_BLUE_BLOBS)])) red_blobs = dict(enumerate([Blob(RED) for i in range(STARTING_RED_BLOBS)])) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() draw_environment([blue_blobs,red_blobs]) clock.tick(60) if __name__ == '__main__': main()",
"e": 29334,
"s": 27796,
"text": null
},
{
"code": null,
"e": 29343,
"s": 29334,
"text": "Output: "
},
{
"code": null,
"e": 29714,
"s": 29343,
"text": "PART(1/2): Blob World In this part, we are creating a simple game environment and some objects in it because visualizing what we have created is an exceptional way of learning programming. The explanation for the creation of the blob world ( i.e, its environment and its objects) using pygame is explained here. All we need to understand is how to make our code modular."
},
{
"code": null,
"e": 30119,
"s": 29714,
"text": "PART(2/2): Modularity In this second part, we are going to understand an essential feature of Object Oriented Programming, i.e Modularity. So far, we’ve not introduced anything that will make this (BLOB WORLD code) too hard to maintain or scale over time, at least within the scope of what we can do with PyGame. What about making it modular? There’s a really easy test for this, let’s try to import it! "
},
{
"code": null,
"e": 30222,
"s": 30119,
"text": "To do this, let’s have two files. Let’s copy the Blob class and random, and make a new file: blob.py "
},
{
"code": null,
"e": 30704,
"s": 30222,
"text": "import random\n\nclass Blob:\n\n def __init__(self, color):\n self.x = random.randrange(0, WIDTH)\n self.y = random.randrange(0, HEIGHT)\n self.size = random.randrange(4,8)\n self.color = color\n\n def move(self):\n self.move_x = random.randrange(-1,2)\n self.move_y = random.randrange(-1,2)\n self.x += self.move_x\n self.y += self.move_y\n\n if self.x WIDTH: self.x = WIDTH\n \n if self.y HEIGHT: self.y = HEIGHT"
},
{
"code": null,
"e": 30797,
"s": 30704,
"text": "Back to our original file, let’s remove the Blob class, and then import Blob from blob.py. "
},
{
"code": null,
"e": 30877,
"s": 30797,
"text": "import pygame\nimport random\nfrom blob import Blob\n\nSTARTING_BLUE_BLOBS = 10\n..."
},
{
"code": null,
"e": 31274,
"s": 30877,
"text": "Immediately, we’re given an error in the blob.py file, regarding our Blob class, where we have some undefined variables. This is definitely a problem with writing classes, we should try to avoid using constants or variables outside of the class. Let’s add these values to the __init__ method, then modify all of the parts where we used the constants. So, here is our new Blob class file :blob.py "
},
{
"code": null,
"e": 31426,
"s": 31274,
"text": "Next, within our original file, when we call the Blob class, it’s expecting some values for those arguments, so you’d add those in the main function: "
},
{
"code": null,
"e": 31655,
"s": 31426,
"text": "def main():\n blue_blobs = dict(enumerate([Blob(BLUE,WIDTH,HEIGHT) for i in range(STARTING_BLUE_BLOBS)]))\n red_blobs = dict(enumerate([Blob(RED,WIDTH,HEIGHT) for i in range(STARTING_RED_BLOBS)]))\n while True:\n ..."
},
{
"code": null,
"e": 32040,
"s": 31655,
"text": "Great, so now our Blob class can at least be imported, so it’s modular by nature already! Another good idea is to attempt to give the developer that is using your code as much power as possible, and to make your class as generalize-able as possible. At least one example where we could definitely give more to the programmer using this class is in the definition of the blob’s size: "
},
{
"code": null,
"e": 32077,
"s": 32040,
"text": " self.size = random.randrange(4,8) "
},
{
"code": null,
"e": 32402,
"s": 32077,
"text": "Is there any reason why we wouldn’t want to give the programmer an easy way to change these? I don’t think so. Unlike x_boundary and y_boundary, however, we do not necessarily *need* the programmer to provide us a value for the size, since we can at least use a reasonable starting default. Thus, we can do something like: "
},
{
"code": null,
"e": 32763,
"s": 32402,
"text": "class Blob:\n\n def __init__(self, color, x_boundary, y_boundary, size_range=(4,8)):\n self.x_boundary = x_boundary\n self.y_boundary = y_boundary\n self.x = random.randrange(0, self.x_boundary)\n self.y = random.randrange(0, self.y_boundary)\n self.size = random.randrange(size_range[0],size_range[1])\n self.color = color"
},
{
"code": null,
"e": 32945,
"s": 32763,
"text": "Now, if the programmer wants to change the size, they can, otherwise they don’t have to. We might also want to allow the programmer to modify the speed of the blob if they want to: "
},
{
"code": null,
"e": 33775,
"s": 32945,
"text": "import random\n\n\nclass Blob:\n\n def __init__(self, color, x_boundary, y_boundary, size_range=(4,8), movement_range=(-1,2)):\n self.size = random.randrange(size_range[0],size_range[1])\n self.color = color\n self.x_boundary = x_boundary\n self.y_boundary = y_boundary\n self.x = random.randrange(0, self.x_boundary)\n self.y = random.randrange(0, self.y_boundary)\n self.movement_range = movement_range\n\n def move(self):\n self.move_x = random.randrange(self.movement_range[0],self.movement_range[1])\n self.move_y = random.randrange(self.movement_range[0],self.movement_range[1])\n self.x += self.move_x\n self.y += self.move_y\n\n if self.x self.x_boundary: self.x = self.x_boundary\n \n if self.y self.y_boundary: self.y = self.y_boundary"
},
{
"code": null,
"e": 34243,
"s": 33775,
"text": "Now we’ve opened up the class quite a bit. Does anything else jump out at us? Yes, the line where we force the blob to remain in-bounds. Might there be examples where we’d like the blobs to be able to roam freely out of view? Certainly! Is this bounding code useful though? Is it likely that programmers will want to make use of this quite often? Certainly! however, that it makes more sense to either not have the code at all, or to give it its own method, like so: "
},
{
"code": null,
"e": 35100,
"s": 34243,
"text": "import random\n\nclass Blob:\n\n def __init__(self, color, x_boundary, y_boundary, size_range=(4,8), movement_range=(-1,2)):\n self.size = random.randrange(size_range[0],size_range[1])\n self.color = color\n self.x_boundary = x_boundary\n self.y_boundary = y_boundary\n self.x = random.randrange(0, self.x_boundary)\n self.y = random.randrange(0, self.y_boundary)\n self.movement_range = movement_range\n\n def move(self):\n self.move_x = random.randrange(self.movement_range[0],self.movement_range[1])\n self.move_y = random.randrange(self.movement_range[0],self.movement_range[1])\n self.x += self.move_x\n self.y += self.move_y\n\n def check_bounds(self):\n if self.x self.x_boundary: self.x = self.x_boundary\n \n if self.y self.y_boundary: self.y = self.y_boundary"
},
{
"code": null,
"e": 35326,
"s": 35100,
"text": "Now, the programmer can decide to use it or not. You could also give some sort of argument in the move method, where, if True, then boundaries would be enforced. So we got a glimpse of how we can make our python code Modular."
},
{
"code": null,
"e": 35338,
"s": 35326,
"text": "Resources: "
},
{
"code": null,
"e": 35387,
"s": 35338,
"text": "Original Video Series (by pythonprogramming.net)"
},
{
"code": null,
"e": 35409,
"s": 35387,
"text": "pythonprogramming.net"
},
{
"code": null,
"e": 35448,
"s": 35409,
"text": "Harrison Kinsley (Thank you H.Kinsley)"
},
{
"code": null,
"e": 35878,
"s": 35448,
"text": "This article is contributed by Amartya Ranjan Saikia. 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": 35887,
"s": 35878,
"text": "sooda367"
},
{
"code": null,
"e": 35895,
"s": 35887,
"text": "Project"
},
{
"code": null,
"e": 35902,
"s": 35895,
"text": "Python"
},
{
"code": null,
"e": 35921,
"s": 35902,
"text": "Technical Scripter"
},
{
"code": null,
"e": 36019,
"s": 35921,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36057,
"s": 36019,
"text": "Banking Transaction System using Java"
},
{
"code": null,
"e": 36089,
"s": 36057,
"text": "E-commerce Website using Django"
},
{
"code": null,
"e": 36140,
"s": 36089,
"text": "Student record management system using linked list"
},
{
"code": null,
"e": 36181,
"s": 36140,
"text": "How to write a good SRS for your Project"
},
{
"code": null,
"e": 36213,
"s": 36181,
"text": "Handling Ajax request in Django"
},
{
"code": null,
"e": 36241,
"s": 36213,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 36291,
"s": 36241,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 36313,
"s": 36291,
"text": "Python map() function"
}
] |
Collect.js reject() Method - GeeksforGeeks
|
30 Nov, 2020
The reject() method is used to filter the given collection of elements using the given callback function. If the callback function returns true, then the element is removed from the resulting collection, otherwise, it is not removed.
Syntax:
collect(array).reject(callback)
Parameters: The collect() method takes one argument that is converted into the collection and then reject() method is applied to it. The reject() method holds the callback as a parameter.
Return Value: This method returns the filtered elements from the collection.
Below example illustrate the reject() method in collect.js:
Example 1:
Javascript
const collect = require('collect.js'); let obj = ['Geeks', 'GFG', 'GeeksforGeeks']; const collection = collect(obj); const filtered = collection.reject( element => element.length > 4); console.log(filtered.all());
Output:
[ 'GFG' ]
Example 2:
Javascript
const collect = require('collect.js'); let obj = [ { name: 'Rahul', marks: 88 }, { name: 'Aditya', marks: 78 }, { name: 'Abhishek', marks: 87 }]; const collection = collect(obj); const filtered = collection.reject( element => element.name.length > 5); console.log(filtered.all());
Output:
[ { name: 'Rahul', marks: 88 } ]
Collect.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
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Express.js express.Router() Function
How to set input type date in dd-mm-yyyy format using HTML ?
Installation of Node.js on Linux
How to create footer to stay at the bottom of a Web page?
How to float three div side by side using CSS?
|
[
{
"code": null,
"e": 24909,
"s": 24881,
"text": "\n30 Nov, 2020"
},
{
"code": null,
"e": 25143,
"s": 24909,
"text": "The reject() method is used to filter the given collection of elements using the given callback function. If the callback function returns true, then the element is removed from the resulting collection, otherwise, it is not removed."
},
{
"code": null,
"e": 25151,
"s": 25143,
"text": "Syntax:"
},
{
"code": null,
"e": 25183,
"s": 25151,
"text": "collect(array).reject(callback)"
},
{
"code": null,
"e": 25371,
"s": 25183,
"text": "Parameters: The collect() method takes one argument that is converted into the collection and then reject() method is applied to it. The reject() method holds the callback as a parameter."
},
{
"code": null,
"e": 25448,
"s": 25371,
"text": "Return Value: This method returns the filtered elements from the collection."
},
{
"code": null,
"e": 25508,
"s": 25448,
"text": "Below example illustrate the reject() method in collect.js:"
},
{
"code": null,
"e": 25519,
"s": 25508,
"text": "Example 1:"
},
{
"code": null,
"e": 25530,
"s": 25519,
"text": "Javascript"
},
{
"code": "const collect = require('collect.js'); let obj = ['Geeks', 'GFG', 'GeeksforGeeks']; const collection = collect(obj); const filtered = collection.reject( element => element.length > 4); console.log(filtered.all());",
"e": 25751,
"s": 25530,
"text": null
},
{
"code": null,
"e": 25759,
"s": 25751,
"text": "Output:"
},
{
"code": null,
"e": 25769,
"s": 25759,
"text": "[ 'GFG' ]"
},
{
"code": null,
"e": 25780,
"s": 25769,
"text": "Example 2:"
},
{
"code": null,
"e": 25791,
"s": 25780,
"text": "Javascript"
},
{
"code": "const collect = require('collect.js'); let obj = [ { name: 'Rahul', marks: 88 }, { name: 'Aditya', marks: 78 }, { name: 'Abhishek', marks: 87 }]; const collection = collect(obj); const filtered = collection.reject( element => element.name.length > 5); console.log(filtered.all());",
"e": 26139,
"s": 25791,
"text": null
},
{
"code": null,
"e": 26147,
"s": 26139,
"text": "Output:"
},
{
"code": null,
"e": 26180,
"s": 26147,
"text": "[ { name: 'Rahul', marks: 88 } ]"
},
{
"code": null,
"e": 26191,
"s": 26180,
"text": "Collect.js"
},
{
"code": null,
"e": 26202,
"s": 26191,
"text": "JavaScript"
},
{
"code": null,
"e": 26219,
"s": 26202,
"text": "Web Technologies"
},
{
"code": null,
"e": 26317,
"s": 26219,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26326,
"s": 26317,
"text": "Comments"
},
{
"code": null,
"e": 26339,
"s": 26326,
"text": "Old Comments"
},
{
"code": null,
"e": 26400,
"s": 26339,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26441,
"s": 26400,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 26495,
"s": 26441,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 26535,
"s": 26495,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26597,
"s": 26535,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 26634,
"s": 26597,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 26695,
"s": 26634,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 26728,
"s": 26695,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26786,
"s": 26728,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
How to Match patterns and strings using the RegEx module in Python
|
The RegEx module stands for Regular expressions. If you have already worked on programming, you would have come across this term several times already. We use the Regular expressions to search and replace, it is used in various text editors, search engines, word processors, etc.
In other words, it helps match a certain pattern that you are looking for.
A good example for this would be how your collage website allows you to use only your university mail and none of the other extensions.
The regular expression module comes packaged within Python. You do not need to download and install it separately.
In order to start accessing its contents, we must first import the module. To import the RegEx module, we use
import re
The RegEx module comes with a lot of functions and it is essential to understand and know the difference between each one of them.
Mentioned below are a few of the important functions you will most certainly use when you start working on Python projects.
re.compile(pattern, flags) #Compiles the pattern to be matched
re.search(pattern, string, flags) #Searches through the string for exact match
re.match(pattern, string, flags) #Checks if there is a match between pattern and string
re.split(pattern, string, max, flag) #Splits the string based on the pattern provided
re.findall(pattern, string, flag) #Prints all the matches found using the pattern
re.finditer(pattern, string, flags) #Returns the string as an iterable object
re.sub(pattern, repl, string, count) #Replaces the string with the pattern
re.subn(pattern, repl, string, count) #Does the same thing as re.sub but returns it in a tuple(string and count)
re.escape(pattern) #Escapes all characters other than ascii characters
Let us take a string, say “Hello world”. Now, let us find out if the above string is present in the string “Hello world! How are things going?”
To do this, we use the re.compile and re.match functions.
x = re.compile(“Hello world”)
y = x.match(“Hello world! How are things going?”)
if (y):
print("Strings match")
else:
print("Strings do not match")
Strings match
If you are wondering, why we cannot do this without using the compile function, you are right! We can do this without using the compile function.
x = re.match(“Hello world”,"Hello world! How are things going?")
if (y):
print("Strings match")
else:
print("Strings do not match")
String match
x = re.split("\W+","Hello,World")
print(x)
x = re.split("(\W+)","Hello,World
print(x)
['Hello', 'World']
['Hello', ',', 'World']
In the above example, the “\W+” basically means start splitting from the left and the + sign means keep moving forward until the end. When it is covered in brackets like in case 2, it splits and adds punctuations as well, like the comma.
x = re.sub(r"there","World","Hello there. Python is fun.")
print(x)
x = re.subn(r"there","World","Hello there. Python is fun. Hello there")
print(x)
Hello World. Python is fun.
('Hello World. Python is fun. Hello World', 2)
In the above example, the re.sub checks if the word “there” exists and replaces it with “world”.
The subn function does the exact same thing but returns a tuple instead of a string and also adds in the total number of replacements done.
One of the real world application/example for using the RegEx module would be to validate passwords.
import re
matching_sequence = r"[0−9]"
while(True):
x = input("Enter your password : ")
r = re.search(matching_sequence,x)
if (r and len(x)>6):
print(x + " is a valid password")
else:
print(x + " is not a valid password. Password MUST be atleast 7 characters with atleast 1 number")
input("Press Enter key to exit ")
The program will check if you have entered a valid password (7+ characters with at least one number) or not.
You’ve learnt the basics of the RegEx module present in Python and all the various different functions present within it.
There are a lot more functions and uses for the RegEx module. If you are interested, you can read more from their official documentation at https://docs.python.org/3/library/re.html.
|
[
{
"code": null,
"e": 1342,
"s": 1062,
"text": "The RegEx module stands for Regular expressions. If you have already worked on programming, you would have come across this term several times already. We use the Regular expressions to search and replace, it is used in various text editors, search engines, word processors, etc."
},
{
"code": null,
"e": 1417,
"s": 1342,
"text": "In other words, it helps match a certain pattern that you are looking for."
},
{
"code": null,
"e": 1553,
"s": 1417,
"text": "A good example for this would be how your collage website allows you to use only your university mail and none of the other extensions."
},
{
"code": null,
"e": 1668,
"s": 1553,
"text": "The regular expression module comes packaged within Python. You do not need to download and install it separately."
},
{
"code": null,
"e": 1778,
"s": 1668,
"text": "In order to start accessing its contents, we must first import the module. To import the RegEx module, we use"
},
{
"code": null,
"e": 1788,
"s": 1778,
"text": "import re"
},
{
"code": null,
"e": 1919,
"s": 1788,
"text": "The RegEx module comes with a lot of functions and it is essential to understand and know the difference between each one of them."
},
{
"code": null,
"e": 2043,
"s": 1919,
"text": "Mentioned below are a few of the important functions you will most certainly use when you start working on Python projects."
},
{
"code": null,
"e": 2778,
"s": 2043,
"text": "re.compile(pattern, flags) #Compiles the pattern to be matched\nre.search(pattern, string, flags) #Searches through the string for exact match\nre.match(pattern, string, flags) #Checks if there is a match between pattern and string\nre.split(pattern, string, max, flag) #Splits the string based on the pattern provided\nre.findall(pattern, string, flag) #Prints all the matches found using the pattern\nre.finditer(pattern, string, flags) #Returns the string as an iterable object\nre.sub(pattern, repl, string, count) #Replaces the string with the pattern\nre.subn(pattern, repl, string, count) #Does the same thing as re.sub but returns it in a tuple(string and count)\nre.escape(pattern) #Escapes all characters other than ascii characters"
},
{
"code": null,
"e": 2922,
"s": 2778,
"text": "Let us take a string, say “Hello world”. Now, let us find out if the above string is present in the string “Hello world! How are things going?”"
},
{
"code": null,
"e": 2980,
"s": 2922,
"text": "To do this, we use the re.compile and re.match functions."
},
{
"code": null,
"e": 3133,
"s": 2980,
"text": "x = re.compile(“Hello world”)\ny = x.match(“Hello world! How are things going?”)\nif (y):\n print(\"Strings match\")\nelse:\n print(\"Strings do not match\")"
},
{
"code": null,
"e": 3147,
"s": 3133,
"text": "Strings match"
},
{
"code": null,
"e": 3293,
"s": 3147,
"text": "If you are wondering, why we cannot do this without using the compile function, you are right! We can do this without using the compile function."
},
{
"code": null,
"e": 3431,
"s": 3293,
"text": "x = re.match(“Hello world”,\"Hello world! How are things going?\")\nif (y):\n print(\"Strings match\")\nelse:\n print(\"Strings do not match\")"
},
{
"code": null,
"e": 3444,
"s": 3431,
"text": "String match"
},
{
"code": null,
"e": 3530,
"s": 3444,
"text": "x = re.split(\"\\W+\",\"Hello,World\")\nprint(x)\nx = re.split(\"(\\W+)\",\"Hello,World\nprint(x)"
},
{
"code": null,
"e": 3573,
"s": 3530,
"text": "['Hello', 'World']\n['Hello', ',', 'World']"
},
{
"code": null,
"e": 3811,
"s": 3573,
"text": "In the above example, the “\\W+” basically means start splitting from the left and the + sign means keep moving forward until the end. When it is covered in brackets like in case 2, it splits and adds punctuations as well, like the comma."
},
{
"code": null,
"e": 3961,
"s": 3811,
"text": "x = re.sub(r\"there\",\"World\",\"Hello there. Python is fun.\")\nprint(x)\n\nx = re.subn(r\"there\",\"World\",\"Hello there. Python is fun. Hello there\")\nprint(x)"
},
{
"code": null,
"e": 4036,
"s": 3961,
"text": "Hello World. Python is fun.\n('Hello World. Python is fun. Hello World', 2)"
},
{
"code": null,
"e": 4133,
"s": 4036,
"text": "In the above example, the re.sub checks if the word “there” exists and replaces it with “world”."
},
{
"code": null,
"e": 4273,
"s": 4133,
"text": "The subn function does the exact same thing but returns a tuple instead of a string and also adds in the total number of replacements done."
},
{
"code": null,
"e": 4374,
"s": 4273,
"text": "One of the real world application/example for using the RegEx module would be to validate passwords."
},
{
"code": null,
"e": 4718,
"s": 4374,
"text": "import re\nmatching_sequence = r\"[0−9]\"\nwhile(True):\n x = input(\"Enter your password : \")\n r = re.search(matching_sequence,x)\n if (r and len(x)>6):\n print(x + \" is a valid password\")\n else:\n print(x + \" is not a valid password. Password MUST be atleast 7 characters with atleast 1 number\")\n input(\"Press Enter key to exit \")"
},
{
"code": null,
"e": 4827,
"s": 4718,
"text": "The program will check if you have entered a valid password (7+ characters with at least one number) or not."
},
{
"code": null,
"e": 4949,
"s": 4827,
"text": "You’ve learnt the basics of the RegEx module present in Python and all the various different functions present within it."
},
{
"code": null,
"e": 5132,
"s": 4949,
"text": "There are a lot more functions and uses for the RegEx module. If you are interested, you can read more from their official documentation at https://docs.python.org/3/library/re.html."
}
] |
CSS - Backgrounds
|
This chapter teaches you how to set backgrounds of various HTML elements. You can set the following background properties of an element −
The background-color property is used to set the background color of an element.
The background-color property is used to set the background color of an element.
The background-image property is used to set the background image of an element.
The background-image property is used to set the background image of an element.
The background-repeat property is used to control the repetition of an image in the background.
The background-repeat property is used to control the repetition of an image in the background.
The background-position property is used to control the position of an image in the background.
The background-position property is used to control the position of an image in the background.
The background-attachment property is used to control the scrolling of an image in the background.
The background-attachment property is used to control the scrolling of an image in the background.
The background property is used as a shorthand to specify a number of other background properties.
The background property is used as a shorthand to specify a number of other background properties.
Following is the example which demonstrates how to set the background color for an element.
<html>
<head>
</head>
<body>
<p style = "background-color:yellow;">
This text has a yellow background color.
</p>
</body>
</html>
This will produce following result −
This text has a yellow background color.
We can set the background image by calling local stored images as shown below −
<html>
<head>
<style>
body {
background-image: url("/css/images/css.jpg");
background-color: #cccccc;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
</body>
<html>
It will produce the following result −
The following example demonstrates how to repeat the background image if an image is small. You can use no-repeat value for background-repeat property if you don't want to repeat an image, in this case image will display only once.
By default background-repeat property will have repeat value.
<html>
<head>
<style>
body {
background-image: url("/css/images/css.jpg");
background-repeat: repeat;
}
</style>
</head>
<body>
<p>Tutorials point</p>
</body>
</html>
It will produce the following result −
Tutorials point
The following example which demonstrates how to repeat the background image vertically.
<html>
<head>
<style>
body {
background-image: url("/css/images/css.jpg");
background-repeat: repeat-y;
}
</style>
</head>
<body>
<p>Tutorials point</p>
</body>
</html>
It will produce the following result −
Tutorials point
The following example demonstrates how to repeat the background image horizontally.
<html>
<head>
<style>
body {
background-image: url("/css/images/css.jpg");
background-repeat: repeat-x;
}
</style>
</head>
<body>
<p>Tutorials point</p>
</body>
</html>
It will produce the following result −
Tutorials point
The following example demonstrates how to set the background image position 100 pixels away from the left side.
<html>
<head>
<style>
body {
background-image: url("/css/images/css.jpg");
background-position:100px;
}
</style>
</head>
<body>
<p>Tutorials point</p>
</body>
</html>
It will produce the following result −
Tutorials point
The following example demonstrates how to set the background image position 100 pixels away from the left side and 200 pixels down from the top.
<html>
<head>
<style>
body {
background-image: url("/css/images/css.jpg");
background-position:100px 200px;
}
</style>
</head>
<body>
<p>Tutorials point</p>
</body>
</html>
It will produce the following result −
Tutorials point
Background attachment determines whether a background image is fixed or scrolls with the rest of the page.
The following example demonstrates how to set the fixed background image.
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url('/css/images/css.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
}
</style>
</head>
<body>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
</body>
</html>
It will produce the following result −
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
If you do not see any scrollbars, try to resize the browser window.
The following example demonstrates how to set the scrolling background image.
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url('/css/images/css.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-attachment:scroll;
}
</style>
</head>
<body>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
</body>
</html>
It will produce the following result −
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
The background-image is fixed. Try to scroll down the page.
If you do not see any scrollbars, try to resize the browser window.
You can use the background property to set all the background properties at once. For example −
<p style = "background:url(/images/pattern1.gif) repeat fixed;">
This parapgraph has fixed repeated background image.
</p>
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2764,
"s": 2626,
"text": "This chapter teaches you how to set backgrounds of various HTML elements. You can set the following background properties of an element −"
},
{
"code": null,
"e": 2845,
"s": 2764,
"text": "The background-color property is used to set the background color of an element."
},
{
"code": null,
"e": 2926,
"s": 2845,
"text": "The background-color property is used to set the background color of an element."
},
{
"code": null,
"e": 3007,
"s": 2926,
"text": "The background-image property is used to set the background image of an element."
},
{
"code": null,
"e": 3088,
"s": 3007,
"text": "The background-image property is used to set the background image of an element."
},
{
"code": null,
"e": 3184,
"s": 3088,
"text": "The background-repeat property is used to control the repetition of an image in the background."
},
{
"code": null,
"e": 3280,
"s": 3184,
"text": "The background-repeat property is used to control the repetition of an image in the background."
},
{
"code": null,
"e": 3376,
"s": 3280,
"text": "The background-position property is used to control the position of an image in the background."
},
{
"code": null,
"e": 3472,
"s": 3376,
"text": "The background-position property is used to control the position of an image in the background."
},
{
"code": null,
"e": 3571,
"s": 3472,
"text": "The background-attachment property is used to control the scrolling of an image in the background."
},
{
"code": null,
"e": 3670,
"s": 3571,
"text": "The background-attachment property is used to control the scrolling of an image in the background."
},
{
"code": null,
"e": 3769,
"s": 3670,
"text": "The background property is used as a shorthand to specify a number of other background properties."
},
{
"code": null,
"e": 3868,
"s": 3769,
"text": "The background property is used as a shorthand to specify a number of other background properties."
},
{
"code": null,
"e": 3960,
"s": 3868,
"text": "Following is the example which demonstrates how to set the background color for an element."
},
{
"code": null,
"e": 4125,
"s": 3960,
"text": "<html>\n <head>\n </head>\n\n <body>\n <p style = \"background-color:yellow;\">\n This text has a yellow background color.\n </p>\n </body>\n</html> "
},
{
"code": null,
"e": 4162,
"s": 4125,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4208,
"s": 4162,
"text": "\n This text has a yellow background color.\n"
},
{
"code": null,
"e": 4288,
"s": 4208,
"text": "We can set the background image by calling local stored images as shown below −"
},
{
"code": null,
"e": 4530,
"s": 4288,
"text": "<html>\n <head>\n <style>\n body {\n background-image: url(\"/css/images/css.jpg\");\n background-color: #cccccc;\n }\n </style>\n </head>\n \n <body>\n <h1>Hello World!</h1>\n </body>\n<html>"
},
{
"code": null,
"e": 4569,
"s": 4530,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 4801,
"s": 4569,
"text": "The following example demonstrates how to repeat the background image if an image is small. You can use no-repeat value for background-repeat property if you don't want to repeat an image, in this case image will display only once."
},
{
"code": null,
"e": 4863,
"s": 4801,
"text": "By default background-repeat property will have repeat value."
},
{
"code": null,
"e": 5103,
"s": 4863,
"text": "<html>\n <head>\n <style>\n body {\n background-image: url(\"/css/images/css.jpg\");\n background-repeat: repeat;\n }\n </style>\n </head>\n\n <body>\n <p>Tutorials point</p>\n </body>\n</html>"
},
{
"code": null,
"e": 5142,
"s": 5103,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5158,
"s": 5142,
"text": "Tutorials point"
},
{
"code": null,
"e": 5246,
"s": 5158,
"text": "The following example which demonstrates how to repeat the background image vertically."
},
{
"code": null,
"e": 5488,
"s": 5246,
"text": "<html>\n <head>\n <style>\n body {\n background-image: url(\"/css/images/css.jpg\");\n background-repeat: repeat-y;\n }\n </style>\n </head>\n\n <body>\n <p>Tutorials point</p>\n </body>\n</html>"
},
{
"code": null,
"e": 5527,
"s": 5488,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5543,
"s": 5527,
"text": "Tutorials point"
},
{
"code": null,
"e": 5627,
"s": 5543,
"text": "The following example demonstrates how to repeat the background image horizontally."
},
{
"code": null,
"e": 5872,
"s": 5627,
"text": "<html>\n <head>\n <style>\n body {\n background-image: url(\"/css/images/css.jpg\");\n background-repeat: repeat-x;\n }\n </style>\n </head>\n \n <body>\n <p>Tutorials point</p>\n </body>\n</html>"
},
{
"code": null,
"e": 5911,
"s": 5872,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5927,
"s": 5911,
"text": "Tutorials point"
},
{
"code": null,
"e": 6039,
"s": 5927,
"text": "The following example demonstrates how to set the background image position 100 pixels away from the left side."
},
{
"code": null,
"e": 6279,
"s": 6039,
"text": "<html>\n <head>\n <style>\n body {\n background-image: url(\"/css/images/css.jpg\");\n background-position:100px;\n }\n </style>\n </head>\n\n <body>\n <p>Tutorials point</p>\n </body>\n</html>"
},
{
"code": null,
"e": 6318,
"s": 6279,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 6334,
"s": 6318,
"text": "Tutorials point"
},
{
"code": null,
"e": 6479,
"s": 6334,
"text": "The following example demonstrates how to set the background image position 100 pixels away from the left side and 200 pixels down from the top."
},
{
"code": null,
"e": 6725,
"s": 6479,
"text": "<html>\n <head>\n <style>\n body {\n background-image: url(\"/css/images/css.jpg\");\n background-position:100px 200px;\n }\n </style>\n </head>\n\n <body>\n <p>Tutorials point</p>\n </body>\n</html>"
},
{
"code": null,
"e": 6764,
"s": 6725,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 6780,
"s": 6764,
"text": "Tutorials point"
},
{
"code": null,
"e": 6887,
"s": 6780,
"text": "Background attachment determines whether a background image is fixed or scrolls with the rest of the page."
},
{
"code": null,
"e": 6961,
"s": 6887,
"text": "The following example demonstrates how to set the fixed background image."
},
{
"code": null,
"e": 7890,
"s": 6961,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n body {\n background-image: url('/css/images/css.jpg');\n background-repeat: no-repeat;\n background-attachment: fixed;\n }\n </style>\n </head>\n\n <body>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n </body>\n</html>"
},
{
"code": null,
"e": 7929,
"s": 7890,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 7989,
"s": 7929,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 8049,
"s": 7989,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 8109,
"s": 8049,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 8169,
"s": 8109,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 8229,
"s": 8169,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 8289,
"s": 8229,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 8349,
"s": 8289,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 8409,
"s": 8349,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 8469,
"s": 8409,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 8529,
"s": 8469,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 8589,
"s": 8529,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 8649,
"s": 8589,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 8709,
"s": 8649,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 8769,
"s": 8709,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 8829,
"s": 8769,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 8897,
"s": 8829,
"text": "If you do not see any scrollbars, try to resize the browser window."
},
{
"code": null,
"e": 8975,
"s": 8897,
"text": "The following example demonstrates how to set the scrolling background image."
},
{
"code": null,
"e": 9946,
"s": 8975,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n body {\n background-image: url('/css/images/css.jpg');\n background-repeat: no-repeat;\n background-attachment: fixed;\n background-attachment:scroll;\n }\n </style>\n </head>\n\n <body>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n <p>The background-image is fixed. Try to scroll down the page.</p>\n </body>\n</html>"
},
{
"code": null,
"e": 9985,
"s": 9946,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 10045,
"s": 9985,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 10105,
"s": 10045,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 10165,
"s": 10105,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 10225,
"s": 10165,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 10285,
"s": 10225,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 10345,
"s": 10285,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 10405,
"s": 10345,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 10465,
"s": 10405,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 10525,
"s": 10465,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 10585,
"s": 10525,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 10645,
"s": 10585,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 10705,
"s": 10645,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 10765,
"s": 10705,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 10825,
"s": 10765,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 10885,
"s": 10825,
"text": "The background-image is fixed. Try to scroll down the page."
},
{
"code": null,
"e": 10953,
"s": 10885,
"text": "If you do not see any scrollbars, try to resize the browser window."
},
{
"code": null,
"e": 11049,
"s": 10953,
"text": "You can use the background property to set all the background properties at once. For example −"
},
{
"code": null,
"e": 11176,
"s": 11049,
"text": "<p style = \"background:url(/images/pattern1.gif) repeat fixed;\">\n This parapgraph has fixed repeated background image.\n</p>\n"
},
{
"code": null,
"e": 11211,
"s": 11176,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11225,
"s": 11211,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 11260,
"s": 11225,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11277,
"s": 11260,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 11312,
"s": 11277,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11343,
"s": 11312,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 11378,
"s": 11343,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11409,
"s": 11378,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 11444,
"s": 11409,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 11475,
"s": 11444,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 11508,
"s": 11475,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11539,
"s": 11508,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 11546,
"s": 11539,
"text": " Print"
},
{
"code": null,
"e": 11557,
"s": 11546,
"text": " Add Notes"
}
] |
D3.js - Scales API
|
D3.js provides scale functions to perform data transformations. These functions map an input domain to an output range.
We can configure the API directly using the following script.
<script src = "https://d3js.org/d3-array.v1.min.js"></script>
<script src = "https://d3js.org/d3-collection.v1.min.js"></script>
<script src = "https://d3js.org/d3-color.v1.min.js"></script>
<script src = "https://d3js.org/d3-format.v1.min.js"></script>
<script src = "https://d3js.org/d3-interpolate.v1.min.js"></script>
<script src = "https://d3js.org/d3-time.v1.min.js"></script>
<script src = "https://d3js.org/d3-time-format.v2.min.js"></script>
<script src = "https://d3js.org/d3-scale.v1.min.js"></script>
<script>
</script>
D3 provides the following important scaling methods for different types of charts. Let us understand then in detail.
d3.scaleLinear() − Constructs a continuous linear scale where we can input data (domain) maps to the specified output range.
d3.scaleLinear() − Constructs a continuous linear scale where we can input data (domain) maps to the specified output range.
d3.scaleIdentity() − Construct a linear scale where the input data is the same as the output.
d3.scaleIdentity() − Construct a linear scale where the input data is the same as the output.
d3.scaleTime() − Construct a linear scale where the input data is in the dates and the output in numbers.
d3.scaleTime() − Construct a linear scale where the input data is in the dates and the output in numbers.
d3.scaleLog() − Construct a logarithmic scale.
d3.scaleLog() − Construct a logarithmic scale.
d3.scaleSqrt() − Construct a square root scale.
d3.scaleSqrt() − Construct a square root scale.
d3.scalePow() − Construct an exponential scale.
d3.scalePow() − Construct an exponential scale.
d3.scaleSequential() − Construct a sequential scale where output range is fixed by interpolator function.
d3.scaleSequential() − Construct a sequential scale where output range is fixed by interpolator function.
d3.scaleQuantize() − Construct a quantize scale with discrete output range.
d3.scaleQuantize() − Construct a quantize scale with discrete output range.
d3.scaleQuantile() − Construct a quantile scale where the input sample data maps to the discrete output range.
d3.scaleQuantile() − Construct a quantile scale where the input sample data maps to the discrete output range.
d3.scaleThreshold() − Construct a scale where the arbitrary input data maps to the discrete output range.
d3.scaleThreshold() − Construct a scale where the arbitrary input data maps to the discrete output range.
d3.scaleBand() − Band scales are like ordinal scales except the output range is continuous and numeric.
d3.scaleBand() − Band scales are like ordinal scales except the output range is continuous and numeric.
d3.scalePoint() − Construct a point scale.
d3.scalePoint() − Construct a point scale.
d3.scaleOrdinal() − Construct an ordinal scale where the input data includes alphabets and are mapped to the discrete numeric output range.
d3.scaleOrdinal() − Construct an ordinal scale where the input data includes alphabets and are mapped to the discrete numeric output range.
Before doing a working example, let us first understand the following two terms −
Domain − The Domain denotes minimum and maximum values of your input data.
Domain − The Domain denotes minimum and maximum values of your input data.
Range − The Range is the output range, which we would like the input values to map to...
Range − The Range is the output range, which we would like the input values to map to...
Let us perform the d3.scaleLinear function in this example. To do this, you need to adhere to the following steps −
Step 1 − Define variables − Define SVG variables and data using the coding below.
var data = [100, 200, 300, 400, 800, 0]
var width = 500,
barHeight = 20,
margin = 1;
Step 2 − Create linear scale − Use the following code to create a linear scale.
var scale = d3.scaleLinear()
.domain([d3.min(data), d3.max(data)])
.range([100, 400]);
Here, for the minimum and maximum value for our domain manually, we can use the built-in d3.min() and d3.max() functions, which will return minimum and maximum values respectively from our data array.
Step 3 − Append SVG attributes − Append the SVG elements using the code given below.
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", barHeight * data.length);
Step 4 − Apply transformation − Apply the transformation using the code below.
var g = svg.selectAll("g")
.data(data).enter().append("g")
.attr("transform", function (d, i) {
return "translate(0," + i * barHeight + ")";
});
Step 5 − Append rect elements − Append the rect elements to scaling as shown below.
g.append("rect")
.attr("width", function (d) {
return scale(d);
})
.attr("height", barHeight - margin)
Step 6 − Display data − Now display the data using the coding given below.
g.append("text")
.attr("x", function (d) { return (scale(d)); })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function (d) { return d; });
Step 7 − Working Example − Now, let us create a bar chart using the d3.scaleLinear() function as follows.
Create a webpage “scales.html” and add the following changes to it.
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var data = [100, 200, 300, 350, 400, 250]
var width = 500, barHeight = 20, margin = 1;
var scale = d3.scaleLinear()
.domain([d3.min(data), d3.max(data)])
.range([100, 400]);
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", barHeight * data.length);
var g = svg.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function (d, i) {
return "translate(0," + i * barHeight + ")";
});
g.append("rect")
.attr("width", function (d) {
return scale(d);
})
.attr("height", barHeight - margin)
g.append("text")
.attr("x", function (d) { return (scale(d)); })
.attr("y", barHeight / 2).attr("dy", ".35em")
.text(function (d) { return d; });
</script>
</body>
</html>
The above code will display the following result in the browser.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2250,
"s": 2130,
"text": "D3.js provides scale functions to perform data transformations. These functions map an input domain to an output range."
},
{
"code": null,
"e": 2312,
"s": 2250,
"text": "We can configure the API directly using the following script."
},
{
"code": null,
"e": 2845,
"s": 2312,
"text": "<script src = \"https://d3js.org/d3-array.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-collection.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-color.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-format.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-interpolate.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-time.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-time-format.v2.min.js\"></script>\n<script src = \"https://d3js.org/d3-scale.v1.min.js\"></script>\n<script>\n\n</script>"
},
{
"code": null,
"e": 2962,
"s": 2845,
"text": "D3 provides the following important scaling methods for different types of charts. Let us understand then in detail."
},
{
"code": null,
"e": 3087,
"s": 2962,
"text": "d3.scaleLinear() − Constructs a continuous linear scale where we can input data (domain) maps to the specified output range."
},
{
"code": null,
"e": 3212,
"s": 3087,
"text": "d3.scaleLinear() − Constructs a continuous linear scale where we can input data (domain) maps to the specified output range."
},
{
"code": null,
"e": 3306,
"s": 3212,
"text": "d3.scaleIdentity() − Construct a linear scale where the input data is the same as the output."
},
{
"code": null,
"e": 3400,
"s": 3306,
"text": "d3.scaleIdentity() − Construct a linear scale where the input data is the same as the output."
},
{
"code": null,
"e": 3506,
"s": 3400,
"text": "d3.scaleTime() − Construct a linear scale where the input data is in the dates and the output in numbers."
},
{
"code": null,
"e": 3612,
"s": 3506,
"text": "d3.scaleTime() − Construct a linear scale where the input data is in the dates and the output in numbers."
},
{
"code": null,
"e": 3659,
"s": 3612,
"text": "d3.scaleLog() − Construct a logarithmic scale."
},
{
"code": null,
"e": 3706,
"s": 3659,
"text": "d3.scaleLog() − Construct a logarithmic scale."
},
{
"code": null,
"e": 3754,
"s": 3706,
"text": "d3.scaleSqrt() − Construct a square root scale."
},
{
"code": null,
"e": 3802,
"s": 3754,
"text": "d3.scaleSqrt() − Construct a square root scale."
},
{
"code": null,
"e": 3850,
"s": 3802,
"text": "d3.scalePow() − Construct an exponential scale."
},
{
"code": null,
"e": 3898,
"s": 3850,
"text": "d3.scalePow() − Construct an exponential scale."
},
{
"code": null,
"e": 4004,
"s": 3898,
"text": "d3.scaleSequential() − Construct a sequential scale where output range is fixed by interpolator function."
},
{
"code": null,
"e": 4110,
"s": 4004,
"text": "d3.scaleSequential() − Construct a sequential scale where output range is fixed by interpolator function."
},
{
"code": null,
"e": 4186,
"s": 4110,
"text": "d3.scaleQuantize() − Construct a quantize scale with discrete output range."
},
{
"code": null,
"e": 4262,
"s": 4186,
"text": "d3.scaleQuantize() − Construct a quantize scale with discrete output range."
},
{
"code": null,
"e": 4373,
"s": 4262,
"text": "d3.scaleQuantile() − Construct a quantile scale where the input sample data maps to the discrete output range."
},
{
"code": null,
"e": 4484,
"s": 4373,
"text": "d3.scaleQuantile() − Construct a quantile scale where the input sample data maps to the discrete output range."
},
{
"code": null,
"e": 4590,
"s": 4484,
"text": "d3.scaleThreshold() − Construct a scale where the arbitrary input data maps to the discrete output range."
},
{
"code": null,
"e": 4696,
"s": 4590,
"text": "d3.scaleThreshold() − Construct a scale where the arbitrary input data maps to the discrete output range."
},
{
"code": null,
"e": 4800,
"s": 4696,
"text": "d3.scaleBand() − Band scales are like ordinal scales except the output range is continuous and numeric."
},
{
"code": null,
"e": 4904,
"s": 4800,
"text": "d3.scaleBand() − Band scales are like ordinal scales except the output range is continuous and numeric."
},
{
"code": null,
"e": 4947,
"s": 4904,
"text": "d3.scalePoint() − Construct a point scale."
},
{
"code": null,
"e": 4990,
"s": 4947,
"text": "d3.scalePoint() − Construct a point scale."
},
{
"code": null,
"e": 5130,
"s": 4990,
"text": "d3.scaleOrdinal() − Construct an ordinal scale where the input data includes alphabets and are mapped to the discrete numeric output range."
},
{
"code": null,
"e": 5270,
"s": 5130,
"text": "d3.scaleOrdinal() − Construct an ordinal scale where the input data includes alphabets and are mapped to the discrete numeric output range."
},
{
"code": null,
"e": 5352,
"s": 5270,
"text": "Before doing a working example, let us first understand the following two terms −"
},
{
"code": null,
"e": 5427,
"s": 5352,
"text": "Domain − The Domain denotes minimum and maximum values of your input data."
},
{
"code": null,
"e": 5502,
"s": 5427,
"text": "Domain − The Domain denotes minimum and maximum values of your input data."
},
{
"code": null,
"e": 5591,
"s": 5502,
"text": "Range − The Range is the output range, which we would like the input values to map to..."
},
{
"code": null,
"e": 5680,
"s": 5591,
"text": "Range − The Range is the output range, which we would like the input values to map to..."
},
{
"code": null,
"e": 5796,
"s": 5680,
"text": "Let us perform the d3.scaleLinear function in this example. To do this, you need to adhere to the following steps −"
},
{
"code": null,
"e": 5878,
"s": 5796,
"text": "Step 1 − Define variables − Define SVG variables and data using the coding below."
},
{
"code": null,
"e": 5980,
"s": 5878,
"text": "var data = [100, 200, 300, 400, 800, 0]\n var width = 500, \n barHeight = 20, \n margin = 1;"
},
{
"code": null,
"e": 6060,
"s": 5980,
"text": "Step 2 − Create linear scale − Use the following code to create a linear scale."
},
{
"code": null,
"e": 6153,
"s": 6060,
"text": "var scale = d3.scaleLinear()\n .domain([d3.min(data), d3.max(data)])\n .range([100, 400]);"
},
{
"code": null,
"e": 6354,
"s": 6153,
"text": "Here, for the minimum and maximum value for our domain manually, we can use the built-in d3.min() and d3.max() functions, which will return minimum and maximum values respectively from our data array."
},
{
"code": null,
"e": 6439,
"s": 6354,
"text": "Step 3 − Append SVG attributes − Append the SVG elements using the code given below."
},
{
"code": null,
"e": 6555,
"s": 6439,
"text": "var svg = d3.select(\"body\")\n .append(\"svg\")\n .attr(\"width\", width)\n .attr(\"height\", barHeight * data.length);"
},
{
"code": null,
"e": 6634,
"s": 6555,
"text": "Step 4 − Apply transformation − Apply the transformation using the code below."
},
{
"code": null,
"e": 6791,
"s": 6634,
"text": "var g = svg.selectAll(\"g\")\n .data(data).enter().append(\"g\")\n .attr(\"transform\", function (d, i) {\n return \"translate(0,\" + i * barHeight + \")\";\n});"
},
{
"code": null,
"e": 6875,
"s": 6791,
"text": "Step 5 − Append rect elements − Append the rect elements to scaling as shown below."
},
{
"code": null,
"e": 6993,
"s": 6875,
"text": "g.append(\"rect\")\n .attr(\"width\", function (d) {\n return scale(d);\n })\n .attr(\"height\", barHeight - margin)"
},
{
"code": null,
"e": 7068,
"s": 6993,
"text": "Step 6 − Display data − Now display the data using the coding given below."
},
{
"code": null,
"e": 7227,
"s": 7068,
"text": "g.append(\"text\")\n .attr(\"x\", function (d) { return (scale(d)); })\n .attr(\"y\", barHeight / 2)\n .attr(\"dy\", \".35em\")\n .text(function (d) { return d; });"
},
{
"code": null,
"e": 7334,
"s": 7227,
"text": "Step 7 − Working Example − Now, let us create a bar chart using the d3.scaleLinear() function as follows. "
},
{
"code": null,
"e": 7402,
"s": 7334,
"text": "Create a webpage “scales.html” and add the following changes to it."
},
{
"code": null,
"e": 8577,
"s": 7402,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n </head>\n\n <body>\n <script>\n var data = [100, 200, 300, 350, 400, 250]\n var width = 500, barHeight = 20, margin = 1;\n \n var scale = d3.scaleLinear()\n .domain([d3.min(data), d3.max(data)])\n .range([100, 400]);\n \n var svg = d3.select(\"body\")\n .append(\"svg\")\n .attr(\"width\", width)\n .attr(\"height\", barHeight * data.length);\n \n var g = svg.selectAll(\"g\")\n .data(data)\n .enter()\n .append(\"g\")\n .attr(\"transform\", function (d, i) {\n return \"translate(0,\" + i * barHeight + \")\";\n });\n \n g.append(\"rect\")\n .attr(\"width\", function (d) {\n return scale(d);\n })\n \n .attr(\"height\", barHeight - margin)\n g.append(\"text\")\n .attr(\"x\", function (d) { return (scale(d)); })\n .attr(\"y\", barHeight / 2).attr(\"dy\", \".35em\")\n .text(function (d) { return d; });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 8642,
"s": 8577,
"text": "The above code will display the following result in the browser."
},
{
"code": null,
"e": 8649,
"s": 8642,
"text": " Print"
},
{
"code": null,
"e": 8660,
"s": 8649,
"text": " Add Notes"
}
] |
Java8 Concatenate Arrays Example | Java Concatenate Two Arrays
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, I am going to show you how to concatenate arrays using Java8 streams.
import java.util.Arrays;
import java.util.stream.Stream;
public class Array_Concatinate {
public static void main(String[] args) {
String[] alphabets = { "AB", "BA", "AC" };
String[] numarics = { "1", "2", "3" };
String[] both = Stream.concat(Arrays.stream(alphabets),
Arrays.stream(numarics)).toArray(String[]::new);
for (String string : both) {
System.out.println(string);
}
}
}
Output:
AB
BA
AC
1
2
3
import java.util.stream.Stream;
public class Array_Concatinate {
public static void main(String[] args) {
String[] alphabets = { "AB", "BA", "AC" };
String[] numarics = { "1", "2", "3" };
String[] both = Stream.of(alphabets, numarics).flatMap(Stream::of)
.toArray(String[]::new);
for (String string : both) {
System.out.println(string);
}
}
}
[/java]
Output:
AB
BA
AC
1
2
3
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Array_Concatinate {
public static void main(String[] args) {
String[] alphabets = { "AB", "BA", "AC" };
String[] numarics = { "1", "2", "3" };
List<String> both = new ArrayList<String>(alphabets.length
+ numarics.length);
Collections.addAll(both, alphabets);
Collections.addAll(both, numarics);
String[] strArray = both.toArray(new String[both.size()]);
for (String string : strArray) {
System.out.println(string);
}
}
}
Output:
AB
BA
AC
1
2
3
Happy Learning 🙂
User defined sorting with Java 8 Comparator
Java 8 Read File Line By Line Example
How to Filter a Map in Java 8
How to Filter null values from Java8 Stream
Java 8 Array contains a specific value ?
Java 8 groupingBy Example
How to sort a Map using Java8
Java 8 Stream Filter Example with Objects
Java 8 How to convert Stream to List
How to get Stream count in Java 8
Java 8 Getting Min and Max values from a Stream
How to Convert Iterable to Stream Java 8
How Java 8 Stream generate random String and Numbers
How to Install Java8 on Windows 10
Java 8 Stream API and Parallelism
User defined sorting with Java 8 Comparator
Java 8 Read File Line By Line Example
How to Filter a Map in Java 8
How to Filter null values from Java8 Stream
Java 8 Array contains a specific value ?
Java 8 groupingBy Example
How to sort a Map using Java8
Java 8 Stream Filter Example with Objects
Java 8 How to convert Stream to List
How to get Stream count in Java 8
Java 8 Getting Min and Max values from a Stream
How to Convert Iterable to Stream Java 8
How Java 8 Stream generate random String and Numbers
How to Install Java8 on Windows 10
Java 8 Stream API and Parallelism
Δ
Java8 – Install Windows
Java8 – foreach
Java8 – forEach with index
Java8 – Stream Filter Objects
Java8 – Comparator Userdefined
Java8 – GroupingBy
Java8 – SummingInt
Java8 – walk ReadFiles
Java8 – JAVA_HOME on Windows
Howto – Install Java on Mac OS
Howto – Convert Iterable to Stream
Howto – Get common elements from two Lists
Howto – Convert List to String
Howto – Concatenate Arrays using Stream
Howto – Remove duplicates from List
Howto – Filter null values from Stream
Howto – Convert List to Map
Howto – Convert Stream to List
Howto – Sort a Map
Howto – Filter a Map
Howto – Get Current UTC Time
Howto – Verify an Array contains a specific value
Howto – Convert ArrayList to Array
Howto – Read File Line By Line
Howto – Convert Date to LocalDate
Howto – Merge Streams
Howto – Resolve NullPointerException in toMap
Howto -Get Stream count
Howto – Get Min and Max values in a Stream
Howto – Convert InputStream to String
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 486,
"s": 398,
"text": "In this tutorial, I am going to show you how to concatenate arrays using Java8 streams."
},
{
"code": null,
"e": 947,
"s": 486,
"text": "import java.util.Arrays;\nimport java.util.stream.Stream;\n\npublic class Array_Concatinate {\n\n public static void main(String[] args) {\n\n String[] alphabets = { \"AB\", \"BA\", \"AC\" };\n String[] numarics = { \"1\", \"2\", \"3\" };\n\n String[] both = Stream.concat(Arrays.stream(alphabets),\n Arrays.stream(numarics)).toArray(String[]::new);\n for (String string : both) {\n System.out.println(string);\n }\n }\n}"
},
{
"code": null,
"e": 955,
"s": 947,
"text": "Output:"
},
{
"code": null,
"e": 970,
"s": 955,
"text": "AB\nBA\nAC\n1\n2\n3"
},
{
"code": null,
"e": 1394,
"s": 970,
"text": "import java.util.stream.Stream;\n\npublic class Array_Concatinate {\n\n public static void main(String[] args) {\n\n String[] alphabets = { \"AB\", \"BA\", \"AC\" };\n String[] numarics = { \"1\", \"2\", \"3\" };\n\n String[] both = Stream.of(alphabets, numarics).flatMap(Stream::of)\n .toArray(String[]::new);\n\n for (String string : both) {\n System.out.println(string);\n }\n }\n}"
},
{
"code": null,
"e": 1402,
"s": 1394,
"text": "[/java]"
},
{
"code": null,
"e": 1410,
"s": 1402,
"text": "Output:"
},
{
"code": null,
"e": 1425,
"s": 1410,
"text": "AB\nBA\nAC\n1\n2\n3"
},
{
"code": null,
"e": 2045,
"s": 1425,
"text": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Array_Concatinate {\n\n public static void main(String[] args) {\n\n String[] alphabets = { \"AB\", \"BA\", \"AC\" };\n String[] numarics = { \"1\", \"2\", \"3\" };\n\n List<String> both = new ArrayList<String>(alphabets.length\n + numarics.length);\n Collections.addAll(both, alphabets);\n Collections.addAll(both, numarics);\n String[] strArray = both.toArray(new String[both.size()]);\n\n for (String string : strArray) {\n System.out.println(string);\n }\n }\n}"
},
{
"code": null,
"e": 2053,
"s": 2045,
"text": "Output:"
},
{
"code": null,
"e": 2068,
"s": 2053,
"text": "AB\nBA\nAC\n1\n2\n3"
},
{
"code": null,
"e": 2085,
"s": 2068,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 2664,
"s": 2085,
"text": "\nUser defined sorting with Java 8 Comparator\nJava 8 Read File Line By Line Example\nHow to Filter a Map in Java 8\nHow to Filter null values from Java8 Stream\nJava 8 Array contains a specific value ?\nJava 8 groupingBy Example\nHow to sort a Map using Java8\nJava 8 Stream Filter Example with Objects\nJava 8 How to convert Stream to List\nHow to get Stream count in Java 8\nJava 8 Getting Min and Max values from a Stream\nHow to Convert Iterable to Stream Java 8\nHow Java 8 Stream generate random String and Numbers\nHow to Install Java8 on Windows 10\nJava 8 Stream API and Parallelism\n"
},
{
"code": null,
"e": 2708,
"s": 2664,
"text": "User defined sorting with Java 8 Comparator"
},
{
"code": null,
"e": 2746,
"s": 2708,
"text": "Java 8 Read File Line By Line Example"
},
{
"code": null,
"e": 2776,
"s": 2746,
"text": "How to Filter a Map in Java 8"
},
{
"code": null,
"e": 2820,
"s": 2776,
"text": "How to Filter null values from Java8 Stream"
},
{
"code": null,
"e": 2861,
"s": 2820,
"text": "Java 8 Array contains a specific value ?"
},
{
"code": null,
"e": 2887,
"s": 2861,
"text": "Java 8 groupingBy Example"
},
{
"code": null,
"e": 2917,
"s": 2887,
"text": "How to sort a Map using Java8"
},
{
"code": null,
"e": 2959,
"s": 2917,
"text": "Java 8 Stream Filter Example with Objects"
},
{
"code": null,
"e": 2996,
"s": 2959,
"text": "Java 8 How to convert Stream to List"
},
{
"code": null,
"e": 3030,
"s": 2996,
"text": "How to get Stream count in Java 8"
},
{
"code": null,
"e": 3078,
"s": 3030,
"text": "Java 8 Getting Min and Max values from a Stream"
},
{
"code": null,
"e": 3119,
"s": 3078,
"text": "How to Convert Iterable to Stream Java 8"
},
{
"code": null,
"e": 3172,
"s": 3119,
"text": "How Java 8 Stream generate random String and Numbers"
},
{
"code": null,
"e": 3207,
"s": 3172,
"text": "How to Install Java8 on Windows 10"
},
{
"code": null,
"e": 3241,
"s": 3207,
"text": "Java 8 Stream API and Parallelism"
},
{
"code": null,
"e": 3247,
"s": 3245,
"text": "Δ"
},
{
"code": null,
"e": 3272,
"s": 3247,
"text": " Java8 – Install Windows"
},
{
"code": null,
"e": 3289,
"s": 3272,
"text": " Java8 – foreach"
},
{
"code": null,
"e": 3317,
"s": 3289,
"text": " Java8 – forEach with index"
},
{
"code": null,
"e": 3348,
"s": 3317,
"text": " Java8 – Stream Filter Objects"
},
{
"code": null,
"e": 3380,
"s": 3348,
"text": " Java8 – Comparator Userdefined"
},
{
"code": null,
"e": 3400,
"s": 3380,
"text": " Java8 – GroupingBy"
},
{
"code": null,
"e": 3420,
"s": 3400,
"text": " Java8 – SummingInt"
},
{
"code": null,
"e": 3444,
"s": 3420,
"text": " Java8 – walk ReadFiles"
},
{
"code": null,
"e": 3474,
"s": 3444,
"text": " Java8 – JAVA_HOME on Windows"
},
{
"code": null,
"e": 3506,
"s": 3474,
"text": " Howto – Install Java on Mac OS"
},
{
"code": null,
"e": 3542,
"s": 3506,
"text": " Howto – Convert Iterable to Stream"
},
{
"code": null,
"e": 3586,
"s": 3542,
"text": " Howto – Get common elements from two Lists"
},
{
"code": null,
"e": 3618,
"s": 3586,
"text": " Howto – Convert List to String"
},
{
"code": null,
"e": 3659,
"s": 3618,
"text": " Howto – Concatenate Arrays using Stream"
},
{
"code": null,
"e": 3696,
"s": 3659,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 3736,
"s": 3696,
"text": " Howto – Filter null values from Stream"
},
{
"code": null,
"e": 3765,
"s": 3736,
"text": " Howto – Convert List to Map"
},
{
"code": null,
"e": 3797,
"s": 3765,
"text": " Howto – Convert Stream to List"
},
{
"code": null,
"e": 3817,
"s": 3797,
"text": " Howto – Sort a Map"
},
{
"code": null,
"e": 3839,
"s": 3817,
"text": " Howto – Filter a Map"
},
{
"code": null,
"e": 3869,
"s": 3839,
"text": " Howto – Get Current UTC Time"
},
{
"code": null,
"e": 3920,
"s": 3869,
"text": " Howto – Verify an Array contains a specific value"
},
{
"code": null,
"e": 3956,
"s": 3920,
"text": " Howto – Convert ArrayList to Array"
},
{
"code": null,
"e": 3988,
"s": 3956,
"text": " Howto – Read File Line By Line"
},
{
"code": null,
"e": 4023,
"s": 3988,
"text": " Howto – Convert Date to LocalDate"
},
{
"code": null,
"e": 4046,
"s": 4023,
"text": " Howto – Merge Streams"
},
{
"code": null,
"e": 4093,
"s": 4046,
"text": " Howto – Resolve NullPointerException in toMap"
},
{
"code": null,
"e": 4118,
"s": 4093,
"text": " Howto -Get Stream count"
},
{
"code": null,
"e": 4162,
"s": 4118,
"text": " Howto – Get Min and Max values in a Stream"
}
] |
How to make a txt file in internal storage in android?
|
This example demonstrates How to make a txt file in internal storage in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<EditText
android:id = "@+id/enterText"
android:hint = "Please enter text here"
android:layout_width = "match_parent"
android:layout_height = "wrap_content" />
<Button
android:id = "@+id/save"
android:text = "Save"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken editext and button. When the user clicks on the button, it will take data from edit text and store in internal storage as /data/data/<your.package.name>/files/text/sample.txt.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import java.io.FileWriter;
public class MainActivity extends AppCompatActivity {
Button save;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText enterText = findViewById(R.id.enterText);
save = findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!enterText.getText().toString().isEmpty()) {
File file = new File(MainActivity.this.getFilesDir(), "text");
if (!file.exists()) {
file.mkdir();
}
try {
File gpxfile = new File(file, "sample");
FileWriter writer = new FileWriter(gpxfile);
writer.append(enterText.getText().toString());
writer.flush();
writer.close();
Toast.makeText(MainActivity.this, "Saved your text", Toast.LENGTH_LONG).show();
} catch (Exception e) { }
}
}
});
}
}
Step 4 − Add the following code to manifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.andy.myapplication">
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity android:name = ".MainActivity">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the 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 −
In the above result, we have added some text and clicked on the save button as shown below –
To verify the above result, /data/data/<your.package.name>/files/text/sample.txt as shown below –
Click here to download the project code
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "This example demonstrates How to make a txt file in internal storage in android."
},
{
"code": null,
"e": 1272,
"s": 1143,
"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": 1337,
"s": 1272,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2027,
"s": 1337,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout 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 = \".MainActivity\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/enterText\"\n android:hint = \"Please enter text here\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/save\"\n android:text = \"Save\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2236,
"s": 2027,
"text": "In the above code, we have taken editext and button. When the user clicks on the button, it will take data from edit text and store in internal storage as /data/data/<your.package.name>/files/text/sample.txt."
},
{
"code": null,
"e": 2293,
"s": 2236,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3700,
"s": 2293,
"text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.Toast;\nimport java.io.File;\nimport java.io.FileWriter;\npublic class MainActivity extends AppCompatActivity {\n Button save;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final EditText enterText = findViewById(R.id.enterText);\n save = findViewById(R.id.save);\n save.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!enterText.getText().toString().isEmpty()) {\n File file = new File(MainActivity.this.getFilesDir(), \"text\");\n if (!file.exists()) {\n file.mkdir();\n }\n try {\n File gpxfile = new File(file, \"sample\");\n FileWriter writer = new FileWriter(gpxfile);\n writer.append(enterText.getText().toString());\n writer.flush();\n writer.close();\n Toast.makeText(MainActivity.this, \"Saved your text\", Toast.LENGTH_LONG).show();\n } catch (Exception e) { }\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 3748,
"s": 3700,
"text": "Step 4 − Add the following code to manifest.xml"
},
{
"code": null,
"e": 4544,
"s": 3748,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\n <uses-permission android:name = \"android.permission.WRITE_EXTERNAL_STORAGE\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4895,
"s": 4544,
"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 the 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": 4988,
"s": 4895,
"text": "In the above result, we have added some text and clicked on the save button as shown below –"
},
{
"code": null,
"e": 5086,
"s": 4988,
"text": "To verify the above result, /data/data/<your.package.name>/files/text/sample.txt as shown below –"
},
{
"code": null,
"e": 5126,
"s": 5086,
"text": "Click here to download the project code"
}
] |
Minimum XOR Value Pair - GeeksforGeeks
|
11 Mar, 2022
Given an array of integers. Find the pair in an array that has a minimum XOR value. Examples :
Input : arr[] = {9, 5, 3}
Output : 6
All pair with xor value (9 ^ 5) => 12,
(5 ^ 3) => 6, (9 ^ 3) => 10.
Minimum XOR value is 6
Input : arr[] = {1, 2, 3, 4, 5}
Output : 1
A Simple Solution is to generate all pairs of the given array and compute XOR their values. Finally, return minimum XOR value. This solution takes O(n2) time.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find minimum XOR value in an array.#include <bits/stdc++.h>using namespace std; // Returns minimum xor value of pair in arr[0..n-1]int minXOR(int arr[], int n){ int min_xor = INT_MAX; // Initialize result // Generate all pair of given array for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // update minimum xor value if required min_xor = min(min_xor, arr[i] ^ arr[j]); return min_xor;} // Driver programint main(){ int arr[] = { 9, 5, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minXOR(arr, n) << endl; return 0;}
// Java program to find minimum XOR value in an array.class GFG { // Returns minimum xor value of pair in arr[0..n-1] static int minXOR(int arr[], int n) { int min_xor = Integer.MAX_VALUE; // Initialize result // Generate all pair of given array for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // update minimum xor value if required min_xor = Math.min(min_xor, arr[i] ^ arr[j]); return min_xor; } // Driver program public static void main(String args[]) { int arr[] = { 9, 5, 3 }; int n = arr.length; System.out.println(minXOR(arr, n)); }}// This code is contributed by Sumit Ghosh
# Python program to find minimum# XOR value in an array. # Function to find minimum XOR pairdef minXOR(arr, n): # Sort given array arr.sort(); min_xor = 999999 val = 0 # calculate min xor of # consecutive pairs for i in range (0, n-1): for j in range (i+1, n-1): # update minimum xor value # if required val = arr[i] ^ arr[j] min_xor = min(min_xor, val) return min_xor # Driver programarr = [ 9, 5, 3 ]n = len(arr) print(minXOR(arr, n)) # This code is contributed by Sam007.
// C# program to find minimum// XOR value in an array.using System; class GFG { // Returns minimum xor value of // pair in arr[0..n-1] static int minXOR(int[] arr, int n) { // Initialize result int min_xor = int.MaxValue; // Generate all pair of given array for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // update minimum xor value if required min_xor = Math.Min(min_xor, arr[i] ^ arr[j]); return min_xor; } // Driver program public static void Main() { int[] arr = { 9, 5, 3 }; int n = arr.Length; Console.WriteLine(minXOR(arr, n)); }} // This code is contributed by Sam007
<?php// PHP program to find minimum// XOR value in an array. // Returns minimum xor value// of pair in arr[0..n-1]function minXOR($arr, $n){ // Initialize result $min_xor = PHP_INT_MAX; // Generate all pair of given array for ( $i = 0; $i < $n; $i++) for ( $j = $i + 1; $j < $n; $j++) // update minimum xor // value if required $min_xor = min($min_xor, $arr[$i] ^ $arr[$j]); return $min_xor;} // Driver Code $arr = array(9, 5, 3); $n = count($arr); echo minXOR($arr, $n); // This code is contributed by anuj_67.?>
<script> // Javascript program to find// minimum XOR value in an array. // Returns minimum xor value of pair in arr[0..n-1]function minXOR(arr, n){ // Initialize result let min_xor = Number.MAX_VALUE; // Generate all pair of given array for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) // update minimum xor value if required min_xor = Math.min(min_xor, arr[i] ^ arr[j]); return min_xor;} // Driver program let arr = [ 9, 5, 3 ]; let n = arr.length; document.write(minXOR(arr, n)); </script>
Output:
6
An Efficient solution can solve this problem in O(nlogn) time. Below is the algorithm:
1). Sort the given array
2). Traverse and check XOR for every consecutive pair
Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std; // Function to find minimum XOR pairint minXOR(int arr[], int n){ // Sort given array sort(arr, arr + n); int minXor = INT_MAX; int val = 0; // calculate min xor of consecutive pairs for (int i = 0; i < n - 1; i++) { val = arr[i] ^ arr[i + 1]; minXor = min(minXor, val); } return minXor;} // Driver programint main(){ int arr[] = { 9, 5, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minXOR(arr, n) << endl; return 0;}
import java.util.Arrays;class GFG { // Function to find minimum XOR pair static int minXOR(int arr[], int n) { // Sort given array Arrays.parallelSort(arr); int minXor = Integer.MAX_VALUE; int val = 0; // calculate min xor of consecutive pairs for (int i = 0; i < n - 1; i++) { val = arr[i] ^ arr[i + 1]; minXor = Math.min(minXor, val); } return minXor; } // Driver program public static void main(String args[]) { int arr[] = { 9, 5, 3 }; int n = arr.length; System.out.println(minXOR(arr, n)); }} // This code is contributed by Sumit Ghosh
import sys # Function to find minimum XOR pairdef minXOR(arr, n): # Sort given array arr.sort() minXor = int(sys.float_info.max) val = 0 # calculate min xor of consecutive pairs for i in range(0,n-1): val = arr[i] ^ arr[i + 1]; minXor = min(minXor, val); return minXor # Driver programarr = [9, 5, 3]n = len(arr)print(minXOR(arr, n)) # This code is contributed by Sam007.
// C# program to find minimum// XOR value in an array.using System; class GFG { // Function to find minimum XOR pair static int minXOR(int[] arr, int n) { // Sort given array Array.Sort(arr); int minXor = int.MaxValue; int val = 0; // calculate min xor of consecutive pairs for (int i = 0; i < n - 1; i++) { val = arr[i] ^ arr[i + 1]; minXor = Math.Min(minXor, val); } return minXor; } // Driver program public static void Main() { int[] arr = { 9, 5, 3 }; int n = arr.Length; Console.WriteLine(minXOR(arr, n)); }} // This code is contributed by Sam007
<?php// Function to find minimum XOR pairfunction minXOR($arr, $n){ // Sort given array sort($arr); $minXor = PHP_INT_MAX; $val = 0; // calculate min xor // of consecutive pairs for ($i = 0; $i < $n - 1; $i++) { $val = $arr[$i] ^ $arr[$i + 1]; $minXor = min($minXor, $val); } return $minXor;} // Driver Code$arr = array(9, 5, 3);$n = count($arr);echo minXOR($arr, $n); // This code is contributed by Smitha.?>
<script> // Function to find minimum XOR pairfunction minXOR(arr, n){ // Sort given array arr.sort(); let minXor = Number.MAX_VALUE; let val = 0; // calculate min xor of consecutive pairs for (let i = 0; i < n - 1; i++) { val = arr[i] ^ arr[i + 1]; minXor = Math.min(minXor, val); } return minXor;} // Driver program let arr = [ 9, 5, 3 ]; let n = arr.length; document.write(minXOR(arr, n)); </script>
Output :
6
Time Complexity: O(N*logN) Space Complexity: O(1) Thanks to Utkarsh Gupta for suggesting above approach. A further more Efficient solution can solve the above problem in O(n) time under the assumption that integers take fixed number of bits to store. The idea is to use Trie Data Structure. Below is algorithm.
1). Create an empty trie. Every node of trie contains two children
for 0 and 1 bits.
2). Initialize min_xor = INT_MAX, insert arr[0] into trie
3). Traversal all array element one-by-one starting from second.
a. First find minimum setbet difference value in trie
do xor of current element with minimum setbit diff that value
b. update min_xor value if required
c. insert current array element in trie
4). return min_xor
Below is the implementation of above algorithm.
C++
Java
Python
// C++ program to find minimum XOR value in an array.#include <bits/stdc++.h>using namespace std;#define INT_SIZE 32 // A Trie Nodestruct TrieNode { int value; // used in leaf node TrieNode* Child[2];}; // Utility function to create a new Trie nodeTrieNode* getNode(){ TrieNode* newNode = new TrieNode; newNode->value = 0; newNode->Child[0] = newNode->Child[1] = NULL; return newNode;} // utility function insert new key in trievoid insert(TrieNode* root, int key){ TrieNode* temp = root; // start from the most significant bit, insert all // bit of key one-by-one into trie for (int i = INT_SIZE - 1; i >= 0; i--) { // Find current bit in given prefix bool current_bit = (key & (1 << i)); // Add a new Node into trie if (temp->Child[current_bit] == NULL) temp->Child[current_bit] = getNode(); temp = temp->Child[current_bit]; } // store value at leafNode temp->value = key;} // Returns minimum XOR value of an integer inserted// in Trie and given key.int minXORUtil(TrieNode* root, int key){ TrieNode* temp = root; for (int i = INT_SIZE - 1; i >= 0; i--) { // Find current bit in given prefix bool current_bit = (key & (1 << i)); // Traversal Trie, look for prefix that has // same bit if (temp->Child[current_bit] != NULL) temp = temp->Child[current_bit]; // if there is no same bit.then looking for // opposite bit else if (temp->Child[1 - current_bit] != NULL) temp = temp->Child[1 - current_bit]; } // return xor value of minimum bit difference value // so we get minimum xor value return key ^ temp->value;} // Returns minimum xor value of pair in arr[0..n-1]int minXOR(int arr[], int n){ int min_xor = INT_MAX; // Initialize result // create a True and insert first element in it TrieNode* root = getNode(); insert(root, arr[0]); // Traverse all array element and find minimum xor // for every element for (int i = 1; i < n; i++) { // Find minimum XOR value of current element with // previous elements inserted in Trie min_xor = min(min_xor, minXORUtil(root, arr[i])); // insert current array value into Trie insert(root, arr[i]); } return min_xor;} // Driver codeint main(){ int arr[] = { 9, 5, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minXOR(arr, n) << endl; return 0;}
// Java program to find minimum XOR value in an array.class GFG { static final int INT_SIZE = 32; // A Trie Node static class TrieNode { int value; // used in leaf node TrieNode[] Child = new TrieNode[2]; public TrieNode() { value = 0; Child[0] = null; Child[1] = null; } } static TrieNode root; // utility function insert new key in trie static void insert(int key) { TrieNode temp = root; // start from the most significant bit, insert all // bit of key one-by-one into trie for (int i = INT_SIZE - 1; i >= 0; i--) { // Find current bit in given prefix int current_bit = (key & (1 << i)) >= 1 ? 1 : 0; // Add a new Node into trie if (temp != null && temp.Child[current_bit] == null) temp.Child[current_bit] = new TrieNode(); temp = temp.Child[current_bit]; } // store value at leafNode temp.value = key; } // Returns minimum XOR value of an integer inserted // in Trie and given key. static int minXORUtil(int key) { TrieNode temp = root; for (int i = INT_SIZE - 1; i >= 0; i--) { // Find current bit in given prefix int current_bit = (key & (1 << i)) >= 1 ? 1 : 0; // Traversal Trie, look for prefix that has // same bit if (temp.Child[current_bit] != null) temp = temp.Child[current_bit]; // if there is no same bit.then looking for // opposite bit else if (temp.Child[1 - current_bit] != null) temp = temp.Child[1 - current_bit]; } // return xor value of minimum bit difference value // so we get minimum xor value return key ^ temp.value; } // Returns minimum xor value of pair in arr[0..n-1] static int minXOR(int arr[], int n) { int min_xor = Integer.MAX_VALUE; // Initialize result // create a True and insert first element in it root = new TrieNode(); insert(arr[0]); // Traverse all array element and find minimum xor // for every element for (int i = 1; i < n; i++) { // Find minimum XOR value of current element with // previous elements inserted in Trie min_xor = Math.min(min_xor, minXORUtil(arr[i])); // insert current array value into Trie insert(arr[i]); } return min_xor; } // Driver code public static void main(String args[]) { int arr[] = { 9, 5, 3 }; int n = arr.length; System.out.println(minXOR(arr, n)); }}// This code is contributed by Sumit Ghosh
# class for the basic Trie Nodeclass TrieNode: def __init__(self): # Child array with 0 and 1 self.child = [None]*2 # meant for the lead Node self.value = None class Trie: def __init__(self): # initialise the root Node self.root = self.getNode() def getNode(self): # get a new Trie Node return TrieNode() # inserts a new element def insert(self,key): temp = self.root # 32 bit valued binary digit for i in range(31,-1,-1): # finding the bit at ith position curr = (key>>i)&(1) # if the child is None create one if(temp.child[curr] is None): temp.child[curr] = self.getNode() temp = temp.child[curr] # add value to the leaf node temp.value = key # traverse the trie and xor with the most similar element def xorUtil(self,key): temp = self.root # 32 bit valued binary digit for i in range(31,-1,-1): # finding the bit at ith position curr = (key>>i)&1 # traverse for the same bit if(temp.child[curr] is not None): temp = temp.child[curr] # traverse if the same bit is not set in trie else if(temp.child[1-curr] is not None): temp = temp.child[1-curr] # return with the xor of the value return temp.value^key def minXor(arr): # set m to a large number m = 2**30 # initialize Trie trie = Trie() # insert the first element trie.insert(arr[0]) # for each element in the array for i in range(1,len(arr)): # find the minimum xor value m = min(m,trie.xorUtil(arr[i])) # insert the new element trie.insert(arr[i]) return m # Driver Codeif __name__=="__main__": sample = [9,5,3] print(minXor(sample)) #code contributed by Ashwin Bhat
Output:
6
Time Complexity O(n)This article is contributed by Nishant_Singh (Pintu). 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.
Sam007
vt_m
Smitha Dinesh Semwal
xendergrunge
subhammahato348
simmytarika5
Bitwise-XOR
Trie
Arrays
Arrays
Trie
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Queue | Set 1 (Introduction and Array Implementation)
Linked List vs Array
Python | Using 2D arrays/lists the right way
Subset Sum Problem | DP-25
Find the Missing Number
Find Second largest element in an array
K'th Smallest/Largest Element in Unsorted Array | Set 1
Array of Strings in C++ (5 Different Ways to Create)
Sort an array of 0s, 1s and 2s
|
[
{
"code": null,
"e": 24846,
"s": 24818,
"text": "\n11 Mar, 2022"
},
{
"code": null,
"e": 24943,
"s": 24846,
"text": "Given an array of integers. Find the pair in an array that has a minimum XOR value. Examples : "
},
{
"code": null,
"e": 25142,
"s": 24943,
"text": "Input : arr[] = {9, 5, 3}\nOutput : 6\n All pair with xor value (9 ^ 5) => 12, \n (5 ^ 3) => 6, (9 ^ 3) => 10.\n Minimum XOR value is 6\n\nInput : arr[] = {1, 2, 3, 4, 5}\nOutput : 1 "
},
{
"code": null,
"e": 25305,
"s": 25144,
"text": "A Simple Solution is to generate all pairs of the given array and compute XOR their values. Finally, return minimum XOR value. This solution takes O(n2) time. "
},
{
"code": null,
"e": 25309,
"s": 25305,
"text": "C++"
},
{
"code": null,
"e": 25314,
"s": 25309,
"text": "Java"
},
{
"code": null,
"e": 25322,
"s": 25314,
"text": "Python3"
},
{
"code": null,
"e": 25325,
"s": 25322,
"text": "C#"
},
{
"code": null,
"e": 25329,
"s": 25325,
"text": "PHP"
},
{
"code": null,
"e": 25340,
"s": 25329,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum XOR value in an array.#include <bits/stdc++.h>using namespace std; // Returns minimum xor value of pair in arr[0..n-1]int minXOR(int arr[], int n){ int min_xor = INT_MAX; // Initialize result // Generate all pair of given array for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // update minimum xor value if required min_xor = min(min_xor, arr[i] ^ arr[j]); return min_xor;} // Driver programint main(){ int arr[] = { 9, 5, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minXOR(arr, n) << endl; return 0;}",
"e": 25948,
"s": 25340,
"text": null
},
{
"code": "// Java program to find minimum XOR value in an array.class GFG { // Returns minimum xor value of pair in arr[0..n-1] static int minXOR(int arr[], int n) { int min_xor = Integer.MAX_VALUE; // Initialize result // Generate all pair of given array for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // update minimum xor value if required min_xor = Math.min(min_xor, arr[i] ^ arr[j]); return min_xor; } // Driver program public static void main(String args[]) { int arr[] = { 9, 5, 3 }; int n = arr.length; System.out.println(minXOR(arr, n)); }}// This code is contributed by Sumit Ghosh",
"e": 26662,
"s": 25948,
"text": null
},
{
"code": "# Python program to find minimum# XOR value in an array. # Function to find minimum XOR pairdef minXOR(arr, n): # Sort given array arr.sort(); min_xor = 999999 val = 0 # calculate min xor of # consecutive pairs for i in range (0, n-1): for j in range (i+1, n-1): # update minimum xor value # if required val = arr[i] ^ arr[j] min_xor = min(min_xor, val) return min_xor # Driver programarr = [ 9, 5, 3 ]n = len(arr) print(minXOR(arr, n)) # This code is contributed by Sam007.",
"e": 27232,
"s": 26662,
"text": null
},
{
"code": "// C# program to find minimum// XOR value in an array.using System; class GFG { // Returns minimum xor value of // pair in arr[0..n-1] static int minXOR(int[] arr, int n) { // Initialize result int min_xor = int.MaxValue; // Generate all pair of given array for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // update minimum xor value if required min_xor = Math.Min(min_xor, arr[i] ^ arr[j]); return min_xor; } // Driver program public static void Main() { int[] arr = { 9, 5, 3 }; int n = arr.Length; Console.WriteLine(minXOR(arr, n)); }} // This code is contributed by Sam007",
"e": 27947,
"s": 27232,
"text": null
},
{
"code": "<?php// PHP program to find minimum// XOR value in an array. // Returns minimum xor value// of pair in arr[0..n-1]function minXOR($arr, $n){ // Initialize result $min_xor = PHP_INT_MAX; // Generate all pair of given array for ( $i = 0; $i < $n; $i++) for ( $j = $i + 1; $j < $n; $j++) // update minimum xor // value if required $min_xor = min($min_xor, $arr[$i] ^ $arr[$j]); return $min_xor;} // Driver Code $arr = array(9, 5, 3); $n = count($arr); echo minXOR($arr, $n); // This code is contributed by anuj_67.?>",
"e": 28536,
"s": 27947,
"text": null
},
{
"code": "<script> // Javascript program to find// minimum XOR value in an array. // Returns minimum xor value of pair in arr[0..n-1]function minXOR(arr, n){ // Initialize result let min_xor = Number.MAX_VALUE; // Generate all pair of given array for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) // update minimum xor value if required min_xor = Math.min(min_xor, arr[i] ^ arr[j]); return min_xor;} // Driver program let arr = [ 9, 5, 3 ]; let n = arr.length; document.write(minXOR(arr, n)); </script>",
"e": 29095,
"s": 28536,
"text": null
},
{
"code": null,
"e": 29105,
"s": 29095,
"text": "Output: "
},
{
"code": null,
"e": 29107,
"s": 29105,
"text": "6"
},
{
"code": null,
"e": 29196,
"s": 29107,
"text": "An Efficient solution can solve this problem in O(nlogn) time. Below is the algorithm: "
},
{
"code": null,
"e": 29275,
"s": 29196,
"text": "1). Sort the given array\n2). Traverse and check XOR for every consecutive pair"
},
{
"code": null,
"e": 29323,
"s": 29275,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 29327,
"s": 29323,
"text": "C++"
},
{
"code": null,
"e": 29332,
"s": 29327,
"text": "Java"
},
{
"code": null,
"e": 29340,
"s": 29332,
"text": "Python3"
},
{
"code": null,
"e": 29343,
"s": 29340,
"text": "C#"
},
{
"code": null,
"e": 29347,
"s": 29343,
"text": "PHP"
},
{
"code": null,
"e": 29358,
"s": 29347,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Function to find minimum XOR pairint minXOR(int arr[], int n){ // Sort given array sort(arr, arr + n); int minXor = INT_MAX; int val = 0; // calculate min xor of consecutive pairs for (int i = 0; i < n - 1; i++) { val = arr[i] ^ arr[i + 1]; minXor = min(minXor, val); } return minXor;} // Driver programint main(){ int arr[] = { 9, 5, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minXOR(arr, n) << endl; return 0;}",
"e": 29881,
"s": 29358,
"text": null
},
{
"code": "import java.util.Arrays;class GFG { // Function to find minimum XOR pair static int minXOR(int arr[], int n) { // Sort given array Arrays.parallelSort(arr); int minXor = Integer.MAX_VALUE; int val = 0; // calculate min xor of consecutive pairs for (int i = 0; i < n - 1; i++) { val = arr[i] ^ arr[i + 1]; minXor = Math.min(minXor, val); } return minXor; } // Driver program public static void main(String args[]) { int arr[] = { 9, 5, 3 }; int n = arr.length; System.out.println(minXOR(arr, n)); }} // This code is contributed by Sumit Ghosh",
"e": 30551,
"s": 29881,
"text": null
},
{
"code": "import sys # Function to find minimum XOR pairdef minXOR(arr, n): # Sort given array arr.sort() minXor = int(sys.float_info.max) val = 0 # calculate min xor of consecutive pairs for i in range(0,n-1): val = arr[i] ^ arr[i + 1]; minXor = min(minXor, val); return minXor # Driver programarr = [9, 5, 3]n = len(arr)print(minXOR(arr, n)) # This code is contributed by Sam007.",
"e": 30977,
"s": 30551,
"text": null
},
{
"code": "// C# program to find minimum// XOR value in an array.using System; class GFG { // Function to find minimum XOR pair static int minXOR(int[] arr, int n) { // Sort given array Array.Sort(arr); int minXor = int.MaxValue; int val = 0; // calculate min xor of consecutive pairs for (int i = 0; i < n - 1; i++) { val = arr[i] ^ arr[i + 1]; minXor = Math.Min(minXor, val); } return minXor; } // Driver program public static void Main() { int[] arr = { 9, 5, 3 }; int n = arr.Length; Console.WriteLine(minXOR(arr, n)); }} // This code is contributed by Sam007",
"e": 31662,
"s": 30977,
"text": null
},
{
"code": "<?php// Function to find minimum XOR pairfunction minXOR($arr, $n){ // Sort given array sort($arr); $minXor = PHP_INT_MAX; $val = 0; // calculate min xor // of consecutive pairs for ($i = 0; $i < $n - 1; $i++) { $val = $arr[$i] ^ $arr[$i + 1]; $minXor = min($minXor, $val); } return $minXor;} // Driver Code$arr = array(9, 5, 3);$n = count($arr);echo minXOR($arr, $n); // This code is contributed by Smitha.?>",
"e": 32119,
"s": 31662,
"text": null
},
{
"code": "<script> // Function to find minimum XOR pairfunction minXOR(arr, n){ // Sort given array arr.sort(); let minXor = Number.MAX_VALUE; let val = 0; // calculate min xor of consecutive pairs for (let i = 0; i < n - 1; i++) { val = arr[i] ^ arr[i + 1]; minXor = Math.min(minXor, val); } return minXor;} // Driver program let arr = [ 9, 5, 3 ]; let n = arr.length; document.write(minXOR(arr, n)); </script>",
"e": 32571,
"s": 32119,
"text": null
},
{
"code": null,
"e": 32582,
"s": 32571,
"text": "Output : "
},
{
"code": null,
"e": 32584,
"s": 32582,
"text": "6"
},
{
"code": null,
"e": 32897,
"s": 32584,
"text": "Time Complexity: O(N*logN) Space Complexity: O(1) Thanks to Utkarsh Gupta for suggesting above approach. A further more Efficient solution can solve the above problem in O(n) time under the assumption that integers take fixed number of bits to store. The idea is to use Trie Data Structure. Below is algorithm. "
},
{
"code": null,
"e": 33349,
"s": 32897,
"text": "1). Create an empty trie. Every node of trie contains two children\n for 0 and 1 bits.\n2). Initialize min_xor = INT_MAX, insert arr[0] into trie\n3). Traversal all array element one-by-one starting from second.\n a. First find minimum setbet difference value in trie \n do xor of current element with minimum setbit diff that value \n b. update min_xor value if required\n c. insert current array element in trie \n4). return min_xor\n "
},
{
"code": null,
"e": 33398,
"s": 33349,
"text": "Below is the implementation of above algorithm. "
},
{
"code": null,
"e": 33402,
"s": 33398,
"text": "C++"
},
{
"code": null,
"e": 33407,
"s": 33402,
"text": "Java"
},
{
"code": null,
"e": 33414,
"s": 33407,
"text": "Python"
},
{
"code": "// C++ program to find minimum XOR value in an array.#include <bits/stdc++.h>using namespace std;#define INT_SIZE 32 // A Trie Nodestruct TrieNode { int value; // used in leaf node TrieNode* Child[2];}; // Utility function to create a new Trie nodeTrieNode* getNode(){ TrieNode* newNode = new TrieNode; newNode->value = 0; newNode->Child[0] = newNode->Child[1] = NULL; return newNode;} // utility function insert new key in trievoid insert(TrieNode* root, int key){ TrieNode* temp = root; // start from the most significant bit, insert all // bit of key one-by-one into trie for (int i = INT_SIZE - 1; i >= 0; i--) { // Find current bit in given prefix bool current_bit = (key & (1 << i)); // Add a new Node into trie if (temp->Child[current_bit] == NULL) temp->Child[current_bit] = getNode(); temp = temp->Child[current_bit]; } // store value at leafNode temp->value = key;} // Returns minimum XOR value of an integer inserted// in Trie and given key.int minXORUtil(TrieNode* root, int key){ TrieNode* temp = root; for (int i = INT_SIZE - 1; i >= 0; i--) { // Find current bit in given prefix bool current_bit = (key & (1 << i)); // Traversal Trie, look for prefix that has // same bit if (temp->Child[current_bit] != NULL) temp = temp->Child[current_bit]; // if there is no same bit.then looking for // opposite bit else if (temp->Child[1 - current_bit] != NULL) temp = temp->Child[1 - current_bit]; } // return xor value of minimum bit difference value // so we get minimum xor value return key ^ temp->value;} // Returns minimum xor value of pair in arr[0..n-1]int minXOR(int arr[], int n){ int min_xor = INT_MAX; // Initialize result // create a True and insert first element in it TrieNode* root = getNode(); insert(root, arr[0]); // Traverse all array element and find minimum xor // for every element for (int i = 1; i < n; i++) { // Find minimum XOR value of current element with // previous elements inserted in Trie min_xor = min(min_xor, minXORUtil(root, arr[i])); // insert current array value into Trie insert(root, arr[i]); } return min_xor;} // Driver codeint main(){ int arr[] = { 9, 5, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minXOR(arr, n) << endl; return 0;}",
"e": 35870,
"s": 33414,
"text": null
},
{
"code": "// Java program to find minimum XOR value in an array.class GFG { static final int INT_SIZE = 32; // A Trie Node static class TrieNode { int value; // used in leaf node TrieNode[] Child = new TrieNode[2]; public TrieNode() { value = 0; Child[0] = null; Child[1] = null; } } static TrieNode root; // utility function insert new key in trie static void insert(int key) { TrieNode temp = root; // start from the most significant bit, insert all // bit of key one-by-one into trie for (int i = INT_SIZE - 1; i >= 0; i--) { // Find current bit in given prefix int current_bit = (key & (1 << i)) >= 1 ? 1 : 0; // Add a new Node into trie if (temp != null && temp.Child[current_bit] == null) temp.Child[current_bit] = new TrieNode(); temp = temp.Child[current_bit]; } // store value at leafNode temp.value = key; } // Returns minimum XOR value of an integer inserted // in Trie and given key. static int minXORUtil(int key) { TrieNode temp = root; for (int i = INT_SIZE - 1; i >= 0; i--) { // Find current bit in given prefix int current_bit = (key & (1 << i)) >= 1 ? 1 : 0; // Traversal Trie, look for prefix that has // same bit if (temp.Child[current_bit] != null) temp = temp.Child[current_bit]; // if there is no same bit.then looking for // opposite bit else if (temp.Child[1 - current_bit] != null) temp = temp.Child[1 - current_bit]; } // return xor value of minimum bit difference value // so we get minimum xor value return key ^ temp.value; } // Returns minimum xor value of pair in arr[0..n-1] static int minXOR(int arr[], int n) { int min_xor = Integer.MAX_VALUE; // Initialize result // create a True and insert first element in it root = new TrieNode(); insert(arr[0]); // Traverse all array element and find minimum xor // for every element for (int i = 1; i < n; i++) { // Find minimum XOR value of current element with // previous elements inserted in Trie min_xor = Math.min(min_xor, minXORUtil(arr[i])); // insert current array value into Trie insert(arr[i]); } return min_xor; } // Driver code public static void main(String args[]) { int arr[] = { 9, 5, 3 }; int n = arr.length; System.out.println(minXOR(arr, n)); }}// This code is contributed by Sumit Ghosh",
"e": 38614,
"s": 35870,
"text": null
},
{
"code": "# class for the basic Trie Nodeclass TrieNode: def __init__(self): # Child array with 0 and 1 self.child = [None]*2 # meant for the lead Node self.value = None class Trie: def __init__(self): # initialise the root Node self.root = self.getNode() def getNode(self): # get a new Trie Node return TrieNode() # inserts a new element def insert(self,key): temp = self.root # 32 bit valued binary digit for i in range(31,-1,-1): # finding the bit at ith position curr = (key>>i)&(1) # if the child is None create one if(temp.child[curr] is None): temp.child[curr] = self.getNode() temp = temp.child[curr] # add value to the leaf node temp.value = key # traverse the trie and xor with the most similar element def xorUtil(self,key): temp = self.root # 32 bit valued binary digit for i in range(31,-1,-1): # finding the bit at ith position curr = (key>>i)&1 # traverse for the same bit if(temp.child[curr] is not None): temp = temp.child[curr] # traverse if the same bit is not set in trie else if(temp.child[1-curr] is not None): temp = temp.child[1-curr] # return with the xor of the value return temp.value^key def minXor(arr): # set m to a large number m = 2**30 # initialize Trie trie = Trie() # insert the first element trie.insert(arr[0]) # for each element in the array for i in range(1,len(arr)): # find the minimum xor value m = min(m,trie.xorUtil(arr[i])) # insert the new element trie.insert(arr[i]) return m # Driver Codeif __name__==\"__main__\": sample = [9,5,3] print(minXor(sample)) #code contributed by Ashwin Bhat ",
"e": 40621,
"s": 38614,
"text": null
},
{
"code": null,
"e": 40631,
"s": 40621,
"text": "Output: "
},
{
"code": null,
"e": 40633,
"s": 40631,
"text": "6"
},
{
"code": null,
"e": 41083,
"s": 40633,
"text": "Time Complexity O(n)This article is contributed by Nishant_Singh (Pintu). 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": 41090,
"s": 41083,
"text": "Sam007"
},
{
"code": null,
"e": 41095,
"s": 41090,
"text": "vt_m"
},
{
"code": null,
"e": 41116,
"s": 41095,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 41129,
"s": 41116,
"text": "xendergrunge"
},
{
"code": null,
"e": 41145,
"s": 41129,
"text": "subhammahato348"
},
{
"code": null,
"e": 41158,
"s": 41145,
"text": "simmytarika5"
},
{
"code": null,
"e": 41170,
"s": 41158,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 41175,
"s": 41170,
"text": "Trie"
},
{
"code": null,
"e": 41182,
"s": 41175,
"text": "Arrays"
},
{
"code": null,
"e": 41189,
"s": 41182,
"text": "Arrays"
},
{
"code": null,
"e": 41194,
"s": 41189,
"text": "Trie"
},
{
"code": null,
"e": 41292,
"s": 41194,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41301,
"s": 41292,
"text": "Comments"
},
{
"code": null,
"e": 41314,
"s": 41301,
"text": "Old Comments"
},
{
"code": null,
"e": 41337,
"s": 41314,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 41391,
"s": 41337,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 41412,
"s": 41391,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 41457,
"s": 41412,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 41484,
"s": 41457,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 41508,
"s": 41484,
"text": "Find the Missing Number"
},
{
"code": null,
"e": 41548,
"s": 41508,
"text": "Find Second largest element in an array"
},
{
"code": null,
"e": 41604,
"s": 41548,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 41657,
"s": 41604,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
}
] |
Python program to count positive and negative numbers in a list
|
In this article, we will learn about the solution and approach to solve the given problem statement.
Given a list iterable we need to count all the positive and negative numbers available in the iterable.
Her we will be discussing two approaches −
Brute-force approach
Using lambda inline function
Live Demo
list1 = [1,-9,15,-16,13]
pos_count, neg_count = 0, 0
for num in list1:
if num >= 0:
pos_count += 1
else:
neg_count += 1
print("Positive numbers : ", pos_count)
print("Negative numbers : ", neg_count)
Positive numbers : 3
Negative numbers : 2
Live Demo
list1 = [1,-9,15,-16,13]
neg_count = len(list(filter(lambda x: (x < 0), list1)))
pos_count = len(list(filter(lambda x: (x >= 0), list1)))
print("Positive numbers : ", pos_count)
print("Negative numbers : ", neg_count)
Positive numbers : 3
Negative numbers : 2
In this article, we learned about the approach to count positive & negative numbers in a list.
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "In this article, we will learn about the solution and approach to solve the given problem statement."
},
{
"code": null,
"e": 1267,
"s": 1163,
"text": "Given a list iterable we need to count all the positive and negative numbers available in the iterable."
},
{
"code": null,
"e": 1310,
"s": 1267,
"text": "Her we will be discussing two approaches −"
},
{
"code": null,
"e": 1331,
"s": 1310,
"text": "Brute-force approach"
},
{
"code": null,
"e": 1360,
"s": 1331,
"text": "Using lambda inline function"
},
{
"code": null,
"e": 1371,
"s": 1360,
"text": " Live Demo"
},
{
"code": null,
"e": 1589,
"s": 1371,
"text": "list1 = [1,-9,15,-16,13]\npos_count, neg_count = 0, 0\nfor num in list1:\n if num >= 0:\n pos_count += 1\n else:\n neg_count += 1\nprint(\"Positive numbers : \", pos_count)\nprint(\"Negative numbers : \", neg_count)"
},
{
"code": null,
"e": 1631,
"s": 1589,
"text": "Positive numbers : 3\nNegative numbers : 2"
},
{
"code": null,
"e": 1642,
"s": 1631,
"text": " Live Demo"
},
{
"code": null,
"e": 1860,
"s": 1642,
"text": "list1 = [1,-9,15,-16,13]\nneg_count = len(list(filter(lambda x: (x < 0), list1)))\npos_count = len(list(filter(lambda x: (x >= 0), list1)))\nprint(\"Positive numbers : \", pos_count)\nprint(\"Negative numbers : \", neg_count)"
},
{
"code": null,
"e": 1902,
"s": 1860,
"text": "Positive numbers : 3\nNegative numbers : 2"
},
{
"code": null,
"e": 1997,
"s": 1902,
"text": "In this article, we learned about the approach to count positive & negative numbers in a list."
}
] |
Find frequency of smallest value in an array - GeeksforGeeks
|
11 May, 2021
Given an array A of N elements. Find the frequency of the smallest value in the array.Examples:
Input : N = 5, arr[] = {3, 2, 3, 4, 4}
Output : 1
The smallest element in the array is 2
and it occurs only once.
Input : N = 6, arr[] = {4, 3, 5, 3, 3, 6}
Output : 3
The smallest element in the array is 3
and it occurs 3 times.
Simple Approach: A simple method is to first find the minimum element in the array in first traversal. Then traverse the array again and find the number of occurrences of the minimum element.Efficient Approach: The efficient approach is to do this in a single traversal. Let us assume the first element to be the current minimum, so the frequency of the current minimum would be 1. Now let’s iterate through the array (1 to N), we come across 2 cases:
Current element is smaller than our current minimum: We change the current minimum to be equal to current element and since this is the first time we are coming across this element, we make it’s frequency 1.
Current element is equal to the current minimum: We increment the frequency of current minimum.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the frequency of// minimum element in the array #include <bits/stdc++.h>using namespace std; // Function to find the frequency of the// smallest value in the arrayint frequencyOfSmallest(int n, int arr[]){ int mn = arr[0], freq = 1; for (int i = 1; i < n; i++) { // If current element is smaller // than minimum if (arr[i] < mn) { mn = arr[i]; freq = 1; } // If current element is equal // to smallest else if (arr[i] == mn) freq++; } return freq;} // Driver Codeint main(){ int N = 5; int arr[] = { 3, 2, 3, 4, 4 }; cout << frequencyOfSmallest(N, arr); return 0;}
// Java program to find the frequency of// minimum element in the arrayimport java.io.*; class GFG{ // Function to find the frequency of the// smallest value in the arraystatic int frequencyOfSmallest(int n, int arr[]){ int mn = arr[0], freq = 1; for (int i = 1; i < n; i++) { // If current element is smaller // than minimum if (arr[i] < mn) { mn = arr[i]; freq = 1; } // If current element is equal // to smallest else if (arr[i] == mn) freq++; } return freq;} // Driver Code public static void main (String[] args) { int N = 5; int arr[] = { 3, 2, 3, 4, 4 }; System.out.println (frequencyOfSmallest(N, arr)); }} // This code is contributed by Tushil.
# Python 3 program to find the frequency of# minimum element in the array # Function to find the frequency of the# smallest value in the arraydef frequencyOfSmallest(n,arr): mn = arr[0] freq = 1 for i in range(1,n): # If current element is smaller # than minimum if (arr[i] < mn): mn = arr[i] freq = 1 # If current element is equal # to smallest elif(arr[i] == mn): freq += 1 return freq # Driver Codeif __name__ == '__main__': N = 5 arr = [3, 2, 3, 4, 4] print(frequencyOfSmallest(N, arr)) # This code is contributed by# Surendra_Gangwar
// C# program to find the frequency of// minimum element in the arrayusing System; class GFG{ // Function to find the frequency of the // smallest value in the array static int frequencyOfSmallest(int n, int []arr) { int mn = arr[0], freq = 1; for (int i = 1; i < n; i++) { // If current element is smaller // than minimum if (arr[i] < mn) { mn = arr[i]; freq = 1; } // If current element is equal // to smallest else if (arr[i] == mn) freq++; } return freq; } // Driver Code public static void Main() { int N = 5; int []arr = { 3, 2, 3, 4, 4 }; Console.WriteLine(frequencyOfSmallest(N, arr)); }} // This code is contributed by Ryuga
<?php// PHP program to find the frequency of// minimum element in the array // Function to find the frequency of the// smallest value in the arrayfunction frequencyOfSmallest($n, $arr){ $mn = $arr[0]; $freq = 1; for ($i = 1; $i < $n; $i++) { // If current element is smaller // than minimum if ($arr[$i] < $mn) { $mn = $arr[$i]; $freq = 1; } // If current element is equal // to smallest else if ($arr[$i] == $mn) $freq++; } return $freq;} // Driver Code$N = 5;$arr = array( 3, 2, 3, 4, 4 ); print(frequencyOfSmallest($N, $arr)); // This code is contributed by mits?>
<script> // Javascript program to find the frequency of // minimum element in the array // required answer // Function to find the frequency of the // smallest value in the array function frequencyOfSmallest(n, arr) { let mn = arr[0], freq = 1; for (let i = 1; i < n; i++) { // If current element is smaller // than minimum if (arr[i] < mn) { mn = arr[i]; freq = 1; } // If current element is equal // to smallest else if (arr[i] == mn) freq++; } return freq; } let N = 5; let arr = [ 3, 2, 3, 4, 4 ]; document.write(frequencyOfSmallest(N, arr)); </script>
1
Time Complexity: O(N)
jit_t
SURENDRA_GANGWAR
ankthon
Mithun Kumar
divyeshrabadiya07
school-programming
Algorithms
Arrays
Arrays
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Quadratic Probing in Hashing
Difference between Informed and Uninformed Search in AI
K means Clustering - Introduction
SCAN (Elevator) Disk Scheduling Algorithms
Arrays in Java
Arrays in C/C++
Stack Data Structure (Introduction and Program)
Program for array rotation
Largest Sum Contiguous Subarray
|
[
{
"code": null,
"e": 24611,
"s": 24583,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 24709,
"s": 24611,
"text": "Given an array A of N elements. Find the frequency of the smallest value in the array.Examples: "
},
{
"code": null,
"e": 24942,
"s": 24709,
"text": "Input : N = 5, arr[] = {3, 2, 3, 4, 4} \nOutput : 1\nThe smallest element in the array is 2 \nand it occurs only once.\n\nInput : N = 6, arr[] = {4, 3, 5, 3, 3, 6}\nOutput : 3\nThe smallest element in the array is 3 \nand it occurs 3 times."
},
{
"code": null,
"e": 25398,
"s": 24944,
"text": "Simple Approach: A simple method is to first find the minimum element in the array in first traversal. Then traverse the array again and find the number of occurrences of the minimum element.Efficient Approach: The efficient approach is to do this in a single traversal. Let us assume the first element to be the current minimum, so the frequency of the current minimum would be 1. Now let’s iterate through the array (1 to N), we come across 2 cases: "
},
{
"code": null,
"e": 25606,
"s": 25398,
"text": "Current element is smaller than our current minimum: We change the current minimum to be equal to current element and since this is the first time we are coming across this element, we make it’s frequency 1."
},
{
"code": null,
"e": 25702,
"s": 25606,
"text": "Current element is equal to the current minimum: We increment the frequency of current minimum."
},
{
"code": null,
"e": 25754,
"s": 25702,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25758,
"s": 25754,
"text": "C++"
},
{
"code": null,
"e": 25763,
"s": 25758,
"text": "Java"
},
{
"code": null,
"e": 25771,
"s": 25763,
"text": "Python3"
},
{
"code": null,
"e": 25774,
"s": 25771,
"text": "C#"
},
{
"code": null,
"e": 25778,
"s": 25774,
"text": "PHP"
},
{
"code": null,
"e": 25789,
"s": 25778,
"text": "Javascript"
},
{
"code": "// C++ program to find the frequency of// minimum element in the array #include <bits/stdc++.h>using namespace std; // Function to find the frequency of the// smallest value in the arrayint frequencyOfSmallest(int n, int arr[]){ int mn = arr[0], freq = 1; for (int i = 1; i < n; i++) { // If current element is smaller // than minimum if (arr[i] < mn) { mn = arr[i]; freq = 1; } // If current element is equal // to smallest else if (arr[i] == mn) freq++; } return freq;} // Driver Codeint main(){ int N = 5; int arr[] = { 3, 2, 3, 4, 4 }; cout << frequencyOfSmallest(N, arr); return 0;}",
"e": 26488,
"s": 25789,
"text": null
},
{
"code": "// Java program to find the frequency of// minimum element in the arrayimport java.io.*; class GFG{ // Function to find the frequency of the// smallest value in the arraystatic int frequencyOfSmallest(int n, int arr[]){ int mn = arr[0], freq = 1; for (int i = 1; i < n; i++) { // If current element is smaller // than minimum if (arr[i] < mn) { mn = arr[i]; freq = 1; } // If current element is equal // to smallest else if (arr[i] == mn) freq++; } return freq;} // Driver Code public static void main (String[] args) { int N = 5; int arr[] = { 3, 2, 3, 4, 4 }; System.out.println (frequencyOfSmallest(N, arr)); }} // This code is contributed by Tushil.",
"e": 27295,
"s": 26488,
"text": null
},
{
"code": "# Python 3 program to find the frequency of# minimum element in the array # Function to find the frequency of the# smallest value in the arraydef frequencyOfSmallest(n,arr): mn = arr[0] freq = 1 for i in range(1,n): # If current element is smaller # than minimum if (arr[i] < mn): mn = arr[i] freq = 1 # If current element is equal # to smallest elif(arr[i] == mn): freq += 1 return freq # Driver Codeif __name__ == '__main__': N = 5 arr = [3, 2, 3, 4, 4] print(frequencyOfSmallest(N, arr)) # This code is contributed by# Surendra_Gangwar",
"e": 27941,
"s": 27295,
"text": null
},
{
"code": "// C# program to find the frequency of// minimum element in the arrayusing System; class GFG{ // Function to find the frequency of the // smallest value in the array static int frequencyOfSmallest(int n, int []arr) { int mn = arr[0], freq = 1; for (int i = 1; i < n; i++) { // If current element is smaller // than minimum if (arr[i] < mn) { mn = arr[i]; freq = 1; } // If current element is equal // to smallest else if (arr[i] == mn) freq++; } return freq; } // Driver Code public static void Main() { int N = 5; int []arr = { 3, 2, 3, 4, 4 }; Console.WriteLine(frequencyOfSmallest(N, arr)); }} // This code is contributed by Ryuga",
"e": 28841,
"s": 27941,
"text": null
},
{
"code": "<?php// PHP program to find the frequency of// minimum element in the array // Function to find the frequency of the// smallest value in the arrayfunction frequencyOfSmallest($n, $arr){ $mn = $arr[0]; $freq = 1; for ($i = 1; $i < $n; $i++) { // If current element is smaller // than minimum if ($arr[$i] < $mn) { $mn = $arr[$i]; $freq = 1; } // If current element is equal // to smallest else if ($arr[$i] == $mn) $freq++; } return $freq;} // Driver Code$N = 5;$arr = array( 3, 2, 3, 4, 4 ); print(frequencyOfSmallest($N, $arr)); // This code is contributed by mits?>",
"e": 29519,
"s": 28841,
"text": null
},
{
"code": "<script> // Javascript program to find the frequency of // minimum element in the array // required answer // Function to find the frequency of the // smallest value in the array function frequencyOfSmallest(n, arr) { let mn = arr[0], freq = 1; for (let i = 1; i < n; i++) { // If current element is smaller // than minimum if (arr[i] < mn) { mn = arr[i]; freq = 1; } // If current element is equal // to smallest else if (arr[i] == mn) freq++; } return freq; } let N = 5; let arr = [ 3, 2, 3, 4, 4 ]; document.write(frequencyOfSmallest(N, arr)); </script>",
"e": 30317,
"s": 29519,
"text": null
},
{
"code": null,
"e": 30319,
"s": 30317,
"text": "1"
},
{
"code": null,
"e": 30344,
"s": 30321,
"text": "Time Complexity: O(N) "
},
{
"code": null,
"e": 30350,
"s": 30344,
"text": "jit_t"
},
{
"code": null,
"e": 30367,
"s": 30350,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 30375,
"s": 30367,
"text": "ankthon"
},
{
"code": null,
"e": 30388,
"s": 30375,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 30406,
"s": 30388,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 30425,
"s": 30406,
"text": "school-programming"
},
{
"code": null,
"e": 30436,
"s": 30425,
"text": "Algorithms"
},
{
"code": null,
"e": 30443,
"s": 30436,
"text": "Arrays"
},
{
"code": null,
"e": 30450,
"s": 30443,
"text": "Arrays"
},
{
"code": null,
"e": 30461,
"s": 30450,
"text": "Algorithms"
},
{
"code": null,
"e": 30559,
"s": 30461,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30568,
"s": 30559,
"text": "Comments"
},
{
"code": null,
"e": 30581,
"s": 30568,
"text": "Old Comments"
},
{
"code": null,
"e": 30606,
"s": 30581,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30635,
"s": 30606,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 30691,
"s": 30635,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 30725,
"s": 30691,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 30768,
"s": 30725,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 30783,
"s": 30768,
"text": "Arrays in Java"
},
{
"code": null,
"e": 30799,
"s": 30783,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 30847,
"s": 30799,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 30874,
"s": 30847,
"text": "Program for array rotation"
}
] |
How to Randomly Shuffle Columns in MATLAB in Matrix? - GeeksforGeeks
|
27 Aug, 2021
In this article, we are going to discuss the “random shuffling of columns in a Matrix ” with the help of size() and randperm() function. The size() function is used to return the size of each dimension of the specified array “X” or the size of the specified matrix “X”.
1) randperm(): The randperm() function is used for the random permutation of integers.
Syntax:
randperm(n)
randperm(n,k)
Here,
randperm(n) returns a row vector that contains a random permutation of the integers from “1” to “n” without any repetition.
randperm(n,k) returns a row vector that contains “k” a number of unique integers that are selected randomly from 1 to n.
Parameters: This function accepts two parameters.
n: This is the specified number up to which a random number is going to be generated from “1” without any repetition.
k: It is the number of unique integers that are selected randomly from 1 to n.
Example:
Matlab
% MATLAB code for calling the randperm()% to generate a random permutation% of the integers from 1 to 5A = randperm(5)
Output:
A =
4 2 3 1 5
Below examples are of the “random shuffling of columns in a Matrix ” which can be done using the combination of the size() and randperm() functions:
2) size: The size() function is used to return the sizes of each dimension of the specified array “X” or the size of the specified matrix “X”.
Syntax:
size(X)
[m,n] = size(X)
size(X,dim)
[d1,d2,d3,...,dn] = size(X)
Here,
size(X) returns the sizes of each dimension of the specified array “X” in a vector d with ndims(X) elements.
[m,n] = size(X) returns the size of the specified matrix “X” in the separate variables m and n.
size(X,dim) returns the size of the dimension of “X” specified by scalar dim.
[d1,d2,d3,...,dn] = size(X) returns the sizes of the first n dimensions of the specified array “X” in separate variables.
Parameters: This function accepts two parameters which are illustrated below:
X: It is the specified array or matrix or dimension.
dim: It is the scalar value for the specified dimension “X”
Example 1:
Matlab
% MATLAB code for size() and randpem()% Specifying a 3*3 matrixA = [1 2 3 4 5 6 7 8 9]; % Calling the size() function over% the above matrix which gives a row vector% whose elements are the lengths of the% corresponding dimensions of Acols = size(A); % Calling the randperm() function for the% random permutation of the above matrix% over its dimension of 3*3P = randperm(cols); % Getting the column wise randomly shuffled matrixB = A(:,P)
Output:
B =
3 1 2
6 4 5
9 7 8
Example 2:
Matlab
% MATLAB code for shuffle 4*4 matrix% using randperm()% Specifying a 4*4 matrixA = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]; % Calling the randperm() function to% randomly shuffle the column of matrix AA(:, randperm(size(A, 2)))
Output:
arorakashish0911
simmytarika5
MATLAB Matrix-Programs
MATLAB-programs
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Differential or Derivatives in MATLAB
How to Apply Median Filter For RGB Image in MATLAB?
Laplace Transform in MATLAB
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
Trigonometric Functions in MATLAB
What is Upsampling in MATLAB?
Turn an Array into a Column Vector in MATLAB
Laplacian of Gaussian Filter in MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Iterate through each element in N-Dimensional matrix in MATLAB?
|
[
{
"code": null,
"e": 24255,
"s": 24227,
"text": "\n27 Aug, 2021"
},
{
"code": null,
"e": 24526,
"s": 24255,
"text": "In this article, we are going to discuss the “random shuffling of columns in a Matrix ” with the help of size() and randperm() function. The size() function is used to return the size of each dimension of the specified array “X” or the size of the specified matrix “X”. "
},
{
"code": null,
"e": 24613,
"s": 24526,
"text": "1) randperm(): The randperm() function is used for the random permutation of integers."
},
{
"code": null,
"e": 24621,
"s": 24613,
"text": "Syntax:"
},
{
"code": null,
"e": 24633,
"s": 24621,
"text": "randperm(n)"
},
{
"code": null,
"e": 24647,
"s": 24633,
"text": "randperm(n,k)"
},
{
"code": null,
"e": 24653,
"s": 24647,
"text": "Here,"
},
{
"code": null,
"e": 24777,
"s": 24653,
"text": "randperm(n) returns a row vector that contains a random permutation of the integers from “1” to “n” without any repetition."
},
{
"code": null,
"e": 24898,
"s": 24777,
"text": "randperm(n,k) returns a row vector that contains “k” a number of unique integers that are selected randomly from 1 to n."
},
{
"code": null,
"e": 24948,
"s": 24898,
"text": "Parameters: This function accepts two parameters."
},
{
"code": null,
"e": 25066,
"s": 24948,
"text": "n: This is the specified number up to which a random number is going to be generated from “1” without any repetition."
},
{
"code": null,
"e": 25145,
"s": 25066,
"text": "k: It is the number of unique integers that are selected randomly from 1 to n."
},
{
"code": null,
"e": 25154,
"s": 25145,
"text": "Example:"
},
{
"code": null,
"e": 25161,
"s": 25154,
"text": "Matlab"
},
{
"code": "% MATLAB code for calling the randperm()% to generate a random permutation% of the integers from 1 to 5A = randperm(5)",
"e": 25280,
"s": 25161,
"text": null
},
{
"code": null,
"e": 25289,
"s": 25280,
"text": "Output: "
},
{
"code": null,
"e": 25313,
"s": 25289,
"text": "A =\n 4 2 3 1 5"
},
{
"code": null,
"e": 25462,
"s": 25313,
"text": "Below examples are of the “random shuffling of columns in a Matrix ” which can be done using the combination of the size() and randperm() functions:"
},
{
"code": null,
"e": 25607,
"s": 25462,
"text": "2) size: The size() function is used to return the sizes of each dimension of the specified array “X” or the size of the specified matrix “X”. "
},
{
"code": null,
"e": 25615,
"s": 25607,
"text": "Syntax:"
},
{
"code": null,
"e": 25623,
"s": 25615,
"text": "size(X)"
},
{
"code": null,
"e": 25639,
"s": 25623,
"text": "[m,n] = size(X)"
},
{
"code": null,
"e": 25651,
"s": 25639,
"text": "size(X,dim)"
},
{
"code": null,
"e": 25679,
"s": 25651,
"text": "[d1,d2,d3,...,dn] = size(X)"
},
{
"code": null,
"e": 25685,
"s": 25679,
"text": "Here,"
},
{
"code": null,
"e": 25794,
"s": 25685,
"text": "size(X) returns the sizes of each dimension of the specified array “X” in a vector d with ndims(X) elements."
},
{
"code": null,
"e": 25890,
"s": 25794,
"text": "[m,n] = size(X) returns the size of the specified matrix “X” in the separate variables m and n."
},
{
"code": null,
"e": 25968,
"s": 25890,
"text": "size(X,dim) returns the size of the dimension of “X” specified by scalar dim."
},
{
"code": null,
"e": 26090,
"s": 25968,
"text": "[d1,d2,d3,...,dn] = size(X) returns the sizes of the first n dimensions of the specified array “X” in separate variables."
},
{
"code": null,
"e": 26169,
"s": 26090,
"text": "Parameters: This function accepts two parameters which are illustrated below: "
},
{
"code": null,
"e": 26222,
"s": 26169,
"text": "X: It is the specified array or matrix or dimension."
},
{
"code": null,
"e": 26282,
"s": 26222,
"text": "dim: It is the scalar value for the specified dimension “X”"
},
{
"code": null,
"e": 26294,
"s": 26282,
"text": "Example 1: "
},
{
"code": null,
"e": 26301,
"s": 26294,
"text": "Matlab"
},
{
"code": "% MATLAB code for size() and randpem()% Specifying a 3*3 matrixA = [1 2 3 4 5 6 7 8 9]; % Calling the size() function over% the above matrix which gives a row vector% whose elements are the lengths of the% corresponding dimensions of Acols = size(A); % Calling the randperm() function for the% random permutation of the above matrix% over its dimension of 3*3P = randperm(cols); % Getting the column wise randomly shuffled matrixB = A(:,P)",
"e": 26754,
"s": 26301,
"text": null
},
{
"code": null,
"e": 26763,
"s": 26754,
"text": "Output: "
},
{
"code": null,
"e": 26803,
"s": 26763,
"text": "B =\n 3 1 2\n 6 4 5\n 9 7 8"
},
{
"code": null,
"e": 26815,
"s": 26803,
"text": "Example 2: "
},
{
"code": null,
"e": 26822,
"s": 26815,
"text": "Matlab"
},
{
"code": "% MATLAB code for shuffle 4*4 matrix% using randperm()% Specifying a 4*4 matrixA = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]; % Calling the randperm() function to% randomly shuffle the column of matrix AA(:, randperm(size(A, 2)))",
"e": 27068,
"s": 26822,
"text": null
},
{
"code": null,
"e": 27077,
"s": 27068,
"text": "Output: "
},
{
"code": null,
"e": 27096,
"s": 27079,
"text": "arorakashish0911"
},
{
"code": null,
"e": 27109,
"s": 27096,
"text": "simmytarika5"
},
{
"code": null,
"e": 27132,
"s": 27109,
"text": "MATLAB Matrix-Programs"
},
{
"code": null,
"e": 27148,
"s": 27132,
"text": "MATLAB-programs"
},
{
"code": null,
"e": 27155,
"s": 27148,
"text": "Picked"
},
{
"code": null,
"e": 27162,
"s": 27155,
"text": "MATLAB"
},
{
"code": null,
"e": 27260,
"s": 27162,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27269,
"s": 27260,
"text": "Comments"
},
{
"code": null,
"e": 27282,
"s": 27269,
"text": "Old Comments"
},
{
"code": null,
"e": 27320,
"s": 27282,
"text": "Differential or Derivatives in MATLAB"
},
{
"code": null,
"e": 27372,
"s": 27320,
"text": "How to Apply Median Filter For RGB Image in MATLAB?"
},
{
"code": null,
"e": 27400,
"s": 27372,
"text": "Laplace Transform in MATLAB"
},
{
"code": null,
"e": 27473,
"s": 27400,
"text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?"
},
{
"code": null,
"e": 27507,
"s": 27473,
"text": "Trigonometric Functions in MATLAB"
},
{
"code": null,
"e": 27537,
"s": 27507,
"text": "What is Upsampling in MATLAB?"
},
{
"code": null,
"e": 27582,
"s": 27537,
"text": "Turn an Array into a Column Vector in MATLAB"
},
{
"code": null,
"e": 27621,
"s": 27582,
"text": "Laplacian of Gaussian Filter in MATLAB"
},
{
"code": null,
"e": 27686,
"s": 27621,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
}
] |
Matplotlib.markers module in Python - GeeksforGeeks
|
07 Oct, 2021
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.dates module provides functions to handle markers in Matplotlib. It is used both by the marker functionality of the plot and scatter.Below is the table defining all possible markers in matplotlib:
Note: It is important to note that the two lines of code below are equivalent,
# line 1
plt.plot([1, 2, 3], marker = 9)
# line 2
plt.plot([1, 2, 3], marker = matplotlib.markers.CARETRIGHTBASE)
Example 1:
Python3
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.lines import Line2D # Draw 5 points for each lineeach_point = np.ones(5) style = dict(color = 'tab:green', linestyle = ':', marker = 'D', markersize = 15, markerfacecoloralt = 'tab:red') figure, axes = plt.subplots() # Plot all filling styles.for y, fill_style in enumerate(Line2D.fillStyles): axes.text(-0.5, y, repr(fill_style), horizontalalignment = 'center', verticalalignment = 'center') axes.plot(y * each_point, fillstyle = fill_style, **style) axes.set_axis_off()axes.set_title('filling style') plt.show()
Output:
Example 2:
Python3
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.lines import Line2D # Drawing 3 points for each lineplotted_points = np.ones(4)txt_style = dict(horizontalalignment = 'right', verticalalignment = 'center', fontsize = 12, fontdict = {'family': 'monospace'}) style = dict(linestyle = ':', color ='0.5', markersize = 10, mfc ="C0", mec ="C0") # helper function for axes formattingdef format_ax(ax): ax.margins(0.2) ax.set_axis_off() ax.invert_yaxis() # helper function for splitting listdef split(a_list): i_half = len(a_list) // 2 return (a_list[:i_half], a_list[i_half:]) figure, axes = plt.subplots(ncols = 2) for ax, markers in zip(axes, split(Line2D.filled_markers)): for y, marker in enumerate(markers): ax.text(-0.5, y, repr(marker), **txt_style) ax.plot(y * plotted_points, marker = marker, **style) format_ax(ax) figure.suptitle('filled markers', fontsize = 14) plt.show()
Output:
anikaseth98
Matplotlib markers-class
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python
Factory method design pattern in Java
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 24114,
"s": 23901,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. "
},
{
"code": null,
"e": 24326,
"s": 24114,
"text": "The matplotlib.dates module provides functions to handle markers in Matplotlib. It is used both by the marker functionality of the plot and scatter.Below is the table defining all possible markers in matplotlib:"
},
{
"code": null,
"e": 24411,
"s": 24330,
"text": "Note: It is important to note that the two lines of code below are equivalent, "
},
{
"code": null,
"e": 24526,
"s": 24411,
"text": "# line 1\nplt.plot([1, 2, 3], marker = 9)\n\n# line 2\nplt.plot([1, 2, 3], marker = matplotlib.markers.CARETRIGHTBASE)"
},
{
"code": null,
"e": 24539,
"s": 24526,
"text": "Example 1: "
},
{
"code": null,
"e": 24547,
"s": 24539,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.lines import Line2D # Draw 5 points for each lineeach_point = np.ones(5) style = dict(color = 'tab:green', linestyle = ':', marker = 'D', markersize = 15, markerfacecoloralt = 'tab:red') figure, axes = plt.subplots() # Plot all filling styles.for y, fill_style in enumerate(Line2D.fillStyles): axes.text(-0.5, y, repr(fill_style), horizontalalignment = 'center', verticalalignment = 'center') axes.plot(y * each_point, fillstyle = fill_style, **style) axes.set_axis_off()axes.set_title('filling style') plt.show()",
"e": 25243,
"s": 24547,
"text": null
},
{
"code": null,
"e": 25253,
"s": 25243,
"text": "Output: "
},
{
"code": null,
"e": 25266,
"s": 25253,
"text": "Example 2: "
},
{
"code": null,
"e": 25274,
"s": 25266,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.lines import Line2D # Drawing 3 points for each lineplotted_points = np.ones(4)txt_style = dict(horizontalalignment = 'right', verticalalignment = 'center', fontsize = 12, fontdict = {'family': 'monospace'}) style = dict(linestyle = ':', color ='0.5', markersize = 10, mfc =\"C0\", mec =\"C0\") # helper function for axes formattingdef format_ax(ax): ax.margins(0.2) ax.set_axis_off() ax.invert_yaxis() # helper function for splitting listdef split(a_list): i_half = len(a_list) // 2 return (a_list[:i_half], a_list[i_half:]) figure, axes = plt.subplots(ncols = 2) for ax, markers in zip(axes, split(Line2D.filled_markers)): for y, marker in enumerate(markers): ax.text(-0.5, y, repr(marker), **txt_style) ax.plot(y * plotted_points, marker = marker, **style) format_ax(ax) figure.suptitle('filled markers', fontsize = 14) plt.show()",
"e": 26355,
"s": 25274,
"text": null
},
{
"code": null,
"e": 26365,
"s": 26355,
"text": "Output: "
},
{
"code": null,
"e": 26379,
"s": 26367,
"text": "anikaseth98"
},
{
"code": null,
"e": 26404,
"s": 26379,
"text": "Matplotlib markers-class"
},
{
"code": null,
"e": 26422,
"s": 26404,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 26429,
"s": 26422,
"text": "Python"
},
{
"code": null,
"e": 26445,
"s": 26429,
"text": "Write From Home"
},
{
"code": null,
"e": 26543,
"s": 26445,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26552,
"s": 26543,
"text": "Comments"
},
{
"code": null,
"e": 26565,
"s": 26552,
"text": "Old Comments"
},
{
"code": null,
"e": 26601,
"s": 26565,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 26624,
"s": 26601,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 26663,
"s": 26624,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26696,
"s": 26663,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 26745,
"s": 26696,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 26781,
"s": 26745,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 26797,
"s": 26781,
"text": "Python infinity"
},
{
"code": null,
"e": 26858,
"s": 26797,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 26894,
"s": 26858,
"text": "Matplotlib.pyplot.title() in Python"
}
] |
How to Count Number of Files and Subdirectories inside a Given Linux Directory?
|
It often becomes essential to know not just the count of files in my current directory but also the count of files from all the subdirectories inside the current directory. This can be found out using the
we can use ls to list the files, then choose only the ones that start with ‘-‘ symbol. The R option along with the l option does a recursive search. The ‘-c’ option counts the number of lines which is the number of files.
ls -lR . | egrep -c '^-'
Running the above code gives us the following result −
13
The find command helps us find the files with certain criteria by recursively traversing all the directories and there subdirectories. We use it with the type option to get only files by supplying the argument f. Here it also counts all the hidden files.
find . -type f | wc -l
Running the above code gives us the following result −
1505
We use the same approach as in the previous command, but use a regular expression pattern to avoid the . character by using the escape character \.
find . -not -path '*/\.*' -type f | wc -l
Running the above code gives us the following result −
13
|
[
{
"code": null,
"e": 1267,
"s": 1062,
"text": "It often becomes essential to know not just the count of files in my current directory but also the count of files from all the subdirectories inside the current directory. This can be found out using the"
},
{
"code": null,
"e": 1489,
"s": 1267,
"text": "we can use ls to list the files, then choose only the ones that start with ‘-‘ symbol. The R option along with the l option does a recursive search. The ‘-c’ option counts the number of lines which is the number of files."
},
{
"code": null,
"e": 1514,
"s": 1489,
"text": "ls -lR . | egrep -c '^-'"
},
{
"code": null,
"e": 1569,
"s": 1514,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1572,
"s": 1569,
"text": "13"
},
{
"code": null,
"e": 1827,
"s": 1572,
"text": "The find command helps us find the files with certain criteria by recursively traversing all the directories and there subdirectories. We use it with the type option to get only files by supplying the argument f. Here it also counts all the hidden files."
},
{
"code": null,
"e": 1850,
"s": 1827,
"text": "find . -type f | wc -l"
},
{
"code": null,
"e": 1905,
"s": 1850,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1911,
"s": 1905,
"text": "1505\n"
},
{
"code": null,
"e": 2059,
"s": 1911,
"text": "We use the same approach as in the previous command, but use a regular expression pattern to avoid the . character by using the escape character \\."
},
{
"code": null,
"e": 2101,
"s": 2059,
"text": "find . -not -path '*/\\.*' -type f | wc -l"
},
{
"code": null,
"e": 2156,
"s": 2101,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2159,
"s": 2156,
"text": "13"
}
] |
Restoring a Docker Container
|
30 Sep, 2021
If you have a backup of your Docker Container stored as a Tar File in your local machine or pushed it on the Docker Hub account, you can restore that Tar File back into a Docker Image, create a Container and use it. In this article, we are going to discuss how to restore a Docker Image from a Tar File or pulling it from your private Docker Hub account.
You can follow these steps to restore a Docker Container:
If you have a Tar file of a Docker Image as a previous backup, you can load it using the following command. In this example, we have a Tar File called my-backup in the home directory which is the backup of an Ubuntu Image with a text file inside it.
sudo docker load -i ~/my-backup.tar
Tar File
Docker Load Command
After you have loaded the Tar File, you can verify if the Image has been added to your local repository using the following command.
sudo docker images
Verifying Image
Step 3 (Optional): Pull a backed up Image from Docker Registry
If you have a backed-up Image that you pushed it earlier into your private Docker Hub account, you can pull it back using the following command.
sudo docker pull my-backup:latest
To run the Container associated with the restored image, you can use the Docker Run command. Using the ls command, you will find the files intact inside the Docker Container.
sudo docker run -it my-backup:latest
ls
Running Container
reimarunger
Docker Container
linux
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 383,
"s": 28,
"text": "If you have a backup of your Docker Container stored as a Tar File in your local machine or pushed it on the Docker Hub account, you can restore that Tar File back into a Docker Image, create a Container and use it. In this article, we are going to discuss how to restore a Docker Image from a Tar File or pulling it from your private Docker Hub account."
},
{
"code": null,
"e": 441,
"s": 383,
"text": "You can follow these steps to restore a Docker Container:"
},
{
"code": null,
"e": 691,
"s": 441,
"text": "If you have a Tar file of a Docker Image as a previous backup, you can load it using the following command. In this example, we have a Tar File called my-backup in the home directory which is the backup of an Ubuntu Image with a text file inside it."
},
{
"code": null,
"e": 727,
"s": 691,
"text": "sudo docker load -i ~/my-backup.tar"
},
{
"code": null,
"e": 736,
"s": 727,
"text": "Tar File"
},
{
"code": null,
"e": 756,
"s": 736,
"text": "Docker Load Command"
},
{
"code": null,
"e": 889,
"s": 756,
"text": "After you have loaded the Tar File, you can verify if the Image has been added to your local repository using the following command."
},
{
"code": null,
"e": 908,
"s": 889,
"text": "sudo docker images"
},
{
"code": null,
"e": 924,
"s": 908,
"text": "Verifying Image"
},
{
"code": null,
"e": 987,
"s": 924,
"text": "Step 3 (Optional): Pull a backed up Image from Docker Registry"
},
{
"code": null,
"e": 1132,
"s": 987,
"text": "If you have a backed-up Image that you pushed it earlier into your private Docker Hub account, you can pull it back using the following command."
},
{
"code": null,
"e": 1166,
"s": 1132,
"text": "sudo docker pull my-backup:latest"
},
{
"code": null,
"e": 1341,
"s": 1166,
"text": "To run the Container associated with the restored image, you can use the Docker Run command. Using the ls command, you will find the files intact inside the Docker Container."
},
{
"code": null,
"e": 1381,
"s": 1341,
"text": "sudo docker run -it my-backup:latest\nls"
},
{
"code": null,
"e": 1399,
"s": 1381,
"text": "Running Container"
},
{
"code": null,
"e": 1411,
"s": 1399,
"text": "reimarunger"
},
{
"code": null,
"e": 1428,
"s": 1411,
"text": "Docker Container"
},
{
"code": null,
"e": 1434,
"s": 1428,
"text": "linux"
},
{
"code": null,
"e": 1460,
"s": 1434,
"text": "Advanced Computer Subject"
}
] |
getx() function in C
|
25 Jan, 2018
The header file graphics.h contains getx() function which returns the X coordinate of the current position.Syntax :
int getx();
Example :
Explanation : Initially, the X coordinate of the current position is 0. On moving the coordinates using moveto() function, the X coordinate changes to 80.
Below is the implementation of getx() function:
// C Implementation for getx()#include <graphics.h>#include <stdio.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; char arr[100]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // sprintf stands for “String print”. // Instead of printing on console, it // store output on char buffer which // are specified in sprintf sprintf(arr, "Current position of x = %d", getx()); // outtext function displays text at // current position. outtext(arr); // moveto function moveto(80, 50); sprintf(arr, "Current position of x = %d", getx()); // outtext function displays text at // current position. outtext(arr); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}
Output :
c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Jan, 2018"
},
{
"code": null,
"e": 170,
"s": 54,
"text": "The header file graphics.h contains getx() function which returns the X coordinate of the current position.Syntax :"
},
{
"code": null,
"e": 183,
"s": 170,
"text": "int getx();\n"
},
{
"code": null,
"e": 193,
"s": 183,
"text": "Example :"
},
{
"code": null,
"e": 350,
"s": 195,
"text": "Explanation : Initially, the X coordinate of the current position is 0. On moving the coordinates using moveto() function, the X coordinate changes to 80."
},
{
"code": null,
"e": 398,
"s": 350,
"text": "Below is the implementation of getx() function:"
},
{
"code": "// C Implementation for getx()#include <graphics.h>#include <stdio.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm; char arr[100]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, \"\"); // sprintf stands for “String print”. // Instead of printing on console, it // store output on char buffer which // are specified in sprintf sprintf(arr, \"Current position of x = %d\", getx()); // outtext function displays text at // current position. outtext(arr); // moveto function moveto(80, 50); sprintf(arr, \"Current position of x = %d\", getx()); // outtext function displays text at // current position. outtext(arr); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}",
"e": 1562,
"s": 398,
"text": null
},
{
"code": null,
"e": 1571,
"s": 1562,
"text": "Output :"
},
{
"code": null,
"e": 1584,
"s": 1573,
"text": "c-graphics"
},
{
"code": null,
"e": 1602,
"s": 1584,
"text": "computer-graphics"
},
{
"code": null,
"e": 1613,
"s": 1602,
"text": "C Language"
}
] |
Python Data Types
|
01 Oct, 2021
Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.
Following are the standard or built-in data type of Python:
Numeric
Sequence Type
Boolean
Set
Dictionary
In Python, numeric data type represent the data which has numeric value. Numeric value can be integer, floating number or even complex numbers. These values are defined as int, float and complex class in Python.
Integers – This value is represented by int class. It contains positive or negative whole numbers (without fraction or decimal). In Python there is no limit to how long an integer value can be.
Float – This value is represented by float class. It is a real number with floating point representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation.
Complex Numbers – Complex number is represented by complex class. It is specified as (real part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.
Python3
# Python program to # demonstrate numeric value a = 5print("Type of a: ", type(a)) b = 5.0print("\nType of b: ", type(b)) c = 2 + 4jprint("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
In Python, sequence is the ordered collection of similar or different data types. Sequences allows to store multiple values in an organized and efficient fashion. There are several sequence types in Python –
String
List
Tuple
In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of one or more characters put in a single quote, double-quote or triple quote. In python there is no character data type, a character is a string of length one. It is represented by str class.
Strings in Python can be created using single quotes or double quotes or even triple quotes.
Python3
# Python Program for # Creation of String # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World'print("String with the use of Single Quotes: ") print(String1) # Creating a String # with double Quotes String1 = "I'm a Geek"print("\nString with the use of Double Quotes: ") print(String1) print(type(String1)) # Creating a String # with triple Quotes String1 = '''I'm a Geek and I live in a world of "Geeks"'''print("\nString with the use of Triple Quotes: ") print(String1) print(type(String1)) # Creating String with triple # Quotes allows multiple lines String1 = '''Geeks For Life'''print("\nCreating a multiline String: ") print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
<class 'str'>
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
<class 'str'>
Creating a multiline String:
Geeks
For
Life
In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character and so on.
Python3
# Python Program to Access # characters of String String1 = "GeeksForGeeks"print("Initial String: ") print(String1) # Printing First character print("\nFirst character of String is: ") print(String1[0]) # Printing Last character print("\nLast character of String is: ") print(String1[-1])
Output:
Initial String:
GeeksForGeeks
First character of String is:
G
Last character of String is:
s
Note – To know more about strings, refer Python String.
Lists are just like the arrays, declared in other languages which is a ordered collection of data. It is very flexible as the items in a list do not need to be of the same type.
Lists in Python can be created by just placing the sequence inside the square brackets[].
Python3
# Python program to demonstrate # Creation of List # Creating a List List = [] print("Initial blank List: ") print(List) # Creating a List with # the use of a String List = ['GeeksForGeeks'] print("\nList with the use of String: ") print(List) # Creating a List with # the use of multiple values List = ["Geeks", "For", "Geeks"] print("\nList containing multiple values: ") print(List[0]) print(List[2]) # Creating a Multi-Dimensional List # (By Nesting a list inside a List) List = [['Geeks', 'For'], ['Geeks']] print("\nMulti-Dimensional List: ") print(List)
Output:
Initial blank List:
[]
List with the use of String:
['GeeksForGeeks']
List containing multiple values:
Geeks
Geeks
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
In order to access the list items refer to the index number. Use the index operator [ ] to access an item in a list. In Python, negative sequence indexes represent positions from the end of the array. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.
Python3
# Python program to demonstrate # accessing of element from list # Creating a List with # the use of multiple values List = ["Geeks", "For", "Geeks"] # accessing a element from the # list using index number print("Accessing element from the list") print(List[0]) print(List[2]) # accessing a element using # negative indexing print("Accessing element using negative indexing") # print the last element of list print(List[-1]) # print the third last element of list print(List[-3])
Output:
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Note – To know more about Lists, refer Python List.
Just like list, tuple is also an ordered collection of Python objects. The only difference between tuple and list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is represented by tuple class.
In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence. Tuples can contain any number of elements and of any datatype (like strings, integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
Python3
# Python program to demonstrate # creation of Set # Creating an empty tuple Tuple1 = () print("Initial empty Tuple: ") print (Tuple1) # Creating a Tuple with # the use of Strings Tuple1 = ('Geeks', 'For') print("\nTuple with the use of String: ") print(Tuple1) # Creating a Tuple with # the use of list list1 = [1, 2, 4, 5, 6] print("\nTuple using List: ") print(tuple(list1)) # Creating a Tuple with the # use of built-in function Tuple1 = tuple('Geeks') print("\nTuple with the use of function: ") print(Tuple1) # Creating a Tuple # with nested tuples Tuple1 = (0, 1, 2, 3) Tuple2 = ('python', 'geek') Tuple3 = (Tuple1, Tuple2) print("\nTuple with nested tuples: ") print(Tuple3)
Output:
Initial empty Tuple:
()
Tuple with the use of String:
('Geeks', 'For')
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of function:
('G', 'e', 'e', 'k', 's')
Tuple with nested tuples:
((0, 1, 2, 3), ('python', 'geek'))
Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.
In order to access the tuple items refer to the index number. Use the index operator [ ] to access an item in a tuple. The index must be an integer. Nested tuples are accessed using nested indexing.
Python3
# Python program to # demonstrate accessing tuple tuple1 = tuple([1, 2, 3, 4, 5]) # Accessing element using indexingprint("First element of tuple")print(tuple1[0]) # Accessing element from last# negative indexingprint("\nLast element of tuple")print(tuple1[-1]) print("\nThird last element of tuple")print(tuple1[-3])
Output:
First element of tuple
1
Last element of tuple
5
Third last element of tuple
3
Note – To know more about tuples, refer Python Tuples.
Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in Boolean context as well and determined to be true or false. It is denoted by the class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error.
Python3
# Python program to # demonstrate boolean type print(type(True))print(type(False)) print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements.
Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by ‘comma’. Type of elements in a set need not be the same, various mixed-up data type values can also be passed to the set.
Python3
# Python program to demonstrate # Creation of Set in Python # Creating a Set set1 = set() print("Initial blank Set: ") print(set1) # Creating a Set with # the use of a String set1 = set("GeeksForGeeks") print("\nSet with the use of String: ") print(set1) # Creating a Set with # the use of a List set1 = set(["Geeks", "For", "Geeks"]) print("\nSet with the use of List: ") print(set1) # Creating a Set with # a mixed type of values # (Having numbers and strings) set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks']) print("\nSet with the use of Mixed Values") print(set1)
Output:
Initial blank Set:
set()
Set with the use of String:
{'F', 'o', 'G', 's', 'r', 'k', 'e'}
Set with the use of List:
{'Geeks', 'For'}
Set with the use of Mixed Values
{1, 2, 4, 6, 'Geeks', 'For'}
Set items cannot be accessed by referring to an index, since sets are unordered the items has no index. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.
Python3
# Python program to demonstrate # Accessing of elements in a set # Creating a set set1 = set(["Geeks", "For", "Geeks"]) print("\nInitial set") print(set1) # Accessing element using # for loop print("\nElements of set: ") for i in set1: print(i, end =" ") # Checking the element # using in keyword print("Geeks" in set1)
Output:
Initial set:
{'Geeks', 'For'}
Elements of set:
Geeks For
True
Note – To know more about sets, refer Python Sets.
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.
In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable. Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing it to curly braces{}.
Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.
Python3
# Creating an empty Dictionary Dict = {} print("Empty Dictionary: ") print(Dict) # Creating a Dictionary # with Integer Keys Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print("\nDictionary with the use of Integer Keys: ") print(Dict) # Creating a Dictionary # with Mixed keys Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} print("\nDictionary with the use of Mixed Keys: ") print(Dict) # Creating a Dictionary # with dict() method Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'}) print("\nDictionary with the use of dict(): ") print(Dict) # Creating a Dictionary # with each item as a Pair Dict = dict([(1, 'Geeks'), (2, 'For')]) print("\nDictionary with each item as a pair: ") print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'Geeks'}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}
In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets. There is also a method called get() that will also help in accessing the element from a dictionary.
Python3
# Python program to demonstrate # accessing a element from a Dictionary # Creating a Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} # accessing a element using key print("Accessing a element using key:") print(Dict['name']) # accessing a element using get() # method print("Accessing a element using get:") print(Dict.get(3))
Output:
Accessing a element using key:
For
Accessing a element using get:
Geeks
shubham_singh
raghav_byte
gabaa406
sweetyty
vinodkalwani2001
Python-datatype
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 356,
"s": 52,
"text": "Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes."
},
{
"code": null,
"e": 416,
"s": 356,
"text": "Following are the standard or built-in data type of Python:"
},
{
"code": null,
"e": 424,
"s": 416,
"text": "Numeric"
},
{
"code": null,
"e": 438,
"s": 424,
"text": "Sequence Type"
},
{
"code": null,
"e": 446,
"s": 438,
"text": "Boolean"
},
{
"code": null,
"e": 450,
"s": 446,
"text": "Set"
},
{
"code": null,
"e": 461,
"s": 450,
"text": "Dictionary"
},
{
"code": null,
"e": 673,
"s": 461,
"text": "In Python, numeric data type represent the data which has numeric value. Numeric value can be integer, floating number or even complex numbers. These values are defined as int, float and complex class in Python."
},
{
"code": null,
"e": 867,
"s": 673,
"text": "Integers – This value is represented by int class. It contains positive or negative whole numbers (without fraction or decimal). In Python there is no limit to how long an integer value can be."
},
{
"code": null,
"e": 1133,
"s": 867,
"text": "Float – This value is represented by float class. It is a real number with floating point representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation."
},
{
"code": null,
"e": 1270,
"s": 1133,
"text": "Complex Numbers – Complex number is represented by complex class. It is specified as (real part) + (imaginary part)j. For example – 2+3j"
},
{
"code": null,
"e": 1337,
"s": 1270,
"text": "Note – type() function is used to determine the type of data type."
},
{
"code": null,
"e": 1345,
"s": 1337,
"text": "Python3"
},
{
"code": "# Python program to # demonstrate numeric value a = 5print(\"Type of a: \", type(a)) b = 5.0print(\"\\nType of b: \", type(b)) c = 2 + 4jprint(\"\\nType of c: \", type(c))",
"e": 1512,
"s": 1345,
"text": null
},
{
"code": null,
"e": 1520,
"s": 1512,
"text": "Output:"
},
{
"code": null,
"e": 1607,
"s": 1520,
"text": "Type of a: <class 'int'>\n\nType of b: <class 'float'>\n\nType of c: <class 'complex'>\n"
},
{
"code": null,
"e": 1815,
"s": 1607,
"text": "In Python, sequence is the ordered collection of similar or different data types. Sequences allows to store multiple values in an organized and efficient fashion. There are several sequence types in Python –"
},
{
"code": null,
"e": 1822,
"s": 1815,
"text": "String"
},
{
"code": null,
"e": 1827,
"s": 1822,
"text": "List"
},
{
"code": null,
"e": 1833,
"s": 1827,
"text": "Tuple"
},
{
"code": null,
"e": 2124,
"s": 1833,
"text": "In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of one or more characters put in a single quote, double-quote or triple quote. In python there is no character data type, a character is a string of length one. It is represented by str class. "
},
{
"code": null,
"e": 2217,
"s": 2124,
"text": "Strings in Python can be created using single quotes or double quotes or even triple quotes."
},
{
"code": null,
"e": 2225,
"s": 2217,
"text": "Python3"
},
{
"code": "# Python Program for # Creation of String # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World'print(\"String with the use of Single Quotes: \") print(String1) # Creating a String # with double Quotes String1 = \"I'm a Geek\"print(\"\\nString with the use of Double Quotes: \") print(String1) print(type(String1)) # Creating a String # with triple Quotes String1 = '''I'm a Geek and I live in a world of \"Geeks\"'''print(\"\\nString with the use of Triple Quotes: \") print(String1) print(type(String1)) # Creating String with triple # Quotes allows multiple lines String1 = '''Geeks For Life'''print(\"\\nCreating a multiline String: \") print(String1) ",
"e": 2929,
"s": 2225,
"text": null
},
{
"code": null,
"e": 2937,
"s": 2929,
"text": "Output:"
},
{
"code": null,
"e": 3239,
"s": 2937,
"text": "String with the use of Single Quotes: \nWelcome to the Geeks World\n\nString with the use of Double Quotes: \nI'm a Geek\n<class 'str'>\n\nString with the use of Triple Quotes: \nI'm a Geek and I live in a world of \"Geeks\"\n<class 'str'>\n\nCreating a multiline String: \nGeeks \n For \n Life\n"
},
{
"code": null,
"e": 3517,
"s": 3241,
"text": "In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character and so on."
},
{
"code": null,
"e": 3525,
"s": 3517,
"text": "Python3"
},
{
"code": "# Python Program to Access # characters of String String1 = \"GeeksForGeeks\"print(\"Initial String: \") print(String1) # Printing First character print(\"\\nFirst character of String is: \") print(String1[0]) # Printing Last character print(\"\\nLast character of String is: \") print(String1[-1]) ",
"e": 3827,
"s": 3525,
"text": null
},
{
"code": null,
"e": 3835,
"s": 3827,
"text": "Output:"
},
{
"code": null,
"e": 3934,
"s": 3835,
"text": "Initial String: \nGeeksForGeeks\n\nFirst character of String is: \nG\n\nLast character of String is: \ns\n"
},
{
"code": null,
"e": 3992,
"s": 3936,
"text": "Note – To know more about strings, refer Python String."
},
{
"code": null,
"e": 4171,
"s": 3992,
"text": "Lists are just like the arrays, declared in other languages which is a ordered collection of data. It is very flexible as the items in a list do not need to be of the same type. "
},
{
"code": null,
"e": 4261,
"s": 4171,
"text": "Lists in Python can be created by just placing the sequence inside the square brackets[]."
},
{
"code": null,
"e": 4269,
"s": 4261,
"text": "Python3"
},
{
"code": "# Python program to demonstrate # Creation of List # Creating a List List = [] print(\"Initial blank List: \") print(List) # Creating a List with # the use of a String List = ['GeeksForGeeks'] print(\"\\nList with the use of String: \") print(List) # Creating a List with # the use of multiple values List = [\"Geeks\", \"For\", \"Geeks\"] print(\"\\nList containing multiple values: \") print(List[0]) print(List[2]) # Creating a Multi-Dimensional List # (By Nesting a list inside a List) List = [['Geeks', 'For'], ['Geeks']] print(\"\\nMulti-Dimensional List: \") print(List) ",
"e": 4851,
"s": 4269,
"text": null
},
{
"code": null,
"e": 4859,
"s": 4851,
"text": "Output:"
},
{
"code": null,
"e": 5036,
"s": 4859,
"text": "Initial blank List: \n[]\n\nList with the use of String: \n['GeeksForGeeks']\n\nList containing multiple values: \nGeeks\nGeeks\n\nMulti-Dimensional List: \n[['Geeks', 'For'], ['Geeks']]\n"
},
{
"code": null,
"e": 5457,
"s": 5038,
"text": "In order to access the list items refer to the index number. Use the index operator [ ] to access an item in a list. In Python, negative sequence indexes represent positions from the end of the array. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc."
},
{
"code": null,
"e": 5465,
"s": 5457,
"text": "Python3"
},
{
"code": "# Python program to demonstrate # accessing of element from list # Creating a List with # the use of multiple values List = [\"Geeks\", \"For\", \"Geeks\"] # accessing a element from the # list using index number print(\"Accessing element from the list\") print(List[0]) print(List[2]) # accessing a element using # negative indexing print(\"Accessing element using negative indexing\") # print the last element of list print(List[-1]) # print the third last element of list print(List[-3]) ",
"e": 5969,
"s": 5465,
"text": null
},
{
"code": null,
"e": 5977,
"s": 5969,
"text": "Output:"
},
{
"code": null,
"e": 6076,
"s": 5977,
"text": "Accessing element from the list\nGeeks\nGeeks\nAccessing element using negative indexing\nGeeks\nGeeks\n"
},
{
"code": null,
"e": 6128,
"s": 6076,
"text": "Note – To know more about Lists, refer Python List."
},
{
"code": null,
"e": 6360,
"s": 6130,
"text": "Just like list, tuple is also an ordered collection of Python objects. The only difference between tuple and list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is represented by tuple class. "
},
{
"code": null,
"e": 6617,
"s": 6360,
"text": "In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence. Tuples can contain any number of elements and of any datatype (like strings, integers, list, etc.)."
},
{
"code": null,
"e": 6807,
"s": 6617,
"text": "Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple."
},
{
"code": null,
"e": 6815,
"s": 6807,
"text": "Python3"
},
{
"code": "# Python program to demonstrate # creation of Set # Creating an empty tuple Tuple1 = () print(\"Initial empty Tuple: \") print (Tuple1) # Creating a Tuple with # the use of Strings Tuple1 = ('Geeks', 'For') print(\"\\nTuple with the use of String: \") print(Tuple1) # Creating a Tuple with # the use of list list1 = [1, 2, 4, 5, 6] print(\"\\nTuple using List: \") print(tuple(list1)) # Creating a Tuple with the # use of built-in function Tuple1 = tuple('Geeks') print(\"\\nTuple with the use of function: \") print(Tuple1) # Creating a Tuple # with nested tuples Tuple1 = (0, 1, 2, 3) Tuple2 = ('python', 'geek') Tuple3 = (Tuple1, Tuple2) print(\"\\nTuple with nested tuples: \") print(Tuple3) ",
"e": 7517,
"s": 6815,
"text": null
},
{
"code": null,
"e": 7525,
"s": 7517,
"text": "Output:"
},
{
"code": null,
"e": 7759,
"s": 7525,
"text": "Initial empty Tuple: \n()\n\nTuple with the use of String: \n('Geeks', 'For')\n\nTuple using List: \n(1, 2, 4, 5, 6)\n\nTuple with the use of function: \n('G', 'e', 'e', 'k', 's')\n\nTuple with nested tuples: \n((0, 1, 2, 3), ('python', 'geek'))\n"
},
{
"code": null,
"e": 7851,
"s": 7761,
"text": "Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing."
},
{
"code": null,
"e": 8050,
"s": 7851,
"text": "In order to access the tuple items refer to the index number. Use the index operator [ ] to access an item in a tuple. The index must be an integer. Nested tuples are accessed using nested indexing."
},
{
"code": null,
"e": 8058,
"s": 8050,
"text": "Python3"
},
{
"code": "# Python program to # demonstrate accessing tuple tuple1 = tuple([1, 2, 3, 4, 5]) # Accessing element using indexingprint(\"First element of tuple\")print(tuple1[0]) # Accessing element from last# negative indexingprint(\"\\nLast element of tuple\")print(tuple1[-1]) print(\"\\nThird last element of tuple\")print(tuple1[-3])",
"e": 8380,
"s": 8058,
"text": null
},
{
"code": null,
"e": 8388,
"s": 8380,
"text": "Output:"
},
{
"code": null,
"e": 8470,
"s": 8388,
"text": "First element of tuple\n1\n\nLast element of tuple\n5\n\nThird last element of tuple\n3\n"
},
{
"code": null,
"e": 8525,
"s": 8470,
"text": "Note – To know more about tuples, refer Python Tuples."
},
{
"code": null,
"e": 8826,
"s": 8525,
"text": "Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in Boolean context as well and determined to be true or false. It is denoted by the class bool."
},
{
"code": null,
"e": 8930,
"s": 8826,
"text": "Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error."
},
{
"code": null,
"e": 8938,
"s": 8930,
"text": "Python3"
},
{
"code": "# Python program to # demonstrate boolean type print(type(True))print(type(False)) print(type(true))",
"e": 9041,
"s": 8938,
"text": null
},
{
"code": null,
"e": 9049,
"s": 9041,
"text": "Output:"
},
{
"code": null,
"e": 9080,
"s": 9049,
"text": "<class 'bool'>\n<class 'bool'>\n"
},
{
"code": null,
"e": 9240,
"s": 9080,
"text": "Traceback (most recent call last):\n File \"/home/7e8862763fb66153d70824099d4f5fb7.py\", line 8, in \n print(type(true))\nNameError: name 'true' is not defined\n"
},
{
"code": null,
"e": 9439,
"s": 9240,
"text": "In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements."
},
{
"code": null,
"e": 9714,
"s": 9439,
"text": "Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by ‘comma’. Type of elements in a set need not be the same, various mixed-up data type values can also be passed to the set."
},
{
"code": null,
"e": 9722,
"s": 9714,
"text": "Python3"
},
{
"code": "# Python program to demonstrate # Creation of Set in Python # Creating a Set set1 = set() print(\"Initial blank Set: \") print(set1) # Creating a Set with # the use of a String set1 = set(\"GeeksForGeeks\") print(\"\\nSet with the use of String: \") print(set1) # Creating a Set with # the use of a List set1 = set([\"Geeks\", \"For\", \"Geeks\"]) print(\"\\nSet with the use of List: \") print(set1) # Creating a Set with # a mixed type of values # (Having numbers and strings) set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks']) print(\"\\nSet with the use of Mixed Values\") print(set1) ",
"e": 10307,
"s": 9722,
"text": null
},
{
"code": null,
"e": 10315,
"s": 10307,
"text": "Output:"
},
{
"code": null,
"e": 10516,
"s": 10315,
"text": "Initial blank Set: \nset()\n\nSet with the use of String: \n{'F', 'o', 'G', 's', 'r', 'k', 'e'}\n\nSet with the use of List: \n{'Geeks', 'For'}\n\nSet with the use of Mixed Values\n{1, 2, 4, 6, 'Geeks', 'For'}\n"
},
{
"code": null,
"e": 10753,
"s": 10518,
"text": "Set items cannot be accessed by referring to an index, since sets are unordered the items has no index. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword."
},
{
"code": null,
"e": 10761,
"s": 10753,
"text": "Python3"
},
{
"code": "# Python program to demonstrate # Accessing of elements in a set # Creating a set set1 = set([\"Geeks\", \"For\", \"Geeks\"]) print(\"\\nInitial set\") print(set1) # Accessing element using # for loop print(\"\\nElements of set: \") for i in set1: print(i, end =\" \") # Checking the element # using in keyword print(\"Geeks\" in set1) ",
"e": 11098,
"s": 10761,
"text": null
},
{
"code": null,
"e": 11106,
"s": 11098,
"text": "Output:"
},
{
"code": null,
"e": 11174,
"s": 11106,
"text": "Initial set: \n{'Geeks', 'For'}\n\nElements of set: \nGeeks For \n\nTrue\n"
},
{
"code": null,
"e": 11227,
"s": 11176,
"text": "Note – To know more about sets, refer Python Sets."
},
{
"code": null,
"e": 11609,
"s": 11227,
"text": "Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’."
},
{
"code": null,
"e": 11988,
"s": 11609,
"text": "In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable. Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing it to curly braces{}."
},
{
"code": null,
"e": 12096,
"s": 11988,
"text": "Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly."
},
{
"code": null,
"e": 12104,
"s": 12096,
"text": "Python3"
},
{
"code": "# Creating an empty Dictionary Dict = {} print(\"Empty Dictionary: \") print(Dict) # Creating a Dictionary # with Integer Keys Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print(\"\\nDictionary with the use of Integer Keys: \") print(Dict) # Creating a Dictionary # with Mixed keys Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} print(\"\\nDictionary with the use of Mixed Keys: \") print(Dict) # Creating a Dictionary # with dict() method Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'}) print(\"\\nDictionary with the use of dict(): \") print(Dict) # Creating a Dictionary # with each item as a Pair Dict = dict([(1, 'Geeks'), (2, 'For')]) print(\"\\nDictionary with each item as a pair: \") print(Dict) ",
"e": 12805,
"s": 12104,
"text": null
},
{
"code": null,
"e": 12813,
"s": 12805,
"text": "Output:"
},
{
"code": null,
"e": 13124,
"s": 12813,
"text": "Empty Dictionary: \n{}\n\nDictionary with the use of Integer Keys: \n{1: 'Geeks', 2: 'For', 3: 'Geeks'}\n\nDictionary with the use of Mixed Keys: \n{1: [1, 2, 3, 4], 'Name': 'Geeks'}\n\nDictionary with the use of dict(): \n{1: 'Geeks', 2: 'For', 3: 'Geeks'}\n\nDictionary with each item as a pair: \n{1: 'Geeks', 2: 'For'}\n"
},
{
"code": null,
"e": 13334,
"s": 13126,
"text": "In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets. There is also a method called get() that will also help in accessing the element from a dictionary."
},
{
"code": null,
"e": 13342,
"s": 13334,
"text": "Python3"
},
{
"code": "# Python program to demonstrate # accessing a element from a Dictionary # Creating a Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} # accessing a element using key print(\"Accessing a element using key:\") print(Dict['name']) # accessing a element using get() # method print(\"Accessing a element using get:\") print(Dict.get(3)) ",
"e": 13694,
"s": 13342,
"text": null
},
{
"code": null,
"e": 13702,
"s": 13694,
"text": "Output:"
},
{
"code": null,
"e": 13775,
"s": 13702,
"text": "Accessing a element using key:\nFor\nAccessing a element using get:\nGeeks\n"
},
{
"code": null,
"e": 13791,
"s": 13777,
"text": "shubham_singh"
},
{
"code": null,
"e": 13803,
"s": 13791,
"text": "raghav_byte"
},
{
"code": null,
"e": 13812,
"s": 13803,
"text": "gabaa406"
},
{
"code": null,
"e": 13821,
"s": 13812,
"text": "sweetyty"
},
{
"code": null,
"e": 13838,
"s": 13821,
"text": "vinodkalwani2001"
},
{
"code": null,
"e": 13854,
"s": 13838,
"text": "Python-datatype"
},
{
"code": null,
"e": 13861,
"s": 13854,
"text": "Python"
}
] |
Working with MySQL BLOB in Python
|
13 Jun, 2022
In Python Programming, We can connect with several databases like MySQL, Oracle, SQLite, etc., using inbuilt support. We have separate modules for each database. We can use SQL Language as a mediator between the python program and database. We will write all queries in our python program and send those commands to the database. So, Using these programs, we can perform several operations such as Insertion, Deletion, Updating, and Retrieving.
Here, In this article, We will discuss working with MySQL BLOB in python. With the help of BLOB(Large Binary Object) data type in MySQL, we can store files or images in our database in binary format.
This connector will connect our python program to database. Just run this command,
pip install mysql-connector-python
Import MySQL database Module
import mysql.connector
For creating a connection between Python Program and Database. Using connect() method, We will connect the python program with our database.
connection = mysql.connector.connect(host=’localhost’, database='<database_name>’, user='<User_name>’, password='<password>’)
Now, create a cursor object by using cursor() method for executing the SQL Queries and holding the result in an object.
cursor = connection.cursor()
For executing SQL queries, we will use a cursor object. For example,
cursor.execute("select * from table_name")
Finally, Once we are done with our operations, we have to close the resources.
cursor.close()
con.close()
We are done with the basic steps of connection. Now, Let’s discuss the main agenda of this article which is the practical implementation of BLOB data type in MySQL Python,
First, We need to create a database in MySQL using the below command.
create database geeksforgeeks;
For Example:
Creating a function through which we can convert images or files in binary format.
Python3
def convertData(filename): # Convert images or files data to binary format with open(filename, 'rb') as file: binary_data = file.read() return binary_data
Check Whether Database Connection is created or not using Python Program. Let’s have a look in below code:
Python3
import mysql.connector connection = mysql.connector.connect( host='localhost', database='geeksforgeeks', user='root', password='shubhanshu') cursor = connection.cursor() if connection is not None: print('Connected Successfully')else: print('Connection Failed')
We are done with all basic which is required. Let’s see the complete code for inserting the images or files in the MySQL database using Python Programs:
Python3
import mysql.connector # Convert images or files data to binary formatdef convert_data(file_name): with open(file_name, 'rb') as file: binary_data = file.read() return binary_data try: connection = mysql.connector.connect(host='localhost', database='geeksforgeeks', user='root', password='shubhanshu') cursor = connection.cursor() # create table query create_table = """CREATE TABLE demo(id INT PRIMARY KEY,\ name VARCHAR (255) NOT NULL, profile_pic BLOB NOT NULL, \ imp_files BLOB NOT NULL) """ # Execute the create_table query first cursor.execute(create_table) # printing successful message print("Table created Successfully") query = """ INSERT INTO demo(id, name, profile_pic, imp_files)\ VALUES (%s,%s,%s,%s)""" # First Data Insertion student_id = "1" student_name = "Shubham" first_profile_picture = convert_data("D:\GFG\images\shubham.png") first_text_file = convert_data('D:\GFG\details1.txt') # Inserting the data in database in tuple format result = cursor.execute( query, (student_id, student_name, first_profile_picture, first_text_file)) # Committing the data connection.commit() print("Successfully Inserted Values") # Print error if occurredexcept mysql.connector.Error as error: print(format(error)) finally: # Closing all resources if connection.is_connected(): cursor.close() connection.close() print("MySQL connection is closed")
Output:
The table formed in MySQL:
Explanation:
Establishing the connection with MySQL database.
Write the create table Query and Using cursor object, Executing it.
Now, Insert data into a table using SQL query and stored in query variable.
Storing the data in variables such as student_id = “1”, Student_name = “Shubham” and for images or files, first we are converting those files into binary data and then stored into a variables.
Using cursor object, Executing the query. Inserting the data in the database in tuple format.
Using commit() method, We are saving the data.
After completing all operations, we have to close all the resources such as the connection and cursor object.
Click here to download PNG file and TXT file.
simmytarika5
adnanirshad158
nikhatkhan11
Picked
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 473,
"s": 28,
"text": "In Python Programming, We can connect with several databases like MySQL, Oracle, SQLite, etc., using inbuilt support. We have separate modules for each database. We can use SQL Language as a mediator between the python program and database. We will write all queries in our python program and send those commands to the database. So, Using these programs, we can perform several operations such as Insertion, Deletion, Updating, and Retrieving."
},
{
"code": null,
"e": 673,
"s": 473,
"text": "Here, In this article, We will discuss working with MySQL BLOB in python. With the help of BLOB(Large Binary Object) data type in MySQL, we can store files or images in our database in binary format."
},
{
"code": null,
"e": 756,
"s": 673,
"text": "This connector will connect our python program to database. Just run this command,"
},
{
"code": null,
"e": 791,
"s": 756,
"text": "pip install mysql-connector-python"
},
{
"code": null,
"e": 820,
"s": 791,
"text": "Import MySQL database Module"
},
{
"code": null,
"e": 843,
"s": 820,
"text": "import mysql.connector"
},
{
"code": null,
"e": 984,
"s": 843,
"text": "For creating a connection between Python Program and Database. Using connect() method, We will connect the python program with our database."
},
{
"code": null,
"e": 1110,
"s": 984,
"text": "connection = mysql.connector.connect(host=’localhost’, database='<database_name>’, user='<User_name>’, password='<password>’)"
},
{
"code": null,
"e": 1230,
"s": 1110,
"text": "Now, create a cursor object by using cursor() method for executing the SQL Queries and holding the result in an object."
},
{
"code": null,
"e": 1259,
"s": 1230,
"text": "cursor = connection.cursor()"
},
{
"code": null,
"e": 1328,
"s": 1259,
"text": "For executing SQL queries, we will use a cursor object. For example,"
},
{
"code": null,
"e": 1371,
"s": 1328,
"text": "cursor.execute(\"select * from table_name\")"
},
{
"code": null,
"e": 1450,
"s": 1371,
"text": "Finally, Once we are done with our operations, we have to close the resources."
},
{
"code": null,
"e": 1477,
"s": 1450,
"text": "cursor.close()\ncon.close()"
},
{
"code": null,
"e": 1650,
"s": 1477,
"text": "We are done with the basic steps of connection. Now, Let’s discuss the main agenda of this article which is the practical implementation of BLOB data type in MySQL Python, "
},
{
"code": null,
"e": 1720,
"s": 1650,
"text": "First, We need to create a database in MySQL using the below command."
},
{
"code": null,
"e": 1751,
"s": 1720,
"text": "create database geeksforgeeks;"
},
{
"code": null,
"e": 1765,
"s": 1751,
"text": "For Example: "
},
{
"code": null,
"e": 1848,
"s": 1765,
"text": "Creating a function through which we can convert images or files in binary format."
},
{
"code": null,
"e": 1856,
"s": 1848,
"text": "Python3"
},
{
"code": "def convertData(filename): # Convert images or files data to binary format with open(filename, 'rb') as file: binary_data = file.read() return binary_data",
"e": 2035,
"s": 1856,
"text": null
},
{
"code": null,
"e": 2142,
"s": 2035,
"text": "Check Whether Database Connection is created or not using Python Program. Let’s have a look in below code:"
},
{
"code": null,
"e": 2150,
"s": 2142,
"text": "Python3"
},
{
"code": "import mysql.connector connection = mysql.connector.connect( host='localhost', database='geeksforgeeks', user='root', password='shubhanshu') cursor = connection.cursor() if connection is not None: print('Connected Successfully')else: print('Connection Failed')",
"e": 2424,
"s": 2150,
"text": null
},
{
"code": null,
"e": 2577,
"s": 2424,
"text": "We are done with all basic which is required. Let’s see the complete code for inserting the images or files in the MySQL database using Python Programs:"
},
{
"code": null,
"e": 2585,
"s": 2577,
"text": "Python3"
},
{
"code": "import mysql.connector # Convert images or files data to binary formatdef convert_data(file_name): with open(file_name, 'rb') as file: binary_data = file.read() return binary_data try: connection = mysql.connector.connect(host='localhost', database='geeksforgeeks', user='root', password='shubhanshu') cursor = connection.cursor() # create table query create_table = \"\"\"CREATE TABLE demo(id INT PRIMARY KEY,\\ name VARCHAR (255) NOT NULL, profile_pic BLOB NOT NULL, \\ imp_files BLOB NOT NULL) \"\"\" # Execute the create_table query first cursor.execute(create_table) # printing successful message print(\"Table created Successfully\") query = \"\"\" INSERT INTO demo(id, name, profile_pic, imp_files)\\ VALUES (%s,%s,%s,%s)\"\"\" # First Data Insertion student_id = \"1\" student_name = \"Shubham\" first_profile_picture = convert_data(\"D:\\GFG\\images\\shubham.png\") first_text_file = convert_data('D:\\GFG\\details1.txt') # Inserting the data in database in tuple format result = cursor.execute( query, (student_id, student_name, first_profile_picture, first_text_file)) # Committing the data connection.commit() print(\"Successfully Inserted Values\") # Print error if occurredexcept mysql.connector.Error as error: print(format(error)) finally: # Closing all resources if connection.is_connected(): cursor.close() connection.close() print(\"MySQL connection is closed\")",
"e": 4187,
"s": 2585,
"text": null
},
{
"code": null,
"e": 4195,
"s": 4187,
"text": "Output:"
},
{
"code": null,
"e": 4222,
"s": 4195,
"text": "The table formed in MySQL:"
},
{
"code": null,
"e": 4235,
"s": 4222,
"text": "Explanation:"
},
{
"code": null,
"e": 4284,
"s": 4235,
"text": "Establishing the connection with MySQL database."
},
{
"code": null,
"e": 4352,
"s": 4284,
"text": "Write the create table Query and Using cursor object, Executing it."
},
{
"code": null,
"e": 4428,
"s": 4352,
"text": "Now, Insert data into a table using SQL query and stored in query variable."
},
{
"code": null,
"e": 4622,
"s": 4428,
"text": "Storing the data in variables such as student_id = “1”, Student_name = “Shubham” and for images or files, first we are converting those files into binary data and then stored into a variables."
},
{
"code": null,
"e": 4716,
"s": 4622,
"text": "Using cursor object, Executing the query. Inserting the data in the database in tuple format."
},
{
"code": null,
"e": 4763,
"s": 4716,
"text": "Using commit() method, We are saving the data."
},
{
"code": null,
"e": 4873,
"s": 4763,
"text": "After completing all operations, we have to close all the resources such as the connection and cursor object."
},
{
"code": null,
"e": 4920,
"s": 4873,
"text": "Click here to download PNG file and TXT file. "
},
{
"code": null,
"e": 4933,
"s": 4920,
"text": "simmytarika5"
},
{
"code": null,
"e": 4948,
"s": 4933,
"text": "adnanirshad158"
},
{
"code": null,
"e": 4961,
"s": 4948,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 4968,
"s": 4961,
"text": "Picked"
},
{
"code": null,
"e": 4981,
"s": 4968,
"text": "Python-mySQL"
},
{
"code": null,
"e": 4988,
"s": 4981,
"text": "Python"
}
] |
Strings in Java
|
27 Jun, 2022
Strings in Java are Objects that are backed internally by a char array. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created.
Syntax:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
<String_Type> <string_variable> = "<sequence_of_string>";
Example:
String str = "Geeks";
Memory allotment of String
Whenever a String Object is created as a literal, the object will be created in String constant pool. This allows JVM to optimize the initialization of String literal.
For example:
String str = "Geeks";
The string can also be declared using new operator i.e. dynamically allocated. In case of String are dynamically allocated they are assigned a new memory location in heap. This string will not be added to String constant pool.
For example:
String str = new String("Geeks");
If you want to store this string in the constant pool then you will need to “intern” it.
For example:
String internedString = str.intern();
// this will add the string to string constant pool.
It is preferred to use String literals as it allows JVM to optimize memory allocation.
An example that shows how to declare a String
Java
// Java code to illustrate Stringimport java.io.*;import java.lang.*; class Test { public static void main(String[] args) { // Declare String without using new operator String s = "GeeksforGeeks"; // Prints the String. System.out.println("String s = " + s); // Declare String using new operator String s1 = new String("GeeksforGeeks"); // Prints the String. System.out.println("String s1 = " + s1); }}
String s = GeeksforGeeks
String s1 = GeeksforGeeks
Interfaces and Classes in Strings in Java
CharBuffer: This class implements the CharSequence interface. This class is used to allow character buffers to be used in place of CharSequences. An example of such usage is the regular-expression package java.util.regex.
String: String is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created.
There are two ways to create a string in Java:
String literal
String s = “GeeksforGeeks”;
Using new keyword
String s = new String (“GeeksforGeeks”);
StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences.
Syntax:
StringBuffer s = new StringBuffer("GeeksforGeeks");
StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternate to String Class, as it creates a mutable sequence of characters.
Syntax:
StringBuilder str = new StringBuilder();
str.append("GFG");
StringTokenizer class in Java is used to break a string into tokens.
Example:
A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed. A token is returned by taking a substring of the string that was used to create the StringTokenizer object.
StringJoiner is a class in java.util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. Though this can also be with the help of StringBuilder class to append delimiter after each string, StringJoiner provides an easy way to do that without much code to write.Syntax:
public StringJoiner(CharSequence delimiter)
Above we saw we can create string by String Literal.
For ex- // String s=”Welcome”;
Here the JVM checks the String Constant Pool. If the string does not exist, then a new string instance is created and placed in a pool. If the string exists, then it will not create a new object. Rather, it will return the reference to the same instance. The cache which stores these string instances is known as the String Constant pool or String Pool. In earlier versions of Java up to JDK 6 String pool was located inside PermGen(Permanent Generation) space. But in JDK 7 it is moved to the main heap area.
Why did the String pool move from PermGen to the normal heap area?
PermGen space is limited, the default size is just 64 MB. it was a problem with creating and storing too many string objects in PermGen space. That’s why the String pool was moved to a larger heap area. To make Java more memory efficient, the concept of string literal is used. By the use of the ‘new’ keyword, The JVM will create a new string object in the normal heap area even if the same string object is present in the string pool.
For ex-
String a=new String(“Bhubaneswar”)
Let’s have a look at the concept with a java program and visualize the actual JVM memory structure:
Program:
Java
class StringStorage { public static void main(String args[]) { String s1 = "TAT"; String s2 = "TAT"; String s3 = new String("TAT"); String s4 = new String("TAT"); System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4); }}
TAT
TAT
TAT
TAT
Note: All objects in Java are stored in a heap. The reference variable is to the object stored in the stack area or they can be contained in other objects which puts them in the heap area also.
Example 1:
Java
//Construct String from subset of char array class GFG{ public static void main(String args[]){byte ascii[]={71,70,71}; String s1= new String(ascii); System.out.println(s1); String s2= new String(ascii,1,2); System.out.println(s2);}}
GFG
FG
Example 2:
Java
// Construct one string from another class GFG{public static void main(String args[]){ char c[]={'G','f','g'}; String s1=new String (c); String s2=new String (s1); System.out.println(s1); System.out.println(s2); }}
Gfg
Gfg
anthonycathers
bitsandbytes
Satyabrata_Jena
singhankitasingh066
java-StringBuffer
Java-StringBuilder
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Jun, 2022"
},
{
"code": null,
"e": 271,
"s": 52,
"text": "Strings in Java are Objects that are backed internally by a char array. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created. "
},
{
"code": null,
"e": 281,
"s": 271,
"text": "Syntax: "
},
{
"code": null,
"e": 290,
"s": 281,
"text": "Chapters"
},
{
"code": null,
"e": 317,
"s": 290,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 367,
"s": 317,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 390,
"s": 367,
"text": "captions off, selected"
},
{
"code": null,
"e": 398,
"s": 390,
"text": "English"
},
{
"code": null,
"e": 422,
"s": 398,
"text": "This is a modal window."
},
{
"code": null,
"e": 491,
"s": 422,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 513,
"s": 491,
"text": "End of dialog window."
},
{
"code": null,
"e": 572,
"s": 513,
"text": "<String_Type> <string_variable> = \"<sequence_of_string>\"; "
},
{
"code": null,
"e": 583,
"s": 572,
"text": "Example: "
},
{
"code": null,
"e": 605,
"s": 583,
"text": "String str = \"Geeks\";"
},
{
"code": null,
"e": 632,
"s": 605,
"text": "Memory allotment of String"
},
{
"code": null,
"e": 800,
"s": 632,
"text": "Whenever a String Object is created as a literal, the object will be created in String constant pool. This allows JVM to optimize the initialization of String literal."
},
{
"code": null,
"e": 814,
"s": 800,
"text": "For example: "
},
{
"code": null,
"e": 836,
"s": 814,
"text": "String str = \"Geeks\";"
},
{
"code": null,
"e": 1063,
"s": 836,
"text": "The string can also be declared using new operator i.e. dynamically allocated. In case of String are dynamically allocated they are assigned a new memory location in heap. This string will not be added to String constant pool."
},
{
"code": null,
"e": 1077,
"s": 1063,
"text": "For example: "
},
{
"code": null,
"e": 1111,
"s": 1077,
"text": "String str = new String(\"Geeks\");"
},
{
"code": null,
"e": 1200,
"s": 1111,
"text": "If you want to store this string in the constant pool then you will need to “intern” it."
},
{
"code": null,
"e": 1213,
"s": 1200,
"text": "For example:"
},
{
"code": null,
"e": 1305,
"s": 1213,
"text": "String internedString = str.intern(); \n// this will add the string to string constant pool."
},
{
"code": null,
"e": 1392,
"s": 1305,
"text": "It is preferred to use String literals as it allows JVM to optimize memory allocation."
},
{
"code": null,
"e": 1439,
"s": 1392,
"text": "An example that shows how to declare a String "
},
{
"code": null,
"e": 1444,
"s": 1439,
"text": "Java"
},
{
"code": "// Java code to illustrate Stringimport java.io.*;import java.lang.*; class Test { public static void main(String[] args) { // Declare String without using new operator String s = \"GeeksforGeeks\"; // Prints the String. System.out.println(\"String s = \" + s); // Declare String using new operator String s1 = new String(\"GeeksforGeeks\"); // Prints the String. System.out.println(\"String s1 = \" + s1); }}",
"e": 1914,
"s": 1444,
"text": null
},
{
"code": null,
"e": 1965,
"s": 1914,
"text": "String s = GeeksforGeeks\nString s1 = GeeksforGeeks"
},
{
"code": null,
"e": 2007,
"s": 1965,
"text": "Interfaces and Classes in Strings in Java"
},
{
"code": null,
"e": 2229,
"s": 2007,
"text": "CharBuffer: This class implements the CharSequence interface. This class is used to allow character buffers to be used in place of CharSequences. An example of such usage is the regular-expression package java.util.regex."
},
{
"code": null,
"e": 2373,
"s": 2229,
"text": "String: String is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created."
},
{
"code": null,
"e": 2421,
"s": 2373,
"text": "There are two ways to create a string in Java: "
},
{
"code": null,
"e": 2436,
"s": 2421,
"text": "String literal"
},
{
"code": null,
"e": 2464,
"s": 2436,
"text": "String s = “GeeksforGeeks”;"
},
{
"code": null,
"e": 2482,
"s": 2464,
"text": "Using new keyword"
},
{
"code": null,
"e": 2523,
"s": 2482,
"text": "String s = new String (“GeeksforGeeks”);"
},
{
"code": null,
"e": 2753,
"s": 2523,
"text": "StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences."
},
{
"code": null,
"e": 2761,
"s": 2753,
"text": "Syntax:"
},
{
"code": null,
"e": 2813,
"s": 2761,
"text": "StringBuffer s = new StringBuffer(\"GeeksforGeeks\");"
},
{
"code": null,
"e": 3067,
"s": 2813,
"text": "StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternate to String Class, as it creates a mutable sequence of characters."
},
{
"code": null,
"e": 3075,
"s": 3067,
"text": "Syntax:"
},
{
"code": null,
"e": 3135,
"s": 3075,
"text": "StringBuilder str = new StringBuilder();\nstr.append(\"GFG\");"
},
{
"code": null,
"e": 3205,
"s": 3135,
"text": "StringTokenizer class in Java is used to break a string into tokens. "
},
{
"code": null,
"e": 3214,
"s": 3205,
"text": "Example:"
},
{
"code": null,
"e": 3499,
"s": 3214,
"text": "A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed. A token is returned by taking a substring of the string that was used to create the StringTokenizer object."
},
{
"code": null,
"e": 3892,
"s": 3499,
"text": "StringJoiner is a class in java.util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. Though this can also be with the help of StringBuilder class to append delimiter after each string, StringJoiner provides an easy way to do that without much code to write.Syntax:"
},
{
"code": null,
"e": 3936,
"s": 3892,
"text": "public StringJoiner(CharSequence delimiter)"
},
{
"code": null,
"e": 3991,
"s": 3936,
"text": "Above we saw we can create string by String Literal. "
},
{
"code": null,
"e": 4023,
"s": 3991,
"text": "For ex- // String s=”Welcome”; "
},
{
"code": null,
"e": 4534,
"s": 4023,
"text": "Here the JVM checks the String Constant Pool. If the string does not exist, then a new string instance is created and placed in a pool. If the string exists, then it will not create a new object. Rather, it will return the reference to the same instance. The cache which stores these string instances is known as the String Constant pool or String Pool. In earlier versions of Java up to JDK 6 String pool was located inside PermGen(Permanent Generation) space. But in JDK 7 it is moved to the main heap area. "
},
{
"code": null,
"e": 4602,
"s": 4534,
"text": "Why did the String pool move from PermGen to the normal heap area? "
},
{
"code": null,
"e": 5040,
"s": 4602,
"text": "PermGen space is limited, the default size is just 64 MB. it was a problem with creating and storing too many string objects in PermGen space. That’s why the String pool was moved to a larger heap area. To make Java more memory efficient, the concept of string literal is used. By the use of the ‘new’ keyword, The JVM will create a new string object in the normal heap area even if the same string object is present in the string pool. "
},
{
"code": null,
"e": 5049,
"s": 5040,
"text": "For ex- "
},
{
"code": null,
"e": 5084,
"s": 5049,
"text": "String a=new String(“Bhubaneswar”)"
},
{
"code": null,
"e": 5185,
"s": 5084,
"text": "Let’s have a look at the concept with a java program and visualize the actual JVM memory structure: "
},
{
"code": null,
"e": 5194,
"s": 5185,
"text": "Program:"
},
{
"code": null,
"e": 5199,
"s": 5194,
"text": "Java"
},
{
"code": "class StringStorage { public static void main(String args[]) { String s1 = \"TAT\"; String s2 = \"TAT\"; String s3 = new String(\"TAT\"); String s4 = new String(\"TAT\"); System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4); }}",
"e": 5526,
"s": 5199,
"text": null
},
{
"code": null,
"e": 5542,
"s": 5526,
"text": "TAT\nTAT\nTAT\nTAT"
},
{
"code": null,
"e": 5736,
"s": 5542,
"text": "Note: All objects in Java are stored in a heap. The reference variable is to the object stored in the stack area or they can be contained in other objects which puts them in the heap area also."
},
{
"code": null,
"e": 5750,
"s": 5738,
"text": "Example 1: "
},
{
"code": null,
"e": 5755,
"s": 5750,
"text": "Java"
},
{
"code": "//Construct String from subset of char array class GFG{ public static void main(String args[]){byte ascii[]={71,70,71}; String s1= new String(ascii); System.out.println(s1); String s2= new String(ascii,1,2); System.out.println(s2);}}",
"e": 6000,
"s": 5755,
"text": null
},
{
"code": null,
"e": 6007,
"s": 6000,
"text": "GFG\nFG"
},
{
"code": null,
"e": 6020,
"s": 6009,
"text": "Example 2:"
},
{
"code": null,
"e": 6025,
"s": 6020,
"text": "Java"
},
{
"code": "// Construct one string from another class GFG{public static void main(String args[]){ char c[]={'G','f','g'}; String s1=new String (c); String s2=new String (s1); System.out.println(s1); System.out.println(s2); }}",
"e": 6255,
"s": 6025,
"text": null
},
{
"code": null,
"e": 6263,
"s": 6255,
"text": "Gfg\nGfg"
},
{
"code": null,
"e": 6278,
"s": 6263,
"text": "anthonycathers"
},
{
"code": null,
"e": 6291,
"s": 6278,
"text": "bitsandbytes"
},
{
"code": null,
"e": 6307,
"s": 6291,
"text": "Satyabrata_Jena"
},
{
"code": null,
"e": 6327,
"s": 6307,
"text": "singhankitasingh066"
},
{
"code": null,
"e": 6345,
"s": 6327,
"text": "java-StringBuffer"
},
{
"code": null,
"e": 6364,
"s": 6345,
"text": "Java-StringBuilder"
},
{
"code": null,
"e": 6377,
"s": 6364,
"text": "Java-Strings"
},
{
"code": null,
"e": 6382,
"s": 6377,
"text": "Java"
},
{
"code": null,
"e": 6395,
"s": 6382,
"text": "Java-Strings"
},
{
"code": null,
"e": 6400,
"s": 6395,
"text": "Java"
}
] |
Java program to check palindrome (using library methods)
|
28 Jun, 2021
Given a string, write a Java function to check if it is palindrome or not. A string is said to be palindrome if reverse of the string is same as string. For example, “abba” is palindrome, but “abbc” is not palindrome. The problem here is solved using string reverse function.
Examples:
Input : malayalam
Output : Yes
Input : GeeksforGeeks
Output : No
// Java program to illustrate checking of a string// if its palindrome or not using reverse functionclass Palindrome{ public static void checkPalindrome(String s) { // reverse the given String String reverse = new StringBuffer(s).reverse().toString(); // check whether the string is palindrome or not if (s.equals(reverse)) System.out.println("Yes"); else System.out.println("No"); } public static void main (String[] args) throws java.lang.Exception { checkPalindrome("malayalam"); checkPalindrome("GeeksforGeeks"); }}
Output:
Yes
No
Related Article :C program to check whether a given string is palindrome or not
This article is contributed by Bhargav Sai Gajula. 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.
palindrome
Java
School Programming
Java
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 329,
"s": 53,
"text": "Given a string, write a Java function to check if it is palindrome or not. A string is said to be palindrome if reverse of the string is same as string. For example, “abba” is palindrome, but “abbc” is not palindrome. The problem here is solved using string reverse function."
},
{
"code": null,
"e": 339,
"s": 329,
"text": "Examples:"
},
{
"code": null,
"e": 407,
"s": 339,
"text": "Input : malayalam\nOutput : Yes\n\nInput : GeeksforGeeks\nOutput : No\n\n"
},
{
"code": "// Java program to illustrate checking of a string// if its palindrome or not using reverse functionclass Palindrome{ public static void checkPalindrome(String s) { // reverse the given String String reverse = new StringBuffer(s).reverse().toString(); // check whether the string is palindrome or not if (s.equals(reverse)) System.out.println(\"Yes\"); else System.out.println(\"No\"); } public static void main (String[] args) throws java.lang.Exception { checkPalindrome(\"malayalam\"); checkPalindrome(\"GeeksforGeeks\"); }}",
"e": 984,
"s": 407,
"text": null
},
{
"code": null,
"e": 992,
"s": 984,
"text": "Output:"
},
{
"code": null,
"e": 1000,
"s": 992,
"text": "Yes\nNo\n"
},
{
"code": null,
"e": 1080,
"s": 1000,
"text": "Related Article :C program to check whether a given string is palindrome or not"
},
{
"code": null,
"e": 1382,
"s": 1080,
"text": "This article is contributed by Bhargav Sai Gajula. 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."
},
{
"code": null,
"e": 1507,
"s": 1382,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1518,
"s": 1507,
"text": "palindrome"
},
{
"code": null,
"e": 1523,
"s": 1518,
"text": "Java"
},
{
"code": null,
"e": 1542,
"s": 1523,
"text": "School Programming"
},
{
"code": null,
"e": 1547,
"s": 1542,
"text": "Java"
},
{
"code": null,
"e": 1558,
"s": 1547,
"text": "palindrome"
}
] |
Specifying the increment in for-loops in Python
|
01 Oct, 2020
Let us see how to control the increment in for-loops in Python. We can do this by using the range() function.
range() allows the user to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end as well as how big the difference will be between one number and the next.
Syntax: range(start, stop, step)
Parameters:
start: integer starting from which the sequence of integers is to be returned
stop: integer before which the sequence of integers is to be returned
step: integer value which determines the increment between each integer in the sequence
Returns: a list
Example 1: Incrementing the iterator by 1.
Python3
for i in range(5): print(i)
Output:
0
1
2
3
4
Example 2: Incrementing the iterator by an integer value n.
Python3
# increment valuen = 3 for i in range(0, 10, n): print(i)
Output:
0
3
6
9
Example 3: Decrementing the iterator by an integer value -n.
Python3
# decrement valuen = -3 for i in range(10, 0, n): print(i)
Output:
10
7
4
1
Example 4: Incrementing the iterator by exponential values of n. We will be using list comprehension.
Python3
# exponential valuen = 2 for i in ([n**x for x in range(5)]): print(i)
Output:
1
2
4
8
16
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 138,
"s": 28,
"text": "Let us see how to control the increment in for-loops in Python. We can do this by using the range() function."
},
{
"code": null,
"e": 428,
"s": 138,
"text": "range() allows the user to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end as well as how big the difference will be between one number and the next."
},
{
"code": null,
"e": 461,
"s": 428,
"text": "Syntax: range(start, stop, step)"
},
{
"code": null,
"e": 473,
"s": 461,
"text": "Parameters:"
},
{
"code": null,
"e": 551,
"s": 473,
"text": "start: integer starting from which the sequence of integers is to be returned"
},
{
"code": null,
"e": 621,
"s": 551,
"text": "stop: integer before which the sequence of integers is to be returned"
},
{
"code": null,
"e": 709,
"s": 621,
"text": "step: integer value which determines the increment between each integer in the sequence"
},
{
"code": null,
"e": 725,
"s": 709,
"text": "Returns: a list"
},
{
"code": null,
"e": 768,
"s": 725,
"text": "Example 1: Incrementing the iterator by 1."
},
{
"code": null,
"e": 776,
"s": 768,
"text": "Python3"
},
{
"code": "for i in range(5): print(i)",
"e": 805,
"s": 776,
"text": null
},
{
"code": null,
"e": 813,
"s": 805,
"text": "Output:"
},
{
"code": null,
"e": 824,
"s": 813,
"text": "0\n1\n2\n3\n4\n"
},
{
"code": null,
"e": 884,
"s": 824,
"text": "Example 2: Incrementing the iterator by an integer value n."
},
{
"code": null,
"e": 892,
"s": 884,
"text": "Python3"
},
{
"code": "# increment valuen = 3 for i in range(0, 10, n): print(i)",
"e": 952,
"s": 892,
"text": null
},
{
"code": null,
"e": 960,
"s": 952,
"text": "Output:"
},
{
"code": null,
"e": 969,
"s": 960,
"text": "0\n3\n6\n9\n"
},
{
"code": null,
"e": 1030,
"s": 969,
"text": "Example 3: Decrementing the iterator by an integer value -n."
},
{
"code": null,
"e": 1038,
"s": 1030,
"text": "Python3"
},
{
"code": "# decrement valuen = -3 for i in range(10, 0, n): print(i)",
"e": 1099,
"s": 1038,
"text": null
},
{
"code": null,
"e": 1107,
"s": 1099,
"text": "Output:"
},
{
"code": null,
"e": 1117,
"s": 1107,
"text": "10\n7\n4\n1\n"
},
{
"code": null,
"e": 1219,
"s": 1117,
"text": "Example 4: Incrementing the iterator by exponential values of n. We will be using list comprehension."
},
{
"code": null,
"e": 1227,
"s": 1219,
"text": "Python3"
},
{
"code": "# exponential valuen = 2 for i in ([n**x for x in range(5)]): print(i)",
"e": 1300,
"s": 1227,
"text": null
},
{
"code": null,
"e": 1308,
"s": 1300,
"text": "Output:"
},
{
"code": null,
"e": 1320,
"s": 1308,
"text": "1\n2\n4\n8\n16\n"
},
{
"code": null,
"e": 1334,
"s": 1320,
"text": "python-basics"
},
{
"code": null,
"e": 1341,
"s": 1334,
"text": "Python"
}
] |
turtle.shape() function in Python
|
20 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to set the turtle shape to shape with a given name or, if the name is not given, return the name of the current shape.
Syntax:
turtle.shape(name=None)
Shape with name must exist in the Turtle Screen’s shape dictionary. Initially, there are the following polygon shapes: “arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”. These images are shown below.
default : ‘classic’
‘arrow’
‘turtle’
‘circle’
‘square’
‘triangle’
Example:
Python3
# import packageimport turtle # for default shapeturtle.forward(100) # for circle shapeturtle.shape("circle")turtle.right(60)turtle.forward(100) # for triangle shapeturtle.shape("triangle")turtle.right(60)turtle.forward(100) # for square shapeturtle.shape("square")turtle.right(60)turtle.forward(100) # for arrow shapeturtle.shape("arrow")turtle.right(60)turtle.forward(100) # for turtle shapeturtle.shape("turtle")turtle.right(60)turtle.forward(100)
Output:
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Jul, 2020"
},
{
"code": null,
"e": 271,
"s": 54,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 412,
"s": 271,
"text": "This function is used to set the turtle shape to shape with a given name or, if the name is not given, return the name of the current shape."
},
{
"code": null,
"e": 420,
"s": 412,
"text": "Syntax:"
},
{
"code": null,
"e": 445,
"s": 420,
"text": "turtle.shape(name=None)\n"
},
{
"code": null,
"e": 657,
"s": 445,
"text": "Shape with name must exist in the Turtle Screen’s shape dictionary. Initially, there are the following polygon shapes: “arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”. These images are shown below."
},
{
"code": null,
"e": 677,
"s": 657,
"text": "default : ‘classic’"
},
{
"code": null,
"e": 685,
"s": 677,
"text": "‘arrow’"
},
{
"code": null,
"e": 694,
"s": 685,
"text": "‘turtle’"
},
{
"code": null,
"e": 703,
"s": 694,
"text": "‘circle’"
},
{
"code": null,
"e": 712,
"s": 703,
"text": "‘square’"
},
{
"code": null,
"e": 723,
"s": 712,
"text": "‘triangle’"
},
{
"code": null,
"e": 732,
"s": 723,
"text": "Example:"
},
{
"code": null,
"e": 740,
"s": 732,
"text": "Python3"
},
{
"code": "# import packageimport turtle # for default shapeturtle.forward(100) # for circle shapeturtle.shape(\"circle\")turtle.right(60)turtle.forward(100) # for triangle shapeturtle.shape(\"triangle\")turtle.right(60)turtle.forward(100) # for square shapeturtle.shape(\"square\")turtle.right(60)turtle.forward(100) # for arrow shapeturtle.shape(\"arrow\")turtle.right(60)turtle.forward(100) # for turtle shapeturtle.shape(\"turtle\")turtle.right(60)turtle.forward(100)",
"e": 1200,
"s": 740,
"text": null
},
{
"code": null,
"e": 1208,
"s": 1200,
"text": "Output:"
},
{
"code": null,
"e": 1222,
"s": 1208,
"text": "Python-turtle"
},
{
"code": null,
"e": 1229,
"s": 1222,
"text": "Python"
}
] |
DataTypes in MongoDB
|
09 Jun, 2022
In MongoDB, the documents are stores in BSON, which is the binary encoded format of JSON and using BSON we can make remote procedure calls in MongoDB. BSON data format supports various data-types. Below are the enlisted MongoDB data types:
1. String: This is the most commonly used data type in MongoDB to store data, BSON strings are of UTF-8. So, the drivers for each programming language convert from the string format of the language to UTF-8 while serializing and de-serializing BSON. The string must be a valid UTF-8.
Example: In the following example we are storing the name of the student in the student collection:
Here, the data type of the value of the name field is a string.
2. Integer: In MongoDB, the integer data type is used to store an integer value. We can store integer data type in two forms 32 -bit signed integer and 64 – bit signed integer.
Example: In the following example we are storing the age of the student in the student collection:
3. Double: The double data type is used to store the floating-point values.
Example: In the following example we are storing the marks of the student in the student collection:
4. Boolean: The boolean data type is used to store either true or false.
Example: In the following example we are storing the final result of the student as pass or fail in boolean values.
5. Null: The null data type is used to store the null value.
Example: In the following example, the student does not have a mobile number so the number field contains the value null.
6. Array: The Array is the set of values. It can store the same or different data types values in it. In MongoDB, the array is created using square brackets([]).
Example: In the following example, we are storing the technical skills of the student as an array.
7. Object: Object data type stores embedded documents. Embedded documents are also known as nested documents. Embedded document or nested documents are those types of documents which contain a document inside another document.
Example: In the following example, we are storing all the information about a book in an embedded document.
8. Object Id: Whenever we create a new document in the collection MongoDB automatically creates a unique object id for that document(if the document does not have it). There is an _id field in MongoDB for each document. The data which is stored in Id is of hexadecimal format and the length of the id is 12 bytes which consist:
4-bytes for Timestamp value.
5-bytes for Random values. i.e., 3-bytes for machine Id and 2-bytes for process Id.
3- bytes for Counter
You can also create your own id field, but make sure that the value of that id field must be unique.
Example: In the following example, when we insert a new document it creates a new unique object id for it.
9. Undefined: This data type stores the undefined values.
Example: In the following example the type of the duration of the project is undefined.
10. Binary Data: This datatype is used to store binary data.
Example: In the following example the value stored in the binaryValue field is of binary type.
11. Date: Date data type stores date. It is a 64-bit integer which represents the number of milliseconds. BSON data type generally supports UTC datetime and it is signed. If the value of the date data type is negative then it represents the dates before 1970. There are various methods to return date, it can be returned either as a string or as a date object. Some method for the date:
Date(): It returns the current date in string format.
new Date(): Returns a date object. Uses the ISODate() wrapper.
new ISODate(): It also returns a date object. Uses the ISODate() wrapper.
Example: In the following example we are using all the above method of the date:
12. Min & Max key: Min key compares the value of the lowest BSON element and Max key compares the value against the highest BSON element. Both are internal data types.
Example:
13. Symbol: This data type similar to the string data type. It is generally not supported by a mongo shell, but if the shell gets a symbol from the database, then it converts this type into a string type.
Example:
14. Regular Expression: This datatype is used to store regular expressions.
Example: In the following example we are storing the regular expression gfg:
15. JavaScript: This datatype is used to store JavaScript code into the document without the scope.
Example: In this example, we are using the JavaScript syntax in the shell:
16. JavaScript with Scope: This MongoDB data type store JavaScript data with a scope. This data type is deprecated in MongoDB 4.4.
Example: In this example, we are using the JavaScript syntax in the shell:
17. Timestamp: In MongoDB, this data type is used to store a timestamp. It is useful when we modify our data to keep a record and the value of this data type is 64-bit. The value of the timestamp data type is always unique.
Example:
18. Decimal: This MongoDB data type store 128-bit decimal-based floating-point value. This data type was introduced in MongoDB version 3.4
Example:
as5853535
khushb99
MongoDB
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 294,
"s": 54,
"text": "In MongoDB, the documents are stores in BSON, which is the binary encoded format of JSON and using BSON we can make remote procedure calls in MongoDB. BSON data format supports various data-types. Below are the enlisted MongoDB data types:"
},
{
"code": null,
"e": 579,
"s": 294,
"text": "1. String: This is the most commonly used data type in MongoDB to store data, BSON strings are of UTF-8. So, the drivers for each programming language convert from the string format of the language to UTF-8 while serializing and de-serializing BSON. The string must be a valid UTF-8. "
},
{
"code": null,
"e": 679,
"s": 579,
"text": "Example: In the following example we are storing the name of the student in the student collection:"
},
{
"code": null,
"e": 743,
"s": 679,
"text": "Here, the data type of the value of the name field is a string."
},
{
"code": null,
"e": 920,
"s": 743,
"text": "2. Integer: In MongoDB, the integer data type is used to store an integer value. We can store integer data type in two forms 32 -bit signed integer and 64 – bit signed integer."
},
{
"code": null,
"e": 1019,
"s": 920,
"text": "Example: In the following example we are storing the age of the student in the student collection:"
},
{
"code": null,
"e": 1096,
"s": 1019,
"text": "3. Double: The double data type is used to store the floating-point values. "
},
{
"code": null,
"e": 1197,
"s": 1096,
"text": "Example: In the following example we are storing the marks of the student in the student collection:"
},
{
"code": null,
"e": 1270,
"s": 1197,
"text": "4. Boolean: The boolean data type is used to store either true or false."
},
{
"code": null,
"e": 1386,
"s": 1270,
"text": "Example: In the following example we are storing the final result of the student as pass or fail in boolean values."
},
{
"code": null,
"e": 1447,
"s": 1386,
"text": "5. Null: The null data type is used to store the null value."
},
{
"code": null,
"e": 1570,
"s": 1447,
"text": "Example: In the following example, the student does not have a mobile number so the number field contains the value null."
},
{
"code": null,
"e": 1733,
"s": 1570,
"text": "6. Array: The Array is the set of values. It can store the same or different data types values in it. In MongoDB, the array is created using square brackets([]). "
},
{
"code": null,
"e": 1832,
"s": 1733,
"text": "Example: In the following example, we are storing the technical skills of the student as an array."
},
{
"code": null,
"e": 2059,
"s": 1832,
"text": "7. Object: Object data type stores embedded documents. Embedded documents are also known as nested documents. Embedded document or nested documents are those types of documents which contain a document inside another document."
},
{
"code": null,
"e": 2167,
"s": 2059,
"text": "Example: In the following example, we are storing all the information about a book in an embedded document."
},
{
"code": null,
"e": 2495,
"s": 2167,
"text": "8. Object Id: Whenever we create a new document in the collection MongoDB automatically creates a unique object id for that document(if the document does not have it). There is an _id field in MongoDB for each document. The data which is stored in Id is of hexadecimal format and the length of the id is 12 bytes which consist:"
},
{
"code": null,
"e": 2524,
"s": 2495,
"text": "4-bytes for Timestamp value."
},
{
"code": null,
"e": 2608,
"s": 2524,
"text": "5-bytes for Random values. i.e., 3-bytes for machine Id and 2-bytes for process Id."
},
{
"code": null,
"e": 2629,
"s": 2608,
"text": "3- bytes for Counter"
},
{
"code": null,
"e": 2730,
"s": 2629,
"text": "You can also create your own id field, but make sure that the value of that id field must be unique."
},
{
"code": null,
"e": 2837,
"s": 2730,
"text": "Example: In the following example, when we insert a new document it creates a new unique object id for it."
},
{
"code": null,
"e": 2895,
"s": 2837,
"text": "9. Undefined: This data type stores the undefined values."
},
{
"code": null,
"e": 2983,
"s": 2895,
"text": "Example: In the following example the type of the duration of the project is undefined."
},
{
"code": null,
"e": 3045,
"s": 2983,
"text": "10. Binary Data: This datatype is used to store binary data. "
},
{
"code": null,
"e": 3140,
"s": 3045,
"text": "Example: In the following example the value stored in the binaryValue field is of binary type."
},
{
"code": null,
"e": 3527,
"s": 3140,
"text": "11. Date: Date data type stores date. It is a 64-bit integer which represents the number of milliseconds. BSON data type generally supports UTC datetime and it is signed. If the value of the date data type is negative then it represents the dates before 1970. There are various methods to return date, it can be returned either as a string or as a date object. Some method for the date:"
},
{
"code": null,
"e": 3581,
"s": 3527,
"text": "Date(): It returns the current date in string format."
},
{
"code": null,
"e": 3645,
"s": 3581,
"text": "new Date(): Returns a date object. Uses the ISODate() wrapper. "
},
{
"code": null,
"e": 3719,
"s": 3645,
"text": "new ISODate(): It also returns a date object. Uses the ISODate() wrapper."
},
{
"code": null,
"e": 3800,
"s": 3719,
"text": "Example: In the following example we are using all the above method of the date:"
},
{
"code": null,
"e": 3968,
"s": 3800,
"text": "12. Min & Max key: Min key compares the value of the lowest BSON element and Max key compares the value against the highest BSON element. Both are internal data types."
},
{
"code": null,
"e": 3978,
"s": 3968,
"text": "Example: "
},
{
"code": null,
"e": 4183,
"s": 3978,
"text": "13. Symbol: This data type similar to the string data type. It is generally not supported by a mongo shell, but if the shell gets a symbol from the database, then it converts this type into a string type."
},
{
"code": null,
"e": 4193,
"s": 4183,
"text": "Example: "
},
{
"code": null,
"e": 4269,
"s": 4193,
"text": "14. Regular Expression: This datatype is used to store regular expressions."
},
{
"code": null,
"e": 4346,
"s": 4269,
"text": "Example: In the following example we are storing the regular expression gfg:"
},
{
"code": null,
"e": 4446,
"s": 4346,
"text": "15. JavaScript: This datatype is used to store JavaScript code into the document without the scope."
},
{
"code": null,
"e": 4521,
"s": 4446,
"text": "Example: In this example, we are using the JavaScript syntax in the shell:"
},
{
"code": null,
"e": 4652,
"s": 4521,
"text": "16. JavaScript with Scope: This MongoDB data type store JavaScript data with a scope. This data type is deprecated in MongoDB 4.4."
},
{
"code": null,
"e": 4727,
"s": 4652,
"text": "Example: In this example, we are using the JavaScript syntax in the shell:"
},
{
"code": null,
"e": 4951,
"s": 4727,
"text": "17. Timestamp: In MongoDB, this data type is used to store a timestamp. It is useful when we modify our data to keep a record and the value of this data type is 64-bit. The value of the timestamp data type is always unique."
},
{
"code": null,
"e": 4961,
"s": 4951,
"text": "Example: "
},
{
"code": null,
"e": 5100,
"s": 4961,
"text": "18. Decimal: This MongoDB data type store 128-bit decimal-based floating-point value. This data type was introduced in MongoDB version 3.4"
},
{
"code": null,
"e": 5110,
"s": 5100,
"text": "Example: "
},
{
"code": null,
"e": 5122,
"s": 5112,
"text": "as5853535"
},
{
"code": null,
"e": 5131,
"s": 5122,
"text": "khushb99"
},
{
"code": null,
"e": 5139,
"s": 5131,
"text": "MongoDB"
},
{
"code": null,
"e": 5146,
"s": 5139,
"text": "Picked"
},
{
"code": null,
"e": 5154,
"s": 5146,
"text": "MongoDB"
}
] |
How to create an empty PySpark DataFrame ?
|
11 Aug, 2021
In this article, we are going to see how to create an empty PySpark dataframe. Empty Pysaprk dataframe is a dataframe containing no data and may or may not specify the schema of the dataframe.
We’ll first create an empty RDD by specifying an empty schema.
emptyRDD() method creates an RDD without any data.
createDataFrame() method creates a pyspark dataframe with the specified data and schema of the dataframe.
Code:
Python3
# Import necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import * # Create a spark sessionspark = SparkSession.builder.appName('Empty_Dataframe').getOrCreate() # Create an empty RDDemp_RDD = spark.sparkContext.emptyRDD() # Create empty schemacolumns = StructType([]) # Create an empty RDD with empty schemadata = spark.createDataFrame(data = emp_RDD, schema = columns) # Print the dataframeprint('Dataframe :')data.show() # Print the schemaprint('Schema :')data.printSchema()
Output:
Dataframe :
++
||
++
++
Schema :
root
It is possible that we will not get a file for processing. However, we must still manually create a DataFrame with the appropriate schema.
Specify the schema of the dataframe as columns = [‘Name’, ‘Age’, ‘Gender’].
Create an empty RDD with an expecting schema.
Code:
Python3
# Import necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import * # Create a spark sessionspark = SparkSession.builder.appName('Empty_Dataframe').getOrCreate() # Create an empty RDDemp_RDD = spark.sparkContext.emptyRDD() # Create an expected schemacolumns = StructType([StructField('Name', StringType(), True), StructField('Age', StringType(), True), StructField('Gender', StringType(), True)]) # Create an empty RDD with expected schemadf = spark.createDataFrame(data = emp_RDD, schema = columns) # Print the dataframeprint('Dataframe :')df.show() # Print the schemaprint('Schema :')df.printSchema()
Output :
Dataframe :
+----+---+------+
|Name|Age|Gender|
+----+---+------+
+----+---+------+
Schema :
root
|-- Name: string (nullable = true)
|-- Age: string (nullable = true)
|-- Gender: string (nullable = true)
Create an empty schema as columns.
Specify data as empty([]) and schema as columns in CreateDataFrame() method.
Code:
Python3
# Import necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import * # Create a spark sessionspark = SparkSession.builder.appName('Empty_Dataframe').getOrCreate() # Create an empty schemacolumns = StructType([]) # Create an empty dataframe with empty schemadf = spark.createDataFrame(data = [], schema = columns) # Print the dataframeprint('Dataframe :')df.show() # Print the schemaprint('Schema :')df.printSchema()
Output:
Dataframe :
++
||
++
++
Schema :
root
Specify the schema of the dataframe as columns = [‘Name’, ‘Age’, ‘Gender’].
Specify data as empty([]) and schema as columns in CreateDataFrame() method.
Code:
Python3
# Import necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import * # Create a spark sessionspark = SparkSession.builder.appName('Empty_Dataframe').getOrCreate() # Create an expected schemacolumns = StructType([StructField('Name', StringType(), True), StructField('Age', StringType(), True), StructField('Gender', StringType(), True)]) # Create a dataframe with expected schemadf = spark.createDataFrame(data = [], schema = columns) # Print the dataframeprint('Dataframe :')df.show() # Print the schemaprint('Schema :')df.printSchema()
Output :
Dataframe :
+----+---+------+
|Name|Age|Gender|
+----+---+------+
+----+---+------+
Schema :
root
|-- Name: string (nullable = true)
|-- Age: string (nullable = true)
|-- Gender: string (nullable = true)
surindertarika1234
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 221,
"s": 28,
"text": "In this article, we are going to see how to create an empty PySpark dataframe. Empty Pysaprk dataframe is a dataframe containing no data and may or may not specify the schema of the dataframe."
},
{
"code": null,
"e": 284,
"s": 221,
"text": "We’ll first create an empty RDD by specifying an empty schema."
},
{
"code": null,
"e": 335,
"s": 284,
"text": "emptyRDD() method creates an RDD without any data."
},
{
"code": null,
"e": 441,
"s": 335,
"text": "createDataFrame() method creates a pyspark dataframe with the specified data and schema of the dataframe."
},
{
"code": null,
"e": 447,
"s": 441,
"text": "Code:"
},
{
"code": null,
"e": 455,
"s": 447,
"text": "Python3"
},
{
"code": "# Import necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import * # Create a spark sessionspark = SparkSession.builder.appName('Empty_Dataframe').getOrCreate() # Create an empty RDDemp_RDD = spark.sparkContext.emptyRDD() # Create empty schemacolumns = StructType([]) # Create an empty RDD with empty schemadata = spark.createDataFrame(data = emp_RDD, schema = columns) # Print the dataframeprint('Dataframe :')data.show() # Print the schemaprint('Schema :')data.printSchema()",
"e": 989,
"s": 455,
"text": null
},
{
"code": null,
"e": 998,
"s": 989,
"text": "Output: "
},
{
"code": null,
"e": 1037,
"s": 998,
"text": "Dataframe :\n++\n||\n++\n++\n\nSchema :\nroot"
},
{
"code": null,
"e": 1176,
"s": 1037,
"text": "It is possible that we will not get a file for processing. However, we must still manually create a DataFrame with the appropriate schema."
},
{
"code": null,
"e": 1252,
"s": 1176,
"text": "Specify the schema of the dataframe as columns = [‘Name’, ‘Age’, ‘Gender’]."
},
{
"code": null,
"e": 1298,
"s": 1252,
"text": "Create an empty RDD with an expecting schema."
},
{
"code": null,
"e": 1304,
"s": 1298,
"text": "Code:"
},
{
"code": null,
"e": 1312,
"s": 1304,
"text": "Python3"
},
{
"code": "# Import necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import * # Create a spark sessionspark = SparkSession.builder.appName('Empty_Dataframe').getOrCreate() # Create an empty RDDemp_RDD = spark.sparkContext.emptyRDD() # Create an expected schemacolumns = StructType([StructField('Name', StringType(), True), StructField('Age', StringType(), True), StructField('Gender', StringType(), True)]) # Create an empty RDD with expected schemadf = spark.createDataFrame(data = emp_RDD, schema = columns) # Print the dataframeprint('Dataframe :')df.show() # Print the schemaprint('Schema :')df.printSchema()",
"e": 2102,
"s": 1312,
"text": null
},
{
"code": null,
"e": 2111,
"s": 2102,
"text": "Output :"
},
{
"code": null,
"e": 2319,
"s": 2111,
"text": "Dataframe :\n+----+---+------+\n|Name|Age|Gender|\n+----+---+------+\n+----+---+------+\n\nSchema :\nroot\n |-- Name: string (nullable = true)\n |-- Age: string (nullable = true)\n |-- Gender: string (nullable = true)"
},
{
"code": null,
"e": 2354,
"s": 2319,
"text": "Create an empty schema as columns."
},
{
"code": null,
"e": 2431,
"s": 2354,
"text": "Specify data as empty([]) and schema as columns in CreateDataFrame() method."
},
{
"code": null,
"e": 2437,
"s": 2431,
"text": "Code:"
},
{
"code": null,
"e": 2445,
"s": 2437,
"text": "Python3"
},
{
"code": "# Import necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import * # Create a spark sessionspark = SparkSession.builder.appName('Empty_Dataframe').getOrCreate() # Create an empty schemacolumns = StructType([]) # Create an empty dataframe with empty schemadf = spark.createDataFrame(data = [], schema = columns) # Print the dataframeprint('Dataframe :')df.show() # Print the schemaprint('Schema :')df.printSchema()",
"e": 2914,
"s": 2445,
"text": null
},
{
"code": null,
"e": 2922,
"s": 2914,
"text": "Output:"
},
{
"code": null,
"e": 2961,
"s": 2922,
"text": "Dataframe :\n++\n||\n++\n++\n\nSchema :\nroot"
},
{
"code": null,
"e": 3037,
"s": 2961,
"text": "Specify the schema of the dataframe as columns = [‘Name’, ‘Age’, ‘Gender’]."
},
{
"code": null,
"e": 3114,
"s": 3037,
"text": "Specify data as empty([]) and schema as columns in CreateDataFrame() method."
},
{
"code": null,
"e": 3120,
"s": 3114,
"text": "Code:"
},
{
"code": null,
"e": 3128,
"s": 3120,
"text": "Python3"
},
{
"code": "# Import necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import * # Create a spark sessionspark = SparkSession.builder.appName('Empty_Dataframe').getOrCreate() # Create an expected schemacolumns = StructType([StructField('Name', StringType(), True), StructField('Age', StringType(), True), StructField('Gender', StringType(), True)]) # Create a dataframe with expected schemadf = spark.createDataFrame(data = [], schema = columns) # Print the dataframeprint('Dataframe :')df.show() # Print the schemaprint('Schema :')df.printSchema()",
"e": 3851,
"s": 3128,
"text": null
},
{
"code": null,
"e": 3860,
"s": 3851,
"text": "Output :"
},
{
"code": null,
"e": 4068,
"s": 3860,
"text": "Dataframe :\n+----+---+------+\n|Name|Age|Gender|\n+----+---+------+\n+----+---+------+\n\nSchema :\nroot\n |-- Name: string (nullable = true)\n |-- Age: string (nullable = true)\n |-- Gender: string (nullable = true)"
},
{
"code": null,
"e": 4087,
"s": 4068,
"text": "surindertarika1234"
},
{
"code": null,
"e": 4094,
"s": 4087,
"text": "Picked"
},
{
"code": null,
"e": 4109,
"s": 4094,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 4116,
"s": 4109,
"text": "Python"
}
] |
How to get file input by selected file name without path using jQuery ? - GeeksforGeeks
|
18 Aug, 2021
The task is to get the file input by selected filename without the path using jQuery. To select the file we will use HTML <input type=”file”>. After that we will get the file name by using the jQuery change() method. This method is used in the JQuery to get the file input by selected file name. And the HTML <input type=”file”> is used to specify the file select field and add a button to choose a file for upload to the form.Syntax:
jQuery change() method:
$(selector).change(function)
HTML <input type=”file”>:
<input type="file">
Below examples illustrates the approach:Example 1: In this example we will display the file name with the extension by using the change() method and the file will be selected by the HTML <input type=”file”>.
html
<!DOCTYPE html><html> <head> <title> How to get the file input by selected file name without the path using jQuery? </title> <style> h1 { color: green; } body { text-align: center; } h4 { color: purple; } </style> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script></head> <body> <h1> GeeksforGeeks </h1> <h3> How to get the file input by selected<br> file name without the path using jQuery? </h3> <input type="file" id="geeks"> <h4><!-- Selected file will get here --></h4> <script> $(document).ready(function() { $('input[type="file"]').change(function(e) { var geekss = e.target.files[0].name; $("h4").text(geekss + ' is the selected file.'); }); }); </script></body> </html>
Output:
Example 2: In this example we will display the filename with the extension through an alert, by using the change() method and the file will be selected by the HTML <input type=”file”>.
html
<!DOCTYPE html><html> <head> <title> How to get the file input by selected file name without the path using jQuery? </title> <style> h1 { color: green; } body { text-align: center; } h4 { color: purple; } </style> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script></head> <body> <h1> GeeksforGeeks </h1> <h3> How to get the file input by selected<br> file name without the path using jQuery? </h3> <input type="file" id="geeks"> <h4><!-- Selected file will get here --></h4> <script> $(document).ready(function(){ $('input[type="file"]').change(function(e){ var geekss = e.target.files[0].name; alert(geekss + ' is the selected file .'); }); }); </script></body> </html>
Output:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
kapoorsagar226
CSS-Misc
HTML-Misc
jQuery-Misc
Picked
CSS
HTML
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
How to set space between the flexbox ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 25954,
"s": 25926,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 26391,
"s": 25954,
"text": "The task is to get the file input by selected filename without the path using jQuery. To select the file we will use HTML <input type=”file”>. After that we will get the file name by using the jQuery change() method. This method is used in the JQuery to get the file input by selected file name. And the HTML <input type=”file”> is used to specify the file select field and add a button to choose a file for upload to the form.Syntax: "
},
{
"code": null,
"e": 26417,
"s": 26391,
"text": "jQuery change() method: "
},
{
"code": null,
"e": 26446,
"s": 26417,
"text": "$(selector).change(function)"
},
{
"code": null,
"e": 26474,
"s": 26446,
"text": "HTML <input type=”file”>: "
},
{
"code": null,
"e": 26495,
"s": 26474,
"text": "<input type=\"file\"> "
},
{
"code": null,
"e": 26705,
"s": 26495,
"text": "Below examples illustrates the approach:Example 1: In this example we will display the file name with the extension by using the change() method and the file will be selected by the HTML <input type=”file”>. "
},
{
"code": null,
"e": 26710,
"s": 26705,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to get the file input by selected file name without the path using jQuery? </title> <style> h1 { color: green; } body { text-align: center; } h4 { color: purple; } </style> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script></head> <body> <h1> GeeksforGeeks </h1> <h3> How to get the file input by selected<br> file name without the path using jQuery? </h3> <input type=\"file\" id=\"geeks\"> <h4><!-- Selected file will get here --></h4> <script> $(document).ready(function() { $('input[type=\"file\"]').change(function(e) { var geekss = e.target.files[0].name; $(\"h4\").text(geekss + ' is the selected file.'); }); }); </script></body> </html> ",
"e": 27656,
"s": 26710,
"text": null
},
{
"code": null,
"e": 27666,
"s": 27656,
"text": "Output: "
},
{
"code": null,
"e": 27853,
"s": 27666,
"text": "Example 2: In this example we will display the filename with the extension through an alert, by using the change() method and the file will be selected by the HTML <input type=”file”>. "
},
{
"code": null,
"e": 27858,
"s": 27853,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to get the file input by selected file name without the path using jQuery? </title> <style> h1 { color: green; } body { text-align: center; } h4 { color: purple; } </style> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script></head> <body> <h1> GeeksforGeeks </h1> <h3> How to get the file input by selected<br> file name without the path using jQuery? </h3> <input type=\"file\" id=\"geeks\"> <h4><!-- Selected file will get here --></h4> <script> $(document).ready(function(){ $('input[type=\"file\"]').change(function(e){ var geekss = e.target.files[0].name; alert(geekss + ' is the selected file .'); }); }); </script></body> </html> ",
"e": 28795,
"s": 27858,
"text": null
},
{
"code": null,
"e": 28805,
"s": 28795,
"text": "Output: "
},
{
"code": null,
"e": 29076,
"s": 28807,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 29215,
"s": 29078,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 29230,
"s": 29215,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 29239,
"s": 29230,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29249,
"s": 29239,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29261,
"s": 29249,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 29268,
"s": 29261,
"text": "Picked"
},
{
"code": null,
"e": 29272,
"s": 29268,
"text": "CSS"
},
{
"code": null,
"e": 29277,
"s": 29272,
"text": "HTML"
},
{
"code": null,
"e": 29284,
"s": 29277,
"text": "JQuery"
},
{
"code": null,
"e": 29301,
"s": 29284,
"text": "Web Technologies"
},
{
"code": null,
"e": 29328,
"s": 29301,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29333,
"s": 29328,
"text": "HTML"
},
{
"code": null,
"e": 29431,
"s": 29333,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29486,
"s": 29431,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 29523,
"s": 29486,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 29587,
"s": 29523,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 29624,
"s": 29587,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29663,
"s": 29624,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29723,
"s": 29663,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29776,
"s": 29723,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 29837,
"s": 29776,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 29861,
"s": 29837,
"text": "REST API (Introduction)"
}
] |
Lowest Common Ancestor in a Binary Tree | Practice | GeeksforGeeks
|
Given a Binary Tree with all unique values and two nodes value, n1 and n2. The task is to find the lowest common ancestor of the given two nodes. We may assume that either both n1 and n2 are present in the tree or none of them are present.
Example 1:
Input:
n1 = 2 , n2 = 3
1
/ \
2 3
Output: 1
Explanation:
LCA of 2 and 3 is 1.
Example 2:
Input:
n1 = 3 , n2 = 4
5
/
2
/ \
3 4
Output: 2
Explanation:
LCA of 3 and 4 is 2.
Your Task:
You don't have to read, input, or print anything. Your task is to complete the function lca() that takes nodes, n1, and n2 as parameters and returns the LCA node as output.
Expected Time Complexity:O(N).
Expected Auxiliary Space:O(Height of Tree).
Constraints:
1 ≤ Number of nodes ≤ 105
1 ≤ Data of a node ≤ 105
+204
rainx7 months ago
LUCID EXPLAINATION
The question is simply asking to find the subtree's root which will contain both n1 and n2, right?! So we do the same,
Well, if there is no root, you gotta return null/root. if(root==nullptr) { return root; } if your root data contains either n1 or n2, you return that root. WHY?? because it will be used in calculation of two different answer A.K.A. left and right side of tree.Now save your Left answer of the left side of tree in a variable, this variable with either have a null or a valid node depending on recursive calls if it finds the required node, Do the same for the Right side make a variable and save the answer.Now, we have two different variables namely left and right. Both contains answer either null or a valid node, now we check three conditionsIf Left answer is not null and right answer is also not null, then the answer is the root itself, since left and right are subtrees of the root and if both are not null it clearly means the values n1 and n2 lies in right as well as left side, For example, Example test case 1 is the perfect example for this caseIf left answer is not null but right answer is null, then it means both n1 and n2 lies on the left side of tree inside the subtree with root as left answer, return left answer. For example, Example test case 2 is the perfect example for this case If right answer is not null but left answer is null, then it means both n1 and n2 lies on the right side of tree inside the subtree with root as right answer, return right answer.
Well, if there is no root, you gotta return null/root. if(root==nullptr) { return root; }
if your root data contains either n1 or n2, you return that root. WHY?? because it will be used in calculation of two different answer A.K.A. left and right side of tree.
Now save your Left answer of the left side of tree in a variable, this variable with either have a null or a valid node depending on recursive calls if it finds the required node, Do the same for the Right side make a variable and save the answer.
Now, we have two different variables namely left and right. Both contains answer either null or a valid node, now we check three conditions
If Left answer is not null and right answer is also not null, then the answer is the root itself, since left and right are subtrees of the root and if both are not null it clearly means the values n1 and n2 lies in right as well as left side, For example, Example test case 1 is the perfect example for this case
If left answer is not null but right answer is null, then it means both n1 and n2 lies on the left side of tree inside the subtree with root as left answer, return left answer. For example, Example test case 2 is the perfect example for this case
If right answer is not null but left answer is null, then it means both n1 and n2 lies on the right side of tree inside the subtree with root as right answer, return right answer.
**SPOLIER ALERT CODE AHEAD**
**SPOLIER ALERT CODE AHEAD**
**SPOLIER ALERT CODE AHEAD**
**SPOLIER ALERT CODE AHEAD**
**SPOLIER ALERT CODE AHEAD**
**SPOLIER ALERT CODE AHEAD**
**SPOLIER ALERT CODE AHEAD**
**SPOLIER ALERT CODE AHEAD**
**SPOLIER ALERT CODE AHEAD**
CODE IMPLEMENTATION
Node* lca(Node* root ,int n1 ,int n2 ) {
if(root==nullptr){
return root;
}
if(root->data==n1 || root->data==n2){
return root;
}
Node* LEFTSIDE =lca(root->left,n1,n2);
Node* RIGHTSIDE =lca(root->right,n1,n2);
if(LEFTSIDE!=nullptr && RIGHTSIDE!=nullptr){
return root;
}
else if(LEFTSIDE!=nullptr){
return LEFTSIDE;
}
else{
return RIGHTSIDE;
}
}
Relevant Right? 🤣🤣🤣🤣🤣🤣
THANKS FOR READING AND DO CARE TO UPVOTE.....😴😴😴
edit: thanks for the crazy amount of upvotes,, appreciate it
0
sharmarahul996111 week ago
if(root==NULL) return NULL; if(root->data==n1 || root->data ==n2){ return root; } Node*l = lca(root->left , n1 ,n2); Node*r= lca(root->right , n1 ,n2); if(l!=NULL && r!=NULL){ return root; } if(l!=NULL)return l; if(r!=NULL) return r;
0
harendersingh78962 weeks ago
class Solution
{
//Function to return the lowest common ancestor in a Binary Tree.
Node lca(Node root, int n1,int n2)
{
// Your code here
if(root == null || root.data == n1 || root.data == n2)
{
return root;
}
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)
{
return right;
}
else if(right == null)
{
return left;
}
else
{
return root;
}
}
}ja
0
saisaran22 weeks ago
finding the path to reach both nodes and finding common division point of both path
class Solution{ public: bool hasPath(Node *root, vector<Node*>& arr, int x){ if (!root) { return false; } arr.push_back(root); if (root->data == x) { return true; } if (hasPath(root->left, arr, x) || hasPath(root->right, arr, x)) return true; arr.pop_back(); return false; } Node* lca(Node* root ,int n1 ,int n2 ) { vector<Node*>v1; vector<Node*>v2; hasPath(root,v1,n1); hasPath(root,v2,n2); int n=min(v1.size(),v2.size()); Node* c=root;
for(int i=0;i<n;i++) { if(v1[i]->data!=v2[i]->data) { c=v1[i-1]; break; } } if(v1[n-1]->data==v2[n-1]->data) { return v1[n-1]; } return c; }};
0
tarunkanade2 weeks ago
0.69/2.06 Java O(n) O(h) with comments
Node lca(Node root, int n1,int n2)
{
// Your code here
if(root == null){
return null;
}
// if current node matches with the given values then this is the ancestor
if(root.data == n1 || root.data == n2){
return root;
}
// check the same in left and right
Node left = lca(root.left, n1, n2);
Node right = lca(root.right, n1, n2);
// if both left and right have some values that means in both subtrees
// we found one one value and that means the current node is the immediate
// ancestor of those nodes (you have to think recursively), we processed
// subtrees so after returning from the above two calls we are at upper level
if(left != null && right != null){
return root;
}
// if left is not null that means this is the ancestor of either both (when
// right will return null) or itself (right will return something)
else if(left != null){
return left;
}
// otherwise return right, it may be null or may not be, but due to recursive
// chanining we will return correct ans (again you have to think recursively)
else{
return right;
}
}
0
shubham211019972 weeks ago
class Solution
{
boolean path(Node root,int n,ArrayList<Node>arr){
if(root==null)return false;
arr.add(root);
if(root.data==n)return true;
if(path(root.left,n,arr)==true ||path(root.right,n,arr)==true)
return true;
arr.remove(arr.size()-1);
return false;
}
Node lca(Node root, int n1,int n2)
{
ArrayList<Node>arr1=new ArrayList<>();
ArrayList<Node>arr2=new ArrayList<>();
boolean p1=path(root,n1,arr1);
boolean p2=path(root,n2,arr2);
if(p1==false ||p2==false)return null;
int i;
for( i=0;i<arr1.size()&& i<arr2.size();i++){
if(arr1.get(i).data!=arr2.get(i).data) break;
}
return arr1.get(i-1);
}
}
0
ashi11100001112 weeks ago
Node* lca(Node* root ,int n1 ,int n2 ) { //Your code here if(root==NULL) return 0; 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) return right; if(right==NULL) return left; return root; }
0
2018uee01551 month ago
Python the most Naive Solution
class Solution:
#Function to return the lowest common ancestor in a Binary Tree.
def lca(self,root, n1, n2):
# Code here
if(root==None):
return root
if(root.data==n1 or root.data==n2):
return root
left=self.lca(root.left,n1,n2)
right=self.lca(root.right,n1,n2)
if(left!=None and right!=None):
return root
elif(left!=None):
return left
else:
return right
0
rohanmeher1641 month ago
// simple java solution
class Solution{ //Function to return the lowest common ancestor in a Binary Tree.Node lca(Node root, int n1,int n2){ if(root== null) return null; if(root.data==n1 || root.data==n2) return root; Node l=lca(root.left,n1,n2); Node r=lca(root.right,n1,n2); if(l!=null && r!=null) return root; else if(l!=null) return l; else return r;}}
-1
agrimjain24111 month ago
Efficient C++ Code using pair (Only 1 traversal and O(1) space)
class Solution
{
public:
//Function to return the lowest common ancestor in a Binary Tree.
Node* LCA = new Node(-1);
Node* lca(Node* root ,int n1 ,int n2 )
{
//Your code here
findLCA(n1,n2,root);
return LCA;
}
pair<int,int> findLCA(int x,int y, Node*root)
{
if(root==NULL)
return {0,0};
// p.first tells if x(n1) exist in subtree
// p.second tells if y(n2) exist in subtree
pair<int,int>l = findLCA(x,y,root->left);
pair<int,int>r = findLCA(x,y,root->right);
if((LCA->data ==-1) && ((root->data == x && (l.second+r.second>=1))
||(root->data == y && (l.first+r.first>=1))
||(l.first + r.second == 2)
||(r.first + l.second ==2)))
{
LCA = root;
return {1,1};
}
pair<int,int>p = {0,0};
if(root->data==x ||((l.first + r.first >= 1)))
p.first = 1;
if(root->data==y ||((l.second + r.second >= 1)))
p.second = 1;
return p;
}
};
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": 479,
"s": 238,
"text": "Given a Binary Tree with all unique values and two nodes value, n1 and n2. The task is to find the lowest common ancestor of the given two nodes. We may assume that either both n1 and n2 are present in the tree or none of them are present. "
},
{
"code": null,
"e": 490,
"s": 479,
"text": "Example 1:"
},
{
"code": null,
"e": 591,
"s": 490,
"text": "Input:\nn1 = 2 , n2 = 3 \n 1 \n / \\ \n 2 3\nOutput: 1\nExplanation:\nLCA of 2 and 3 is 1."
},
{
"code": null,
"e": 602,
"s": 591,
"text": "Example 2:"
},
{
"code": null,
"e": 743,
"s": 602,
"text": "Input:\nn1 = 3 , n2 = 4\n 5 \n / \n 2 \n / \\ \n 3 4\nOutput: 2\nExplanation:\nLCA of 3 and 4 is 2. "
},
{
"code": null,
"e": 928,
"s": 743,
"text": "Your Task:\nYou don't have to read, input, or print anything. Your task is to complete the function lca() that takes nodes, n1, and n2 as parameters and returns the LCA node as output. "
},
{
"code": null,
"e": 1003,
"s": 928,
"text": "Expected Time Complexity:O(N).\nExpected Auxiliary Space:O(Height of Tree)."
},
{
"code": null,
"e": 1067,
"s": 1003,
"text": "Constraints:\n1 ≤ Number of nodes ≤ 105\n1 ≤ Data of a node ≤ 105"
},
{
"code": null,
"e": 1072,
"s": 1067,
"text": "+204"
},
{
"code": null,
"e": 1090,
"s": 1072,
"text": "rainx7 months ago"
},
{
"code": null,
"e": 1109,
"s": 1090,
"text": "LUCID EXPLAINATION"
},
{
"code": null,
"e": 1228,
"s": 1109,
"text": "The question is simply asking to find the subtree's root which will contain both n1 and n2, right?! So we do the same,"
},
{
"code": null,
"e": 2616,
"s": 1230,
"text": "Well, if there is no root, you gotta return null/root. if(root==nullptr) { return root; } if your root data contains either n1 or n2, you return that root. WHY?? because it will be used in calculation of two different answer A.K.A. left and right side of tree.Now save your Left answer of the left side of tree in a variable, this variable with either have a null or a valid node depending on recursive calls if it finds the required node, Do the same for the Right side make a variable and save the answer.Now, we have two different variables namely left and right. Both contains answer either null or a valid node, now we check three conditionsIf Left answer is not null and right answer is also not null, then the answer is the root itself, since left and right are subtrees of the root and if both are not null it clearly means the values n1 and n2 lies in right as well as left side, For example, Example test case 1 is the perfect example for this caseIf left answer is not null but right answer is null, then it means both n1 and n2 lies on the left side of tree inside the subtree with root as left answer, return left answer. For example, Example test case 2 is the perfect example for this case If right answer is not null but left answer is null, then it means both n1 and n2 lies on the right side of tree inside the subtree with root as right answer, return right answer."
},
{
"code": null,
"e": 2708,
"s": 2616,
"text": "Well, if there is no root, you gotta return null/root. if(root==nullptr) { return root; } "
},
{
"code": null,
"e": 2879,
"s": 2708,
"text": "if your root data contains either n1 or n2, you return that root. WHY?? because it will be used in calculation of two different answer A.K.A. left and right side of tree."
},
{
"code": null,
"e": 3127,
"s": 2879,
"text": "Now save your Left answer of the left side of tree in a variable, this variable with either have a null or a valid node depending on recursive calls if it finds the required node, Do the same for the Right side make a variable and save the answer."
},
{
"code": null,
"e": 3267,
"s": 3127,
"text": "Now, we have two different variables namely left and right. Both contains answer either null or a valid node, now we check three conditions"
},
{
"code": null,
"e": 3580,
"s": 3267,
"text": "If Left answer is not null and right answer is also not null, then the answer is the root itself, since left and right are subtrees of the root and if both are not null it clearly means the values n1 and n2 lies in right as well as left side, For example, Example test case 1 is the perfect example for this case"
},
{
"code": null,
"e": 3827,
"s": 3580,
"text": "If left answer is not null but right answer is null, then it means both n1 and n2 lies on the left side of tree inside the subtree with root as left answer, return left answer. For example, Example test case 2 is the perfect example for this case"
},
{
"code": null,
"e": 4008,
"s": 3827,
"text": " If right answer is not null but left answer is null, then it means both n1 and n2 lies on the right side of tree inside the subtree with root as right answer, return right answer."
},
{
"code": null,
"e": 4058,
"s": 4008,
"text": " **SPOLIER ALERT CODE AHEAD**"
},
{
"code": null,
"e": 4108,
"s": 4058,
"text": " **SPOLIER ALERT CODE AHEAD**"
},
{
"code": null,
"e": 4158,
"s": 4108,
"text": " **SPOLIER ALERT CODE AHEAD**"
},
{
"code": null,
"e": 4208,
"s": 4158,
"text": " **SPOLIER ALERT CODE AHEAD**"
},
{
"code": null,
"e": 4258,
"s": 4208,
"text": " **SPOLIER ALERT CODE AHEAD**"
},
{
"code": null,
"e": 4308,
"s": 4258,
"text": " **SPOLIER ALERT CODE AHEAD**"
},
{
"code": null,
"e": 4358,
"s": 4308,
"text": " **SPOLIER ALERT CODE AHEAD**"
},
{
"code": null,
"e": 4408,
"s": 4358,
"text": " **SPOLIER ALERT CODE AHEAD**"
},
{
"code": null,
"e": 4458,
"s": 4408,
"text": " **SPOLIER ALERT CODE AHEAD**"
},
{
"code": null,
"e": 4484,
"s": 4464,
"text": "CODE IMPLEMENTATION"
},
{
"code": null,
"e": 5042,
"s": 4486,
"text": "Node* lca(Node* root ,int n1 ,int n2 ) {\n\n if(root==nullptr){\n return root;\n }\n \n if(root->data==n1 || root->data==n2){\n return root;\n }\n \n Node* LEFTSIDE =lca(root->left,n1,n2);\n Node* RIGHTSIDE =lca(root->right,n1,n2);\n \n if(LEFTSIDE!=nullptr && RIGHTSIDE!=nullptr){\n return root;\n } \n \n else if(LEFTSIDE!=nullptr){\n return LEFTSIDE;\n }\n \n else{\n return RIGHTSIDE;\n }\n \n}"
},
{
"code": null,
"e": 5067,
"s": 5044,
"text": "Relevant Right? 🤣🤣🤣🤣🤣🤣"
},
{
"code": null,
"e": 5120,
"s": 5071,
"text": "THANKS FOR READING AND DO CARE TO UPVOTE.....😴😴😴"
},
{
"code": null,
"e": 5183,
"s": 5122,
"text": "edit: thanks for the crazy amount of upvotes,, appreciate it"
},
{
"code": null,
"e": 5185,
"s": 5183,
"text": "0"
},
{
"code": null,
"e": 5212,
"s": 5185,
"text": "sharmarahul996111 week ago"
},
{
"code": null,
"e": 5514,
"s": 5212,
"text": " if(root==NULL) return NULL; if(root->data==n1 || root->data ==n2){ return root; } Node*l = lca(root->left , n1 ,n2); Node*r= lca(root->right , n1 ,n2); if(l!=NULL && r!=NULL){ return root; } if(l!=NULL)return l; if(r!=NULL) return r;"
},
{
"code": null,
"e": 5516,
"s": 5514,
"text": "0"
},
{
"code": null,
"e": 5545,
"s": 5516,
"text": "harendersingh78962 weeks ago"
},
{
"code": null,
"e": 6073,
"s": 5545,
"text": "class Solution\n{\n //Function to return the lowest common ancestor in a Binary Tree.\n\tNode lca(Node root, int n1,int n2)\n\t{\n\t\t// Your code here\n\t\tif(root == null || root.data == n1 || root.data == n2)\n\t\t{\n\t\t return root;\n\t\t}\n\t\t\n\t\tif(root.data == n1 || root.data == n2)\n\t\t{\n\t\t return root;\n\t\t}\n\t\t\n\t\tNode left = lca(root.left, n1, n2);\n\t\tNode right = lca(root.right, n1, n2);\n\t\t\n\t\tif(left == null)\n\t\t{\n\t\t return right;\n\t\t}\n\t\telse if(right == null)\n\t\t{\n\t\t return left;\n\t\t}\n\t\telse\n\t\t{\n\t\t return root;\n\t\t}\n\t\t\n\t}\n}ja"
},
{
"code": null,
"e": 6075,
"s": 6073,
"text": "0"
},
{
"code": null,
"e": 6096,
"s": 6075,
"text": "saisaran22 weeks ago"
},
{
"code": null,
"e": 6180,
"s": 6096,
"text": "finding the path to reach both nodes and finding common division point of both path"
},
{
"code": null,
"e": 6719,
"s": 6180,
"text": "class Solution{ public: bool hasPath(Node *root, vector<Node*>& arr, int x){ if (!root) { return false; } arr.push_back(root); if (root->data == x) { return true; } if (hasPath(root->left, arr, x) || hasPath(root->right, arr, x)) return true; arr.pop_back(); return false; } Node* lca(Node* root ,int n1 ,int n2 ) { vector<Node*>v1; vector<Node*>v2; hasPath(root,v1,n1); hasPath(root,v2,n2); int n=min(v1.size(),v2.size()); Node* c=root;"
},
{
"code": null,
"e": 6986,
"s": 6719,
"text": " for(int i=0;i<n;i++) { if(v1[i]->data!=v2[i]->data) { c=v1[i-1]; break; } } if(v1[n-1]->data==v2[n-1]->data) { return v1[n-1]; } return c; }};"
},
{
"code": null,
"e": 6988,
"s": 6986,
"text": "0"
},
{
"code": null,
"e": 7011,
"s": 6988,
"text": "tarunkanade2 weeks ago"
},
{
"code": null,
"e": 7050,
"s": 7011,
"text": "0.69/2.06 Java O(n) O(h) with comments"
},
{
"code": null,
"e": 8179,
"s": 7050,
"text": "Node lca(Node root, int n1,int n2)\n\t{\n\t\t// Your code here\n\t\tif(root == null){\n\t\t return null;\n\t\t}\n\t\t\n\t\t// if current node matches with the given values then this is the ancestor\n\t\tif(root.data == n1 || root.data == n2){\n\t\t return root;\n\t\t}\n\t\t\n\t\t// check the same in left and right\n\t\tNode left = lca(root.left, n1, n2);\n\t\tNode right = lca(root.right, n1, n2);\n\t\t\n\t\t// if both left and right have some values that means in both subtrees\n\t\t// we found one one value and that means the current node is the immediate\n\t\t// ancestor of those nodes (you have to think recursively), we processed\n\t\t// subtrees so after returning from the above two calls we are at upper level\n\t\tif(left != null && right != null){\n\t\t return root;\n\t\t}\n\t\t\n\t\t// if left is not null that means this is the ancestor of either both (when\n\t\t// right will return null) or itself (right will return something)\n\t\telse if(left != null){\n\t\t return left;\n\t\t}\n\t\t\n\t\t// otherwise return right, it may be null or may not be, but due to recursive\n\t\t// chanining we will return correct ans (again you have to think recursively)\n\t\telse{\n\t\t return right;\n\t\t}\n\t}"
},
{
"code": null,
"e": 8181,
"s": 8179,
"text": "0"
},
{
"code": null,
"e": 8208,
"s": 8181,
"text": "shubham211019972 weeks ago"
},
{
"code": null,
"e": 8878,
"s": 8208,
"text": "class Solution\n{\n boolean path(Node root,int n,ArrayList<Node>arr){\n if(root==null)return false;\n arr.add(root);\n if(root.data==n)return true;\n if(path(root.left,n,arr)==true ||path(root.right,n,arr)==true)\n return true;\n arr.remove(arr.size()-1);\n return false;\n }\nNode lca(Node root, int n1,int n2)\n{\nArrayList<Node>arr1=new ArrayList<>();\nArrayList<Node>arr2=new ArrayList<>();\n boolean p1=path(root,n1,arr1);\n boolean p2=path(root,n2,arr2);\n if(p1==false ||p2==false)return null;\n int i;\n for( i=0;i<arr1.size()&& i<arr2.size();i++){\n if(arr1.get(i).data!=arr2.get(i).data) break;\n }\n return arr1.get(i-1); \n}\n}\n"
},
{
"code": null,
"e": 8880,
"s": 8878,
"text": "0"
},
{
"code": null,
"e": 8906,
"s": 8880,
"text": "ashi11100001112 weeks ago"
},
{
"code": null,
"e": 9291,
"s": 8906,
"text": "Node* lca(Node* root ,int n1 ,int n2 ) { //Your code here if(root==NULL) return 0; 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) return right; if(right==NULL) return left; return root; }"
},
{
"code": null,
"e": 9293,
"s": 9291,
"text": "0"
},
{
"code": null,
"e": 9316,
"s": 9293,
"text": "2018uee01551 month ago"
},
{
"code": null,
"e": 9348,
"s": 9316,
"text": "Python the most Naive Solution"
},
{
"code": null,
"e": 9845,
"s": 9350,
"text": "class Solution:\n #Function to return the lowest common ancestor in a Binary Tree.\n def lca(self,root, n1, n2):\n # Code here\n if(root==None):\n return root\n if(root.data==n1 or root.data==n2):\n return root\n left=self.lca(root.left,n1,n2)\n right=self.lca(root.right,n1,n2)\n \n if(left!=None and right!=None):\n return root\n elif(left!=None):\n return left\n else:\n return right"
},
{
"code": null,
"e": 9847,
"s": 9845,
"text": "0"
},
{
"code": null,
"e": 9872,
"s": 9847,
"text": "rohanmeher1641 month ago"
},
{
"code": null,
"e": 9896,
"s": 9872,
"text": "// simple java solution"
},
{
"code": null,
"e": 10238,
"s": 9898,
"text": "class Solution{ //Function to return the lowest common ancestor in a Binary Tree.Node lca(Node root, int n1,int n2){ if(root== null) return null; if(root.data==n1 || root.data==n2) return root; Node l=lca(root.left,n1,n2); Node r=lca(root.right,n1,n2); if(l!=null && r!=null) return root; else if(l!=null) return l; else return r;}}"
},
{
"code": null,
"e": 10241,
"s": 10238,
"text": "-1"
},
{
"code": null,
"e": 10266,
"s": 10241,
"text": "agrimjain24111 month ago"
},
{
"code": null,
"e": 10330,
"s": 10266,
"text": "Efficient C++ Code using pair (Only 1 traversal and O(1) space)"
},
{
"code": null,
"e": 11449,
"s": 10330,
"text": "class Solution\n{\n public:\n //Function to return the lowest common ancestor in a Binary Tree.\n Node* LCA = new Node(-1);\n Node* lca(Node* root ,int n1 ,int n2 )\n {\n //Your code here\n findLCA(n1,n2,root);\n return LCA;\n }\n \n pair<int,int> findLCA(int x,int y, Node*root)\n {\n if(root==NULL)\n return {0,0};\n // p.first tells if x(n1) exist in subtree\n // p.second tells if y(n2) exist in subtree\n \n pair<int,int>l = findLCA(x,y,root->left);\n pair<int,int>r = findLCA(x,y,root->right);\n \n if((LCA->data ==-1) && ((root->data == x && (l.second+r.second>=1)) \n ||(root->data == y && (l.first+r.first>=1))\n ||(l.first + r.second == 2)\n ||(r.first + l.second ==2)))\n {\n LCA = root;\n return {1,1};\n }\n \n pair<int,int>p = {0,0};\n \n if(root->data==x ||((l.first + r.first >= 1)))\n p.first = 1;\n \n if(root->data==y ||((l.second + r.second >= 1)))\n p.second = 1;\n \n return p;\n }\n};\n\n"
},
{
"code": null,
"e": 11595,
"s": 11449,
"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": 11631,
"s": 11595,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 11641,
"s": 11631,
"text": "\nProblem\n"
},
{
"code": null,
"e": 11651,
"s": 11641,
"text": "\nContest\n"
},
{
"code": null,
"e": 11714,
"s": 11651,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 11862,
"s": 11714,
"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": 12070,
"s": 11862,
"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": 12176,
"s": 12070,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Object.assign( ) in JavaScript
|
13 Sep, 2021
Object and Object Constructors in JavaScript? In the living world of object-oriented programming we already know the importance of classes and objects but unlike other programming languages, JavaScript does not have the traditional classes as seen in other languages. But JavaScript has objects and constructors which work mostly in the same way to perform the same kind of operations. Constructors are general JavaScript functions which are used with the “new” keyword. Constructors are of two types in JavaScript i.e. built-in constructors(array and object) and custom constructors(define properties and methods for specific objects). Constructors can be useful when we need a way to create an object “type” that can be used multiple times without having to redefine the object every time and this could be achieved using the Object Constructor function. It’s a convention to capitalize the name of constructors to distinguish them from regular functions. For instance, consider the following code:
function Automobile(color) {
this.color=color;
}
var vehicle1 = new Automobile ("red");
The function “Automobile()” is an object constructor, and its properties and methods i.e “color” is declared inside it by prefixing it with the keyword “this”. Objects defined using an object constructor are then made instants using the keyword “new”. When new Automobile() is called, JavaScript does two things:
It creates a fresh new object(instance) Automobile() and assigns it to a variable.It sets the constructor property i.e “color” of the object to Automobile.
It creates a fresh new object(instance) Automobile() and assigns it to a variable.
It sets the constructor property i.e “color” of the object to Automobile.
Object.assign() Method Among the Object constructor methods, there is a method Object.assign() which is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]] on the source and [[Set]] on the target. It returns the target object which has properties and values copied from the target object. Object.assign() does not throw on null or undefined source values. Applications:
Object.assign() is used for cloning an object.
Object.assign() is used to merge object with same properties.
Syntax:
Object.assign(target, ...sources)
Parameters Used:
target: It is the target object to which values and properties have to be copied.sources: It is the source object from which values and properties have to be copied.
target: It is the target object to which values and properties have to be copied.
sources: It is the source object from which values and properties have to be copied.
Return Value: Object.assign() returns the target object.Examples of the above function are provided below.Examples:
Input : var obj1 = { a: 10 };
var new_obj = Object.assign({}, obj1);
console.log(new_obj);
Output : Object { a: 10 }
Explanation: Here in this example the properties of object "obj1" i.e. { a: 10 } is copied to the target object "new_obj".
Input : var obj1 = { a: 10 };
var obj2 = { b: 20 };
var obj3 = { c: 30 };
var new_obj = Object.assign(obj1, obj2, obj3);
console.log(new_obj);
Output : Object { a: 10, b: 20, c: 30 }
Explanation: Here in this example the properties of three source objects "obj1, obj2, obj3" are copied to the target object "new_obj". The value of any pre-existing key-value pair that existed in the previous object will be over-written.
For example: obj1.b which has value of 10 will now be overwritten with obj2.b which has a value of 20
Input : var obj1 = { a: 10, b: 10, c: 10 };
var obj2 = { b: 20, c: 20 };
var obj3 = { c: 30 };
var new_obj = Object.assign({}, obj1, obj2, obj3);
console.log(new_obj);
Output : Object { a: 10, b: 20, c: 30 }
Explanation: Here in this example the properties of three source objects "obj1, obj2, obj3" are copied to the target object "new_obj" and the target object gets the overwritten values.
Codes for the above function are provided below.Code 1:
html
<script><!-- creating an object constructor and assigning values to it -->const obj1 = { a: 1 }; <!--creating a target object and copying values and properties to it using object.assign() method --><!--Here, obj1 is the source object-->const new_obj = Object.assign({}, obj1); <!-- Displaying the target object -->console.log(new_obj);</script>
OUTPUT :
Object { a: 1 }
Code 2:
html
<script><!-- creating 3 object constructors and assigning values to it -->var obj1 = { a: 10 };var obj2 = { b: 20 };var obj3 = { c: 30 }; <!--creating a target object and copying values and properties to it using object.assign() method -->var new_obj = Object.assign({}, obj1, obj2, obj3); <!-- Displaying the target object -->console.log(new_obj);</script>
OUTPUT :
Object { a: 10, b: 20, c: 30 }
Code 3:
html
<script> <!-- creating 3 object constructors and assigning values to it -->var obj1 = { a: 10, b: 10, c: 10 };var obj2 = { b: 20, c: 20 };var obj3 = { c: 30 }; <!--creating a target object and copying values and properties to it using object.assign() method -->var new_obj = Object.assign({}, obj1, obj2, obj3); <!-- Displaying the target object -->console.log(new_obj);</script>
OUTPUT :
Object { a: 10, b: 20, c: 30 }
Explanation :In the above code the properties are overwritten by other objects that have the same properties later in the same order of parameters.Errors and Exceptions
A TypeError is raised if the property is non-writable.
The target object can be changed only if the properties are added before the error is raised.
Object.assign() does not throw on null or undefined source values.
Supported Browsers:
Google Chrome 6.0 and above
Internet Explorer 9.0 and above
Mozilla 4.0 and above
Opera 11.1 and above
Safari 5.0 and above
kumarvivek1
adegbenga
ysachin2314
javascript-functions
javascript-object
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 1056,
"s": 54,
"text": "Object and Object Constructors in JavaScript? In the living world of object-oriented programming we already know the importance of classes and objects but unlike other programming languages, JavaScript does not have the traditional classes as seen in other languages. But JavaScript has objects and constructors which work mostly in the same way to perform the same kind of operations. Constructors are general JavaScript functions which are used with the “new” keyword. Constructors are of two types in JavaScript i.e. built-in constructors(array and object) and custom constructors(define properties and methods for specific objects). Constructors can be useful when we need a way to create an object “type” that can be used multiple times without having to redefine the object every time and this could be achieved using the Object Constructor function. It’s a convention to capitalize the name of constructors to distinguish them from regular functions. For instance, consider the following code: "
},
{
"code": null,
"e": 1147,
"s": 1056,
"text": "function Automobile(color) {\n this.color=color;\n}\n\nvar vehicle1 = new Automobile (\"red\");"
},
{
"code": null,
"e": 1462,
"s": 1147,
"text": "The function “Automobile()” is an object constructor, and its properties and methods i.e “color” is declared inside it by prefixing it with the keyword “this”. Objects defined using an object constructor are then made instants using the keyword “new”. When new Automobile() is called, JavaScript does two things: "
},
{
"code": null,
"e": 1618,
"s": 1462,
"text": "It creates a fresh new object(instance) Automobile() and assigns it to a variable.It sets the constructor property i.e “color” of the object to Automobile."
},
{
"code": null,
"e": 1701,
"s": 1618,
"text": "It creates a fresh new object(instance) Automobile() and assigns it to a variable."
},
{
"code": null,
"e": 1775,
"s": 1701,
"text": "It sets the constructor property i.e “color” of the object to Automobile."
},
{
"code": null,
"e": 2244,
"s": 1775,
"text": "Object.assign() Method Among the Object constructor methods, there is a method Object.assign() which is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]] on the source and [[Set]] on the target. It returns the target object which has properties and values copied from the target object. Object.assign() does not throw on null or undefined source values. Applications: "
},
{
"code": null,
"e": 2291,
"s": 2244,
"text": "Object.assign() is used for cloning an object."
},
{
"code": null,
"e": 2353,
"s": 2291,
"text": "Object.assign() is used to merge object with same properties."
},
{
"code": null,
"e": 2363,
"s": 2353,
"text": "Syntax: "
},
{
"code": null,
"e": 2397,
"s": 2363,
"text": "Object.assign(target, ...sources)"
},
{
"code": null,
"e": 2416,
"s": 2397,
"text": "Parameters Used: "
},
{
"code": null,
"e": 2582,
"s": 2416,
"text": "target: It is the target object to which values and properties have to be copied.sources: It is the source object from which values and properties have to be copied."
},
{
"code": null,
"e": 2664,
"s": 2582,
"text": "target: It is the target object to which values and properties have to be copied."
},
{
"code": null,
"e": 2749,
"s": 2664,
"text": "sources: It is the source object from which values and properties have to be copied."
},
{
"code": null,
"e": 2867,
"s": 2749,
"text": "Return Value: Object.assign() returns the target object.Examples of the above function are provided below.Examples: "
},
{
"code": null,
"e": 4111,
"s": 2867,
"text": "Input : var obj1 = { a: 10 };\n var new_obj = Object.assign({}, obj1);\n console.log(new_obj);\nOutput : Object { a: 10 }\n\nExplanation: Here in this example the properties of object \"obj1\" i.e. { a: 10 } is copied to the target object \"new_obj\".\n\nInput : var obj1 = { a: 10 };\n var obj2 = { b: 20 };\n var obj3 = { c: 30 };\n var new_obj = Object.assign(obj1, obj2, obj3);\n console.log(new_obj);\nOutput : Object { a: 10, b: 20, c: 30 }\n\nExplanation: Here in this example the properties of three source objects \"obj1, obj2, obj3\" are copied to the target object \"new_obj\". The value of any pre-existing key-value pair that existed in the previous object will be over-written.\n\nFor example: obj1.b which has value of 10 will now be overwritten with obj2.b which has a value of 20\n\nInput : var obj1 = { a: 10, b: 10, c: 10 };\n var obj2 = { b: 20, c: 20 };\n var obj3 = { c: 30 };\n var new_obj = Object.assign({}, obj1, obj2, obj3);\n console.log(new_obj); \nOutput : Object { a: 10, b: 20, c: 30 }\n\nExplanation: Here in this example the properties of three source objects \"obj1, obj2, obj3\" are copied to the target object \"new_obj\" and the target object gets the overwritten values."
},
{
"code": null,
"e": 4168,
"s": 4111,
"text": "Codes for the above function are provided below.Code 1: "
},
{
"code": null,
"e": 4173,
"s": 4168,
"text": "html"
},
{
"code": "<script><!-- creating an object constructor and assigning values to it -->const obj1 = { a: 1 }; <!--creating a target object and copying values and properties to it using object.assign() method --><!--Here, obj1 is the source object-->const new_obj = Object.assign({}, obj1); <!-- Displaying the target object -->console.log(new_obj);</script>",
"e": 4518,
"s": 4173,
"text": null
},
{
"code": null,
"e": 4529,
"s": 4518,
"text": "OUTPUT : "
},
{
"code": null,
"e": 4545,
"s": 4529,
"text": "Object { a: 1 }"
},
{
"code": null,
"e": 4554,
"s": 4545,
"text": "Code 2: "
},
{
"code": null,
"e": 4559,
"s": 4554,
"text": "html"
},
{
"code": "<script><!-- creating 3 object constructors and assigning values to it -->var obj1 = { a: 10 };var obj2 = { b: 20 };var obj3 = { c: 30 }; <!--creating a target object and copying values and properties to it using object.assign() method -->var new_obj = Object.assign({}, obj1, obj2, obj3); <!-- Displaying the target object -->console.log(new_obj);</script>",
"e": 4917,
"s": 4559,
"text": null
},
{
"code": null,
"e": 4928,
"s": 4917,
"text": "OUTPUT : "
},
{
"code": null,
"e": 4959,
"s": 4928,
"text": "Object { a: 10, b: 20, c: 30 }"
},
{
"code": null,
"e": 4968,
"s": 4959,
"text": "Code 3: "
},
{
"code": null,
"e": 4973,
"s": 4968,
"text": "html"
},
{
"code": "<script> <!-- creating 3 object constructors and assigning values to it -->var obj1 = { a: 10, b: 10, c: 10 };var obj2 = { b: 20, c: 20 };var obj3 = { c: 30 }; <!--creating a target object and copying values and properties to it using object.assign() method -->var new_obj = Object.assign({}, obj1, obj2, obj3); <!-- Displaying the target object -->console.log(new_obj);</script>",
"e": 5353,
"s": 4973,
"text": null
},
{
"code": null,
"e": 5364,
"s": 5353,
"text": "OUTPUT : "
},
{
"code": null,
"e": 5395,
"s": 5364,
"text": "Object { a: 10, b: 20, c: 30 }"
},
{
"code": null,
"e": 5566,
"s": 5395,
"text": "Explanation :In the above code the properties are overwritten by other objects that have the same properties later in the same order of parameters.Errors and Exceptions "
},
{
"code": null,
"e": 5621,
"s": 5566,
"text": "A TypeError is raised if the property is non-writable."
},
{
"code": null,
"e": 5715,
"s": 5621,
"text": "The target object can be changed only if the properties are added before the error is raised."
},
{
"code": null,
"e": 5782,
"s": 5715,
"text": "Object.assign() does not throw on null or undefined source values."
},
{
"code": null,
"e": 5802,
"s": 5782,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 5830,
"s": 5802,
"text": "Google Chrome 6.0 and above"
},
{
"code": null,
"e": 5862,
"s": 5830,
"text": "Internet Explorer 9.0 and above"
},
{
"code": null,
"e": 5884,
"s": 5862,
"text": "Mozilla 4.0 and above"
},
{
"code": null,
"e": 5905,
"s": 5884,
"text": "Opera 11.1 and above"
},
{
"code": null,
"e": 5926,
"s": 5905,
"text": "Safari 5.0 and above"
},
{
"code": null,
"e": 5938,
"s": 5926,
"text": "kumarvivek1"
},
{
"code": null,
"e": 5948,
"s": 5938,
"text": "adegbenga"
},
{
"code": null,
"e": 5960,
"s": 5948,
"text": "ysachin2314"
},
{
"code": null,
"e": 5981,
"s": 5960,
"text": "javascript-functions"
},
{
"code": null,
"e": 5999,
"s": 5981,
"text": "javascript-object"
},
{
"code": null,
"e": 6010,
"s": 5999,
"text": "JavaScript"
}
] |
How to change color of regression line in R ?
|
24 Jun, 2021
A regression line is basically used in statistical models which help to estimate the relationship between a dependent variable and at least one independent variable. In this article, we are going to see how to plot a regression line using ggplot2 in R programming language and different methods to change the color using a built-in data set as an example.
Dataset Used: Here we are using a built-in data frame “Orange” which consists of details about the growth of five different types of orange trees. The data frame has 35 rows and 3 columns. The columns in this data frame are :
Tree: The ordering of trees on which experiment is made on the basis of increasing diameter values of the orange.
Age: The age of the trees since when they were planted.
Circumference: The circumference of the orange.
First, we will draw a scatter plot. We will use the function geom_point( ) to plot the scatter plot which comes under the ggplot2 library.
Syntax:
geom_point( mapping=NULL, data=NULL, stat=identity, position=”identity”)
Basically, we are doing a comparative analysis of the circumference vs age of the oranges. The function used is geom_smooth( ) to plot a smooth line or regression line.
Syntax:
geom_smooth(method=”auto”,se=FALSE,fullrange=TRUE,level=0.95)
Parameter :
method : The smoothing method is assigned using the keyword loess, lm, glm etc
lm : linear model, loess : default for smooth lines during small data set observations.
formula : You can also use formulas for smooth lines. For example : y~poly(x,4) which will plot a smooth line of degree 4. Higher the degree more bends the smooth line will have.
se : It takes logical values either “TRUE” or “FALSE”.
fullrange : It takes logical value either “TRUE” or “FALSE”.
level : By default level is 0.95 for the confidence interval.
Let us first draw a regular plot so that the difference is apparent.
Example:
R
# Scatter Plot and Regression Linelibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age))+ geom_point()+ geom_smooth(method=lm,se=FALSE,fullrange=TRUE)+ theme_classic()ggplt
Output:
By default, the regression line is blue. To change the color we have to use the keyword color inside the geom_smooth( ) function.
Syntax:
geom_smooth(method=”auto”, color=”color_name”)
Color code is of the form “#RedRedBlueBlueGreenGreen”
Example:
R
# Change Regression Line Color using name of colorlibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age))+ geom_point()+ geom_smooth(method=lm,se=FALSE,fullrange=TRUE,color="cyan")+ theme_classic()ggplt
Output:
Example:
R
# Change Regression Line Color using Color Codelibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age))+ geom_point()+ geom_smooth(method=lm,se=FALSE,fullrange=TRUE,color="#006000")+ theme_classic()ggplt
Output:
The data frame consists of information about five different types of orange trees. So, let’s segregate the scatter points on the basis of the group “Tree”. The shape of the points will be on the basis of the category of the trees.
Example:
R
# Scatter Plot with multiple groupslibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age,shape=Tree))+ geom_point()+ theme_classic() ggplt # Plotting Regression Lines on the basis# of groupsggplt+geom_smooth(method=lm,se=FALSE,fullrange=TRUE)
We can see that all the regression lines are of the same color. Now we will see two different methods on how to assign different colors to multiple regression lines.
Method 1: Using color
It is the default method where color is assigned automatically by the R compiler. The key idea is to assign color on the basis of Trees since every Tree group has different regression lines. So, we write the below command inside the geom_smooth( ) function:
aes(color=grp_var)
grp_var : The column in the data frame through which grouping is done.
Example:
R
# Scatter Plotlibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age,shape=Tree))+ geom_point()+ theme_classic()ggplt # Plotting Regression Lines on the basis of groupsggplt+geom_smooth(method=lm,se=FALSE,fullrange=TRUE) # Changing color of Regression Lines manuallyggplt+geom_smooth(method=lm,se=FALSE,fullrange=TRUE,aes(color=Tree))
Output:
Method 2: Changing Color Manually
1. Scale_color_manual( ): This function is used to add color manually on the basis of users’ choice.
Syntax:
scale_color_manual(values=c(“color1”, “color2” , “color3”,....))
color : color name or color code
Example:
R
# Scatter Plot and Regression Linelibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age,shape=Tree,color=Tree))+ geom_point()+ geom_smooth(method=lm,se=FALSE,fullrange=TRUE)+ theme_classic() ggplt # Manually changing color of Regression Lines ggplt+scale_color_manual(values=c("Red","Purple","#006000","Brown","Cyan"))
Output:
2. Scale_color_brewer( ) : R provides us with various color palettes which contain different shades of color.
Syntax:
scale_color_brewer(palette=”palette_name”)
palette_name : The name of the palette. In our case we have used the palette “Greens”.
Example:
R
# Scatter Plot and Regression Linelibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age,shape=Tree,color=Tree))+ geom_point()+ geom_smooth(method=lm,se=FALSE,fullrange=TRUE)+ theme_classic() ggplt # Manually changing color of Regression Lines ggplt+scale_color_brewer(palette="Greens")
Output:
3. Scale_color_grey( ): It is used to assign grayscale value to the regression lines. Simply invoke the function to add grayscale in regression lines.
Example:
R
# Scatter Plot and Regression Linelibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age,shape=Tree,color=Tree))+ geom_point()+ geom_smooth(method=lm,se=FALSE,fullrange=TRUE)+ theme_classic()ggplt # Manually changing color of Regression Lines ggplt+scale_color_grey()
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 384,
"s": 28,
"text": "A regression line is basically used in statistical models which help to estimate the relationship between a dependent variable and at least one independent variable. In this article, we are going to see how to plot a regression line using ggplot2 in R programming language and different methods to change the color using a built-in data set as an example."
},
{
"code": null,
"e": 610,
"s": 384,
"text": "Dataset Used: Here we are using a built-in data frame “Orange” which consists of details about the growth of five different types of orange trees. The data frame has 35 rows and 3 columns. The columns in this data frame are :"
},
{
"code": null,
"e": 724,
"s": 610,
"text": "Tree: The ordering of trees on which experiment is made on the basis of increasing diameter values of the orange."
},
{
"code": null,
"e": 780,
"s": 724,
"text": "Age: The age of the trees since when they were planted."
},
{
"code": null,
"e": 828,
"s": 780,
"text": "Circumference: The circumference of the orange."
},
{
"code": null,
"e": 968,
"s": 828,
"text": "First, we will draw a scatter plot. We will use the function geom_point( ) to plot the scatter plot which comes under the ggplot2 library. "
},
{
"code": null,
"e": 976,
"s": 968,
"text": "Syntax:"
},
{
"code": null,
"e": 1049,
"s": 976,
"text": "geom_point( mapping=NULL, data=NULL, stat=identity, position=”identity”)"
},
{
"code": null,
"e": 1219,
"s": 1049,
"text": "Basically, we are doing a comparative analysis of the circumference vs age of the oranges. The function used is geom_smooth( ) to plot a smooth line or regression line. "
},
{
"code": null,
"e": 1227,
"s": 1219,
"text": "Syntax:"
},
{
"code": null,
"e": 1289,
"s": 1227,
"text": "geom_smooth(method=”auto”,se=FALSE,fullrange=TRUE,level=0.95)"
},
{
"code": null,
"e": 1301,
"s": 1289,
"text": "Parameter :"
},
{
"code": null,
"e": 1380,
"s": 1301,
"text": "method : The smoothing method is assigned using the keyword loess, lm, glm etc"
},
{
"code": null,
"e": 1468,
"s": 1380,
"text": "lm : linear model, loess : default for smooth lines during small data set observations."
},
{
"code": null,
"e": 1647,
"s": 1468,
"text": "formula : You can also use formulas for smooth lines. For example : y~poly(x,4) which will plot a smooth line of degree 4. Higher the degree more bends the smooth line will have."
},
{
"code": null,
"e": 1702,
"s": 1647,
"text": "se : It takes logical values either “TRUE” or “FALSE”."
},
{
"code": null,
"e": 1763,
"s": 1702,
"text": "fullrange : It takes logical value either “TRUE” or “FALSE”."
},
{
"code": null,
"e": 1825,
"s": 1763,
"text": "level : By default level is 0.95 for the confidence interval."
},
{
"code": null,
"e": 1894,
"s": 1825,
"text": "Let us first draw a regular plot so that the difference is apparent."
},
{
"code": null,
"e": 1903,
"s": 1894,
"text": "Example:"
},
{
"code": null,
"e": 1905,
"s": 1903,
"text": "R"
},
{
"code": "# Scatter Plot and Regression Linelibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age))+ geom_point()+ geom_smooth(method=lm,se=FALSE,fullrange=TRUE)+ theme_classic()ggplt",
"e": 2116,
"s": 1905,
"text": null
},
{
"code": null,
"e": 2124,
"s": 2116,
"text": "Output:"
},
{
"code": null,
"e": 2255,
"s": 2124,
"text": "By default, the regression line is blue. To change the color we have to use the keyword color inside the geom_smooth( ) function. "
},
{
"code": null,
"e": 2263,
"s": 2255,
"text": "Syntax:"
},
{
"code": null,
"e": 2310,
"s": 2263,
"text": "geom_smooth(method=”auto”, color=”color_name”)"
},
{
"code": null,
"e": 2364,
"s": 2310,
"text": "Color code is of the form “#RedRedBlueBlueGreenGreen”"
},
{
"code": null,
"e": 2373,
"s": 2364,
"text": "Example:"
},
{
"code": null,
"e": 2375,
"s": 2373,
"text": "R"
},
{
"code": "# Change Regression Line Color using name of colorlibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age))+ geom_point()+ geom_smooth(method=lm,se=FALSE,fullrange=TRUE,color=\"cyan\")+ theme_classic()ggplt",
"e": 2615,
"s": 2375,
"text": null
},
{
"code": null,
"e": 2623,
"s": 2615,
"text": "Output:"
},
{
"code": null,
"e": 2632,
"s": 2623,
"text": "Example:"
},
{
"code": null,
"e": 2634,
"s": 2632,
"text": "R"
},
{
"code": "# Change Regression Line Color using Color Codelibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age))+ geom_point()+ geom_smooth(method=lm,se=FALSE,fullrange=TRUE,color=\"#006000\")+ theme_classic()ggplt",
"e": 2874,
"s": 2634,
"text": null
},
{
"code": null,
"e": 2882,
"s": 2874,
"text": "Output:"
},
{
"code": null,
"e": 3114,
"s": 2882,
"text": "The data frame consists of information about five different types of orange trees. So, let’s segregate the scatter points on the basis of the group “Tree”. The shape of the points will be on the basis of the category of the trees."
},
{
"code": null,
"e": 3123,
"s": 3114,
"text": "Example:"
},
{
"code": null,
"e": 3125,
"s": 3123,
"text": "R"
},
{
"code": "# Scatter Plot with multiple groupslibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age,shape=Tree))+ geom_point()+ theme_classic() ggplt # Plotting Regression Lines on the basis# of groupsggplt+geom_smooth(method=lm,se=FALSE,fullrange=TRUE)",
"e": 3399,
"s": 3125,
"text": null
},
{
"code": null,
"e": 3565,
"s": 3399,
"text": "We can see that all the regression lines are of the same color. Now we will see two different methods on how to assign different colors to multiple regression lines."
},
{
"code": null,
"e": 3587,
"s": 3565,
"text": "Method 1: Using color"
},
{
"code": null,
"e": 3845,
"s": 3587,
"text": "It is the default method where color is assigned automatically by the R compiler. The key idea is to assign color on the basis of Trees since every Tree group has different regression lines. So, we write the below command inside the geom_smooth( ) function:"
},
{
"code": null,
"e": 3864,
"s": 3845,
"text": "aes(color=grp_var)"
},
{
"code": null,
"e": 3935,
"s": 3864,
"text": "grp_var : The column in the data frame through which grouping is done."
},
{
"code": null,
"e": 3944,
"s": 3935,
"text": "Example:"
},
{
"code": null,
"e": 3946,
"s": 3944,
"text": "R"
},
{
"code": "# Scatter Plotlibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age,shape=Tree))+ geom_point()+ theme_classic()ggplt # Plotting Regression Lines on the basis of groupsggplt+geom_smooth(method=lm,se=FALSE,fullrange=TRUE) # Changing color of Regression Lines manuallyggplt+geom_smooth(method=lm,se=FALSE,fullrange=TRUE,aes(color=Tree))",
"e": 4311,
"s": 3946,
"text": null
},
{
"code": null,
"e": 4319,
"s": 4311,
"text": "Output:"
},
{
"code": null,
"e": 4353,
"s": 4319,
"text": "Method 2: Changing Color Manually"
},
{
"code": null,
"e": 4455,
"s": 4353,
"text": "1. Scale_color_manual( ): This function is used to add color manually on the basis of users’ choice. "
},
{
"code": null,
"e": 4463,
"s": 4455,
"text": "Syntax:"
},
{
"code": null,
"e": 4528,
"s": 4463,
"text": "scale_color_manual(values=c(“color1”, “color2” , “color3”,....))"
},
{
"code": null,
"e": 4561,
"s": 4528,
"text": "color : color name or color code"
},
{
"code": null,
"e": 4570,
"s": 4561,
"text": "Example:"
},
{
"code": null,
"e": 4572,
"s": 4570,
"text": "R"
},
{
"code": "# Scatter Plot and Regression Linelibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age,shape=Tree,color=Tree))+ geom_point()+ geom_smooth(method=lm,se=FALSE,fullrange=TRUE)+ theme_classic() ggplt # Manually changing color of Regression Lines ggplt+scale_color_manual(values=c(\"Red\",\"Purple\",\"#006000\",\"Brown\",\"Cyan\"))",
"e": 4930,
"s": 4572,
"text": null
},
{
"code": null,
"e": 4938,
"s": 4930,
"text": "Output:"
},
{
"code": null,
"e": 5049,
"s": 4938,
"text": "2. Scale_color_brewer( ) : R provides us with various color palettes which contain different shades of color. "
},
{
"code": null,
"e": 5057,
"s": 5049,
"text": "Syntax:"
},
{
"code": null,
"e": 5101,
"s": 5057,
"text": "scale_color_brewer(palette=”palette_name”) "
},
{
"code": null,
"e": 5188,
"s": 5101,
"text": "palette_name : The name of the palette. In our case we have used the palette “Greens”."
},
{
"code": null,
"e": 5197,
"s": 5188,
"text": "Example:"
},
{
"code": null,
"e": 5199,
"s": 5197,
"text": "R"
},
{
"code": "# Scatter Plot and Regression Linelibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age,shape=Tree,color=Tree))+ geom_point()+ geom_smooth(method=lm,se=FALSE,fullrange=TRUE)+ theme_classic() ggplt # Manually changing color of Regression Lines ggplt+scale_color_brewer(palette=\"Greens\")",
"e": 5524,
"s": 5199,
"text": null
},
{
"code": null,
"e": 5532,
"s": 5524,
"text": "Output:"
},
{
"code": null,
"e": 5683,
"s": 5532,
"text": "3. Scale_color_grey( ): It is used to assign grayscale value to the regression lines. Simply invoke the function to add grayscale in regression lines."
},
{
"code": null,
"e": 5692,
"s": 5683,
"text": "Example:"
},
{
"code": null,
"e": 5694,
"s": 5692,
"text": "R"
},
{
"code": "# Scatter Plot and Regression Linelibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age,shape=Tree,color=Tree))+ geom_point()+ geom_smooth(method=lm,se=FALSE,fullrange=TRUE)+ theme_classic()ggplt # Manually changing color of Regression Lines ggplt+scale_color_grey()",
"e": 5999,
"s": 5694,
"text": null
},
{
"code": null,
"e": 6007,
"s": 5999,
"text": "Output:"
},
{
"code": null,
"e": 6014,
"s": 6007,
"text": "Picked"
},
{
"code": null,
"e": 6023,
"s": 6014,
"text": "R-ggplot"
},
{
"code": null,
"e": 6034,
"s": 6023,
"text": "R Language"
}
] |
Tracking bird migration using Python-3
|
29 Sep, 2021
One fascinating area of research uses GPS to track the movements of animals. It is now possible to manufacture a small GPS device that is solar charged, so you don’t need to change batteries and use it to track flight patterns of birds. The data for this case study comes from the LifeWatch INBO project. Several data sets have been released as part of this project. We will use a small data set that consists of migration data for three gulls named Eric, Nico, and Sanne. The official_datasets; used dataset – CSV”>csv file contains eight columns and includes variables like latitude, longitude, altitude, and time stamps. In this case study, we will first load the data, visualize some simple flight trajectories, track flight speed, learn about daytime, and much, much more.
Aim: Track the movement of three gulls namely – Eric, Nico & SanneDataset: official_datasets; used dataset – csv Dependencies: Matplotlib, Pandas, Numpy, Cartopy, ShapelyRepository(Github): source code (check the repository for the documentation of source code.) Writeup: explanation(.pdf)
We will divide our case study into five parts: 1. Visualizing longitude and latitude data of the gulls. 2. Visualize the variation of the speed of the gulls. 3. Visualize the time required by the gulls to cover equal distances over the journey. 4. Visualize the daily mean speed of the gulls. 5. Cartographic view of the journey of the gulls.
PART (1/5): Latitude and Longitude In this part, we are going to visualize the location of the birds. We are going to plot latitude and longitude along the y and x-axis respectively and visualize the location data present in the csv file.
Python
import pandas as pdimport matplotlib.pyplot as pltimport numpy as np birddata = pd.read_csv("bird_tracking.csv")bird_names = pd.unique(birddata.bird_name) # storing the indices of the bird Ericix = birddata.bird_name == "Eric"x,y = birddata.longitude[ix], birddata.latitude[ix]plt.figure(figsize = (7,7))plt.plot(x,y,"b.") ''' To look at all the birds trajectories, we plot each bird in the same plot '''plt.figure(figsize = (7,7))for bird_name in bird_names: # storing the indices of the bird Eric ix = birddata.bird_name == bird_name x,y = birddata.longitude[ix], birddata.latitude[ix] plt.plot(x,y,".", label=bird_name)plt.xlabel("Longitude")plt.ylabel("Latitude")plt.legend(loc="lower right")plt.show()
plt.figure(figsize = (7,7))
plt.plot(x,y,"b.")
We use the matplotlib function, figure() to initialize size of the figure as 7 x 7 and plot it using the plot() function.The parameters inside the function plot() i.e x, y and “b.” are specifying to use longitude data along x axis(for x), latitude along y(for y) and b=blue, . = circles in the visualization.
Output : You must have all the dependencies.Install them using "pip install dependency_name"
PART (2/5): 2D Speed Vs Frequency In this second part of the case study, we are going to visualize 2D speed vs Frequency for the gull named “Eric”.
Python
import pandas as pdimport matplotlib.pyplot as pltimport numpy as np birddata = pd.read_csv("bird_tracking.csv")bird_names = pd.unique(birddata.bird_name) # storing the indices of the bird Ericix = birddata.bird_name == "Eric"speed = birddata.speed_2d[ix] plt.figure(figsize = (8,4))ind = np.isnan(speed)plt.hist(speed[~ind], bins = np.linspace(0,30,20), normed=True)plt.xlabel(" 2D speed (m/s) ")plt.ylabel(" Frequency ")plt.show()
ind = np.isnan(speed)
plt.hist(speed[~ind], bins = np.linspace(0,30,20), normed=True)
plt.xlabel(" 2D speed (m/s) ")
plt.ylabel(" Frequency ")
plt.show()
The parameters speed[~ind] indicates that we will include only those entries for which ind != True, bins=np.linspace(0,30,20) indicates the bins along the x-axis will vary from 0 to 30 with 20 bins within them, linearly spaced. Lastly, we plot 2D speed in m/s along the x-axis and Frequency along the y-axis using the xlabel() and ylabel() functions respectively and plot the data using plt.show().
Output :
PART (3/5): Time and Date The third part is associated with date and time. We are going to visualize the time(in days) required by Eric to cover constant distances through his journey. If he covers equal distances in an equal amount of time, then the Elapsed time vs Observation curve will be linear.
Python
import pandas as pdimport matplotlib.pyplot as pltimport datetimeimport numpy as np birddata = pd.read_csv("bird_tracking.csv")bird_names = pd.unique(birddata.bird_name) timestamps = []for k in range(len(birddata)): timestamps.append(datetime.datetime.strptime(birddata.date_time.iloc[k][:-3], "%Y-%m-%d %H:%M:%S")) birddata["timestamp"] = pd.Series(timestamps, index = birddata.index) times = birddata.timestamp[birddata.bird_name == "Eric"]elapsed_time = [time-times[0] for time in times] plt.plot(np.array(elapsed_time)/datetime.timedelta(days=1))plt.xlabel(" Observation ")plt.ylabel(" Elapsed time (days) ")plt.show()
for k in range(len(birddata)):
timestamps.append(datetime.datetime.strptime(birddata.date_time.iloc[k][:-3], "%Y-%m-%d %H:%M:%S"))
“>>>datetime.datetime.today()”, returns the current Date (yy-mm-dd) & time (h:m:s). “>>>date_str[:-3]”, slices/removes the UTC +00 coordinated time stamps. “>>>datetime.datetime.strptime(date_str[:-3], “%Y-%m-%d %H:%M:%S”)” ,the time-stamp strings from date_str are converted to datetime object to be worked upon. “%Y-%m-%d %H:%M:%S” is the Year-Month-Date and Hour-Minute-Second format.
Output:
PART (4/5): Daily Mean Speed We are going to visualize the daily mean speed of the gull named “Eric” for the total number of days of recorded flight.
Python
import pandas as pdimport matplotlib.pyplot as pltimport datetimeimport numpy as np birddata = pd.read_csv("bird_tracking.csv")bird_names = pd.unique(birddata.bird_name) timestamps = []for k in range(len(birddata)): timestamps.append(datetime.datetime.strptime(birddata.date_time.iloc[k][:-3], "%Y-%m-%d %H:%M:%S"))birddata["timestamp"] = pd.Series(timestamps, index = birddata.index) data = birddata[birddata.bird_name == "Eric"]times = data.timestampelapsed_time = [time-times[0] for time in times]elapsed_days = np.array(elapsed_time)/datetime.timedelta(days=1) next_day = 1inds = []daily_mean_speed = []for (i,t) in enumerate(elapsed_days): if t < next_day: inds.append(i) else: daily_mean_speed.append(np.mean(data.speed_2d[inds])) next_day += 1 inds = [] plt.figure(figsize = (8,6))plt.plot(daily_mean_speed, "rs-")plt.xlabel(" Day ")plt.ylabel(" Mean Speed (m/s) ");plt.show()
enumerate() - is one of the built-in Python functions. It returns an enumerated object. In our case, that object is a list of tuples (immutable lists), each containing a pair of count/index and value.
Output:
PART (5/5): Cartographic View In this last part, we are going to track the Birds over a map.
Python
import pandas as pdimport cartopy.crs as ccrsimport cartopy.feature as cfeatureimport matplotlib.pyplot as plt birddata = pd.read_csv("bird_tracking.csv")bird_names = pd.unique(birddata.bird_name) # To move forward, we need to specify a# specific projection that we're interested# in using.proj = ccrs.Mercator() plt.figure(figsize=(10,10))ax = plt.axes(projection=proj)ax.set_extent((-25.0, 20.0, 52.0, 10.0))ax.add_feature(cfeature.LAND)ax.add_feature(cfeature.OCEAN)ax.add_feature(cfeature.COASTLINE)ax.add_feature(cfeature.BORDERS, linestyle=':')for name in bird_names: ix = birddata['bird_name'] == name x,y = birddata.longitude[ix], birddata.latitude[ix] ax.plot(x,y,'.', transform=ccrs.Geodetic(), label=name)plt.legend(loc="upper left")plt.show()
import cartopy.crs as ccrs
import cartopy.feature as cfeature
These modules are important for mapping data.
ax.add_feature(cfeature.LAND)
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.BORDERS, linestyle=':')
We add the salient physical features of a map.
Output:
Resources : 1. edX – HarvardX – Using Python for Research 2. Python functions doc_I 3. Python functions doc_II
This article is contributed by Amartya Ranjan Saikia. 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.
ddeevviissaavviittaa
simmytarika5
Python-projects
python-utility
Project
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
10 Best Web Development Projects For Your Resume
A Group chat application in Java
Student Information Management System
Face Detection using Python and OpenCV with webcam
E-commerce Website using Django
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 830,
"s": 52,
"text": "One fascinating area of research uses GPS to track the movements of animals. It is now possible to manufacture a small GPS device that is solar charged, so you don’t need to change batteries and use it to track flight patterns of birds. The data for this case study comes from the LifeWatch INBO project. Several data sets have been released as part of this project. We will use a small data set that consists of migration data for three gulls named Eric, Nico, and Sanne. The official_datasets; used dataset – CSV”>csv file contains eight columns and includes variables like latitude, longitude, altitude, and time stamps. In this case study, we will first load the data, visualize some simple flight trajectories, track flight speed, learn about daytime, and much, much more."
},
{
"code": null,
"e": 1120,
"s": 830,
"text": "Aim: Track the movement of three gulls namely – Eric, Nico & SanneDataset: official_datasets; used dataset – csv Dependencies: Matplotlib, Pandas, Numpy, Cartopy, ShapelyRepository(Github): source code (check the repository for the documentation of source code.) Writeup: explanation(.pdf)"
},
{
"code": null,
"e": 1463,
"s": 1120,
"text": "We will divide our case study into five parts: 1. Visualizing longitude and latitude data of the gulls. 2. Visualize the variation of the speed of the gulls. 3. Visualize the time required by the gulls to cover equal distances over the journey. 4. Visualize the daily mean speed of the gulls. 5. Cartographic view of the journey of the gulls."
},
{
"code": null,
"e": 1703,
"s": 1463,
"text": "PART (1/5): Latitude and Longitude In this part, we are going to visualize the location of the birds. We are going to plot latitude and longitude along the y and x-axis respectively and visualize the location data present in the csv file. "
},
{
"code": null,
"e": 1710,
"s": 1703,
"text": "Python"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as pltimport numpy as np birddata = pd.read_csv(\"bird_tracking.csv\")bird_names = pd.unique(birddata.bird_name) # storing the indices of the bird Ericix = birddata.bird_name == \"Eric\"x,y = birddata.longitude[ix], birddata.latitude[ix]plt.figure(figsize = (7,7))plt.plot(x,y,\"b.\") ''' To look at all the birds trajectories, we plot each bird in the same plot '''plt.figure(figsize = (7,7))for bird_name in bird_names: # storing the indices of the bird Eric ix = birddata.bird_name == bird_name x,y = birddata.longitude[ix], birddata.latitude[ix] plt.plot(x,y,\".\", label=bird_name)plt.xlabel(\"Longitude\")plt.ylabel(\"Latitude\")plt.legend(loc=\"lower right\")plt.show()",
"e": 2435,
"s": 1710,
"text": null
},
{
"code": null,
"e": 2482,
"s": 2435,
"text": "plt.figure(figsize = (7,7))\nplt.plot(x,y,\"b.\")"
},
{
"code": null,
"e": 2792,
"s": 2482,
"text": "We use the matplotlib function, figure() to initialize size of the figure as 7 x 7 and plot it using the plot() function.The parameters inside the function plot() i.e x, y and “b.” are specifying to use longitude data along x axis(for x), latitude along y(for y) and b=blue, . = circles in the visualization. "
},
{
"code": null,
"e": 2885,
"s": 2792,
"text": "Output : You must have all the dependencies.Install them using \"pip install dependency_name\""
},
{
"code": null,
"e": 3033,
"s": 2885,
"text": "PART (2/5): 2D Speed Vs Frequency In this second part of the case study, we are going to visualize 2D speed vs Frequency for the gull named “Eric”."
},
{
"code": null,
"e": 3040,
"s": 3033,
"text": "Python"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as pltimport numpy as np birddata = pd.read_csv(\"bird_tracking.csv\")bird_names = pd.unique(birddata.bird_name) # storing the indices of the bird Ericix = birddata.bird_name == \"Eric\"speed = birddata.speed_2d[ix] plt.figure(figsize = (8,4))ind = np.isnan(speed)plt.hist(speed[~ind], bins = np.linspace(0,30,20), normed=True)plt.xlabel(\" 2D speed (m/s) \")plt.ylabel(\" Frequency \")plt.show()",
"e": 3473,
"s": 3040,
"text": null
},
{
"code": null,
"e": 3627,
"s": 3473,
"text": "ind = np.isnan(speed)\nplt.hist(speed[~ind], bins = np.linspace(0,30,20), normed=True)\nplt.xlabel(\" 2D speed (m/s) \")\nplt.ylabel(\" Frequency \")\nplt.show()"
},
{
"code": null,
"e": 4026,
"s": 3627,
"text": "The parameters speed[~ind] indicates that we will include only those entries for which ind != True, bins=np.linspace(0,30,20) indicates the bins along the x-axis will vary from 0 to 30 with 20 bins within them, linearly spaced. Lastly, we plot 2D speed in m/s along the x-axis and Frequency along the y-axis using the xlabel() and ylabel() functions respectively and plot the data using plt.show()."
},
{
"code": null,
"e": 4036,
"s": 4026,
"text": "Output : "
},
{
"code": null,
"e": 4338,
"s": 4036,
"text": "PART (3/5): Time and Date The third part is associated with date and time. We are going to visualize the time(in days) required by Eric to cover constant distances through his journey. If he covers equal distances in an equal amount of time, then the Elapsed time vs Observation curve will be linear. "
},
{
"code": null,
"e": 4345,
"s": 4338,
"text": "Python"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as pltimport datetimeimport numpy as np birddata = pd.read_csv(\"bird_tracking.csv\")bird_names = pd.unique(birddata.bird_name) timestamps = []for k in range(len(birddata)): timestamps.append(datetime.datetime.strptime(birddata.date_time.iloc[k][:-3], \"%Y-%m-%d %H:%M:%S\")) birddata[\"timestamp\"] = pd.Series(timestamps, index = birddata.index) times = birddata.timestamp[birddata.bird_name == \"Eric\"]elapsed_time = [time-times[0] for time in times] plt.plot(np.array(elapsed_time)/datetime.timedelta(days=1))plt.xlabel(\" Observation \")plt.ylabel(\" Elapsed time (days) \")plt.show()",
"e": 4971,
"s": 4345,
"text": null
},
{
"code": null,
"e": 5106,
"s": 4971,
"text": "for k in range(len(birddata)):\n timestamps.append(datetime.datetime.strptime(birddata.date_time.iloc[k][:-3], \"%Y-%m-%d %H:%M:%S\"))"
},
{
"code": null,
"e": 5494,
"s": 5106,
"text": "“>>>datetime.datetime.today()”, returns the current Date (yy-mm-dd) & time (h:m:s). “>>>date_str[:-3]”, slices/removes the UTC +00 coordinated time stamps. “>>>datetime.datetime.strptime(date_str[:-3], “%Y-%m-%d %H:%M:%S”)” ,the time-stamp strings from date_str are converted to datetime object to be worked upon. “%Y-%m-%d %H:%M:%S” is the Year-Month-Date and Hour-Minute-Second format."
},
{
"code": null,
"e": 5503,
"s": 5494,
"text": "Output: "
},
{
"code": null,
"e": 5654,
"s": 5503,
"text": "PART (4/5): Daily Mean Speed We are going to visualize the daily mean speed of the gull named “Eric” for the total number of days of recorded flight. "
},
{
"code": null,
"e": 5661,
"s": 5654,
"text": "Python"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as pltimport datetimeimport numpy as np birddata = pd.read_csv(\"bird_tracking.csv\")bird_names = pd.unique(birddata.bird_name) timestamps = []for k in range(len(birddata)): timestamps.append(datetime.datetime.strptime(birddata.date_time.iloc[k][:-3], \"%Y-%m-%d %H:%M:%S\"))birddata[\"timestamp\"] = pd.Series(timestamps, index = birddata.index) data = birddata[birddata.bird_name == \"Eric\"]times = data.timestampelapsed_time = [time-times[0] for time in times]elapsed_days = np.array(elapsed_time)/datetime.timedelta(days=1) next_day = 1inds = []daily_mean_speed = []for (i,t) in enumerate(elapsed_days): if t < next_day: inds.append(i) else: daily_mean_speed.append(np.mean(data.speed_2d[inds])) next_day += 1 inds = [] plt.figure(figsize = (8,6))plt.plot(daily_mean_speed, \"rs-\")plt.xlabel(\" Day \")plt.ylabel(\" Mean Speed (m/s) \");plt.show()",
"e": 6583,
"s": 5661,
"text": null
},
{
"code": null,
"e": 6784,
"s": 6583,
"text": "enumerate() - is one of the built-in Python functions. It returns an enumerated object. In our case, that object is a list of tuples (immutable lists), each containing a pair of count/index and value."
},
{
"code": null,
"e": 6793,
"s": 6784,
"text": "Output: "
},
{
"code": null,
"e": 6887,
"s": 6793,
"text": "PART (5/5): Cartographic View In this last part, we are going to track the Birds over a map. "
},
{
"code": null,
"e": 6894,
"s": 6887,
"text": "Python"
},
{
"code": "import pandas as pdimport cartopy.crs as ccrsimport cartopy.feature as cfeatureimport matplotlib.pyplot as plt birddata = pd.read_csv(\"bird_tracking.csv\")bird_names = pd.unique(birddata.bird_name) # To move forward, we need to specify a# specific projection that we're interested# in using.proj = ccrs.Mercator() plt.figure(figsize=(10,10))ax = plt.axes(projection=proj)ax.set_extent((-25.0, 20.0, 52.0, 10.0))ax.add_feature(cfeature.LAND)ax.add_feature(cfeature.OCEAN)ax.add_feature(cfeature.COASTLINE)ax.add_feature(cfeature.BORDERS, linestyle=':')for name in bird_names: ix = birddata['bird_name'] == name x,y = birddata.longitude[ix], birddata.latitude[ix] ax.plot(x,y,'.', transform=ccrs.Geodetic(), label=name)plt.legend(loc=\"upper left\")plt.show()",
"e": 7658,
"s": 6894,
"text": null
},
{
"code": null,
"e": 7720,
"s": 7658,
"text": "import cartopy.crs as ccrs\nimport cartopy.feature as cfeature"
},
{
"code": null,
"e": 7766,
"s": 7720,
"text": "These modules are important for mapping data."
},
{
"code": null,
"e": 7910,
"s": 7766,
"text": "ax.add_feature(cfeature.LAND)\nax.add_feature(cfeature.OCEAN)\nax.add_feature(cfeature.COASTLINE)\nax.add_feature(cfeature.BORDERS, linestyle=':')"
},
{
"code": null,
"e": 7957,
"s": 7910,
"text": "We add the salient physical features of a map."
},
{
"code": null,
"e": 7966,
"s": 7957,
"text": "Output: "
},
{
"code": null,
"e": 8077,
"s": 7966,
"text": "Resources : 1. edX – HarvardX – Using Python for Research 2. Python functions doc_I 3. Python functions doc_II"
},
{
"code": null,
"e": 8507,
"s": 8077,
"text": "This article is contributed by Amartya Ranjan Saikia. 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": 8528,
"s": 8507,
"text": "ddeevviissaavviittaa"
},
{
"code": null,
"e": 8541,
"s": 8528,
"text": "simmytarika5"
},
{
"code": null,
"e": 8557,
"s": 8541,
"text": "Python-projects"
},
{
"code": null,
"e": 8572,
"s": 8557,
"text": "python-utility"
},
{
"code": null,
"e": 8580,
"s": 8572,
"text": "Project"
},
{
"code": null,
"e": 8587,
"s": 8580,
"text": "Python"
},
{
"code": null,
"e": 8685,
"s": 8587,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8734,
"s": 8685,
"text": "10 Best Web Development Projects For Your Resume"
},
{
"code": null,
"e": 8767,
"s": 8734,
"text": "A Group chat application in Java"
},
{
"code": null,
"e": 8805,
"s": 8767,
"text": "Student Information Management System"
},
{
"code": null,
"e": 8856,
"s": 8805,
"text": "Face Detection using Python and OpenCV with webcam"
},
{
"code": null,
"e": 8888,
"s": 8856,
"text": "E-commerce Website using Django"
},
{
"code": null,
"e": 8916,
"s": 8888,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 8966,
"s": 8916,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 8988,
"s": 8966,
"text": "Python map() function"
}
] |
Working with IP Addresses in Python
|
18 Aug, 2021
IP (Internet Protocol) -Address is the basic fundamental concept of computer networks which provides the address assigning capabilities to a network. Python provides ipaddress module which is used to validate and categorize the IP address according to their types(IPv4 or IPv6). This module is also used for performing wide range of operation like arithmetic, comparison, etc to manipulate the IP addresses.
For validating IP addresses python uses ip_address() function provided by the ipaddress module which raises error if values of IP exceeds the range of the type of the IP address.
IPv4 : It is a 32-bit number typically written in decimal digits formatted as four 8-bit numbers separated by dots, is used to identify the network interface of a machine. The ip_address() function throws an error if the range value exceeds from 0 to 255.
Python3
# Import moduleimport ipaddress # Example of valid IPv4 addressprint (ipaddress.ip_address(u'175.198.42.211')) # Invalid IPv4 address raises errorprint (ipaddress.ip_address(u'175.198.42.270'))
Output :
175.198.42.211
ValueError: ‘175.198.42.270’ does not appear to be an IPv4 or IPv6 address
IPv6 : It is represented by eight groups of four hexadecimal digits separated by colons, where each group represents 16 bits, two octets also known as hextet. The ip_address() function throws an error if the range value exceeds from 0 to FFFF.
Python3
# Import moduleimport ipaddress # Example of valid IPv6 addressprint (ipaddress.ip_address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334')) # Invalid IPv6 address raises errorprint (ipaddress.ip_address(u'2001:0db8:85a3:0ff0:00000:8a2e:0370:7334'))
Output :
2001:db8:85a3:2bfe:70d:8a2e:370:7334
ValueError: ‘2001:0db8:85a3:0ff0:00000:8a2e:0370:7334’ does not appear to be an IPv4 or IPv6 address
Various operations like arithmetic, comparison, type, etc can be performed on the IP addresses with the help of ipaddress module. Some operations are listed below:
Type Check operation: The type() method takes various formats of IP addresses as input and recognizes whether it is IPv4 or IPv6 address, indicating the category of the IP address.
Python3
# Import moduleimport ipaddress # IPv4 addressprint(type(ipaddress.ip_address(u'175.198.42.211')))print(type(ipaddress.ip_address(u'5.0.0.1'))) # IPv6 addressprint(type(ipaddress.ip_address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334')))print(type(ipaddress.ip_address(u'0000:f0f0::7b8a:ffff')))
Output :
<class ‘ipaddress.IPv4Address’>
<class ‘ipaddress.IPv4Address’>
<class ‘ipaddress.IPv6Address’>
<class ‘ipaddress.IPv6Address’>
IP Comparison Operations : The basic logical operators can be used to compare the IP addresses, whether one value is equal or greater or less than the other.
Python3
# Import moduleimport ipaddress # Comparisonprint(ipaddress.IPv4Address(u'175.199.42.211') > ipaddress.IPv4Address(u'175.198.42.255')) print(ipaddress.IPv6Address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334') == ipaddress.IPv6Address(u'2001:0dff:85a3:2bfe:070d:8a2e:0370:7334')) print(ipaddress.IPv4Address(u'179.198.42.211') != ipaddress.IPv4Address(u'175.198.42.255')) print(ipaddress.IPv6Address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334') < ipaddress.IPv6Address(u'2001:0dff:85a3:2bfe:070d:8a2e:0370:7334'))
Output :
True
False
True
True
Arithmetic Operations: IP Addresses can be manipulated by performing some arithmetic operations. Integers can be added or subtracted from the IP addresses. Under addition if value of last octet exceeds 255 then previous octet is incremented and so on, same in the case of subtraction if the value of the last octet becomes less than zero, then the previous octet is decremented, and so on.
Python3
# Import moduleimport ipaddress # Arithmetic Operation on IPv4 addressprint(ipaddress.IPv4Address(u'129.117.0.0')-6)print (ipaddress.IPv4Address(u'175.199.42.211')+55)print (ipaddress.IPv4Address(u'0.0.0.0')-1)print (ipaddress.IPv4Address(u'255.255.255.255')+1) # Arithmetic Operation on IPv6 addressprint (ipaddress.IPv6Address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334')-330)print (ipaddress.IPv6Address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334')+1000)print (ipaddress.IPv6Address(u'0000::0000')-1)print (ipaddress.IPv6Address(u'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff')+1)
Output :
129.116.255.250
175.199.43.10
AddressValueError: -1 (< 0) is not permitted as an IPv4 address
AddressValueError: 4294967296 (>= 2**32) is not permitted as an IPv4 address
2001:db8:85a3:2bfe:70d:8a2e:370:71ea
2001:db8:85a3:2bfe:70d:8a2e:370:771c
AddressValueError: -1 (< 0) is not permitted as an IPv6 address
AddressValueError: 340282366920938463463374607431768211456 (>= 2**128) is not permitted as an IPv6 address
arorakashish0911
Python-Networking
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 436,
"s": 28,
"text": "IP (Internet Protocol) -Address is the basic fundamental concept of computer networks which provides the address assigning capabilities to a network. Python provides ipaddress module which is used to validate and categorize the IP address according to their types(IPv4 or IPv6). This module is also used for performing wide range of operation like arithmetic, comparison, etc to manipulate the IP addresses."
},
{
"code": null,
"e": 615,
"s": 436,
"text": "For validating IP addresses python uses ip_address() function provided by the ipaddress module which raises error if values of IP exceeds the range of the type of the IP address."
},
{
"code": null,
"e": 871,
"s": 615,
"text": "IPv4 : It is a 32-bit number typically written in decimal digits formatted as four 8-bit numbers separated by dots, is used to identify the network interface of a machine. The ip_address() function throws an error if the range value exceeds from 0 to 255."
},
{
"code": null,
"e": 879,
"s": 871,
"text": "Python3"
},
{
"code": "# Import moduleimport ipaddress # Example of valid IPv4 addressprint (ipaddress.ip_address(u'175.198.42.211')) # Invalid IPv4 address raises errorprint (ipaddress.ip_address(u'175.198.42.270'))",
"e": 1073,
"s": 879,
"text": null
},
{
"code": null,
"e": 1083,
"s": 1073,
"text": "Output : "
},
{
"code": null,
"e": 1099,
"s": 1083,
"text": "175.198.42.211 "
},
{
"code": null,
"e": 1175,
"s": 1099,
"text": "ValueError: ‘175.198.42.270’ does not appear to be an IPv4 or IPv6 address "
},
{
"code": null,
"e": 1419,
"s": 1175,
"text": "IPv6 : It is represented by eight groups of four hexadecimal digits separated by colons, where each group represents 16 bits, two octets also known as hextet. The ip_address() function throws an error if the range value exceeds from 0 to FFFF."
},
{
"code": null,
"e": 1427,
"s": 1419,
"text": "Python3"
},
{
"code": "# Import moduleimport ipaddress # Example of valid IPv6 addressprint (ipaddress.ip_address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334')) # Invalid IPv6 address raises errorprint (ipaddress.ip_address(u'2001:0db8:85a3:0ff0:00000:8a2e:0370:7334'))",
"e": 1672,
"s": 1427,
"text": null
},
{
"code": null,
"e": 1682,
"s": 1672,
"text": "Output : "
},
{
"code": null,
"e": 1720,
"s": 1682,
"text": "2001:db8:85a3:2bfe:70d:8a2e:370:7334 "
},
{
"code": null,
"e": 1822,
"s": 1720,
"text": "ValueError: ‘2001:0db8:85a3:0ff0:00000:8a2e:0370:7334’ does not appear to be an IPv4 or IPv6 address "
},
{
"code": null,
"e": 1987,
"s": 1822,
"text": "Various operations like arithmetic, comparison, type, etc can be performed on the IP addresses with the help of ipaddress module. Some operations are listed below: "
},
{
"code": null,
"e": 2168,
"s": 1987,
"text": "Type Check operation: The type() method takes various formats of IP addresses as input and recognizes whether it is IPv4 or IPv6 address, indicating the category of the IP address."
},
{
"code": null,
"e": 2176,
"s": 2168,
"text": "Python3"
},
{
"code": "# Import moduleimport ipaddress # IPv4 addressprint(type(ipaddress.ip_address(u'175.198.42.211')))print(type(ipaddress.ip_address(u'5.0.0.1'))) # IPv6 addressprint(type(ipaddress.ip_address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334')))print(type(ipaddress.ip_address(u'0000:f0f0::7b8a:ffff')))",
"e": 2470,
"s": 2176,
"text": null
},
{
"code": null,
"e": 2480,
"s": 2470,
"text": "Output : "
},
{
"code": null,
"e": 2513,
"s": 2480,
"text": "<class ‘ipaddress.IPv4Address’> "
},
{
"code": null,
"e": 2546,
"s": 2513,
"text": "<class ‘ipaddress.IPv4Address’> "
},
{
"code": null,
"e": 2579,
"s": 2546,
"text": "<class ‘ipaddress.IPv6Address’> "
},
{
"code": null,
"e": 2612,
"s": 2579,
"text": "<class ‘ipaddress.IPv6Address’> "
},
{
"code": null,
"e": 2770,
"s": 2612,
"text": "IP Comparison Operations : The basic logical operators can be used to compare the IP addresses, whether one value is equal or greater or less than the other."
},
{
"code": null,
"e": 2778,
"s": 2770,
"text": "Python3"
},
{
"code": "# Import moduleimport ipaddress # Comparisonprint(ipaddress.IPv4Address(u'175.199.42.211') > ipaddress.IPv4Address(u'175.198.42.255')) print(ipaddress.IPv6Address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334') == ipaddress.IPv6Address(u'2001:0dff:85a3:2bfe:070d:8a2e:0370:7334')) print(ipaddress.IPv4Address(u'179.198.42.211') != ipaddress.IPv4Address(u'175.198.42.255')) print(ipaddress.IPv6Address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334') < ipaddress.IPv6Address(u'2001:0dff:85a3:2bfe:070d:8a2e:0370:7334'))",
"e": 3308,
"s": 2778,
"text": null
},
{
"code": null,
"e": 3317,
"s": 3308,
"text": "Output :"
},
{
"code": null,
"e": 3323,
"s": 3317,
"text": "True "
},
{
"code": null,
"e": 3330,
"s": 3323,
"text": "False "
},
{
"code": null,
"e": 3336,
"s": 3330,
"text": "True "
},
{
"code": null,
"e": 3342,
"s": 3336,
"text": "True "
},
{
"code": null,
"e": 3732,
"s": 3342,
"text": "Arithmetic Operations: IP Addresses can be manipulated by performing some arithmetic operations. Integers can be added or subtracted from the IP addresses. Under addition if value of last octet exceeds 255 then previous octet is incremented and so on, same in the case of subtraction if the value of the last octet becomes less than zero, then the previous octet is decremented, and so on."
},
{
"code": null,
"e": 3740,
"s": 3732,
"text": "Python3"
},
{
"code": "# Import moduleimport ipaddress # Arithmetic Operation on IPv4 addressprint(ipaddress.IPv4Address(u'129.117.0.0')-6)print (ipaddress.IPv4Address(u'175.199.42.211')+55)print (ipaddress.IPv4Address(u'0.0.0.0')-1)print (ipaddress.IPv4Address(u'255.255.255.255')+1) # Arithmetic Operation on IPv6 addressprint (ipaddress.IPv6Address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334')-330)print (ipaddress.IPv6Address(u'2001:0db8:85a3:2bfe:070d:8a2e:0370:7334')+1000)print (ipaddress.IPv6Address(u'0000::0000')-1)print (ipaddress.IPv6Address(u'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff')+1)",
"e": 4317,
"s": 3740,
"text": null
},
{
"code": null,
"e": 4327,
"s": 4317,
"text": "Output : "
},
{
"code": null,
"e": 4344,
"s": 4327,
"text": "129.116.255.250 "
},
{
"code": null,
"e": 4359,
"s": 4344,
"text": "175.199.43.10 "
},
{
"code": null,
"e": 4423,
"s": 4359,
"text": "AddressValueError: -1 (< 0) is not permitted as an IPv4 address"
},
{
"code": null,
"e": 4502,
"s": 4423,
"text": " AddressValueError: 4294967296 (>= 2**32) is not permitted as an IPv4 address "
},
{
"code": null,
"e": 4540,
"s": 4502,
"text": "2001:db8:85a3:2bfe:70d:8a2e:370:71ea "
},
{
"code": null,
"e": 4578,
"s": 4540,
"text": "2001:db8:85a3:2bfe:70d:8a2e:370:771c "
},
{
"code": null,
"e": 4643,
"s": 4578,
"text": "AddressValueError: -1 (< 0) is not permitted as an IPv6 address "
},
{
"code": null,
"e": 4751,
"s": 4643,
"text": "AddressValueError: 340282366920938463463374607431768211456 (>= 2**128) is not permitted as an IPv6 address "
},
{
"code": null,
"e": 4770,
"s": 4753,
"text": "arorakashish0911"
},
{
"code": null,
"e": 4788,
"s": 4770,
"text": "Python-Networking"
},
{
"code": null,
"e": 4795,
"s": 4788,
"text": "Python"
},
{
"code": null,
"e": 4893,
"s": 4795,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4925,
"s": 4893,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4952,
"s": 4925,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4973,
"s": 4952,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4996,
"s": 4973,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 5052,
"s": 4996,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 5083,
"s": 5052,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 5125,
"s": 5083,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 5167,
"s": 5125,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 5206,
"s": 5167,
"text": "Python | datetime.timedelta() function"
}
] |
Temperature Converter using Tkinter
|
20 Jan, 2022
Prerequisites: Python GUI – tkinterPython Tkinter is a GUI programming package or built-in library. Tkinter provides the Tk GUI toolkit with a potent object-oriented interface. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.Approach:
Importing the module – tkinter, functools from partial
Create the main window
Add number of widgets to the main window:Button, Entry, Label
Displaying message
Apply the event trigger on the widgets.
Below is the implementation.
python3
import tkinter as tkfrom tkinter import messageboxfrom functools import partial # Declaration of global variabletemp_Val = "Celsius" # getting drop down valuedef store_temp(set_temp): global temp_Val temp_Val = set_temp # Conversion of temperaturedef call_convert(rlabel1, inputn): temp = inputn.get() if temp_Val == 'Celsius': # Conversion of celsius temperature to fahrenheit f = float((float(temp) * 9 / 5) + 32) rlabel1.config(text ="%.1f Fahrenheit" % f) messagebox.showinfo("Temperature Converter", "Successfully converted to Fahrenheit ", ) if temp_Val == 'Fahrenheit': # Conversion of fahrenheit temperature # to celsius c = float((float(temp) - 32) * 5 / 9) rlabel1.config(text ="%.1f Celsius" % c) messagebox.showinfo("Temperature Converter", "Successfully converted to Celsius ") return # creating Tk windowroot = tk.Tk() # setting geometry of tk windowroot.geometry('300x150 + 600 + 200') # Using title() to display a message in the# dialogue box of the message in the title barroot.title('Temperature Converter') # Lay out widgetsroot.grid_columnconfigure(1, weight = 1)root.grid_rowconfigure(1, weight = 1) inputNumber = tk.StringVar()var = tk.StringVar() # label and entry fieldinput_label = tk.Label(root, text ="Enter temperature")input_entry = tk.Entry(root, textvariable = inputNumber)input_label.grid(row = 1)input_entry.grid(row = 1, column = 1)result_label = tk.Label(root)result_label.grid(row = 3, columnspan = 4) # drop down setupdropDownList = ["Celsius", "Fahrenheit"]drop_down = tk.OptionMenu(root, var, *dropDownList, command = store_temp)var.set(dropDownList[0])drop_down.grid(row = 1, column = 2) # button widgetcall_convert = partial(call_convert, result_label, inputNumber)result_button = tk.Button(root, text ="Convert", command = call_convert)result_button.grid(row = 2, columnspan = 2) # infinite loop which is required to# run tkinter program infinitely# until an interrupt occursroot.mainloop()
Output:
sumitgumber28
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 341,
"s": 28,
"text": "Prerequisites: Python GUI – tkinterPython Tkinter is a GUI programming package or built-in library. Tkinter provides the Tk GUI toolkit with a potent object-oriented interface. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.Approach: "
},
{
"code": null,
"e": 396,
"s": 341,
"text": "Importing the module – tkinter, functools from partial"
},
{
"code": null,
"e": 419,
"s": 396,
"text": "Create the main window"
},
{
"code": null,
"e": 481,
"s": 419,
"text": "Add number of widgets to the main window:Button, Entry, Label"
},
{
"code": null,
"e": 500,
"s": 481,
"text": "Displaying message"
},
{
"code": null,
"e": 540,
"s": 500,
"text": "Apply the event trigger on the widgets."
},
{
"code": null,
"e": 571,
"s": 540,
"text": "Below is the implementation. "
},
{
"code": null,
"e": 579,
"s": 571,
"text": "python3"
},
{
"code": "import tkinter as tkfrom tkinter import messageboxfrom functools import partial # Declaration of global variabletemp_Val = \"Celsius\" # getting drop down valuedef store_temp(set_temp): global temp_Val temp_Val = set_temp # Conversion of temperaturedef call_convert(rlabel1, inputn): temp = inputn.get() if temp_Val == 'Celsius': # Conversion of celsius temperature to fahrenheit f = float((float(temp) * 9 / 5) + 32) rlabel1.config(text =\"%.1f Fahrenheit\" % f) messagebox.showinfo(\"Temperature Converter\", \"Successfully converted to Fahrenheit \", ) if temp_Val == 'Fahrenheit': # Conversion of fahrenheit temperature # to celsius c = float((float(temp) - 32) * 5 / 9) rlabel1.config(text =\"%.1f Celsius\" % c) messagebox.showinfo(\"Temperature Converter\", \"Successfully converted to Celsius \") return # creating Tk windowroot = tk.Tk() # setting geometry of tk windowroot.geometry('300x150 + 600 + 200') # Using title() to display a message in the# dialogue box of the message in the title barroot.title('Temperature Converter') # Lay out widgetsroot.grid_columnconfigure(1, weight = 1)root.grid_rowconfigure(1, weight = 1) inputNumber = tk.StringVar()var = tk.StringVar() # label and entry fieldinput_label = tk.Label(root, text =\"Enter temperature\")input_entry = tk.Entry(root, textvariable = inputNumber)input_label.grid(row = 1)input_entry.grid(row = 1, column = 1)result_label = tk.Label(root)result_label.grid(row = 3, columnspan = 4) # drop down setupdropDownList = [\"Celsius\", \"Fahrenheit\"]drop_down = tk.OptionMenu(root, var, *dropDownList, command = store_temp)var.set(dropDownList[0])drop_down.grid(row = 1, column = 2) # button widgetcall_convert = partial(call_convert, result_label, inputNumber)result_button = tk.Button(root, text =\"Convert\", command = call_convert)result_button.grid(row = 2, columnspan = 2) # infinite loop which is required to# run tkinter program infinitely# until an interrupt occursroot.mainloop()",
"e": 2755,
"s": 579,
"text": null
},
{
"code": null,
"e": 2764,
"s": 2755,
"text": "Output: "
},
{
"code": null,
"e": 2780,
"s": 2766,
"text": "sumitgumber28"
},
{
"code": null,
"e": 2805,
"s": 2780,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 2820,
"s": 2805,
"text": "Python-tkinter"
},
{
"code": null,
"e": 2827,
"s": 2820,
"text": "Python"
},
{
"code": null,
"e": 2925,
"s": 2827,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2970,
"s": 2925,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 3020,
"s": 2970,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 3036,
"s": 3020,
"text": "Deque in Python"
},
{
"code": null,
"e": 3052,
"s": 3036,
"text": "Queue in Python"
},
{
"code": null,
"e": 3074,
"s": 3052,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3116,
"s": 3074,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3143,
"s": 3116,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3166,
"s": 3143,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 3185,
"s": 3166,
"text": "reduce() in Python"
}
] |
system() in C/C++
|
29 May, 2017
system() is used to invoke an operating system command from a C/C++ program.
int system(const char *command);
Note: stdlib.h or cstdlib needs to be included to call system.
Using system(), we can execute any command that can run on terminal if operating system allows. For example, we can call system(“dir”) on Windows and system(“ls”) to list contents of a directory.
Writing a C/C++ program that compiles and runs other program?We can invoke gcc from our program using system(). See below code written for Linux. We can easily change code to run on windows.
// A C++ program that compiles and runs another C++ // program#include <bits/stdc++.h>using namespace std;int main (){ char filename[100]; cout << "Enter file name to compile "; cin.getline(filename, 100); // Build command to execute. For example if the input // file name is a.cpp, then str holds "gcc -o a.out a.cpp" // Here -o is used to specify executable file name string str = "gcc "; str = str + " -o a.out " + filename; // Convert string to const char * as system requires // parameter of type const char * const char *command = str.c_str(); cout << "Compiling file using " << command << endl; system(command); cout << "\nRunning file "; system("./a.out"); return 0;}
system() vs using library functions:Some common uses of system() in Windows OS are, system(“pause”) which is used to execute pause command and make the screen/terminal wait for a key press, and system(“cls”) which is used to make the screen/terminal clear.
However, making a call to system command should be avoided due to the following reasons:
It’s a very expensive and resource heavy function callIt’s not portable: Using system() makes the program very non-portable i.e. this works only on systems that have the pause command at the system level, like DOS or Windows. But not Linux, MAC OSX and most others.
It’s a very expensive and resource heavy function call
It’s not portable: Using system() makes the program very non-portable i.e. this works only on systems that have the pause command at the system level, like DOS or Windows. But not Linux, MAC OSX and most others.
Let us take a simple C++ code to output Hello World using system(“pause”):
// A C++ program that pauses screen at the end in Windows OS#include <iostream>using namespace std;int main (){ cout << "Hello World!" << endl; system("pause"); return 0;}
The output of the above program in Windows OS:
Hello World!
Press any key to continue...
This program is OS dependent and uses following heavy steps.
It suspends your program and simultaneously calls the operating system to opens the operating system shell.
The OS finds the pause and allocate the memory to execute the command.
It then deallocate the memory, exit the Operating System and resumes the program.
Instead of using the system(“pause”), we can also use the functions that are defined natively in C/C++.
Let us take a simple example to output Hello World with cin.get():
// Replacing system() with library function#include <iostream>#include <cstdlib>using namespace std;int main (){ cout << "Hello World!" << endl; cin.get(); // or getchar() return 0;}
The output of the program is :
Hello World!
Thus, we see that, both system(“pause”) and cin.get() are actually performing a wait for a key to be pressed, but, cin.get() is not OS dependent and neither it follows the above mentioned steps to pause the program.Similarly, in C language, getchar() can be used to pause the program without printing the message “Press any key to continue...”.
A common way to check if we can run commands using system() in an OS?If we pass null pointer in place of string for command parameter, system returns nonzero if command processor exists (or system can run). Otherwise returns 0.
// C++ program to check if we can run commands using // system()#include <iostream>#include <cstdlib>using namespace std;int main (){ if (system(NULL)) cout << "Command processor exists"; else cout << "Command processor doesn't exists"; return 0;}
Note that the above programs may not work on online compiler as System command is disabled in most of the online compilers including GeeksforGeeks IDE.
This article is contributed by Subhankar Das. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 May, 2017"
},
{
"code": null,
"e": 129,
"s": 52,
"text": "system() is used to invoke an operating system command from a C/C++ program."
},
{
"code": null,
"e": 167,
"s": 129,
"text": " int system(const char *command);\n"
},
{
"code": null,
"e": 230,
"s": 167,
"text": "Note: stdlib.h or cstdlib needs to be included to call system."
},
{
"code": null,
"e": 426,
"s": 230,
"text": "Using system(), we can execute any command that can run on terminal if operating system allows. For example, we can call system(“dir”) on Windows and system(“ls”) to list contents of a directory."
},
{
"code": null,
"e": 617,
"s": 426,
"text": "Writing a C/C++ program that compiles and runs other program?We can invoke gcc from our program using system(). See below code written for Linux. We can easily change code to run on windows."
},
{
"code": "// A C++ program that compiles and runs another C++ // program#include <bits/stdc++.h>using namespace std;int main (){ char filename[100]; cout << \"Enter file name to compile \"; cin.getline(filename, 100); // Build command to execute. For example if the input // file name is a.cpp, then str holds \"gcc -o a.out a.cpp\" // Here -o is used to specify executable file name string str = \"gcc \"; str = str + \" -o a.out \" + filename; // Convert string to const char * as system requires // parameter of type const char * const char *command = str.c_str(); cout << \"Compiling file using \" << command << endl; system(command); cout << \"\\nRunning file \"; system(\"./a.out\"); return 0;}",
"e": 1353,
"s": 617,
"text": null
},
{
"code": null,
"e": 1610,
"s": 1353,
"text": "system() vs using library functions:Some common uses of system() in Windows OS are, system(“pause”) which is used to execute pause command and make the screen/terminal wait for a key press, and system(“cls”) which is used to make the screen/terminal clear."
},
{
"code": null,
"e": 1699,
"s": 1610,
"text": "However, making a call to system command should be avoided due to the following reasons:"
},
{
"code": null,
"e": 1965,
"s": 1699,
"text": "It’s a very expensive and resource heavy function callIt’s not portable: Using system() makes the program very non-portable i.e. this works only on systems that have the pause command at the system level, like DOS or Windows. But not Linux, MAC OSX and most others."
},
{
"code": null,
"e": 2020,
"s": 1965,
"text": "It’s a very expensive and resource heavy function call"
},
{
"code": null,
"e": 2232,
"s": 2020,
"text": "It’s not portable: Using system() makes the program very non-portable i.e. this works only on systems that have the pause command at the system level, like DOS or Windows. But not Linux, MAC OSX and most others."
},
{
"code": null,
"e": 2307,
"s": 2232,
"text": "Let us take a simple C++ code to output Hello World using system(“pause”):"
},
{
"code": "// A C++ program that pauses screen at the end in Windows OS#include <iostream>using namespace std;int main (){ cout << \"Hello World!\" << endl; system(\"pause\"); return 0;}",
"e": 2488,
"s": 2307,
"text": null
},
{
"code": null,
"e": 2535,
"s": 2488,
"text": "The output of the above program in Windows OS:"
},
{
"code": null,
"e": 2577,
"s": 2535,
"text": "Hello World!\nPress any key to continue..."
},
{
"code": null,
"e": 2638,
"s": 2577,
"text": "This program is OS dependent and uses following heavy steps."
},
{
"code": null,
"e": 2746,
"s": 2638,
"text": "It suspends your program and simultaneously calls the operating system to opens the operating system shell."
},
{
"code": null,
"e": 2817,
"s": 2746,
"text": "The OS finds the pause and allocate the memory to execute the command."
},
{
"code": null,
"e": 2899,
"s": 2817,
"text": "It then deallocate the memory, exit the Operating System and resumes the program."
},
{
"code": null,
"e": 3003,
"s": 2899,
"text": "Instead of using the system(“pause”), we can also use the functions that are defined natively in C/C++."
},
{
"code": null,
"e": 3070,
"s": 3003,
"text": "Let us take a simple example to output Hello World with cin.get():"
},
{
"code": "// Replacing system() with library function#include <iostream>#include <cstdlib>using namespace std;int main (){ cout << \"Hello World!\" << endl; cin.get(); // or getchar() return 0;}",
"e": 3263,
"s": 3070,
"text": null
},
{
"code": null,
"e": 3294,
"s": 3263,
"text": "The output of the program is :"
},
{
"code": null,
"e": 3308,
"s": 3294,
"text": " Hello World!"
},
{
"code": null,
"e": 3653,
"s": 3308,
"text": "Thus, we see that, both system(“pause”) and cin.get() are actually performing a wait for a key to be pressed, but, cin.get() is not OS dependent and neither it follows the above mentioned steps to pause the program.Similarly, in C language, getchar() can be used to pause the program without printing the message “Press any key to continue...”."
},
{
"code": null,
"e": 3881,
"s": 3653,
"text": "A common way to check if we can run commands using system() in an OS?If we pass null pointer in place of string for command parameter, system returns nonzero if command processor exists (or system can run). Otherwise returns 0."
},
{
"code": "// C++ program to check if we can run commands using // system()#include <iostream>#include <cstdlib>using namespace std;int main (){ if (system(NULL)) cout << \"Command processor exists\"; else cout << \"Command processor doesn't exists\"; return 0;}",
"e": 4152,
"s": 3881,
"text": null
},
{
"code": null,
"e": 4304,
"s": 4152,
"text": "Note that the above programs may not work on online compiler as System command is disabled in most of the online compilers including GeeksforGeeks IDE."
},
{
"code": null,
"e": 4571,
"s": 4304,
"text": "This article is contributed by Subhankar Das. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4696,
"s": 4571,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4708,
"s": 4696,
"text": "CPP-Library"
},
{
"code": null,
"e": 4719,
"s": 4708,
"text": "C Language"
},
{
"code": null,
"e": 4723,
"s": 4719,
"text": "C++"
},
{
"code": null,
"e": 4727,
"s": 4723,
"text": "CPP"
},
{
"code": null,
"e": 4825,
"s": 4727,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4842,
"s": 4825,
"text": "Substring in C++"
},
{
"code": null,
"e": 4864,
"s": 4842,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 4909,
"s": 4864,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 4934,
"s": 4909,
"text": "std::string class in C++"
},
{
"code": null,
"e": 4982,
"s": 4934,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 5000,
"s": 4982,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 5043,
"s": 5000,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5089,
"s": 5043,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 5132,
"s": 5089,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to Create a Basic Project using MVT in Django ?
|
16 Aug, 2021
Prerequisite – Django Project MVT Structure
Assuming you have gone through the previous article. This article focuses on creating a basic project to render a template using MVT architecture. We will use MVT (Models, Views, Templates) to render data to a local server.
Create a basic Project:
To initiate a project of Django on Your PC, open Terminal and Enter the following command
django-admin startproject projectName
A New Folder with the name projectName will be created. To enter in the project using the terminal enter command
cd projectName
Create a new file views.py inside the project folder where settings.py, urls.py and other files are stored and save the following code in it-
Python3
# HttpResponse is used to# pass the information# back to viewfrom django.http import HttpResponse # Defining a function which# will receive request and# perform task depending# upon function definitiondef hello_geek (request) : # This will return Hello Geeks # string as HttpResponse return HttpResponse("Hello Geeks")
Open urls.py inside project folder (projectName) and add your entry- Import hello_geek function from views.py file.
Import hello_geek function from views.py file.
from projectName.views import hello_geeks
Add an entry in url field inside url patterns-
path('geek/', hello_geek),
Now to run the server follow these steps- Open command prompt and change directory to env_site by this command-
Open command prompt and change directory to env_site by this command-
$ cd env_site
Go to Script directory inside env_site and activate virtual environment-
$ cd Script
$ activate
Return to the env_site directory and goto the project directory-
$ cd ..
$ cd geeks_site
Start the server- Start the server by typing following command in cmd-
$ python manage.py runserver
Checking – Open the browser and type this url-
http://127.0.0.1:8000/geek/
ddeevviissaavviittaa
Django-basics
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 97,
"s": 52,
"text": "Prerequisite – Django Project MVT Structure "
},
{
"code": null,
"e": 322,
"s": 97,
"text": "Assuming you have gone through the previous article. This article focuses on creating a basic project to render a template using MVT architecture. We will use MVT (Models, Views, Templates) to render data to a local server. "
},
{
"code": null,
"e": 347,
"s": 322,
"text": "Create a basic Project: "
},
{
"code": null,
"e": 438,
"s": 347,
"text": "To initiate a project of Django on Your PC, open Terminal and Enter the following command "
},
{
"code": null,
"e": 476,
"s": 438,
"text": "django-admin startproject projectName"
},
{
"code": null,
"e": 590,
"s": 476,
"text": "A New Folder with the name projectName will be created. To enter in the project using the terminal enter command "
},
{
"code": null,
"e": 605,
"s": 590,
"text": "cd projectName"
},
{
"code": null,
"e": 748,
"s": 605,
"text": "Create a new file views.py inside the project folder where settings.py, urls.py and other files are stored and save the following code in it- "
},
{
"code": null,
"e": 756,
"s": 748,
"text": "Python3"
},
{
"code": "# HttpResponse is used to# pass the information# back to viewfrom django.http import HttpResponse # Defining a function which# will receive request and# perform task depending# upon function definitiondef hello_geek (request) : # This will return Hello Geeks # string as HttpResponse return HttpResponse(\"Hello Geeks\")",
"e": 1085,
"s": 756,
"text": null
},
{
"code": null,
"e": 1202,
"s": 1085,
"text": "Open urls.py inside project folder (projectName) and add your entry- Import hello_geek function from views.py file. "
},
{
"code": null,
"e": 1250,
"s": 1202,
"text": "Import hello_geek function from views.py file. "
},
{
"code": null,
"e": 1292,
"s": 1250,
"text": "from projectName.views import hello_geeks"
},
{
"code": null,
"e": 1340,
"s": 1292,
"text": "Add an entry in url field inside url patterns- "
},
{
"code": null,
"e": 1369,
"s": 1340,
"text": "path('geek/', hello_geek), \n"
},
{
"code": null,
"e": 1482,
"s": 1369,
"text": "Now to run the server follow these steps- Open command prompt and change directory to env_site by this command- "
},
{
"code": null,
"e": 1553,
"s": 1482,
"text": "Open command prompt and change directory to env_site by this command- "
},
{
"code": null,
"e": 1567,
"s": 1553,
"text": "$ cd env_site"
},
{
"code": null,
"e": 1641,
"s": 1567,
"text": "Go to Script directory inside env_site and activate virtual environment- "
},
{
"code": null,
"e": 1653,
"s": 1641,
"text": "$ cd Script"
},
{
"code": null,
"e": 1664,
"s": 1653,
"text": "$ activate"
},
{
"code": null,
"e": 1730,
"s": 1664,
"text": "Return to the env_site directory and goto the project directory- "
},
{
"code": null,
"e": 1738,
"s": 1730,
"text": "$ cd .."
},
{
"code": null,
"e": 1754,
"s": 1738,
"text": "$ cd geeks_site"
},
{
"code": null,
"e": 1826,
"s": 1754,
"text": "Start the server- Start the server by typing following command in cmd- "
},
{
"code": null,
"e": 1855,
"s": 1826,
"text": "$ python manage.py runserver"
},
{
"code": null,
"e": 1903,
"s": 1855,
"text": "Checking – Open the browser and type this url- "
},
{
"code": null,
"e": 1931,
"s": 1903,
"text": "http://127.0.0.1:8000/geek/"
},
{
"code": null,
"e": 1952,
"s": 1931,
"text": "ddeevviissaavviittaa"
},
{
"code": null,
"e": 1966,
"s": 1952,
"text": "Django-basics"
},
{
"code": null,
"e": 1980,
"s": 1966,
"text": "Python Django"
},
{
"code": null,
"e": 1987,
"s": 1980,
"text": "Python"
},
{
"code": null,
"e": 2085,
"s": 1987,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2113,
"s": 2085,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2163,
"s": 2113,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2185,
"s": 2163,
"text": "Python map() function"
},
{
"code": null,
"e": 2229,
"s": 2185,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 2271,
"s": 2229,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2293,
"s": 2271,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2328,
"s": 2293,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2354,
"s": 2328,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2386,
"s": 2354,
"text": "How to Install PIP on Windows ?"
}
] |
Python | Pair iteration in list
|
22 Jan, 2019
List iteration is common in programming, but sometimes one requires to print the elements in consecutive pairs. This particular problem is quite common and having a solution to it always turns out to be handy. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehensionList comprehension can be used to print the pairs by accessing current and next element in the list and then printing the same. Care has to be taken while pairing the last element with the first one to form a cyclic pair.
# Python3 code to demonstrate # pair iteration in list # using list comprehensionfrom itertools import compress # initializing list test_list = [0, 1, 2, 3, 4, 5] # printing original listprint ("The original list is : " + str(test_list)) # using list comprehension# to perform pair iteration in list res = [((i), (i + 1) % len(test_list)) for i in range(len(test_list))] # printing resultprint ("The pair list is : " + str(res))
The original list is : [0, 1, 2, 3, 4, 5]
The pair list is : [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)]
Method #2 : Using zip() + list slicing
zip function can be used to extract pairs over the list and slicing can be used to successively pair the current element with the next one for the efficient pairing.
# Python3 code to demonstrate # pair iteration in list # using zip() + list slicing from itertools import compress # initializing list test_list = [0, 1, 2, 3, 4, 5] # printing original listprint ("The original list is : " + str(test_list)) # using zip() + list slicing # to perform pair iteration in list res = list(zip(test_list, test_list[1:] + test_list[:1])) # printing resultprint ("The pair list is : " + str(res))
The original list is : [0, 1, 2, 3, 4, 5]
The pair list is : [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)]
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jan, 2019"
},
{
"code": null,
"e": 328,
"s": 54,
"text": "List iteration is common in programming, but sometimes one requires to print the elements in consecutive pairs. This particular problem is quite common and having a solution to it always turns out to be handy. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 586,
"s": 328,
"text": "Method #1 : Using list comprehensionList comprehension can be used to print the pairs by accessing current and next element in the list and then printing the same. Care has to be taken while pairing the last element with the first one to form a cyclic pair."
},
{
"code": "# Python3 code to demonstrate # pair iteration in list # using list comprehensionfrom itertools import compress # initializing list test_list = [0, 1, 2, 3, 4, 5] # printing original listprint (\"The original list is : \" + str(test_list)) # using list comprehension# to perform pair iteration in list res = [((i), (i + 1) % len(test_list)) for i in range(len(test_list))] # printing resultprint (\"The pair list is : \" + str(res))",
"e": 1029,
"s": 586,
"text": null
},
{
"code": null,
"e": 1140,
"s": 1029,
"text": "The original list is : [0, 1, 2, 3, 4, 5]\nThe pair list is : [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)]\n"
},
{
"code": null,
"e": 1180,
"s": 1140,
"text": " Method #2 : Using zip() + list slicing"
},
{
"code": null,
"e": 1346,
"s": 1180,
"text": "zip function can be used to extract pairs over the list and slicing can be used to successively pair the current element with the next one for the efficient pairing."
},
{
"code": "# Python3 code to demonstrate # pair iteration in list # using zip() + list slicing from itertools import compress # initializing list test_list = [0, 1, 2, 3, 4, 5] # printing original listprint (\"The original list is : \" + str(test_list)) # using zip() + list slicing # to perform pair iteration in list res = list(zip(test_list, test_list[1:] + test_list[:1])) # printing resultprint (\"The pair list is : \" + str(res))",
"e": 1773,
"s": 1346,
"text": null
},
{
"code": null,
"e": 1884,
"s": 1773,
"text": "The original list is : [0, 1, 2, 3, 4, 5]\nThe pair list is : [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)]\n"
},
{
"code": null,
"e": 1905,
"s": 1884,
"text": "Python list-programs"
},
{
"code": null,
"e": 1917,
"s": 1905,
"text": "python-list"
},
{
"code": null,
"e": 1924,
"s": 1917,
"text": "Python"
},
{
"code": null,
"e": 1940,
"s": 1924,
"text": "Python Programs"
},
{
"code": null,
"e": 1952,
"s": 1940,
"text": "python-list"
},
{
"code": null,
"e": 2050,
"s": 1952,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2068,
"s": 2050,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2110,
"s": 2068,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2132,
"s": 2110,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2167,
"s": 2132,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2193,
"s": 2167,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2236,
"s": 2193,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2258,
"s": 2236,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2297,
"s": 2258,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2335,
"s": 2297,
"text": "Python | Convert a list to dictionary"
}
] |
Program to find the Nth term of the series 3, 7, 13, 21, 31.....
|
07 Oct, 2021
Given a number N, the task is to find the Nth term of this series:
3, 7, 13, 21, 31, .......
Examples:
Input: N = 4
Output: 21
Explanation:
Nth term = (pow(N, 2) + N + 1)
= (pow(4, 2) + 4 + 1)
= 21
Input: N = 11
Output: 133
Approach:Subtracting these two equations we get Therefore, the Nth Term of the given series is:
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the Nth term of given series.#include <iostream>#include <math.h>using namespace std; // Function to calculate sumlong long int getNthTerm(long long int N){ // Return Nth term return (pow(N, 2) + N + 1);} // driver codeint main(){ // declaration of number of terms long long int N = 11; // Get the Nth term cout << getNthTerm(N); return 0;}
// Java code to find the Nth term of given series.import java.util.*; class solution{ // Function to calculate sumstatic long getNthTerm(long N){ // Return Nth term return ((int)Math.pow(N, 2) + N + 1);} //Driver programpublic static void main(String arr[]){ // declaration of number of terms long N = 11; // Get the Nth term System.out.println(getNthTerm(N)); }}//THis code is contributed by//Surendra_Gangwar
# Python3 Code to find the# Nth term of given series. # Function to calculate sumdef getNthTerm(N): # Return Nth term return (pow(N, 2) + N + 1) # driver codeif __name__=='__main__': # declaration of number of terms N = 11 # Get the Nth term print(getNthTerm(N)) # This code is contributed by# Sanjit_Prasad
// C# code to find the Nth// term of given series.using System; class GFG{ // Function to calculate sumstatic long getNthTerm(long N){ // Return Nth term return ((int)Math.Pow(N, 2) + N + 1);} // Driver Codestatic public void Main (){ // declaration of number // of terms long N = 11; // Get the Nth term Console.Write(getNthTerm(N));}} // This code is contributed by Raj
<?php// PHP program to find the// Nth term of given series // Function to calculate sumfunction getNthTerm($N){ // Return Nth term return (pow($N, 2) + $N + 1);} // Driver code // declaration of number of terms$N = 11; // Get the Nth termecho getNthTerm($N); // This code is contributed by Raj?>
<script>// JavaScript program to find the Nth term of given series. // Function to calculate sumfunction getNthTerm(N){ // Return Nth term return (Math.pow(N, 2) + N + 1);} // driver code // declaration of number of terms let N = 11; // Get the Nth term document.write(getNthTerm(N)); // This code is contributed by Surbhi Tyagi </script>
133
Time Complexity: O(1)
Sanjit_Prasad
SURENDRA_GANGWAR
R_Raj
surbhityagi15
surinderdawra388
ruhelaa48
series
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Sieve of Eratosthenes
Program to find GCD or HCF of two numbers
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 119,
"s": 52,
"text": "Given a number N, the task is to find the Nth term of this series:"
},
{
"code": null,
"e": 145,
"s": 119,
"text": "3, 7, 13, 21, 31, ......."
},
{
"code": null,
"e": 156,
"s": 145,
"text": "Examples: "
},
{
"code": null,
"e": 296,
"s": 156,
"text": "Input: N = 4\nOutput: 21\nExplanation:\nNth term = (pow(N, 2) + N + 1)\n = (pow(4, 2) + 4 + 1)\n = 21\n\nInput: N = 11\nOutput: 133"
},
{
"code": null,
"e": 393,
"s": 296,
"text": "Approach:Subtracting these two equations we get Therefore, the Nth Term of the given series is: "
},
{
"code": null,
"e": 445,
"s": 393,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 449,
"s": 445,
"text": "C++"
},
{
"code": null,
"e": 454,
"s": 449,
"text": "Java"
},
{
"code": null,
"e": 462,
"s": 454,
"text": "Python3"
},
{
"code": null,
"e": 465,
"s": 462,
"text": "C#"
},
{
"code": null,
"e": 469,
"s": 465,
"text": "PHP"
},
{
"code": null,
"e": 480,
"s": 469,
"text": "Javascript"
},
{
"code": "// CPP program to find the Nth term of given series.#include <iostream>#include <math.h>using namespace std; // Function to calculate sumlong long int getNthTerm(long long int N){ // Return Nth term return (pow(N, 2) + N + 1);} // driver codeint main(){ // declaration of number of terms long long int N = 11; // Get the Nth term cout << getNthTerm(N); return 0;}",
"e": 867,
"s": 480,
"text": null
},
{
"code": "// Java code to find the Nth term of given series.import java.util.*; class solution{ // Function to calculate sumstatic long getNthTerm(long N){ // Return Nth term return ((int)Math.pow(N, 2) + N + 1);} //Driver programpublic static void main(String arr[]){ // declaration of number of terms long N = 11; // Get the Nth term System.out.println(getNthTerm(N)); }}//THis code is contributed by//Surendra_Gangwar",
"e": 1305,
"s": 867,
"text": null
},
{
"code": "# Python3 Code to find the# Nth term of given series. # Function to calculate sumdef getNthTerm(N): # Return Nth term return (pow(N, 2) + N + 1) # driver codeif __name__=='__main__': # declaration of number of terms N = 11 # Get the Nth term print(getNthTerm(N)) # This code is contributed by# Sanjit_Prasad",
"e": 1638,
"s": 1305,
"text": null
},
{
"code": "// C# code to find the Nth// term of given series.using System; class GFG{ // Function to calculate sumstatic long getNthTerm(long N){ // Return Nth term return ((int)Math.Pow(N, 2) + N + 1);} // Driver Codestatic public void Main (){ // declaration of number // of terms long N = 11; // Get the Nth term Console.Write(getNthTerm(N));}} // This code is contributed by Raj",
"e": 2038,
"s": 1638,
"text": null
},
{
"code": "<?php// PHP program to find the// Nth term of given series // Function to calculate sumfunction getNthTerm($N){ // Return Nth term return (pow($N, 2) + $N + 1);} // Driver code // declaration of number of terms$N = 11; // Get the Nth termecho getNthTerm($N); // This code is contributed by Raj?>",
"e": 2340,
"s": 2038,
"text": null
},
{
"code": "<script>// JavaScript program to find the Nth term of given series. // Function to calculate sumfunction getNthTerm(N){ // Return Nth term return (Math.pow(N, 2) + N + 1);} // driver code // declaration of number of terms let N = 11; // Get the Nth term document.write(getNthTerm(N)); // This code is contributed by Surbhi Tyagi </script>",
"e": 2701,
"s": 2340,
"text": null
},
{
"code": null,
"e": 2705,
"s": 2701,
"text": "133"
},
{
"code": null,
"e": 2730,
"s": 2707,
"text": "Time Complexity: O(1) "
},
{
"code": null,
"e": 2744,
"s": 2730,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 2761,
"s": 2744,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 2767,
"s": 2761,
"text": "R_Raj"
},
{
"code": null,
"e": 2781,
"s": 2767,
"text": "surbhityagi15"
},
{
"code": null,
"e": 2798,
"s": 2781,
"text": "surinderdawra388"
},
{
"code": null,
"e": 2808,
"s": 2798,
"text": "ruhelaa48"
},
{
"code": null,
"e": 2815,
"s": 2808,
"text": "series"
},
{
"code": null,
"e": 2828,
"s": 2815,
"text": "Mathematical"
},
{
"code": null,
"e": 2847,
"s": 2828,
"text": "School Programming"
},
{
"code": null,
"e": 2860,
"s": 2847,
"text": "Mathematical"
},
{
"code": null,
"e": 2867,
"s": 2860,
"text": "series"
},
{
"code": null,
"e": 2965,
"s": 2867,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2989,
"s": 2965,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 3010,
"s": 2989,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 3024,
"s": 3010,
"text": "Prime Numbers"
},
{
"code": null,
"e": 3046,
"s": 3024,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 3088,
"s": 3046,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 3106,
"s": 3088,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3131,
"s": 3106,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 3147,
"s": 3131,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 3170,
"s": 3147,
"text": "Introduction To PYTHON"
}
] |
Java | CDMA (Code Division Multiple Access)
|
11 Mar, 2022
CDMA is a channelization protocol for Multiple Access, where information can be sent simultaneously through several transmitters over a single communication channel.
It is achieved in below steps:
A signal is generated which extends over a wide bandwidth.
The code which performs this action is called spreading code.
Later on, a specific signal can be selected with a given code even in the presence of many other signals.
It is mainly used in mobile networks like 2G and 3G.
How does CDMA work?
To see how CDMA works, we have to understand orthogonal sequences (also known as chips).
Let N be the number of stations establishing multiple access over a common channel.
Then the properties of orthogonal sequences can be stated as follows:
An orthogonal sequence can be thought of as a 1xN matrix.Eg: [+1 -1 +1 -1] for N = 4.Scalar multiplication and matrix addition rules follow as usual.Eg: 3.[+1 -1 +1 -1] = [+3 -3 +3 -3]Eg: [+1 -1 +1 -1] + [-1 -1 -1 -1] = [0 -2 0 -2]Inner Product: It is evaluated by multiplying two sequences element by element and then adding all elements of the resulting list.Inner Product of a sequence with itself is equal to N[+1 -1 +1 -1].[+1 -1 +1 -1] = 1 + 1 + 1 + 1 = 4Inner Product of two distinct sequences is zero[+1 -1 +1 -1].[+1 +1 +1 +1] = 1-1+1-1 = 0
An orthogonal sequence can be thought of as a 1xN matrix.Eg: [+1 -1 +1 -1] for N = 4.
Scalar multiplication and matrix addition rules follow as usual.Eg: 3.[+1 -1 +1 -1] = [+3 -3 +3 -3]Eg: [+1 -1 +1 -1] + [-1 -1 -1 -1] = [0 -2 0 -2]
Eg: [+1 -1 +1 -1] + [-1 -1 -1 -1] = [0 -2 0 -2]
Inner Product: It is evaluated by multiplying two sequences element by element and then adding all elements of the resulting list.Inner Product of a sequence with itself is equal to N[+1 -1 +1 -1].[+1 -1 +1 -1] = 1 + 1 + 1 + 1 = 4Inner Product of two distinct sequences is zero[+1 -1 +1 -1].[+1 +1 +1 +1] = 1-1+1-1 = 0
Inner Product of a sequence with itself is equal to N[+1 -1 +1 -1].[+1 -1 +1 -1] = 1 + 1 + 1 + 1 = 4
Inner Product of two distinct sequences is zero[+1 -1 +1 -1].[+1 +1 +1 +1] = 1-1+1-1 = 0
To generate valid orthogonal sequences, use a Walsh Table as follows:
Rule 1:
Rule 2: Where = Complement of (Replace +1 by -1 and -1 by +1)Example: Each row of the matrix represents an orthogonal sequence.Hence we can construct sequences for N = . Now let’s take a look at how CDMA works by using orthogonal sequences.
Where = Complement of (Replace +1 by -1 and -1 by +1)
Example:
Each row of the matrix represents an orthogonal sequence.Hence we can construct sequences for N = . Now let’s take a look at how CDMA works by using orthogonal sequences.
Procedure:
The station encodes its data bit as follows.+1 if bit = 1-1 if bit = 0no signal(interpreted as 0) if station is idleEach station is assigned a unique orthogonal sequence (code) which is N bit long for N stationsEach station does a scalar multiplication of its encoded data bit and code sequence.The resulting sequence is then placed on the channel.Since the channel is common, amplitudes add up and hence resultant channel sequence is sum of sequences from all channels.If station 1 wants to listen to station 2, it multiplies (inner product) the channel sequence with code of station S2.The inner product is then divided by N to get data bit transmitted from station 2.
The station encodes its data bit as follows.+1 if bit = 1-1 if bit = 0no signal(interpreted as 0) if station is idle
+1 if bit = 1
-1 if bit = 0
no signal(interpreted as 0) if station is idle
Each station is assigned a unique orthogonal sequence (code) which is N bit long for N stations
Each station does a scalar multiplication of its encoded data bit and code sequence.
The resulting sequence is then placed on the channel.
Since the channel is common, amplitudes add up and hence resultant channel sequence is sum of sequences from all channels.
If station 1 wants to listen to station 2, it multiplies (inner product) the channel sequence with code of station S2.
The inner product is then divided by N to get data bit transmitted from station 2.
Example: Assume 4 stations S1, S2, S3, S4. We’ll use 4×4 Walsh Table to assign codes to them.
C1 = [+1 +1 +1 +1]
C2 = [+1 -1 +1 -1]
C3 = [+1 +1 -1 -1]
C4 = [+1 -1 -1 +1]
Let their data bits currently be:
D1 = -1
D2 = -1
D3 = 0 (Silent)
D4 = +1
Resultant channel sequence = C1.D1 + C2.D2 + C3.D3 + C4.D4
= [-1 -1 -1 -1] + [-1 +1 -1 +1] + [0 0 0 0]
+ [+1 -1 -1 +1]
= [-1 -1 -3 +1]
Now suppose station 1 wants to listen to station 2.
Inner Product = [-1 -1 -3 +1] x C2
= -1 + 1 - 3 - 1 = -4
Data bit that was sent = -4/4 = -1.
Below program illustrate implementation of a simple CDMA channel:
// Java code illustrating a simple implementation of CDMA import java.util.*; public class CDMA { private int[][] wtable; private int[][] copy; private int[] channel_sequence; public void setUp(int[] data, int num_stations) { wtable = new int[num_stations][num_stations]; copy = new int[num_stations][num_stations]; buildWalshTable(num_stations, 0, num_stations - 1, 0, num_stations - 1, false); showWalshTable(num_stations); for (int i = 0; i < num_stations; i++) { for (int j = 0; j < num_stations; j++) { // Making a copy of walsh table // to be used later copy[i][j] = wtable[i][j]; // each row in table is code for one station. // So we multiply each row with station data wtable[i][j] *= data[i]; } } channel_sequence = new int[num_stations]; for (int i = 0; i < num_stations; i++) { for (int j = 0; j < num_stations; j++) { // Adding all sequences to get channel sequence channel_sequence[i] += wtable[j][i]; } } } public void listenTo(int sourceStation, int num_stations) { int innerProduct = 0; for (int i = 0; i < num_stations; i++) { // multiply channel sequence and source station code innerProduct += copy[sourceStation][i] * channel_sequence[i]; } System.out.println("The data received is: " + (innerProduct / num_stations)); } public int buildWalshTable(int len, int i1, int i2, int j1, int j2, boolean isBar) { // len = size of matrix. (i1, j1), (i2, j2) are // starting and ending indices of wtable. // isBar represents whether we want to add simple entry // or complement(southeast submatrix) to wtable. if (len == 2) { if (!isBar) { wtable[i1][j1] = 1; wtable[i1][j2] = 1; wtable[i2][j1] = 1; wtable[i2][j2] = -1; } else { wtable[i1][j1] = -1; wtable[i1][j2] = -1; wtable[i2][j1] = -1; wtable[i2][j2] = +1; } return 0; } int midi = (i1 + i2) / 2; int midj = (j1 + j2) / 2; buildWalshTable(len / 2, i1, midi, j1, midj, isBar); buildWalshTable(len / 2, i1, midi, midj + 1, j2, isBar); buildWalshTable(len / 2, midi + 1, i2, j1, midj, isBar); buildWalshTable(len / 2, midi + 1, i2, midj + 1, j2, !isBar); return 0; } public void showWalshTable(int num_stations) { System.out.print("\n"); for (int i = 0; i < num_stations; i++) { for (int j = 0; j < num_stations; j++) { System.out.print(wtable[i][j] + " "); } System.out.print("\n"); } System.out.println("-------------------------"); System.out.print("\n"); } // Driver Code public static void main(String[] args) { int num_stations = 4; int[] data = new int[num_stations]; //data bits corresponding to each station data[0] = -1; data[1] = -1; data[2] = 0; data[3] = 1; CDMA channel = new CDMA(); channel.setUp(data, num_stations); // station you want to listen to int sourceStation = 3; channel.listenTo(sourceStation, num_stations); }}
Output:
1 1 1 1
1 -1 1 -1
1 1 -1 -1
1 -1 -1 1
The data received is: 1
Advantages of CDMA: Unlike other channelization schemes like FDMA or TDMA which divide the channel based on frequency or time slots, CDMA allows all stations to have access to the full bandwidth of the channel for the entire duration.
shivamtiwari00021
Computer Networks
Java
Java
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GSM in Wireless Communication
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Introduction of Mobile Ad hoc Network (MANET)
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Mar, 2022"
},
{
"code": null,
"e": 220,
"s": 54,
"text": "CDMA is a channelization protocol for Multiple Access, where information can be sent simultaneously through several transmitters over a single communication channel."
},
{
"code": null,
"e": 251,
"s": 220,
"text": "It is achieved in below steps:"
},
{
"code": null,
"e": 310,
"s": 251,
"text": "A signal is generated which extends over a wide bandwidth."
},
{
"code": null,
"e": 372,
"s": 310,
"text": "The code which performs this action is called spreading code."
},
{
"code": null,
"e": 478,
"s": 372,
"text": "Later on, a specific signal can be selected with a given code even in the presence of many other signals."
},
{
"code": null,
"e": 531,
"s": 478,
"text": "It is mainly used in mobile networks like 2G and 3G."
},
{
"code": null,
"e": 551,
"s": 531,
"text": "How does CDMA work?"
},
{
"code": null,
"e": 640,
"s": 551,
"text": "To see how CDMA works, we have to understand orthogonal sequences (also known as chips)."
},
{
"code": null,
"e": 724,
"s": 640,
"text": "Let N be the number of stations establishing multiple access over a common channel."
},
{
"code": null,
"e": 794,
"s": 724,
"text": "Then the properties of orthogonal sequences can be stated as follows:"
},
{
"code": null,
"e": 1344,
"s": 794,
"text": "An orthogonal sequence can be thought of as a 1xN matrix.Eg: [+1 -1 +1 -1] for N = 4.Scalar multiplication and matrix addition rules follow as usual.Eg: 3.[+1 -1 +1 -1] = [+3 -3 +3 -3]Eg: [+1 -1 +1 -1] + [-1 -1 -1 -1] = [0 -2 0 -2]Inner Product: It is evaluated by multiplying two sequences element by element and then adding all elements of the resulting list.Inner Product of a sequence with itself is equal to N[+1 -1 +1 -1].[+1 -1 +1 -1] = 1 + 1 + 1 + 1 = 4Inner Product of two distinct sequences is zero[+1 -1 +1 -1].[+1 +1 +1 +1] = 1-1+1-1 = 0"
},
{
"code": null,
"e": 1430,
"s": 1344,
"text": "An orthogonal sequence can be thought of as a 1xN matrix.Eg: [+1 -1 +1 -1] for N = 4."
},
{
"code": null,
"e": 1577,
"s": 1430,
"text": "Scalar multiplication and matrix addition rules follow as usual.Eg: 3.[+1 -1 +1 -1] = [+3 -3 +3 -3]Eg: [+1 -1 +1 -1] + [-1 -1 -1 -1] = [0 -2 0 -2]"
},
{
"code": null,
"e": 1625,
"s": 1577,
"text": "Eg: [+1 -1 +1 -1] + [-1 -1 -1 -1] = [0 -2 0 -2]"
},
{
"code": null,
"e": 1944,
"s": 1625,
"text": "Inner Product: It is evaluated by multiplying two sequences element by element and then adding all elements of the resulting list.Inner Product of a sequence with itself is equal to N[+1 -1 +1 -1].[+1 -1 +1 -1] = 1 + 1 + 1 + 1 = 4Inner Product of two distinct sequences is zero[+1 -1 +1 -1].[+1 +1 +1 +1] = 1-1+1-1 = 0"
},
{
"code": null,
"e": 2045,
"s": 1944,
"text": "Inner Product of a sequence with itself is equal to N[+1 -1 +1 -1].[+1 -1 +1 -1] = 1 + 1 + 1 + 1 = 4"
},
{
"code": null,
"e": 2134,
"s": 2045,
"text": "Inner Product of two distinct sequences is zero[+1 -1 +1 -1].[+1 +1 +1 +1] = 1-1+1-1 = 0"
},
{
"code": null,
"e": 2204,
"s": 2134,
"text": "To generate valid orthogonal sequences, use a Walsh Table as follows:"
},
{
"code": null,
"e": 2216,
"s": 2204,
"text": "Rule 1: "
},
{
"code": null,
"e": 2474,
"s": 2221,
"text": "Rule 2: Where = Complement of (Replace +1 by -1 and -1 by +1)Example: Each row of the matrix represents an orthogonal sequence.Hence we can construct sequences for N = . Now let’s take a look at how CDMA works by using orthogonal sequences."
},
{
"code": null,
"e": 2535,
"s": 2479,
"text": "Where = Complement of (Replace +1 by -1 and -1 by +1)"
},
{
"code": null,
"e": 2544,
"s": 2535,
"text": "Example:"
},
{
"code": null,
"e": 2725,
"s": 2554,
"text": "Each row of the matrix represents an orthogonal sequence.Hence we can construct sequences for N = . Now let’s take a look at how CDMA works by using orthogonal sequences."
},
{
"code": null,
"e": 2736,
"s": 2725,
"text": "Procedure:"
},
{
"code": null,
"e": 3407,
"s": 2736,
"text": "The station encodes its data bit as follows.+1 if bit = 1-1 if bit = 0no signal(interpreted as 0) if station is idleEach station is assigned a unique orthogonal sequence (code) which is N bit long for N stationsEach station does a scalar multiplication of its encoded data bit and code sequence.The resulting sequence is then placed on the channel.Since the channel is common, amplitudes add up and hence resultant channel sequence is sum of sequences from all channels.If station 1 wants to listen to station 2, it multiplies (inner product) the channel sequence with code of station S2.The inner product is then divided by N to get data bit transmitted from station 2."
},
{
"code": null,
"e": 3524,
"s": 3407,
"text": "The station encodes its data bit as follows.+1 if bit = 1-1 if bit = 0no signal(interpreted as 0) if station is idle"
},
{
"code": null,
"e": 3538,
"s": 3524,
"text": "+1 if bit = 1"
},
{
"code": null,
"e": 3552,
"s": 3538,
"text": "-1 if bit = 0"
},
{
"code": null,
"e": 3599,
"s": 3552,
"text": "no signal(interpreted as 0) if station is idle"
},
{
"code": null,
"e": 3695,
"s": 3599,
"text": "Each station is assigned a unique orthogonal sequence (code) which is N bit long for N stations"
},
{
"code": null,
"e": 3780,
"s": 3695,
"text": "Each station does a scalar multiplication of its encoded data bit and code sequence."
},
{
"code": null,
"e": 3834,
"s": 3780,
"text": "The resulting sequence is then placed on the channel."
},
{
"code": null,
"e": 3957,
"s": 3834,
"text": "Since the channel is common, amplitudes add up and hence resultant channel sequence is sum of sequences from all channels."
},
{
"code": null,
"e": 4076,
"s": 3957,
"text": "If station 1 wants to listen to station 2, it multiplies (inner product) the channel sequence with code of station S2."
},
{
"code": null,
"e": 4159,
"s": 4076,
"text": "The inner product is then divided by N to get data bit transmitted from station 2."
},
{
"code": null,
"e": 4253,
"s": 4159,
"text": "Example: Assume 4 stations S1, S2, S3, S4. We’ll use 4×4 Walsh Table to assign codes to them."
},
{
"code": null,
"e": 4814,
"s": 4253,
"text": "C1 = [+1 +1 +1 +1]\nC2 = [+1 -1 +1 -1]\nC3 = [+1 +1 -1 -1]\nC4 = [+1 -1 -1 +1]\n\nLet their data bits currently be: \nD1 = -1\nD2 = -1\nD3 = 0 (Silent)\nD4 = +1\n\nResultant channel sequence = C1.D1 + C2.D2 + C3.D3 + C4.D4 \n = [-1 -1 -1 -1] + [-1 +1 -1 +1] + [0 0 0 0]\n + [+1 -1 -1 +1]\n = [-1 -1 -3 +1]\n\nNow suppose station 1 wants to listen to station 2. \nInner Product = [-1 -1 -3 +1] x C2\n = -1 + 1 - 3 - 1 = -4\n\nData bit that was sent = -4/4 = -1.\n"
},
{
"code": null,
"e": 4880,
"s": 4814,
"text": "Below program illustrate implementation of a simple CDMA channel:"
},
{
"code": "// Java code illustrating a simple implementation of CDMA import java.util.*; public class CDMA { private int[][] wtable; private int[][] copy; private int[] channel_sequence; public void setUp(int[] data, int num_stations) { wtable = new int[num_stations][num_stations]; copy = new int[num_stations][num_stations]; buildWalshTable(num_stations, 0, num_stations - 1, 0, num_stations - 1, false); showWalshTable(num_stations); for (int i = 0; i < num_stations; i++) { for (int j = 0; j < num_stations; j++) { // Making a copy of walsh table // to be used later copy[i][j] = wtable[i][j]; // each row in table is code for one station. // So we multiply each row with station data wtable[i][j] *= data[i]; } } channel_sequence = new int[num_stations]; for (int i = 0; i < num_stations; i++) { for (int j = 0; j < num_stations; j++) { // Adding all sequences to get channel sequence channel_sequence[i] += wtable[j][i]; } } } public void listenTo(int sourceStation, int num_stations) { int innerProduct = 0; for (int i = 0; i < num_stations; i++) { // multiply channel sequence and source station code innerProduct += copy[sourceStation][i] * channel_sequence[i]; } System.out.println(\"The data received is: \" + (innerProduct / num_stations)); } public int buildWalshTable(int len, int i1, int i2, int j1, int j2, boolean isBar) { // len = size of matrix. (i1, j1), (i2, j2) are // starting and ending indices of wtable. // isBar represents whether we want to add simple entry // or complement(southeast submatrix) to wtable. if (len == 2) { if (!isBar) { wtable[i1][j1] = 1; wtable[i1][j2] = 1; wtable[i2][j1] = 1; wtable[i2][j2] = -1; } else { wtable[i1][j1] = -1; wtable[i1][j2] = -1; wtable[i2][j1] = -1; wtable[i2][j2] = +1; } return 0; } int midi = (i1 + i2) / 2; int midj = (j1 + j2) / 2; buildWalshTable(len / 2, i1, midi, j1, midj, isBar); buildWalshTable(len / 2, i1, midi, midj + 1, j2, isBar); buildWalshTable(len / 2, midi + 1, i2, j1, midj, isBar); buildWalshTable(len / 2, midi + 1, i2, midj + 1, j2, !isBar); return 0; } public void showWalshTable(int num_stations) { System.out.print(\"\\n\"); for (int i = 0; i < num_stations; i++) { for (int j = 0; j < num_stations; j++) { System.out.print(wtable[i][j] + \" \"); } System.out.print(\"\\n\"); } System.out.println(\"-------------------------\"); System.out.print(\"\\n\"); } // Driver Code public static void main(String[] args) { int num_stations = 4; int[] data = new int[num_stations]; //data bits corresponding to each station data[0] = -1; data[1] = -1; data[2] = 0; data[3] = 1; CDMA channel = new CDMA(); channel.setUp(data, num_stations); // station you want to listen to int sourceStation = 3; channel.listenTo(sourceStation, num_stations); }}",
"e": 8624,
"s": 4880,
"text": null
},
{
"code": null,
"e": 8632,
"s": 8624,
"text": "Output:"
},
{
"code": null,
"e": 8706,
"s": 8632,
"text": "1 1 1 1 \n1 -1 1 -1 \n1 1 -1 -1 \n1 -1 -1 1 \n\nThe data received is: 1\n"
},
{
"code": null,
"e": 8941,
"s": 8706,
"text": "Advantages of CDMA: Unlike other channelization schemes like FDMA or TDMA which divide the channel based on frequency or time slots, CDMA allows all stations to have access to the full bandwidth of the channel for the entire duration."
},
{
"code": null,
"e": 8959,
"s": 8941,
"text": "shivamtiwari00021"
},
{
"code": null,
"e": 8977,
"s": 8959,
"text": "Computer Networks"
},
{
"code": null,
"e": 8982,
"s": 8977,
"text": "Java"
},
{
"code": null,
"e": 8987,
"s": 8982,
"text": "Java"
},
{
"code": null,
"e": 9005,
"s": 8987,
"text": "Computer Networks"
},
{
"code": null,
"e": 9103,
"s": 9005,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9133,
"s": 9103,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 9159,
"s": 9133,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 9189,
"s": 9159,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 9229,
"s": 9189,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 9275,
"s": 9229,
"text": "Introduction of Mobile Ad hoc Network (MANET)"
},
{
"code": null,
"e": 9290,
"s": 9275,
"text": "Arrays in Java"
},
{
"code": null,
"e": 9326,
"s": 9290,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 9370,
"s": 9326,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 9395,
"s": 9370,
"text": "Reverse a string in Java"
}
] |
Modifiers for Vector in C++ STL
|
28 Jun, 2021
Click here for Set 1 of Vectors.
Modifiers1.1 assign(input_iterator first, input_iterator last) – Assigns new content to vector and resize1.2 assign(size_type n, const value_type g) – Assigns new content to vector and resize
#include <iostream>#include <vector> using namespace std; int main(){ vector <int> g1; vector <int> g2; vector <int> g3; g1.assign(5, 10); // 5 elements with value 10 each vector <int> :: iterator it; it = g1.begin() + 1; g2.assign(it, g1.end() - 1); // the 3 middle values of g1 int gquiz[] = {1, 2}; g3.assign(gquiz, gquiz + 2); // assigning from array cout << "Size of g1: " << int(g1.size()) << '\n'; cout << "Size of g2: " << int(g2.size()) << '\n'; cout << "Size of g3: " << int(g3.size()) << '\n'; return 0;}
The output of the above program is :
Size of g1: 5
Size of g2: 3
Size of g3: 2
2. push_back(const value_type g) – Adds a new element ‘g’ at the end of the vector and increases the vector container size by 13. pop_back() – Removes the element at the end of the vector, i.e., the last element and decreases the vector container size by 1
#include <iostream>#include <vector> using namespace std; int main(){ vector <int> gquiz; int sum = 0; gquiz.push_back(10); gquiz.push_back(20); gquiz.push_back(30); while (!gquiz.empty()) { sum += gquiz.back(); gquiz.pop_back(); } cout << "The sum of the elements of gquiz is : " << sum << '\n'; return 0;}
The output of the above program is :
The sum of the elements of gquiz is : 60
4.1 insert(const_iterator q, const value_type g) – Adds element ‘g’ before the element referenced by iterator ‘q’ and returns an iterator that points to the newly added element4.2insert(const_iterator q, size_type n, const value_type g) – Adds ‘n’ elements each with value ‘g’ before the element currently referenced by iterator ‘q’ and returns an iterator that points to the first of the newly added elements4.3 insert(const_iterator q, InputIterator first, InputIterator last) – Adds a range of elements starting from first to last, the elements being inserted before the position currently referred by ‘q’
#include <iostream>#include <vector> using namespace std; int main(){ vector <int> gquiz1(3, 10); vector <int> :: iterator it; it = gquiz1.begin(); it = gquiz1.insert(it, 20); gquiz1.insert(it, 2, 30); it = gquiz1.begin(); vector <int> gquiz2(2, 40); gquiz1.insert(it + 2, gquiz2.begin(), gquiz2.end()); int gq [] = {50, 60, 70}; gquiz1.insert(gquiz1.begin(), gq, gq + 3); cout << "gquiz1 contains : "; for (it = gquiz1.begin(); it < gquiz1.end(); it++) cout << *it << '\t'; return 0;}
The output of the above program is :
gquiz1 contains : 50 60 70 30 30
40 40 20 10 10 10
5.1 erase(const_iterator q) – Deletes the element referred by ‘q’ and returns an iterator to the element followed by the deleted element5.2 erase(const_iterator first, const_iterator last) – Deletes the elements in the range first to last, with the first iterator included in the range and the last iterator not included, and returns an iterator to the element followed by the last deleted element
#include <iostream>#include <vector>using namespace std; int main (){ vector <int> gquiz; for (int i = 1; i <= 10; i++) gquiz.push_back(i * 2); // erase the 5th element gquiz.erase(gquiz.begin() + 4); // erase the first 5 elements: gquiz.erase(gquiz.begin(), gquiz.begin() + 5); cout << "gquiz contains :"; for (int i = 0; i < gquiz.size(); ++i) cout << gquiz[i] << '\t'; return 0;}
The output of the above program is :
gquiz contains :14 16 18 20
6. swap(vector q, vector r) – Swaps the contents of ‘q’ and ‘r’7. clear() – Removes all elements from the vector
#include <iostream>#include <vector> using namespace std; int main(){ vector <int> gquiz1; vector <int> gquiz2; vector <int> :: iterator i; gquiz1.push_back(10); gquiz1.push_back(20); gquiz2.push_back(30); gquiz2.push_back(40); cout << "Before Swapping, \n" <<"Contents of vector gquiz1 : "; for (i = gquiz1.begin(); i != gquiz1.end(); ++i) cout << *i << '\t'; cout << "\nContents of vector gquiz2 : "; for (i = gquiz2.begin(); i != gquiz2.end(); ++i) cout << *i << '\t'; swap(gquiz1, gquiz2); cout << "\n\nAfter Swapping, \n"; cout << "Contents of vector gquiz1 : "; for (i = gquiz1.begin(); i != gquiz1.end(); ++i) cout << *i << '\t'; cout << "\nContents of vector gquiz2 : "; for (i = gquiz2.begin(); i != gquiz2.end(); ++i) cout << *i << '\t'; cout << "\n\nNow, we clear() and then add " << "an element 1000 to vector gquiz1 : "; gquiz1.clear(); gquiz1.push_back(1000); cout << gquiz1.front(); return 0;}
The output of the above program is :
Before Swapping,
Contents of vector gquiz1 : 10 20
Contents of vector gquiz2 : 30 40
After Swapping,
Contents of vector gquiz1 : 30 40
Contents of vector gquiz2 : 10 20
Now, we clear() and then add an element 1000 to vector gquiz1 : 1000
Click here for Set 3 of Vectors. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
cpp-containers-library
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 87,
"s": 54,
"text": "Click here for Set 1 of Vectors."
},
{
"code": null,
"e": 281,
"s": 89,
"text": "Modifiers1.1 assign(input_iterator first, input_iterator last) – Assigns new content to vector and resize1.2 assign(size_type n, const value_type g) – Assigns new content to vector and resize"
},
{
"code": "#include <iostream>#include <vector> using namespace std; int main(){ vector <int> g1; vector <int> g2; vector <int> g3; g1.assign(5, 10); // 5 elements with value 10 each vector <int> :: iterator it; it = g1.begin() + 1; g2.assign(it, g1.end() - 1); // the 3 middle values of g1 int gquiz[] = {1, 2}; g3.assign(gquiz, gquiz + 2); // assigning from array cout << \"Size of g1: \" << int(g1.size()) << '\\n'; cout << \"Size of g2: \" << int(g2.size()) << '\\n'; cout << \"Size of g3: \" << int(g3.size()) << '\\n'; return 0;}",
"e": 852,
"s": 281,
"text": null
},
{
"code": null,
"e": 889,
"s": 852,
"text": "The output of the above program is :"
},
{
"code": null,
"e": 932,
"s": 889,
"text": "Size of g1: 5\nSize of g2: 3\nSize of g3: 2\n"
},
{
"code": null,
"e": 1189,
"s": 932,
"text": "2. push_back(const value_type g) – Adds a new element ‘g’ at the end of the vector and increases the vector container size by 13. pop_back() – Removes the element at the end of the vector, i.e., the last element and decreases the vector container size by 1"
},
{
"code": "#include <iostream>#include <vector> using namespace std; int main(){ vector <int> gquiz; int sum = 0; gquiz.push_back(10); gquiz.push_back(20); gquiz.push_back(30); while (!gquiz.empty()) { sum += gquiz.back(); gquiz.pop_back(); } cout << \"The sum of the elements of gquiz is : \" << sum << '\\n'; return 0;}",
"e": 1528,
"s": 1189,
"text": null
},
{
"code": null,
"e": 1565,
"s": 1528,
"text": "The output of the above program is :"
},
{
"code": null,
"e": 1607,
"s": 1565,
"text": "The sum of the elements of gquiz is : 60\n"
},
{
"code": null,
"e": 2216,
"s": 1607,
"text": "4.1 insert(const_iterator q, const value_type g) – Adds element ‘g’ before the element referenced by iterator ‘q’ and returns an iterator that points to the newly added element4.2insert(const_iterator q, size_type n, const value_type g) – Adds ‘n’ elements each with value ‘g’ before the element currently referenced by iterator ‘q’ and returns an iterator that points to the first of the newly added elements4.3 insert(const_iterator q, InputIterator first, InputIterator last) – Adds a range of elements starting from first to last, the elements being inserted before the position currently referred by ‘q’"
},
{
"code": "#include <iostream>#include <vector> using namespace std; int main(){ vector <int> gquiz1(3, 10); vector <int> :: iterator it; it = gquiz1.begin(); it = gquiz1.insert(it, 20); gquiz1.insert(it, 2, 30); it = gquiz1.begin(); vector <int> gquiz2(2, 40); gquiz1.insert(it + 2, gquiz2.begin(), gquiz2.end()); int gq [] = {50, 60, 70}; gquiz1.insert(gquiz1.begin(), gq, gq + 3); cout << \"gquiz1 contains : \"; for (it = gquiz1.begin(); it < gquiz1.end(); it++) cout << *it << '\\t'; return 0;}",
"e": 2764,
"s": 2216,
"text": null
},
{
"code": null,
"e": 2801,
"s": 2764,
"text": "The output of the above program is :"
},
{
"code": null,
"e": 2884,
"s": 2801,
"text": "gquiz1 contains : 50 60 70 30 30 \n40 40 20 10 10 10\n"
},
{
"code": null,
"e": 3282,
"s": 2884,
"text": "5.1 erase(const_iterator q) – Deletes the element referred by ‘q’ and returns an iterator to the element followed by the deleted element5.2 erase(const_iterator first, const_iterator last) – Deletes the elements in the range first to last, with the first iterator included in the range and the last iterator not included, and returns an iterator to the element followed by the last deleted element"
},
{
"code": "#include <iostream>#include <vector>using namespace std; int main (){ vector <int> gquiz; for (int i = 1; i <= 10; i++) gquiz.push_back(i * 2); // erase the 5th element gquiz.erase(gquiz.begin() + 4); // erase the first 5 elements: gquiz.erase(gquiz.begin(), gquiz.begin() + 5); cout << \"gquiz contains :\"; for (int i = 0; i < gquiz.size(); ++i) cout << gquiz[i] << '\\t'; return 0;}",
"e": 3717,
"s": 3282,
"text": null
},
{
"code": null,
"e": 3754,
"s": 3717,
"text": "The output of the above program is :"
},
{
"code": null,
"e": 3792,
"s": 3754,
"text": "gquiz contains :14 16 18 20\n"
},
{
"code": null,
"e": 3905,
"s": 3792,
"text": "6. swap(vector q, vector r) – Swaps the contents of ‘q’ and ‘r’7. clear() – Removes all elements from the vector"
},
{
"code": "#include <iostream>#include <vector> using namespace std; int main(){ vector <int> gquiz1; vector <int> gquiz2; vector <int> :: iterator i; gquiz1.push_back(10); gquiz1.push_back(20); gquiz2.push_back(30); gquiz2.push_back(40); cout << \"Before Swapping, \\n\" <<\"Contents of vector gquiz1 : \"; for (i = gquiz1.begin(); i != gquiz1.end(); ++i) cout << *i << '\\t'; cout << \"\\nContents of vector gquiz2 : \"; for (i = gquiz2.begin(); i != gquiz2.end(); ++i) cout << *i << '\\t'; swap(gquiz1, gquiz2); cout << \"\\n\\nAfter Swapping, \\n\"; cout << \"Contents of vector gquiz1 : \"; for (i = gquiz1.begin(); i != gquiz1.end(); ++i) cout << *i << '\\t'; cout << \"\\nContents of vector gquiz2 : \"; for (i = gquiz2.begin(); i != gquiz2.end(); ++i) cout << *i << '\\t'; cout << \"\\n\\nNow, we clear() and then add \" << \"an element 1000 to vector gquiz1 : \"; gquiz1.clear(); gquiz1.push_back(1000); cout << gquiz1.front(); return 0;}",
"e": 4946,
"s": 3905,
"text": null
},
{
"code": null,
"e": 4983,
"s": 4946,
"text": "The output of the above program is :"
},
{
"code": null,
"e": 5254,
"s": 4983,
"text": "Before Swapping, \nContents of vector gquiz1 : 10 20 \nContents of vector gquiz2 : 30 40 \n\nAfter Swapping, \nContents of vector gquiz1 : 30 40 \nContents of vector gquiz2 : 10 20 \n\nNow, we clear() and then add an element 1000 to vector gquiz1 : 1000\n"
},
{
"code": null,
"e": 5412,
"s": 5254,
"text": " Click here for Set 3 of Vectors. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 5435,
"s": 5412,
"text": "cpp-containers-library"
},
{
"code": null,
"e": 5446,
"s": 5435,
"text": "cpp-vector"
},
{
"code": null,
"e": 5450,
"s": 5446,
"text": "STL"
},
{
"code": null,
"e": 5454,
"s": 5450,
"text": "C++"
},
{
"code": null,
"e": 5458,
"s": 5454,
"text": "STL"
},
{
"code": null,
"e": 5462,
"s": 5458,
"text": "CPP"
}
] |
Iterative Preorder Traversal
|
17 Jun, 2022
Given a Binary Tree, write an iterative function to print the Preorder traversal of the given binary tree.Refer to this for recursive preorder traversal of Binary Tree. To convert an inherently recursive procedure to iterative, we need an explicit stack.
Following is a simple stack based iterative process to print Preorder traversal.
Create an empty stack nodeStack and push root node to stack. Do the following while nodeStack is not empty. Pop an item from the stack and print it. Push right child of a popped item to stack Push left child of a popped item to stack
Create an empty stack nodeStack and push root node to stack.
Do the following while nodeStack is not empty. Pop an item from the stack and print it. Push right child of a popped item to stack Push left child of a popped item to stack
Pop an item from the stack and print it. Push right child of a popped item to stack Push left child of a popped item to stack
Pop an item from the stack and print it.
Push right child of a popped item to stack
Push left child of a popped item to stack
The right child is pushed before the left child to make sure that the left subtree is processed first.
C++
Java
Python3
C#
Javascript
// C++ program to implement iterative preorder traversal#include <bits/stdc++.h> using namespace std; /* A binary tree node has data, left child and right child */struct node { int data; struct node* left; struct node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers.*/struct node* newNode(int data){ struct node* node = new struct node; node->data = data; node->left = NULL; node->right = NULL; return (node);} // An iterative process to print preorder traversal of Binary treevoid iterativePreorder(node* root){ // Base Case if (root == NULL) return; // Create an empty stack and push root to it stack<node*> nodeStack; nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ while (nodeStack.empty() == false) { // Pop the top item from stack and print it struct node* node = nodeStack.top(); printf("%d ", node->data); nodeStack.pop(); // Push right and left children of the popped node to stack if (node->right) nodeStack.push(node->right); if (node->left) nodeStack.push(node->left); }} // Driver program to test above functionsint main(){ /* Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2 */ struct node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->left = newNode(2); iterativePreorder(root); return 0;}
// Java program to implement iterative preorder traversalimport java.util.Stack; // A binary tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; void iterativePreorder() { iterativePreorder(root); } // An iterative process to print preorder traversal of Binary tree void iterativePreorder(Node node) { // Base Case if (node == null) { return; } // Create an empty stack and push root to it Stack<Node> nodeStack = new Stack<Node>(); nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ while (nodeStack.empty() == false) { // Pop the top item from stack and print it Node mynode = nodeStack.peek(); System.out.print(mynode.data + " "); nodeStack.pop(); // Push right and left children of the popped node to stack if (mynode.right != null) { nodeStack.push(mynode.right); } if (mynode.left != null) { nodeStack.push(mynode.left); } } } // driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.left = new Node(2); tree.iterativePreorder(); }} // This code has been contributed by Mayank Jaiswal
# Python program to perform iterative preorder traversal # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # An iterative process to print preorder traversal of BTdef iterativePreorder(root): # Base CAse if root is None: return # create an empty stack and push root to it nodeStack = [] nodeStack.append(root) # Pop all items one by one. Do following for every popped item # a) print it # b) push its right child # c) push its left child # Note that right child is pushed first so that left # is processed first */ while(len(nodeStack) > 0): # Pop the top item from stack and print it node = nodeStack.pop() print (node.data, end=" ") # Push right and left children of the popped node # to stack if node.right is not None: nodeStack.append(node.right) if node.left is not None: nodeStack.append(node.left) # Driver program to test above functionroot = Node(10)root.left = Node(8)root.right = Node(2)root.left.left = Node(3)root.left.right = Node(5)root.right.left = Node(2)iterativePreorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// C# program to implement iterative// preorder traversalusing System;using System.Collections.Generic; // A binary tree nodepublic class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class GFG { public Node root; public virtual void iterativePreorder() { iterativePreorder(root); } // An iterative process to print preorder // traversal of Binary tree public virtual void iterativePreorder(Node node) { // Base Case if (node == null) { return; } // Create an empty stack and push root to it Stack<Node> nodeStack = new Stack<Node>(); nodeStack.Push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ while (nodeStack.Count > 0) { // Pop the top item from stack and print it Node mynode = nodeStack.Peek(); Console.Write(mynode.data + " "); nodeStack.Pop(); // Push right and left children of // the popped node to stack if (mynode.right != null) { nodeStack.Push(mynode.right); } if (mynode.left != null) { nodeStack.Push(mynode.left); } } } // Driver Code public static void Main(string[] args) { GFG tree = new GFG(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.left = new Node(2); tree.iterativePreorder(); }} // This code is contributed by Shrikant13
<script> // Javascript program to implement iterative// preorder traversal // A binary tree nodeclass Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} var root = null; // An iterative process to print preorder// traversal of Binary treefunction iterativePreorder(node){ // Base Case if (node == null) { return; } // Create an empty stack and push root to it var nodeStack = []; nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ while (nodeStack.length > 0) { // Pop the top item from stack and print it var mynode = nodeStack[nodeStack.length - 1]; document.write(mynode.data + " "); nodeStack.pop(); // Push right and left children of // the popped node to stack if (mynode.right != null) { nodeStack.push(mynode.right); } if (mynode.left != null) { nodeStack.push(mynode.left); } }} // Driver Coderoot = new Node(10);root.left = new Node(8);root.right = new Node(2);root.left.left = new Node(3);root.left.right = new Node(5);root.right.left = new Node(2); iterativePreorder(root); // This code is contributed by itsok </script>
10 8 3 5 2 2
Time Complexity: O(N) Auxiliary Space: O(H), where H is the height of the tree.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Another Solution: In the previous solution we can see that the left child is popped as soon as it is pushed to the stack, therefore it is not required to push it into the stack.
The idea is to start traversing the tree from the root node, and keep printing the left child while exists and simultaneously, push the right child of every node in an auxiliary stack. Once we reach a null node, pop a right child from the auxiliary stack and repeat the process while the auxiliary stack is not-empty.
This is a micro-optimization over the previous approach, both the solutions use asymptotically similar auxiliary space.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; // Tree Nodestruct Node { int data; Node *left, *right; Node(int data) { this->data = data; this->left = this->right = NULL; }}; // Iterative function to do Preorder traversal of the treevoid preorderIterative(Node* root){ if (root == NULL) return; stack<Node*> st; // start from root node (set current node to root node) Node* curr = root; // run till stack is not empty or current is // not NULL while (!st.empty() || curr != NULL) { // Print left children while exist // and keep pushing right into the // stack. while (curr != NULL) { cout << curr->data << " "; if (curr->right) st.push(curr->right); curr = curr->left; } // We reach when curr is NULL, so We // take out a right child from stack if (st.empty() == false) { curr = st.top(); st.pop(); } }} // Driver Codeint main(){ Node* root = new Node(10); root->left = new Node(20); root->right = new Node(30); root->left->left = new Node(40); root->left->left->left = new Node(70); root->left->right = new Node(50); root->right->left = new Node(60); root->left->left->right = new Node(80); preorderIterative(root); return 0;}
import java.util.Stack; // A binary tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; void preorderIterative(){ preorderIterative(root);} // Iterative function to do Preorder// traversal of the treevoid preorderIterative(Node node){ if (node == null) { return; } Stack<Node> st = new Stack<Node>(); // Start from root node (set curr // node to root node) Node curr = node; // Run till stack is not empty or // current is not NULL while (curr != null || !st.isEmpty()) { // Print left children while exist // and keep pushing right into the // stack. while (curr != null) { System.out.print(curr.data + " "); if (curr.right != null) st.push(curr.right); curr = curr.left; } // We reach when curr is NULL, so We // take out a right child from stack if (!st.isEmpty()) { curr = st.pop(); } }} // Driver codepublic static void main(String args[]){ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(20); tree.root.right = new Node(30); tree.root.left.left = new Node(40); tree.root.left.left.left = new Node(70); tree.root.left.right = new Node(50); tree.root.right.left = new Node(60); tree.root.left.left.right = new Node(80); tree.preorderIterative();}} // This code is contributed by Vivek Singh Bhadauria
# Tree Nodeclass Node: def __init__(self, data = 0): self.data = data self.left = None self.right = None # Iterative function to do Preorder traversal of the treedef preorderIterative(root): if (root == None): return st = [] # start from root node (set current node to root node) curr = root # run till stack is not empty or current is # not NULL while (len(st) or curr != None): # Print left children while exist # and keep appending right into the # stack. while (curr != None): print(curr.data, end = " ") if (curr.right != None): st.append(curr.right) curr = curr.left # We reach when curr is NULL, so We # take out a right child from stack if (len(st) > 0): curr = st[-1] st.pop() # Driver Code root = Node(10)root.left = Node(20)root.right = Node(30)root.left.left = Node(40)root.left.left.left = Node(70)root.left.right = Node(50)root.right.left = Node(60)root.left.left.right = Node(80) preorderIterative(root) # This code is contributed by Arnab Kundu
using System;using System.Collections.Generic; // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ Node root; void preorderIterative(){ preorderIterative(root);} // Iterative function to do Preorder// traversal of the treevoid preorderIterative(Node node){ if (node == null) { return; } Stack<Node> st = new Stack<Node>(); // Start from root node (set curr // node to root node) Node curr = node; // Run till stack is not empty or // current is not NULL while (curr != null || st.Count!=0) { // Print left children while exist // and keep pushing right into the // stack. while (curr != null) { Console.Write(curr.data + " "); if (curr.right != null) st.Push(curr.right); curr = curr.left; } // We reach when curr is NULL, so We // take out a right child from stack if (st.Count != 0) { curr = st.Pop(); } }} // Driver codepublic static void Main(String []args){ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(20); tree.root.right = new Node(30); tree.root.left.left = new Node(40); tree.root.left.left.left = new Node(70); tree.root.left.right = new Node(50); tree.root.right.left = new Node(60); tree.root.left.left.right = new Node(80); tree.preorderIterative();}} // This code is contributed by Amit Katiyar
<script> class Node{ constructor(item) { this.left = null; this.right = null; this.data = item; }} let root; // Iterative function to do Preorder// traversal of the treefunction preorderiterative(node){ if (node == null) { return; } let st = []; // Start from root node (set curr // node to root node) let curr = node; // Run till stack is not empty or // current is not NULL while (curr != null || st.length > 0) { // Print left children while exist // and keep pushing right into the // stack. while (curr != null) { document.write(curr.data + " "); if (curr.right != null) st.push(curr.right); curr = curr.left; } // We reach when curr is NULL, so We // take out a right child from stack if (st.length > 0) { curr = st.pop(); } }} function preorderIterative(){ preorderiterative(root);} // Driver coderoot = new Node(10);root.left = new Node(20);root.right = new Node(30);root.left.left = new Node(40);root.left.left.left = new Node(70);root.left.right = new Node(50);root.right.left = new Node(60);root.left.left.right = new Node(80); preorderIterative(); // This code is contributed by decode2207 </script>
10 20 40 70 80 50 30 60
Time Complexity: O(N) Auxiliary Space: O(H), where H is the height of the tree.
shrikanth13
andrew1234
vivek singh bhadauri
amit143katiyar
user282
itsok
decode2207
surinderdawra388
amartyaghoshgfg
dhairya bhardwaj
hardikkoriintern
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
A program to check if a binary tree is BST or not
Decision Tree
Top 50 Tree Coding Problems for Interviews
Segment Tree | Set 1 (Sum of given range)
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Sorted Array to Balanced BST
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 308,
"s": 52,
"text": "Given a Binary Tree, write an iterative function to print the Preorder traversal of the given binary tree.Refer to this for recursive preorder traversal of Binary Tree. To convert an inherently recursive procedure to iterative, we need an explicit stack. "
},
{
"code": null,
"e": 390,
"s": 308,
"text": "Following is a simple stack based iterative process to print Preorder traversal. "
},
{
"code": null,
"e": 624,
"s": 390,
"text": "Create an empty stack nodeStack and push root node to stack. Do the following while nodeStack is not empty. Pop an item from the stack and print it. Push right child of a popped item to stack Push left child of a popped item to stack"
},
{
"code": null,
"e": 686,
"s": 624,
"text": "Create an empty stack nodeStack and push root node to stack. "
},
{
"code": null,
"e": 859,
"s": 686,
"text": "Do the following while nodeStack is not empty. Pop an item from the stack and print it. Push right child of a popped item to stack Push left child of a popped item to stack"
},
{
"code": null,
"e": 985,
"s": 859,
"text": "Pop an item from the stack and print it. Push right child of a popped item to stack Push left child of a popped item to stack"
},
{
"code": null,
"e": 1027,
"s": 985,
"text": "Pop an item from the stack and print it. "
},
{
"code": null,
"e": 1071,
"s": 1027,
"text": "Push right child of a popped item to stack "
},
{
"code": null,
"e": 1113,
"s": 1071,
"text": "Push left child of a popped item to stack"
},
{
"code": null,
"e": 1216,
"s": 1113,
"text": "The right child is pushed before the left child to make sure that the left subtree is processed first."
},
{
"code": null,
"e": 1220,
"s": 1216,
"text": "C++"
},
{
"code": null,
"e": 1225,
"s": 1220,
"text": "Java"
},
{
"code": null,
"e": 1233,
"s": 1225,
"text": "Python3"
},
{
"code": null,
"e": 1236,
"s": 1233,
"text": "C#"
},
{
"code": null,
"e": 1247,
"s": 1236,
"text": "Javascript"
},
{
"code": "// C++ program to implement iterative preorder traversal#include <bits/stdc++.h> using namespace std; /* A binary tree node has data, left child and right child */struct node { int data; struct node* left; struct node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers.*/struct node* newNode(int data){ struct node* node = new struct node; node->data = data; node->left = NULL; node->right = NULL; return (node);} // An iterative process to print preorder traversal of Binary treevoid iterativePreorder(node* root){ // Base Case if (root == NULL) return; // Create an empty stack and push root to it stack<node*> nodeStack; nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ while (nodeStack.empty() == false) { // Pop the top item from stack and print it struct node* node = nodeStack.top(); printf(\"%d \", node->data); nodeStack.pop(); // Push right and left children of the popped node to stack if (node->right) nodeStack.push(node->right); if (node->left) nodeStack.push(node->left); }} // Driver program to test above functionsint main(){ /* Constructed binary tree is 10 / \\ 8 2 / \\ / 3 5 2 */ struct node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->left = newNode(2); iterativePreorder(root); return 0;}",
"e": 3017,
"s": 1247,
"text": null
},
{
"code": "// Java program to implement iterative preorder traversalimport java.util.Stack; // A binary tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; void iterativePreorder() { iterativePreorder(root); } // An iterative process to print preorder traversal of Binary tree void iterativePreorder(Node node) { // Base Case if (node == null) { return; } // Create an empty stack and push root to it Stack<Node> nodeStack = new Stack<Node>(); nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ while (nodeStack.empty() == false) { // Pop the top item from stack and print it Node mynode = nodeStack.peek(); System.out.print(mynode.data + \" \"); nodeStack.pop(); // Push right and left children of the popped node to stack if (mynode.right != null) { nodeStack.push(mynode.right); } if (mynode.left != null) { nodeStack.push(mynode.left); } } } // driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.left = new Node(2); tree.iterativePreorder(); }} // This code has been contributed by Mayank Jaiswal",
"e": 4867,
"s": 3017,
"text": null
},
{
"code": "# Python program to perform iterative preorder traversal # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # An iterative process to print preorder traversal of BTdef iterativePreorder(root): # Base CAse if root is None: return # create an empty stack and push root to it nodeStack = [] nodeStack.append(root) # Pop all items one by one. Do following for every popped item # a) print it # b) push its right child # c) push its left child # Note that right child is pushed first so that left # is processed first */ while(len(nodeStack) > 0): # Pop the top item from stack and print it node = nodeStack.pop() print (node.data, end=\" \") # Push right and left children of the popped node # to stack if node.right is not None: nodeStack.append(node.right) if node.left is not None: nodeStack.append(node.left) # Driver program to test above functionroot = Node(10)root.left = Node(8)root.right = Node(2)root.left.left = Node(3)root.left.right = Node(5)root.right.left = Node(2)iterativePreorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 6193,
"s": 4867,
"text": null
},
{
"code": "// C# program to implement iterative// preorder traversalusing System;using System.Collections.Generic; // A binary tree nodepublic class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class GFG { public Node root; public virtual void iterativePreorder() { iterativePreorder(root); } // An iterative process to print preorder // traversal of Binary tree public virtual void iterativePreorder(Node node) { // Base Case if (node == null) { return; } // Create an empty stack and push root to it Stack<Node> nodeStack = new Stack<Node>(); nodeStack.Push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ while (nodeStack.Count > 0) { // Pop the top item from stack and print it Node mynode = nodeStack.Peek(); Console.Write(mynode.data + \" \"); nodeStack.Pop(); // Push right and left children of // the popped node to stack if (mynode.right != null) { nodeStack.Push(mynode.right); } if (mynode.left != null) { nodeStack.Push(mynode.left); } } } // Driver Code public static void Main(string[] args) { GFG tree = new GFG(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.left = new Node(2); tree.iterativePreorder(); }} // This code is contributed by Shrikant13",
"e": 8070,
"s": 6193,
"text": null
},
{
"code": "<script> // Javascript program to implement iterative// preorder traversal // A binary tree nodeclass Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} var root = null; // An iterative process to print preorder// traversal of Binary treefunction iterativePreorder(node){ // Base Case if (node == null) { return; } // Create an empty stack and push root to it var nodeStack = []; nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ while (nodeStack.length > 0) { // Pop the top item from stack and print it var mynode = nodeStack[nodeStack.length - 1]; document.write(mynode.data + \" \"); nodeStack.pop(); // Push right and left children of // the popped node to stack if (mynode.right != null) { nodeStack.push(mynode.right); } if (mynode.left != null) { nodeStack.push(mynode.left); } }} // Driver Coderoot = new Node(10);root.left = new Node(8);root.right = new Node(2);root.left.left = new Node(3);root.left.right = new Node(5);root.right.left = new Node(2); iterativePreorder(root); // This code is contributed by itsok </script>",
"e": 9531,
"s": 8070,
"text": null
},
{
"code": null,
"e": 9544,
"s": 9531,
"text": "10 8 3 5 2 2"
},
{
"code": null,
"e": 9626,
"s": 9546,
"text": "Time Complexity: O(N) Auxiliary Space: O(H), where H is the height of the tree."
},
{
"code": null,
"e": 9635,
"s": 9626,
"text": "Chapters"
},
{
"code": null,
"e": 9662,
"s": 9635,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 9712,
"s": 9662,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 9735,
"s": 9712,
"text": "captions off, selected"
},
{
"code": null,
"e": 9743,
"s": 9735,
"text": "English"
},
{
"code": null,
"e": 9767,
"s": 9743,
"text": "This is a modal window."
},
{
"code": null,
"e": 9836,
"s": 9767,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 9858,
"s": 9836,
"text": "End of dialog window."
},
{
"code": null,
"e": 10037,
"s": 9858,
"text": "Another Solution: In the previous solution we can see that the left child is popped as soon as it is pushed to the stack, therefore it is not required to push it into the stack. "
},
{
"code": null,
"e": 10356,
"s": 10037,
"text": "The idea is to start traversing the tree from the root node, and keep printing the left child while exists and simultaneously, push the right child of every node in an auxiliary stack. Once we reach a null node, pop a right child from the auxiliary stack and repeat the process while the auxiliary stack is not-empty. "
},
{
"code": null,
"e": 10476,
"s": 10356,
"text": "This is a micro-optimization over the previous approach, both the solutions use asymptotically similar auxiliary space."
},
{
"code": null,
"e": 10528,
"s": 10476,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 10532,
"s": 10528,
"text": "C++"
},
{
"code": null,
"e": 10537,
"s": 10532,
"text": "Java"
},
{
"code": null,
"e": 10545,
"s": 10537,
"text": "Python3"
},
{
"code": null,
"e": 10548,
"s": 10545,
"text": "C#"
},
{
"code": null,
"e": 10559,
"s": 10548,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Tree Nodestruct Node { int data; Node *left, *right; Node(int data) { this->data = data; this->left = this->right = NULL; }}; // Iterative function to do Preorder traversal of the treevoid preorderIterative(Node* root){ if (root == NULL) return; stack<Node*> st; // start from root node (set current node to root node) Node* curr = root; // run till stack is not empty or current is // not NULL while (!st.empty() || curr != NULL) { // Print left children while exist // and keep pushing right into the // stack. while (curr != NULL) { cout << curr->data << \" \"; if (curr->right) st.push(curr->right); curr = curr->left; } // We reach when curr is NULL, so We // take out a right child from stack if (st.empty() == false) { curr = st.top(); st.pop(); } }} // Driver Codeint main(){ Node* root = new Node(10); root->left = new Node(20); root->right = new Node(30); root->left->left = new Node(40); root->left->left->left = new Node(70); root->left->right = new Node(50); root->right->left = new Node(60); root->left->left->right = new Node(80); preorderIterative(root); return 0;}",
"e": 11919,
"s": 10559,
"text": null
},
{
"code": "import java.util.Stack; // A binary tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; void preorderIterative(){ preorderIterative(root);} // Iterative function to do Preorder// traversal of the treevoid preorderIterative(Node node){ if (node == null) { return; } Stack<Node> st = new Stack<Node>(); // Start from root node (set curr // node to root node) Node curr = node; // Run till stack is not empty or // current is not NULL while (curr != null || !st.isEmpty()) { // Print left children while exist // and keep pushing right into the // stack. while (curr != null) { System.out.print(curr.data + \" \"); if (curr.right != null) st.push(curr.right); curr = curr.left; } // We reach when curr is NULL, so We // take out a right child from stack if (!st.isEmpty()) { curr = st.pop(); } }} // Driver codepublic static void main(String args[]){ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(20); tree.root.right = new Node(30); tree.root.left.left = new Node(40); tree.root.left.left.left = new Node(70); tree.root.left.right = new Node(50); tree.root.right.left = new Node(60); tree.root.left.left.right = new Node(80); tree.preorderIterative();}} // This code is contributed by Vivek Singh Bhadauria",
"e": 13556,
"s": 11919,
"text": null
},
{
"code": "# Tree Nodeclass Node: def __init__(self, data = 0): self.data = data self.left = None self.right = None # Iterative function to do Preorder traversal of the treedef preorderIterative(root): if (root == None): return st = [] # start from root node (set current node to root node) curr = root # run till stack is not empty or current is # not NULL while (len(st) or curr != None): # Print left children while exist # and keep appending right into the # stack. while (curr != None): print(curr.data, end = \" \") if (curr.right != None): st.append(curr.right) curr = curr.left # We reach when curr is NULL, so We # take out a right child from stack if (len(st) > 0): curr = st[-1] st.pop() # Driver Code root = Node(10)root.left = Node(20)root.right = Node(30)root.left.left = Node(40)root.left.left.left = Node(70)root.left.right = Node(50)root.right.left = Node(60)root.left.left.right = Node(80) preorderIterative(root) # This code is contributed by Arnab Kundu",
"e": 14734,
"s": 13556,
"text": null
},
{
"code": "using System;using System.Collections.Generic; // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ Node root; void preorderIterative(){ preorderIterative(root);} // Iterative function to do Preorder// traversal of the treevoid preorderIterative(Node node){ if (node == null) { return; } Stack<Node> st = new Stack<Node>(); // Start from root node (set curr // node to root node) Node curr = node; // Run till stack is not empty or // current is not NULL while (curr != null || st.Count!=0) { // Print left children while exist // and keep pushing right into the // stack. while (curr != null) { Console.Write(curr.data + \" \"); if (curr.right != null) st.Push(curr.right); curr = curr.left; } // We reach when curr is NULL, so We // take out a right child from stack if (st.Count != 0) { curr = st.Pop(); } }} // Driver codepublic static void Main(String []args){ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(20); tree.root.right = new Node(30); tree.root.left.left = new Node(40); tree.root.left.left.left = new Node(70); tree.root.left.right = new Node(50); tree.root.right.left = new Node(60); tree.root.left.left.right = new Node(80); tree.preorderIterative();}} // This code is contributed by Amit Katiyar",
"e": 16415,
"s": 14734,
"text": null
},
{
"code": "<script> class Node{ constructor(item) { this.left = null; this.right = null; this.data = item; }} let root; // Iterative function to do Preorder// traversal of the treefunction preorderiterative(node){ if (node == null) { return; } let st = []; // Start from root node (set curr // node to root node) let curr = node; // Run till stack is not empty or // current is not NULL while (curr != null || st.length > 0) { // Print left children while exist // and keep pushing right into the // stack. while (curr != null) { document.write(curr.data + \" \"); if (curr.right != null) st.push(curr.right); curr = curr.left; } // We reach when curr is NULL, so We // take out a right child from stack if (st.length > 0) { curr = st.pop(); } }} function preorderIterative(){ preorderiterative(root);} // Driver coderoot = new Node(10);root.left = new Node(20);root.right = new Node(30);root.left.left = new Node(40);root.left.left.left = new Node(70);root.left.right = new Node(50);root.right.left = new Node(60);root.left.left.right = new Node(80); preorderIterative(); // This code is contributed by decode2207 </script>",
"e": 17755,
"s": 16415,
"text": null
},
{
"code": null,
"e": 17779,
"s": 17755,
"text": "10 20 40 70 80 50 30 60"
},
{
"code": null,
"e": 17861,
"s": 17781,
"text": "Time Complexity: O(N) Auxiliary Space: O(H), where H is the height of the tree."
},
{
"code": null,
"e": 17873,
"s": 17861,
"text": "shrikanth13"
},
{
"code": null,
"e": 17884,
"s": 17873,
"text": "andrew1234"
},
{
"code": null,
"e": 17905,
"s": 17884,
"text": "vivek singh bhadauri"
},
{
"code": null,
"e": 17920,
"s": 17905,
"text": "amit143katiyar"
},
{
"code": null,
"e": 17928,
"s": 17920,
"text": "user282"
},
{
"code": null,
"e": 17934,
"s": 17928,
"text": "itsok"
},
{
"code": null,
"e": 17945,
"s": 17934,
"text": "decode2207"
},
{
"code": null,
"e": 17962,
"s": 17945,
"text": "surinderdawra388"
},
{
"code": null,
"e": 17978,
"s": 17962,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 17995,
"s": 17978,
"text": "dhairya bhardwaj"
},
{
"code": null,
"e": 18012,
"s": 17995,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 18017,
"s": 18012,
"text": "Tree"
},
{
"code": null,
"e": 18022,
"s": 18017,
"text": "Tree"
},
{
"code": null,
"e": 18120,
"s": 18022,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18149,
"s": 18120,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 18181,
"s": 18149,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 18245,
"s": 18181,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 18295,
"s": 18245,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 18309,
"s": 18295,
"text": "Decision Tree"
},
{
"code": null,
"e": 18352,
"s": 18309,
"text": "Top 50 Tree Coding Problems for Interviews"
},
{
"code": null,
"e": 18394,
"s": 18352,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 18464,
"s": 18394,
"text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)"
},
{
"code": null,
"e": 18547,
"s": 18464,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
}
] |
How to put images in a box without space using Bootstrap?
|
19 Feb, 2020
Bootstrap 4 is a CSS a library for frontend web development developed by Twitter which helps the developer to beautify the way the webpage looks. The bootstrap library has pre-defined CSS classes that are easy to use and it helps the developer to provide an artistic look to the website with minimal effort.
The following line shows the syntax for inserting a simple image into the webpage
<img src="image-path" alt="Show this text if image does not appear" />
There are actually three ways to solve this problem. I am going to provide all three solutions here.
By providing a border to the image. Hence, it makes the image to be appearing inside the box.By using custom css to insert a image inside a div having border properties.By using bootstrap.
By providing a border to the image. Hence, it makes the image to be appearing inside the box.
By using custom css to insert a image inside a div having border properties.
By using bootstrap.
Let us see the demonstration of the above-stated ways.
By providing a border to the image.<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Bootstrap - Image inside Box</title></head><!-- Custom css to provide border to the image --><style> img{ border:5px solid green; /* This line gives a green border of 5 pixels width to all images on the webpage. */ This line does not cause any space between the image and the border. */ }</style><body> <h2> Putting image inside a Box </h2><!-- Put the path of image in the src of image tag. --> <img src="..." alt="Image Loading Failed" /> </body></html>Output:By using custom css<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Bootstrap - Image inside Box</title></head> <!-- Custom css to provide border to the div --><style> /* border class is used to give border to the div tag. */ .border{ border:5px solid green; /* green border of 5 pixels width */ padding:0; /* padding to remove the space between inner components of the div*/ max-width: fit-content; /* making the div take the size of the image */ } img{ display: block; /* to make the image occupy the whole container */ } </style><body> <h2> Putting image inside a Box </h2> <!-- Enclosing the image tag inside the div having border class. --> <div class="border"> <img src="..." alt="Image Loading Failed" /> </div> </body></html>Output:Using bootstrap 4 css: We will be using the pre-defined class known as cards to make image appear inside a box.<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Bootstrap - Image inside Box</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css" integrity="sha256-A47OwxL/nAN0ydiDFTSGX7ftbfTJTKgiJ0zqCuTPDh4=" crossorigin="anonymous" /></head><style> .border { border: 5px solid green !important; /* Border of width 5 pixels green in color */ width: fit-content; /* To make the image take whole space of container */ }</style> <body> <!-- Providing necessary padding and margin --> <h2 class="mx-5 mt-5"> Putting image inside a Box </h2> <!-- using card class to place image inside a box --> <!-- Added custom css class border for additional properties --> <!-- Added necessary padding and margin classes --> <div class="card mx-5 px-0 py-0 border"> <!-- Added card-img-top class to show the image on the top of the card. --> <!-- Since the image is the only content in card --> <!-- Image appears to be taking the whole card. --> <img src="..." alt="Image Loading Failed" class="card-img-top" /> </div> </body> </html>Output:
By providing a border to the image.<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Bootstrap - Image inside Box</title></head><!-- Custom css to provide border to the image --><style> img{ border:5px solid green; /* This line gives a green border of 5 pixels width to all images on the webpage. */ This line does not cause any space between the image and the border. */ }</style><body> <h2> Putting image inside a Box </h2><!-- Put the path of image in the src of image tag. --> <img src="..." alt="Image Loading Failed" /> </body></html>Output:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Bootstrap - Image inside Box</title></head><!-- Custom css to provide border to the image --><style> img{ border:5px solid green; /* This line gives a green border of 5 pixels width to all images on the webpage. */ This line does not cause any space between the image and the border. */ }</style><body> <h2> Putting image inside a Box </h2><!-- Put the path of image in the src of image tag. --> <img src="..." alt="Image Loading Failed" /> </body></html>
Output:
By using custom css<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Bootstrap - Image inside Box</title></head> <!-- Custom css to provide border to the div --><style> /* border class is used to give border to the div tag. */ .border{ border:5px solid green; /* green border of 5 pixels width */ padding:0; /* padding to remove the space between inner components of the div*/ max-width: fit-content; /* making the div take the size of the image */ } img{ display: block; /* to make the image occupy the whole container */ } </style><body> <h2> Putting image inside a Box </h2> <!-- Enclosing the image tag inside the div having border class. --> <div class="border"> <img src="..." alt="Image Loading Failed" /> </div> </body></html>Output:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Bootstrap - Image inside Box</title></head> <!-- Custom css to provide border to the div --><style> /* border class is used to give border to the div tag. */ .border{ border:5px solid green; /* green border of 5 pixels width */ padding:0; /* padding to remove the space between inner components of the div*/ max-width: fit-content; /* making the div take the size of the image */ } img{ display: block; /* to make the image occupy the whole container */ } </style><body> <h2> Putting image inside a Box </h2> <!-- Enclosing the image tag inside the div having border class. --> <div class="border"> <img src="..." alt="Image Loading Failed" /> </div> </body></html>
Output:
Using bootstrap 4 css: We will be using the pre-defined class known as cards to make image appear inside a box.<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Bootstrap - Image inside Box</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css" integrity="sha256-A47OwxL/nAN0ydiDFTSGX7ftbfTJTKgiJ0zqCuTPDh4=" crossorigin="anonymous" /></head><style> .border { border: 5px solid green !important; /* Border of width 5 pixels green in color */ width: fit-content; /* To make the image take whole space of container */ }</style> <body> <!-- Providing necessary padding and margin --> <h2 class="mx-5 mt-5"> Putting image inside a Box </h2> <!-- using card class to place image inside a box --> <!-- Added custom css class border for additional properties --> <!-- Added necessary padding and margin classes --> <div class="card mx-5 px-0 py-0 border"> <!-- Added card-img-top class to show the image on the top of the card. --> <!-- Since the image is the only content in card --> <!-- Image appears to be taking the whole card. --> <img src="..." alt="Image Loading Failed" class="card-img-top" /> </div> </body> </html>Output:
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Bootstrap - Image inside Box</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css" integrity="sha256-A47OwxL/nAN0ydiDFTSGX7ftbfTJTKgiJ0zqCuTPDh4=" crossorigin="anonymous" /></head><style> .border { border: 5px solid green !important; /* Border of width 5 pixels green in color */ width: fit-content; /* To make the image take whole space of container */ }</style> <body> <!-- Providing necessary padding and margin --> <h2 class="mx-5 mt-5"> Putting image inside a Box </h2> <!-- using card class to place image inside a box --> <!-- Added custom css class border for additional properties --> <!-- Added necessary padding and margin classes --> <div class="card mx-5 px-0 py-0 border"> <!-- Added card-img-top class to show the image on the top of the card. --> <!-- Since the image is the only content in card --> <!-- Image appears to be taking the whole card. --> <img src="..." alt="Image Loading Failed" class="card-img-top" /> </div> </body> </html>
Output:
Bootstrap-Misc
Picked
Technical Scripter 2019
Bootstrap
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
How to Add Image into Dropdown List for each items ?
How to make Bootstrap table with sticky table head?
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": 28,
"s": 0,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 336,
"s": 28,
"text": "Bootstrap 4 is a CSS a library for frontend web development developed by Twitter which helps the developer to beautify the way the webpage looks. The bootstrap library has pre-defined CSS classes that are easy to use and it helps the developer to provide an artistic look to the website with minimal effort."
},
{
"code": null,
"e": 418,
"s": 336,
"text": "The following line shows the syntax for inserting a simple image into the webpage"
},
{
"code": "<img src=\"image-path\" alt=\"Show this text if image does not appear\" />",
"e": 489,
"s": 418,
"text": null
},
{
"code": null,
"e": 590,
"s": 489,
"text": "There are actually three ways to solve this problem. I am going to provide all three solutions here."
},
{
"code": null,
"e": 779,
"s": 590,
"text": "By providing a border to the image. Hence, it makes the image to be appearing inside the box.By using custom css to insert a image inside a div having border properties.By using bootstrap."
},
{
"code": null,
"e": 873,
"s": 779,
"text": "By providing a border to the image. Hence, it makes the image to be appearing inside the box."
},
{
"code": null,
"e": 950,
"s": 873,
"text": "By using custom css to insert a image inside a div having border properties."
},
{
"code": null,
"e": 970,
"s": 950,
"text": "By using bootstrap."
},
{
"code": null,
"e": 1025,
"s": 970,
"text": "Let us see the demonstration of the above-stated ways."
},
{
"code": null,
"e": 4415,
"s": 1025,
"text": "By providing a border to the image.<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Bootstrap - Image inside Box</title></head><!-- Custom css to provide border to the image --><style> img{ border:5px solid green; /* This line gives a green border of 5 pixels width to all images on the webpage. */ This line does not cause any space between the image and the border. */ }</style><body> <h2> Putting image inside a Box </h2><!-- Put the path of image in the src of image tag. --> <img src=\"...\" alt=\"Image Loading Failed\" /> </body></html>Output:By using custom css<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Bootstrap - Image inside Box</title></head> <!-- Custom css to provide border to the div --><style> /* border class is used to give border to the div tag. */ .border{ border:5px solid green; /* green border of 5 pixels width */ padding:0; /* padding to remove the space between inner components of the div*/ max-width: fit-content; /* making the div take the size of the image */ } img{ display: block; /* to make the image occupy the whole container */ } </style><body> <h2> Putting image inside a Box </h2> <!-- Enclosing the image tag inside the div having border class. --> <div class=\"border\"> <img src=\"...\" alt=\"Image Loading Failed\" /> </div> </body></html>Output:Using bootstrap 4 css: We will be using the pre-defined class known as cards to make image appear inside a box.<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Bootstrap - Image inside Box</title> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css\" integrity=\"sha256-A47OwxL/nAN0ydiDFTSGX7ftbfTJTKgiJ0zqCuTPDh4=\" crossorigin=\"anonymous\" /></head><style> .border { border: 5px solid green !important; /* Border of width 5 pixels green in color */ width: fit-content; /* To make the image take whole space of container */ }</style> <body> <!-- Providing necessary padding and margin --> <h2 class=\"mx-5 mt-5\"> Putting image inside a Box </h2> <!-- using card class to place image inside a box --> <!-- Added custom css class border for additional properties --> <!-- Added necessary padding and margin classes --> <div class=\"card mx-5 px-0 py-0 border\"> <!-- Added card-img-top class to show the image on the top of the card. --> <!-- Since the image is the only content in card --> <!-- Image appears to be taking the whole card. --> <img src=\"...\" alt=\"Image Loading Failed\" class=\"card-img-top\" /> </div> </body> </html>Output:"
},
{
"code": null,
"e": 5196,
"s": 4415,
"text": "By providing a border to the image.<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Bootstrap - Image inside Box</title></head><!-- Custom css to provide border to the image --><style> img{ border:5px solid green; /* This line gives a green border of 5 pixels width to all images on the webpage. */ This line does not cause any space between the image and the border. */ }</style><body> <h2> Putting image inside a Box </h2><!-- Put the path of image in the src of image tag. --> <img src=\"...\" alt=\"Image Loading Failed\" /> </body></html>Output:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Bootstrap - Image inside Box</title></head><!-- Custom css to provide border to the image --><style> img{ border:5px solid green; /* This line gives a green border of 5 pixels width to all images on the webpage. */ This line does not cause any space between the image and the border. */ }</style><body> <h2> Putting image inside a Box </h2><!-- Put the path of image in the src of image tag. --> <img src=\"...\" alt=\"Image Loading Failed\" /> </body></html>",
"e": 5935,
"s": 5196,
"text": null
},
{
"code": null,
"e": 5943,
"s": 5935,
"text": "Output:"
},
{
"code": null,
"e": 7038,
"s": 5943,
"text": "By using custom css<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Bootstrap - Image inside Box</title></head> <!-- Custom css to provide border to the div --><style> /* border class is used to give border to the div tag. */ .border{ border:5px solid green; /* green border of 5 pixels width */ padding:0; /* padding to remove the space between inner components of the div*/ max-width: fit-content; /* making the div take the size of the image */ } img{ display: block; /* to make the image occupy the whole container */ } </style><body> <h2> Putting image inside a Box </h2> <!-- Enclosing the image tag inside the div having border class. --> <div class=\"border\"> <img src=\"...\" alt=\"Image Loading Failed\" /> </div> </body></html>Output:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Bootstrap - Image inside Box</title></head> <!-- Custom css to provide border to the div --><style> /* border class is used to give border to the div tag. */ .border{ border:5px solid green; /* green border of 5 pixels width */ padding:0; /* padding to remove the space between inner components of the div*/ max-width: fit-content; /* making the div take the size of the image */ } img{ display: block; /* to make the image occupy the whole container */ } </style><body> <h2> Putting image inside a Box </h2> <!-- Enclosing the image tag inside the div having border class. --> <div class=\"border\"> <img src=\"...\" alt=\"Image Loading Failed\" /> </div> </body></html>",
"e": 8107,
"s": 7038,
"text": null
},
{
"code": null,
"e": 8115,
"s": 8107,
"text": "Output:"
},
{
"code": null,
"e": 9631,
"s": 8115,
"text": "Using bootstrap 4 css: We will be using the pre-defined class known as cards to make image appear inside a box.<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Bootstrap - Image inside Box</title> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css\" integrity=\"sha256-A47OwxL/nAN0ydiDFTSGX7ftbfTJTKgiJ0zqCuTPDh4=\" crossorigin=\"anonymous\" /></head><style> .border { border: 5px solid green !important; /* Border of width 5 pixels green in color */ width: fit-content; /* To make the image take whole space of container */ }</style> <body> <!-- Providing necessary padding and margin --> <h2 class=\"mx-5 mt-5\"> Putting image inside a Box </h2> <!-- using card class to place image inside a box --> <!-- Added custom css class border for additional properties --> <!-- Added necessary padding and margin classes --> <div class=\"card mx-5 px-0 py-0 border\"> <!-- Added card-img-top class to show the image on the top of the card. --> <!-- Since the image is the only content in card --> <!-- Image appears to be taking the whole card. --> <img src=\"...\" alt=\"Image Loading Failed\" class=\"card-img-top\" /> </div> </body> </html>Output:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Bootstrap - Image inside Box</title> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css\" integrity=\"sha256-A47OwxL/nAN0ydiDFTSGX7ftbfTJTKgiJ0zqCuTPDh4=\" crossorigin=\"anonymous\" /></head><style> .border { border: 5px solid green !important; /* Border of width 5 pixels green in color */ width: fit-content; /* To make the image take whole space of container */ }</style> <body> <!-- Providing necessary padding and margin --> <h2 class=\"mx-5 mt-5\"> Putting image inside a Box </h2> <!-- using card class to place image inside a box --> <!-- Added custom css class border for additional properties --> <!-- Added necessary padding and margin classes --> <div class=\"card mx-5 px-0 py-0 border\"> <!-- Added card-img-top class to show the image on the top of the card. --> <!-- Since the image is the only content in card --> <!-- Image appears to be taking the whole card. --> <img src=\"...\" alt=\"Image Loading Failed\" class=\"card-img-top\" /> </div> </body> </html>",
"e": 11029,
"s": 9631,
"text": null
},
{
"code": null,
"e": 11037,
"s": 11029,
"text": "Output:"
},
{
"code": null,
"e": 11052,
"s": 11037,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 11059,
"s": 11052,
"text": "Picked"
},
{
"code": null,
"e": 11083,
"s": 11059,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 11093,
"s": 11083,
"text": "Bootstrap"
},
{
"code": null,
"e": 11112,
"s": 11093,
"text": "Technical Scripter"
},
{
"code": null,
"e": 11129,
"s": 11112,
"text": "Web Technologies"
},
{
"code": null,
"e": 11227,
"s": 11129,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11268,
"s": 11227,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 11331,
"s": 11268,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 11364,
"s": 11331,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 11417,
"s": 11364,
"text": "How to Add Image into Dropdown List for each items ?"
},
{
"code": null,
"e": 11469,
"s": 11417,
"text": "How to make Bootstrap table with sticky table head?"
},
{
"code": null,
"e": 11531,
"s": 11469,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 11564,
"s": 11531,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 11625,
"s": 11564,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 11675,
"s": 11625,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Keras - Locally connected layer
|
Locally connected layers are similar to Conv1D layer but the difference is Conv1D layer weights are shared but here weights are unshared. We can use different set of filters to apply different patch of input.
Locally connected layer has one arguments and it is as follows −
keras.layers.LocallyConnected1D(n)
A simple example to use Locally connected 1D layer is as follows −
>>> from keras.models import Sequential
>>> from keras.layers import Activation, Dense,LocallyConnected1D
>>> model = Sequential()
# apply a unshared weight convolution 1-dimension of length 3 to a sequence with
# 10 timesteps, with 16 output filters
>>> model.add(LocallyConnected1D(16, 3, input_shape = (10, 8)))
# add a new conv1d on top
>>> model.add(LocallyConnected1D(8, 3))
The signature of the Locally connected 1D layer function and its arguments with default value is as follows −
keras.layers.LocallyConnected1D (
filters,
kernel_size,
strides = 1,
padding = 'valid',
data_format = None,
activation = None,
use_bias = True,
kernel_initializer = 'glorot_uniform',
bias_initializer = 'zeros',
kernel_regularizer = None,
bias_regularizer = None,
activity_regularizer = None,
kernel_constraint = None,
bias_constraint = None
)
Here,
kernel_initializer refers initializer for the kernel weights matrix
kernel_initializer refers initializer for the kernel weights matrix
kernel_regularizer is used to apply regularize function to the kernel weights matrix.
kernel_regularizer is used to apply regularize function to the kernel weights matrix.
bias_regularizer is used to apply regularizer function to the bias vector.
bias_regularizer is used to apply regularizer function to the bias vector.
activity_regularizer is used to apply regularizer function to the output of the layer.
activity_regularizer is used to apply regularizer function to the output of the layer.
Similarly, we can use 2D and 3D layers as well.
It is used in Recurrent neural networks(RNN). It is defined as shown below −
keras.engine.base_layer.wrapped_fn()
It supports the following parameters −
cell refers an instance.
cell refers an instance.
return_sequences return the last output in the output sequence, or the full sequence.
return_sequences return the last output in the output sequence, or the full sequence.
return_state returns the last state in addition to the output.
return_state returns the last state in addition to the output.
go_backwards returns a boolean result. If the value is true, then process the input sequence backwards otherwise return the reversed sequence.
go_backwards returns a boolean result. If the value is true, then process the input sequence backwards otherwise return the reversed sequence.
stateful refers the state for each index.
stateful refers the state for each index.
unroll specifies whether the network to be unrolled or not.
unroll specifies whether the network to be unrolled or not.
input_dim refers the input dimension.
input_dim refers the input dimension.
input_length refers the length of input sequence.
input_length refers the length of input sequence.
|
[
{
"code": null,
"e": 2394,
"s": 2185,
"text": "Locally connected layers are similar to Conv1D layer but the difference is Conv1D layer weights are shared but here weights are unshared. We can use different set of filters to apply different patch of input."
},
{
"code": null,
"e": 2459,
"s": 2394,
"text": "Locally connected layer has one arguments and it is as follows −"
},
{
"code": null,
"e": 2495,
"s": 2459,
"text": "keras.layers.LocallyConnected1D(n)\n"
},
{
"code": null,
"e": 2562,
"s": 2495,
"text": "A simple example to use Locally connected 1D layer is as follows −"
},
{
"code": null,
"e": 2953,
"s": 2562,
"text": ">>> from keras.models import Sequential \n>>> from keras.layers import Activation, Dense,LocallyConnected1D \n>>> model = Sequential() \n\n# apply a unshared weight convolution 1-dimension of length 3 to a sequence with \n# 10 timesteps, with 16 output filters \n\n>>> model.add(LocallyConnected1D(16, 3, input_shape = (10, 8))) \n\n# add a new conv1d on top \n>>> model.add(LocallyConnected1D(8, 3))"
},
{
"code": null,
"e": 3063,
"s": 2953,
"text": "The signature of the Locally connected 1D layer function and its arguments with default value is as follows −"
},
{
"code": null,
"e": 3461,
"s": 3063,
"text": "keras.layers.LocallyConnected1D (\n filters, \n kernel_size, \n strides = 1, \n padding = 'valid', \n data_format = None, \n activation = None, \n use_bias = True, \n kernel_initializer = 'glorot_uniform', \n bias_initializer = 'zeros', \n kernel_regularizer = None, \n bias_regularizer = None, \n activity_regularizer = None, \n kernel_constraint = None, \n bias_constraint = None\n)"
},
{
"code": null,
"e": 3467,
"s": 3461,
"text": "Here,"
},
{
"code": null,
"e": 3535,
"s": 3467,
"text": "kernel_initializer refers initializer for the kernel weights matrix"
},
{
"code": null,
"e": 3603,
"s": 3535,
"text": "kernel_initializer refers initializer for the kernel weights matrix"
},
{
"code": null,
"e": 3689,
"s": 3603,
"text": "kernel_regularizer is used to apply regularize function to the kernel weights matrix."
},
{
"code": null,
"e": 3775,
"s": 3689,
"text": "kernel_regularizer is used to apply regularize function to the kernel weights matrix."
},
{
"code": null,
"e": 3850,
"s": 3775,
"text": "bias_regularizer is used to apply regularizer function to the bias vector."
},
{
"code": null,
"e": 3925,
"s": 3850,
"text": "bias_regularizer is used to apply regularizer function to the bias vector."
},
{
"code": null,
"e": 4012,
"s": 3925,
"text": "activity_regularizer is used to apply regularizer function to the output of the layer."
},
{
"code": null,
"e": 4099,
"s": 4012,
"text": "activity_regularizer is used to apply regularizer function to the output of the layer."
},
{
"code": null,
"e": 4147,
"s": 4099,
"text": "Similarly, we can use 2D and 3D layers as well."
},
{
"code": null,
"e": 4224,
"s": 4147,
"text": "It is used in Recurrent neural networks(RNN). It is defined as shown below −"
},
{
"code": null,
"e": 4262,
"s": 4224,
"text": "keras.engine.base_layer.wrapped_fn()\n"
},
{
"code": null,
"e": 4301,
"s": 4262,
"text": "It supports the following parameters −"
},
{
"code": null,
"e": 4326,
"s": 4301,
"text": "cell refers an instance."
},
{
"code": null,
"e": 4351,
"s": 4326,
"text": "cell refers an instance."
},
{
"code": null,
"e": 4437,
"s": 4351,
"text": "return_sequences return the last output in the output sequence, or the full sequence."
},
{
"code": null,
"e": 4523,
"s": 4437,
"text": "return_sequences return the last output in the output sequence, or the full sequence."
},
{
"code": null,
"e": 4586,
"s": 4523,
"text": "return_state returns the last state in addition to the output."
},
{
"code": null,
"e": 4649,
"s": 4586,
"text": "return_state returns the last state in addition to the output."
},
{
"code": null,
"e": 4792,
"s": 4649,
"text": "go_backwards returns a boolean result. If the value is true, then process the input sequence backwards otherwise return the reversed sequence."
},
{
"code": null,
"e": 4935,
"s": 4792,
"text": "go_backwards returns a boolean result. If the value is true, then process the input sequence backwards otherwise return the reversed sequence."
},
{
"code": null,
"e": 4977,
"s": 4935,
"text": "stateful refers the state for each index."
},
{
"code": null,
"e": 5019,
"s": 4977,
"text": "stateful refers the state for each index."
},
{
"code": null,
"e": 5079,
"s": 5019,
"text": "unroll specifies whether the network to be unrolled or not."
},
{
"code": null,
"e": 5139,
"s": 5079,
"text": "unroll specifies whether the network to be unrolled or not."
},
{
"code": null,
"e": 5177,
"s": 5139,
"text": "input_dim refers the input dimension."
},
{
"code": null,
"e": 5215,
"s": 5177,
"text": "input_dim refers the input dimension."
},
{
"code": null,
"e": 5265,
"s": 5215,
"text": "input_length refers the length of input sequence."
}
] |
Running GUI Applications on Docker in Linux
|
21 Oct, 2020
Let’s say you are trying to build a UI application and deploying it as a Docker Container. If you want that UI application to display the user interface on your local machine while running the application inside the Docker Container, you will have to connect the display of the Docker Container with the display of your local machine. Let’s suppose you want to run Mozilla Firefox inside a Docker Container but you want to access the Firefox browser on your local machine. You can do this using some simple steps that we are going to discuss in this article.
Skimming through the entire process, you need to forward the X11 socket of your local Linux machine to the Docker Container for it to use directly. Along with this, you also need to forward the environment variable called display. After that, you need to set the permissions for the server host. Let’s run through these steps along with the code.
Create a dockerfile with the following code.
FROM ubuntu:latest
RUN apt-get -y update
RUN apt-get -y install firefox
RUN apt-get -y install xauth
EXPOSE 8887
CMD firefox
The above dockerfile contains the sequence of instructions to create an Ubuntu base image, runs an apt update on it, installs Xauth and Firefox. It then exposes port 8887 and runs Firefox. Xauth simply allows Docker Containers to access the Display Servers.
On your local machine, get the cookie value using the following command.
xauth list
Authorization Cookie
Copy the output which would be of the form as shown below:
<username>/unix: MIT-MAGIC-COOKIE-1 f1fa006c1e51fa8386209f85c57947c4
Create the Docker Image using the following command.
docker build -t <image-name> .
Docker build command
Run the Docker Image using the Docker run command.
docker run -it --net=host -e DISPLAY -v /tmp/.X11-unix <image-name> bash
Docker run command
The Docker image is now built and the Container is started. It pops up an interactive Ubuntu bash.
You need to add the cookie copied in the previous step using the following command.
xauth add <cookie>
xauth list
Adding Cookie
The list command will verify that the cookie has been added successfully.
6. Run the Firefox Instance from the bash
To run a Firefox instance, simply type “firefox” inside the bash. You will find that the Firefox browser pops up on your local machine even though it is running inside the Docker Container. Using a similar process, you can run almost any user interface application inside Docker Containers and access it on your local machine.
Running Firefox Instance
To conclude, in this article we saw how to create a Docker Image using the dockerfile, build and run the image. We also discussed how to connect the display of the Docker Container to the display of the local machine and accessed a UI application running inside Container on the local machine.
Docker Container
linux
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Oct, 2020"
},
{
"code": null,
"e": 611,
"s": 52,
"text": "Let’s say you are trying to build a UI application and deploying it as a Docker Container. If you want that UI application to display the user interface on your local machine while running the application inside the Docker Container, you will have to connect the display of the Docker Container with the display of your local machine. Let’s suppose you want to run Mozilla Firefox inside a Docker Container but you want to access the Firefox browser on your local machine. You can do this using some simple steps that we are going to discuss in this article."
},
{
"code": null,
"e": 958,
"s": 611,
"text": "Skimming through the entire process, you need to forward the X11 socket of your local Linux machine to the Docker Container for it to use directly. Along with this, you also need to forward the environment variable called display. After that, you need to set the permissions for the server host. Let’s run through these steps along with the code."
},
{
"code": null,
"e": 1003,
"s": 958,
"text": "Create a dockerfile with the following code."
},
{
"code": null,
"e": 1131,
"s": 1003,
"text": "FROM ubuntu:latest\nRUN apt-get -y update\nRUN apt-get -y install firefox\nRUN apt-get -y install xauth\n\nEXPOSE 8887\nCMD firefox\n\n"
},
{
"code": null,
"e": 1389,
"s": 1131,
"text": "The above dockerfile contains the sequence of instructions to create an Ubuntu base image, runs an apt update on it, installs Xauth and Firefox. It then exposes port 8887 and runs Firefox. Xauth simply allows Docker Containers to access the Display Servers."
},
{
"code": null,
"e": 1462,
"s": 1389,
"text": "On your local machine, get the cookie value using the following command."
},
{
"code": null,
"e": 1475,
"s": 1462,
"text": "xauth list\n\n"
},
{
"code": null,
"e": 1496,
"s": 1475,
"text": "Authorization Cookie"
},
{
"code": null,
"e": 1556,
"s": 1496,
"text": "Copy the output which would be of the form as shown below:"
},
{
"code": null,
"e": 1629,
"s": 1556,
"text": "<username>/unix: MIT-MAGIC-COOKIE-1 f1fa006c1e51fa8386209f85c57947c4\n\n"
},
{
"code": null,
"e": 1682,
"s": 1629,
"text": "Create the Docker Image using the following command."
},
{
"code": null,
"e": 1715,
"s": 1682,
"text": "docker build -t <image-name> .\n\n"
},
{
"code": null,
"e": 1736,
"s": 1715,
"text": "Docker build command"
},
{
"code": null,
"e": 1787,
"s": 1736,
"text": "Run the Docker Image using the Docker run command."
},
{
"code": null,
"e": 1862,
"s": 1787,
"text": "docker run -it --net=host -e DISPLAY -v /tmp/.X11-unix <image-name> bash\n\n"
},
{
"code": null,
"e": 1881,
"s": 1862,
"text": "Docker run command"
},
{
"code": null,
"e": 1980,
"s": 1881,
"text": "The Docker image is now built and the Container is started. It pops up an interactive Ubuntu bash."
},
{
"code": null,
"e": 2064,
"s": 1980,
"text": "You need to add the cookie copied in the previous step using the following command."
},
{
"code": null,
"e": 2096,
"s": 2064,
"text": "xauth add <cookie>\nxauth list\n\n"
},
{
"code": null,
"e": 2110,
"s": 2096,
"text": "Adding Cookie"
},
{
"code": null,
"e": 2184,
"s": 2110,
"text": "The list command will verify that the cookie has been added successfully."
},
{
"code": null,
"e": 2226,
"s": 2184,
"text": "6. Run the Firefox Instance from the bash"
},
{
"code": null,
"e": 2553,
"s": 2226,
"text": "To run a Firefox instance, simply type “firefox” inside the bash. You will find that the Firefox browser pops up on your local machine even though it is running inside the Docker Container. Using a similar process, you can run almost any user interface application inside Docker Containers and access it on your local machine."
},
{
"code": null,
"e": 2578,
"s": 2553,
"text": "Running Firefox Instance"
},
{
"code": null,
"e": 2872,
"s": 2578,
"text": "To conclude, in this article we saw how to create a Docker Image using the dockerfile, build and run the image. We also discussed how to connect the display of the Docker Container to the display of the local machine and accessed a UI application running inside Container on the local machine."
},
{
"code": null,
"e": 2889,
"s": 2872,
"text": "Docker Container"
},
{
"code": null,
"e": 2895,
"s": 2889,
"text": "linux"
},
{
"code": null,
"e": 2906,
"s": 2895,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3004,
"s": 2906,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3030,
"s": 3004,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3065,
"s": 3030,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 3102,
"s": 3065,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 3131,
"s": 3102,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 3168,
"s": 3131,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 3202,
"s": 3168,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 3239,
"s": 3202,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 3279,
"s": 3239,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 3318,
"s": 3279,
"text": "Introduction to Linux Operating System"
}
] |
factor command in Linux with examples
|
15 May, 2019
The factor command in Linux is used to print the prime factors of the given numbers, either given from command line or read from standard input.
The numbers given through standard input may be delimited by tabs, spaces or newlines.
Syntax:
factor [NUMBER]
Factor 100 (non-prime number):We get the prime factors 2 and 5 that make up 100.
Factor 13 (prime number itself) :
Factor of 221 (product of two primes) :Under the hood, the factor command uses the Pollard-Brent rho algorithm to find out the prime factors.
Under the hood, the factor command uses the Pollard-Brent rho algorithm to find out the prime factors.
factor --help : This command only supports a few numbers of options, that is its help command and version number.
linux-command
Linux-misc-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
TCP Server-Client implementation in C
Conditional Statements | Shell Script
Tail command in Linux with examples
UDP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
Cat command in Linux with examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 173,
"s": 28,
"text": "The factor command in Linux is used to print the prime factors of the given numbers, either given from command line or read from standard input."
},
{
"code": null,
"e": 260,
"s": 173,
"text": "The numbers given through standard input may be delimited by tabs, spaces or newlines."
},
{
"code": null,
"e": 268,
"s": 260,
"text": "Syntax:"
},
{
"code": null,
"e": 284,
"s": 268,
"text": "factor [NUMBER]"
},
{
"code": null,
"e": 365,
"s": 284,
"text": "Factor 100 (non-prime number):We get the prime factors 2 and 5 that make up 100."
},
{
"code": null,
"e": 399,
"s": 365,
"text": "Factor 13 (prime number itself) :"
},
{
"code": null,
"e": 541,
"s": 399,
"text": "Factor of 221 (product of two primes) :Under the hood, the factor command uses the Pollard-Brent rho algorithm to find out the prime factors."
},
{
"code": null,
"e": 644,
"s": 541,
"text": "Under the hood, the factor command uses the Pollard-Brent rho algorithm to find out the prime factors."
},
{
"code": null,
"e": 758,
"s": 644,
"text": "factor --help : This command only supports a few numbers of options, that is its help command and version number."
},
{
"code": null,
"e": 772,
"s": 758,
"text": "linux-command"
},
{
"code": null,
"e": 792,
"s": 772,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 799,
"s": 792,
"text": "Picked"
},
{
"code": null,
"e": 823,
"s": 799,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 834,
"s": 823,
"text": "Linux-Unix"
},
{
"code": null,
"e": 853,
"s": 834,
"text": "Technical Scripter"
},
{
"code": null,
"e": 951,
"s": 853,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 986,
"s": 951,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 1021,
"s": 986,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 1057,
"s": 1021,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 1095,
"s": 1057,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 1133,
"s": 1095,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 1169,
"s": 1133,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 1207,
"s": 1169,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 1233,
"s": 1207,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1268,
"s": 1233,
"text": "scp command in Linux with Examples"
}
] |
sciPy stats.variation() function | Python
|
13 Feb, 2019
scipy.stats.variation(arr, axis = None) function computes the coefficient of variation. It is defined as the ratio of standard deviation to mean.
Parameters :arr : [array_like] input array.axis : [int or tuples of int] axis along which we want to calculate the coefficient of variation.-> axis = 0 coefficient of variation along the column.-> axis = 1 coefficient of variation working along the row.
Results : Coefficient of variation of the array with values along specified axis.
Code #1: Use of variation()
from scipy.stats import variation import numpy as np arr = np.random.randn(5, 5) print ("array : \n", arr) # rows: axis = 0, cols: axis = 1 print ("\nVariation at axis = 0: \n", variation(arr, axis = 0)) print ("\nVariation at axis = 1: \n", variation(arr, axis = 1))
array :
[[-1.16536706 -1.29744691 -0.39964651 2.14909277 -1.00669835]
[ 0.79979681 0.91566149 -0.823054 0.9189682 -0.01061181]
[ 0.9532622 0.38630077 -0.79026789 -0.70154086 0.79087801]
[ 0.53553389 1.46409899 1.89903817 -0.35360202 -0.14597738]
[-1.53582875 -0.50077039 -0.23073327 0.32457064 -0.43269088]]
Variation at axis = 0:
[-12.73042404 5.10272979 -14.6476392 2.15882202 -3.64031032]
Variation at axis = 1:
[-3.73200773 1.90419038 5.77300406 1.29451485 -1.27228112]
Code #2: How to implement without variation()
import numpy as np arr = np.random.randn(5, 5) print ("array : \n", arr) # this function works similar to variation()cv = lambda x: np.std(x) / np.mean(x) var1 = np.apply_along_axis(cv, axis = 0, arr = arr)print ("\nVariation at axis = 0: \n", var1) var2 = np.apply_along_axis(cv, axis = 1, arr = arr)print ("\nVariation at axis = 0: \n", var2)
array :
[[ 0.51268414 -1.93697931 0.41573223 2.14911168 0.15036631]
[-0.50407207 1.51519879 -0.42217231 -1.09609322 1.93184432]
[-1.07727163 0.27195529 -0.1308108 -1.75406388 0.94046395]
[ 1.23283059 -0.03112461 0.59725109 0.06671002 -0.97537666]
[ 1.1233506 0.97658799 -1.10309113 -1.33142901 -0.28470146]]
Variation at axis = 0:
[ 3.52845174 7.40891024 -4.74078192 -3.57928544 2.85092056]
Variation at axis = 0:
[ 5.04874565 4.22763514 -2.74104828 4.10772935 -8.24126977]
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Feb, 2019"
},
{
"code": null,
"e": 174,
"s": 28,
"text": "scipy.stats.variation(arr, axis = None) function computes the coefficient of variation. It is defined as the ratio of standard deviation to mean."
},
{
"code": null,
"e": 428,
"s": 174,
"text": "Parameters :arr : [array_like] input array.axis : [int or tuples of int] axis along which we want to calculate the coefficient of variation.-> axis = 0 coefficient of variation along the column.-> axis = 1 coefficient of variation working along the row."
},
{
"code": null,
"e": 510,
"s": 428,
"text": "Results : Coefficient of variation of the array with values along specified axis."
},
{
"code": null,
"e": 538,
"s": 510,
"text": "Code #1: Use of variation()"
},
{
"code": "from scipy.stats import variation import numpy as np arr = np.random.randn(5, 5) print (\"array : \\n\", arr) # rows: axis = 0, cols: axis = 1 print (\"\\nVariation at axis = 0: \\n\", variation(arr, axis = 0)) print (\"\\nVariation at axis = 1: \\n\", variation(arr, axis = 1))",
"e": 811,
"s": 538,
"text": null
},
{
"code": null,
"e": 1319,
"s": 811,
"text": "array : \n [[-1.16536706 -1.29744691 -0.39964651 2.14909277 -1.00669835]\n [ 0.79979681 0.91566149 -0.823054 0.9189682 -0.01061181]\n [ 0.9532622 0.38630077 -0.79026789 -0.70154086 0.79087801]\n [ 0.53553389 1.46409899 1.89903817 -0.35360202 -0.14597738]\n [-1.53582875 -0.50077039 -0.23073327 0.32457064 -0.43269088]]\n\nVariation at axis = 0: \n [-12.73042404 5.10272979 -14.6476392 2.15882202 -3.64031032]\n\nVariation at axis = 1: \n [-3.73200773 1.90419038 5.77300406 1.29451485 -1.27228112]\n"
},
{
"code": null,
"e": 1366,
"s": 1319,
"text": " Code #2: How to implement without variation()"
},
{
"code": "import numpy as np arr = np.random.randn(5, 5) print (\"array : \\n\", arr) # this function works similar to variation()cv = lambda x: np.std(x) / np.mean(x) var1 = np.apply_along_axis(cv, axis = 0, arr = arr)print (\"\\nVariation at axis = 0: \\n\", var1) var2 = np.apply_along_axis(cv, axis = 1, arr = arr)print (\"\\nVariation at axis = 0: \\n\", var2)",
"e": 1716,
"s": 1366,
"text": null
},
{
"code": null,
"e": 2219,
"s": 1716,
"text": "array : \n [[ 0.51268414 -1.93697931 0.41573223 2.14911168 0.15036631]\n [-0.50407207 1.51519879 -0.42217231 -1.09609322 1.93184432]\n [-1.07727163 0.27195529 -0.1308108 -1.75406388 0.94046395]\n [ 1.23283059 -0.03112461 0.59725109 0.06671002 -0.97537666]\n [ 1.1233506 0.97658799 -1.10309113 -1.33142901 -0.28470146]]\n\nVariation at axis = 0: \n [ 3.52845174 7.40891024 -4.74078192 -3.57928544 2.85092056]\n\nVariation at axis = 0: \n [ 5.04874565 4.22763514 -2.74104828 4.10772935 -8.24126977]\n"
},
{
"code": null,
"e": 2248,
"s": 2219,
"text": "Python scipy-stats-functions"
},
{
"code": null,
"e": 2261,
"s": 2248,
"text": "Python-scipy"
},
{
"code": null,
"e": 2268,
"s": 2261,
"text": "Python"
}
] |
Product of minimum edge weight between all pairs of a Tree
|
05 May, 2022
Given a tree with N vertices and N-1 Edges. Let’s define a function F(a, b) which is equal to the minimum edge weight in the path between node a & b. The task is to calculate the product of all such F(a, b). Here a&b are unordered pairs and a!=b.So, basically, we need to find the value of:
where 0<=i<j<=n-1.
In the input, we will be given the value of N and then N-1 lines follow. Each line contains 3 integers u, v, w denoting edge between node u and v and it’s weight w. Since the product will be very large, output it modulo 10^9+7. Examples:
Input :
N = 4
1 2 1
1 3 3
4 3 2
Output : 12
Given tree is:
1
(1)/ \(3)
2 3
\(2)
4
We will calculate the minimum edge weight between all the pairs:
F(1, 2) = 1 F(2, 3) = 1
F(1, 3) = 3 F(2, 4) = 1
F(1, 4) = 2 F(3, 4) = 2
Product of all F(i, j) = 1*3*2*1*1*2 = 12 mod (10^9 +7) =12
Input :
N = 5
1 2 1
1 3 3
4 3 2
1 5 4
Output :
288
If we observe carefully then we will see that if there is a set of nodes in which minimum edge weight is w and if we add a node to this set that connects the node with the whole set by an edge of weight W such that W<w then path formed between recently added node to all nodes present in the set will have minimum weight W. So, here we can apply Disjoint-Set Union concept to solve the problem. First, sort the data structure according to decreasing weight. Initially assign all nodes as a single set. Now when we merge two sets then do the following:-
Product=(present weight)^(size of set1*size of set2).
We will multiply this product value for all edges of the tree.Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// C++ Implementation of above approach#include <bits/stdc++.h>using namespace std;#define mod 1000000007 // Function to return (x^y) mod pint power(int x, unsigned int y, int p){ int res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res;} // Declaring size array globallyint size[300005];int freq[300004];vector<pair<int, pair<int, int> > > edges; // Initializing DSU data structurevoid initialize(int Arr[], int N){ for (int i = 0; i < N; i++) { Arr[i] = i; size[i] = 1; }} // Function to find the root of ith// node in the disjoint setint root(int Arr[], int i){ while (Arr[i] != i) { i = Arr[i]; } return i;} // Weighted union using Path Compressionvoid weighted_union(int Arr[], int size[], int A, int B){ int root_A = root(Arr, A); int root_B = root(Arr, B); // size of set A is small than size of set B if (size[root_A] < size[root_B]) { Arr[root_A] = Arr[root_B]; size[root_B] += size[root_A]; } // size of set B is small than size of set A else { Arr[root_B] = Arr[root_A]; size[root_A] += size[root_B]; }} // Function to add an edge in the treevoid AddEdge(int a, int b, int w){ edges.push_back({ w, { a, b } });} // Build the treevoid MakeTree(){ AddEdge(1, 2, 1); AddEdge(1, 3, 3); AddEdge(3, 4, 2);} // Function to return the required productint MinProduct(){ int result = 1; // Sorting the edges with respect to its weight sort(edges.begin(), edges.end()); // Start iterating in decreasing order of weight for (int i = edges.size() - 1; i >= 0; i--) { // Determine Current edge values int curr_weight = edges[i].first; int Node1 = edges[i].second.first; int Node2 = edges[i].second.second; // Calculate root of each node // and size of each set int Root1 = root(freq, Node1); int Set1_size = size[Root1]; int Root2 = root(freq, Node2); int Set2_size = size[Root2]; // Using the formula int prod = Set1_size * Set2_size; int Product = power(curr_weight, prod, mod); // Calculating final result result = ((result % mod) * (Product % mod)) % mod; // Weighted union using Path Compression weighted_union(freq, size, Node1, Node2); } return result % mod;} // Driver codeint main(){ int n = 4; initialize(freq, n); MakeTree(); cout << MinProduct();}
// Java Implementation of above approach import java.util.ArrayList;import java.util.Collections; public class Product { // to store first vertex, second vertex and weight of // the edge static class Edge implements Comparable<Edge> { int first, second, weight; Edge(int x, int y, int w) { this.first = x; this.second = y; this.weight = w; } @Override public int compareTo(Edge edge) { return this.weight - edge.weight; } } static int mod = 1000000007; // Function to return (x^y) mod p static int power(int x, int y, int p) { int res = 1; x = x % p; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } // Declaring size array globally static int size[] = new int[300005]; static int freq[] = new int[300004]; static ArrayList<Edge> edges = new ArrayList<Edge>(); // Initializing DSU data structure static void initialize(int Arr[], int N) { for (int i = 0; i < N; i++) { Arr[i] = i; size[i] = 1; } } // Function to find the root of ith // node in the disjoint set static int root(int Arr[], int i) { while (Arr[i] != i) { i = Arr[i]; } return i; } // Weighted union using Path Compression static void weighted_union(int Arr[], int size[], int A, int B) { int root_A = root(Arr, A); int root_B = root(Arr, B); // size of set A is small than size of set B if (size[root_A] < size[root_B]) { Arr[root_A] = Arr[root_B]; size[root_B] += size[root_A]; } // size of set B is small than size of set A else { Arr[root_B] = Arr[root_A]; size[root_A] += size[root_B]; } } // Function to add an edge in the tree static void AddEdge(int a, int b, int w) { edges.add(new Edge(a, b, w)); } // Build the tree static void MakeTree() { AddEdge(1, 2, 1); AddEdge(1, 3, 3); AddEdge(3, 4, 2); } // Function to return the required product static int MinProduct() { int result = 1; // Sorting the edges with respect to its weight // ascending order Collections.sort(edges); // Start iterating in decreasing order of weight for (int i = edges.size() - 1; i >= 0; i--) { // Determine Current edge values int curr_weight = edges.get(i).weight; int Node1 = edges.get(i).first; int Node2 = edges.get(i).second; // Calculate root of each node // and size of each set int Root1 = root(freq, Node1); int Set1_size = size[Root1]; int Root2 = root(freq, Node2); int Set2_size = size[Root2]; // Using the formula int prod = Set1_size * Set2_size; int Product = power(curr_weight, prod, mod); // Calculating final result result = ((result % mod) * (Product % mod)) % mod; // Weighted union using Path Compression weighted_union(freq, size, Node1, Node2); } return result % mod; } // Driver code public static void main(String[] args) { int n = 4; initialize(freq, n); MakeTree(); System.out.println(MinProduct()); }} // This code is contributed by jainlovely450
# Python3 implementation of the approachmod = 1000000007 # Function to return (x^y) mod pdef power(x: int, y: int, p: int) -> int: res = 1 x %= p while y > 0: if y & 1: res = (res * x) % p y = y // 2 x = (x * x) % p return res # Declaring size array globallysize = [0] * 300005freq = [0] * 300004edges = [] # Initializing DSU data structuredef initialize(arr: list, N: int): for i in range(N): arr[i] = i size[i] = 1 # Function to find the root of ith# node in the disjoint setdef root(arr: list, i: int) -> int: while arr[i] != i: i = arr[i] return i # Weighted union using Path Compressiondef weighted_union(arr: list, size: list, A: int, B: int): root_A = root(arr, A) root_B = root(arr, B) # size of set A is small than size of set B if size[root_A] < size[root_B]: arr[root_A] = arr[root_B] size[root_B] += size[root_A] # size of set B is small than size of set A else: arr[root_B] = arr[root_A] size[root_A] += size[root_B] # Function to add an edge in the treedef AddEdge(a: int, b: int, w: int): edges.append((w, (a, b))) # Build the treedef makeTree(): AddEdge(1, 2, 1) AddEdge(1, 3, 3) AddEdge(3, 4, 2) # Function to return the required productdef minProduct() -> int: result = 1 # Sorting the edges with respect to its weight edges.sort(key = lambda a: a[0]) # Start iterating in decreasing order of weight for i in range(len(edges) - 1, -1, -1): # Determine Current edge values curr_weight = edges[i][0] node1 = edges[i][1][0] node2 = edges[i][1][1] # Calculate root of each node # and size of each set root1 = root(freq, node1) set1_size = size[root1] root2 = root(freq, node2) set2_size = size[root2] # Using the formula prod = set1_size * set2_size product = power(curr_weight, prod, mod) # Calculating final result result = ((result % mod) * (product % mod)) % mod # Weighted union using Path Compression weighted_union(freq, size, node1, node2) return result % mod # Driver Codeif __name__ == "__main__": # Number of nodes and edges n = 4 initialize(freq, n) makeTree() print(minProduct()) # This code is contributed by# sanjeev2552
<script> // JavaScript implementation of the approachconst mod = 1000000007 // Function to return (x^y) mod pfunction power(x, y, p){ let res = 1 x %= p while(y > 0){ if(y & 1) res = (res * x) % p y = Math.floor(y / 2) x = (x * x) % p } return res} // Declaring size array globallylet size = new Array(300005).fill(0)let freq = new Array(300004).fill(0)let edges = [] // Initializing DSU data structurefunction initialize(arr, N){ for(let i=0;i<N;i++){ arr[i] = i size[i] = 1 }} // Function to find the root of ith// node in the disjoint setfunction root(arr, i){ while(arr[i] != i) i = arr[i] return i} // Weighted union using Path Compressionfunction weighted_union(arr, size, A, B){ let root_A = root(arr, A) let root_B = root(arr, B) // size of set A is small than size of set B if(size[root_A] < size[root_B]){ arr[root_A] = arr[root_B] size[root_B] += size[root_A] } // size of set B is small than size of set A else{ arr[root_B] = arr[root_A] size[root_A] += size[root_B] }} // Function to add an edge in the treefunction AddEdge(a, b, w){ edges.push([w, [a, b]])} // Build the treefunction makeTree(){ AddEdge(1, 2, 1) AddEdge(1, 3, 3) AddEdge(3, 4, 2)} // Function to return the required productfunction minProduct(){ let result = 1 // Sorting the edges with respect to its weight edges.sort((a,b)=>a[0]-b[0]) // Start iterating in decreasing order of weight for(let i=edges.length - 1;i>=0;i--){ // Determine Current edge values let curr_weight = edges[i][0] let node1 = edges[i][1][0] let node2 = edges[i][1][1] // Calculate root of each node // and size of each set let root1 = root(freq, node1) let set1_size = size[root1] let root2 = root(freq, node2) let set2_size = size[root2] // Using the formula let prod = set1_size * set2_size let product = power(curr_weight, prod, mod) // Calculating final result result = ((result % mod) * (product % mod)) % mod // Weighted union using Path Compression weighted_union(freq, size, node1, node2) } return result % mod} // Driver Code // Number of nodes and edgeslet n = 4initialize(freq, n)makeTree()document.write(minProduct(),"</br>") // This code is contributed by shinjanpatra</script>
12
Time Complexity : O(N*logN)
sanjeev2552
arorakashish0911
jainlovely450
shinjanpatra
union-find
Graph
Sorting
Tree
Sorting
Graph
Tree
union-find
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in a directed graph
Topological Sorting
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Detect Cycle in a Directed Graph
Introduction to Data Structures
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 May, 2022"
},
{
"code": null,
"e": 345,
"s": 52,
"text": "Given a tree with N vertices and N-1 Edges. Let’s define a function F(a, b) which is equal to the minimum edge weight in the path between node a & b. The task is to calculate the product of all such F(a, b). Here a&b are unordered pairs and a!=b.So, basically, we need to find the value of: "
},
{
"code": null,
"e": 391,
"s": 345,
"text": " where 0<=i<j<=n-1."
},
{
"code": null,
"e": 630,
"s": 391,
"text": "In the input, we will be given the value of N and then N-1 lines follow. Each line contains 3 integers u, v, w denoting edge between node u and v and it’s weight w. Since the product will be very large, output it modulo 10^9+7. Examples: "
},
{
"code": null,
"e": 1042,
"s": 630,
"text": "Input :\nN = 4\n1 2 1\n1 3 3\n4 3 2\nOutput : 12\nGiven tree is:\n 1\n (1)/ \\(3)\n 2 3\n \\(2)\n 4\nWe will calculate the minimum edge weight between all the pairs:\nF(1, 2) = 1 F(2, 3) = 1\nF(1, 3) = 3 F(2, 4) = 1\nF(1, 4) = 2 F(3, 4) = 2\nProduct of all F(i, j) = 1*3*2*1*1*2 = 12 mod (10^9 +7) =12\n\nInput :\nN = 5\n1 2 1\n1 3 3\n4 3 2\n1 5 4\nOutput :\n288"
},
{
"code": null,
"e": 1599,
"s": 1044,
"text": "If we observe carefully then we will see that if there is a set of nodes in which minimum edge weight is w and if we add a node to this set that connects the node with the whole set by an edge of weight W such that W<w then path formed between recently added node to all nodes present in the set will have minimum weight W. So, here we can apply Disjoint-Set Union concept to solve the problem. First, sort the data structure according to decreasing weight. Initially assign all nodes as a single set. Now when we merge two sets then do the following:- "
},
{
"code": null,
"e": 1679,
"s": 1599,
"text": " Product=(present weight)^(size of set1*size of set2). "
},
{
"code": null,
"e": 1794,
"s": 1679,
"text": "We will multiply this product value for all edges of the tree.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1798,
"s": 1794,
"text": "C++"
},
{
"code": null,
"e": 1803,
"s": 1798,
"text": "Java"
},
{
"code": null,
"e": 1811,
"s": 1803,
"text": "Python3"
},
{
"code": null,
"e": 1822,
"s": 1811,
"text": "Javascript"
},
{
"code": "// C++ Implementation of above approach#include <bits/stdc++.h>using namespace std;#define mod 1000000007 // Function to return (x^y) mod pint power(int x, unsigned int y, int p){ int res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res;} // Declaring size array globallyint size[300005];int freq[300004];vector<pair<int, pair<int, int> > > edges; // Initializing DSU data structurevoid initialize(int Arr[], int N){ for (int i = 0; i < N; i++) { Arr[i] = i; size[i] = 1; }} // Function to find the root of ith// node in the disjoint setint root(int Arr[], int i){ while (Arr[i] != i) { i = Arr[i]; } return i;} // Weighted union using Path Compressionvoid weighted_union(int Arr[], int size[], int A, int B){ int root_A = root(Arr, A); int root_B = root(Arr, B); // size of set A is small than size of set B if (size[root_A] < size[root_B]) { Arr[root_A] = Arr[root_B]; size[root_B] += size[root_A]; } // size of set B is small than size of set A else { Arr[root_B] = Arr[root_A]; size[root_A] += size[root_B]; }} // Function to add an edge in the treevoid AddEdge(int a, int b, int w){ edges.push_back({ w, { a, b } });} // Build the treevoid MakeTree(){ AddEdge(1, 2, 1); AddEdge(1, 3, 3); AddEdge(3, 4, 2);} // Function to return the required productint MinProduct(){ int result = 1; // Sorting the edges with respect to its weight sort(edges.begin(), edges.end()); // Start iterating in decreasing order of weight for (int i = edges.size() - 1; i >= 0; i--) { // Determine Current edge values int curr_weight = edges[i].first; int Node1 = edges[i].second.first; int Node2 = edges[i].second.second; // Calculate root of each node // and size of each set int Root1 = root(freq, Node1); int Set1_size = size[Root1]; int Root2 = root(freq, Node2); int Set2_size = size[Root2]; // Using the formula int prod = Set1_size * Set2_size; int Product = power(curr_weight, prod, mod); // Calculating final result result = ((result % mod) * (Product % mod)) % mod; // Weighted union using Path Compression weighted_union(freq, size, Node1, Node2); } return result % mod;} // Driver codeint main(){ int n = 4; initialize(freq, n); MakeTree(); cout << MinProduct();}",
"e": 4398,
"s": 1822,
"text": null
},
{
"code": "// Java Implementation of above approach import java.util.ArrayList;import java.util.Collections; public class Product { // to store first vertex, second vertex and weight of // the edge static class Edge implements Comparable<Edge> { int first, second, weight; Edge(int x, int y, int w) { this.first = x; this.second = y; this.weight = w; } @Override public int compareTo(Edge edge) { return this.weight - edge.weight; } } static int mod = 1000000007; // Function to return (x^y) mod p static int power(int x, int y, int p) { int res = 1; x = x % p; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } // Declaring size array globally static int size[] = new int[300005]; static int freq[] = new int[300004]; static ArrayList<Edge> edges = new ArrayList<Edge>(); // Initializing DSU data structure static void initialize(int Arr[], int N) { for (int i = 0; i < N; i++) { Arr[i] = i; size[i] = 1; } } // Function to find the root of ith // node in the disjoint set static int root(int Arr[], int i) { while (Arr[i] != i) { i = Arr[i]; } return i; } // Weighted union using Path Compression static void weighted_union(int Arr[], int size[], int A, int B) { int root_A = root(Arr, A); int root_B = root(Arr, B); // size of set A is small than size of set B if (size[root_A] < size[root_B]) { Arr[root_A] = Arr[root_B]; size[root_B] += size[root_A]; } // size of set B is small than size of set A else { Arr[root_B] = Arr[root_A]; size[root_A] += size[root_B]; } } // Function to add an edge in the tree static void AddEdge(int a, int b, int w) { edges.add(new Edge(a, b, w)); } // Build the tree static void MakeTree() { AddEdge(1, 2, 1); AddEdge(1, 3, 3); AddEdge(3, 4, 2); } // Function to return the required product static int MinProduct() { int result = 1; // Sorting the edges with respect to its weight // ascending order Collections.sort(edges); // Start iterating in decreasing order of weight for (int i = edges.size() - 1; i >= 0; i--) { // Determine Current edge values int curr_weight = edges.get(i).weight; int Node1 = edges.get(i).first; int Node2 = edges.get(i).second; // Calculate root of each node // and size of each set int Root1 = root(freq, Node1); int Set1_size = size[Root1]; int Root2 = root(freq, Node2); int Set2_size = size[Root2]; // Using the formula int prod = Set1_size * Set2_size; int Product = power(curr_weight, prod, mod); // Calculating final result result = ((result % mod) * (Product % mod)) % mod; // Weighted union using Path Compression weighted_union(freq, size, Node1, Node2); } return result % mod; } // Driver code public static void main(String[] args) { int n = 4; initialize(freq, n); MakeTree(); System.out.println(MinProduct()); }} // This code is contributed by jainlovely450",
"e": 8009,
"s": 4398,
"text": null
},
{
"code": "# Python3 implementation of the approachmod = 1000000007 # Function to return (x^y) mod pdef power(x: int, y: int, p: int) -> int: res = 1 x %= p while y > 0: if y & 1: res = (res * x) % p y = y // 2 x = (x * x) % p return res # Declaring size array globallysize = [0] * 300005freq = [0] * 300004edges = [] # Initializing DSU data structuredef initialize(arr: list, N: int): for i in range(N): arr[i] = i size[i] = 1 # Function to find the root of ith# node in the disjoint setdef root(arr: list, i: int) -> int: while arr[i] != i: i = arr[i] return i # Weighted union using Path Compressiondef weighted_union(arr: list, size: list, A: int, B: int): root_A = root(arr, A) root_B = root(arr, B) # size of set A is small than size of set B if size[root_A] < size[root_B]: arr[root_A] = arr[root_B] size[root_B] += size[root_A] # size of set B is small than size of set A else: arr[root_B] = arr[root_A] size[root_A] += size[root_B] # Function to add an edge in the treedef AddEdge(a: int, b: int, w: int): edges.append((w, (a, b))) # Build the treedef makeTree(): AddEdge(1, 2, 1) AddEdge(1, 3, 3) AddEdge(3, 4, 2) # Function to return the required productdef minProduct() -> int: result = 1 # Sorting the edges with respect to its weight edges.sort(key = lambda a: a[0]) # Start iterating in decreasing order of weight for i in range(len(edges) - 1, -1, -1): # Determine Current edge values curr_weight = edges[i][0] node1 = edges[i][1][0] node2 = edges[i][1][1] # Calculate root of each node # and size of each set root1 = root(freq, node1) set1_size = size[root1] root2 = root(freq, node2) set2_size = size[root2] # Using the formula prod = set1_size * set2_size product = power(curr_weight, prod, mod) # Calculating final result result = ((result % mod) * (product % mod)) % mod # Weighted union using Path Compression weighted_union(freq, size, node1, node2) return result % mod # Driver Codeif __name__ == \"__main__\": # Number of nodes and edges n = 4 initialize(freq, n) makeTree() print(minProduct()) # This code is contributed by# sanjeev2552",
"e": 10354,
"s": 8009,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approachconst mod = 1000000007 // Function to return (x^y) mod pfunction power(x, y, p){ let res = 1 x %= p while(y > 0){ if(y & 1) res = (res * x) % p y = Math.floor(y / 2) x = (x * x) % p } return res} // Declaring size array globallylet size = new Array(300005).fill(0)let freq = new Array(300004).fill(0)let edges = [] // Initializing DSU data structurefunction initialize(arr, N){ for(let i=0;i<N;i++){ arr[i] = i size[i] = 1 }} // Function to find the root of ith// node in the disjoint setfunction root(arr, i){ while(arr[i] != i) i = arr[i] return i} // Weighted union using Path Compressionfunction weighted_union(arr, size, A, B){ let root_A = root(arr, A) let root_B = root(arr, B) // size of set A is small than size of set B if(size[root_A] < size[root_B]){ arr[root_A] = arr[root_B] size[root_B] += size[root_A] } // size of set B is small than size of set A else{ arr[root_B] = arr[root_A] size[root_A] += size[root_B] }} // Function to add an edge in the treefunction AddEdge(a, b, w){ edges.push([w, [a, b]])} // Build the treefunction makeTree(){ AddEdge(1, 2, 1) AddEdge(1, 3, 3) AddEdge(3, 4, 2)} // Function to return the required productfunction minProduct(){ let result = 1 // Sorting the edges with respect to its weight edges.sort((a,b)=>a[0]-b[0]) // Start iterating in decreasing order of weight for(let i=edges.length - 1;i>=0;i--){ // Determine Current edge values let curr_weight = edges[i][0] let node1 = edges[i][1][0] let node2 = edges[i][1][1] // Calculate root of each node // and size of each set let root1 = root(freq, node1) let set1_size = size[root1] let root2 = root(freq, node2) let set2_size = size[root2] // Using the formula let prod = set1_size * set2_size let product = power(curr_weight, prod, mod) // Calculating final result result = ((result % mod) * (product % mod)) % mod // Weighted union using Path Compression weighted_union(freq, size, node1, node2) } return result % mod} // Driver Code // Number of nodes and edgeslet n = 4initialize(freq, n)makeTree()document.write(minProduct(),\"</br>\") // This code is contributed by shinjanpatra</script>",
"e": 12794,
"s": 10354,
"text": null
},
{
"code": null,
"e": 12797,
"s": 12794,
"text": "12"
},
{
"code": null,
"e": 12828,
"s": 12799,
"text": "Time Complexity : O(N*logN) "
},
{
"code": null,
"e": 12840,
"s": 12828,
"text": "sanjeev2552"
},
{
"code": null,
"e": 12857,
"s": 12840,
"text": "arorakashish0911"
},
{
"code": null,
"e": 12871,
"s": 12857,
"text": "jainlovely450"
},
{
"code": null,
"e": 12884,
"s": 12871,
"text": "shinjanpatra"
},
{
"code": null,
"e": 12895,
"s": 12884,
"text": "union-find"
},
{
"code": null,
"e": 12901,
"s": 12895,
"text": "Graph"
},
{
"code": null,
"e": 12909,
"s": 12901,
"text": "Sorting"
},
{
"code": null,
"e": 12914,
"s": 12909,
"text": "Tree"
},
{
"code": null,
"e": 12922,
"s": 12914,
"text": "Sorting"
},
{
"code": null,
"e": 12928,
"s": 12922,
"text": "Graph"
},
{
"code": null,
"e": 12933,
"s": 12928,
"text": "Tree"
},
{
"code": null,
"e": 12944,
"s": 12933,
"text": "union-find"
},
{
"code": null,
"e": 13042,
"s": 12944,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13107,
"s": 13042,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 13127,
"s": 13107,
"text": "Topological Sorting"
},
{
"code": null,
"e": 13185,
"s": 13127,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 13218,
"s": 13185,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 13250,
"s": 13218,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 13261,
"s": 13250,
"text": "Merge Sort"
},
{
"code": null,
"e": 13283,
"s": 13261,
"text": "Bubble Sort Algorithm"
},
{
"code": null,
"e": 13293,
"s": 13283,
"text": "QuickSort"
},
{
"code": null,
"e": 13308,
"s": 13293,
"text": "Insertion Sort"
}
] |
Artificial Intelligence Opportunities & Challenges in Businesses | by Robert Adixon | Towards Data Science
|
● Looking for opportunities and challenges that businesses face with implementing AI?
● Confused about whether to start AI based development or not in your business?
● How is AI imapacting your business growth and profit?
Here, in this blog, you will find answers to all such questions. Let’s start!
Artificial Intelligence is a technology for which even a layman is curious about! The reason lies in the strong tendency that it has to disrupt every aspect of life. Artificial intelligence seems to radiate enthusiasm and skepticism collectively. Obviously, in different measures!
Before that let’s look at some stats and facts of AI:
● AI technology can increase business productivity by up to 40 percent (Accenture)
● The number of AI startups since 2000 has magnified to 14 times. (Forbes)
● AI will automate 16% of American jobs (Forrester)
● 15 percent of enterprises are using AI, and 31 percent of them say that it is their agenda for the next 12 months (Adobe)
It is quite true that AI is no more confined to innovation labs only. It is being praised for its amazing potential to transform businesses. However, businesses need to tackle certain challenges before they can find out the real potential of this technology.
1. Computing is not that Advanced
Machine Learning and deep learning techniques that seem most beneficial require a series of calculations to made very quickly ( in microseconds or nanoseconds or slower than that! ).
It clearly indicates that these AI techniques utilize a lot of processing power.
AI has been in the expert discussion for a long time. And always it came out that there is not enough power to implement these AI techniques.
Cloud computing and massively parallel processing systems have created hope to implementation of these techniques for short term, but as data volumes go up, and deep learning moves towards automated creation of increasingly complex algorithms, cloud computing would not help!
2. Fewer people support
AI implementation does not have enough use cases in the market. And without it, no organization would be interested to invest money in AI-based projects. It clearly means that there have been comparatively few organizations interested in putting money into the development of AI-based products.
Moreover, there are not enough people who can make other businesses understand the vision of machine powered progress in the world. In simple words, we can say that there are not enough people who know how to operate machines which think and learn by themselves.
For a remedy to this problem, a mild cure is a citizen data scientist. But this is also not a permanent or real solution. Another alternative is a shift towards offering platforms and tools that permit AI driven work “as a service”. Rather than starting everything from scratch, organizations are able to take ready-made solutions and plug in their own data.
3. Creating Trust
The problem with AI is that it is like a black box for people. People don’t feel comfortable when they don’t understand how the decision was made. For instance, banks use simple algorithms that are based on linear maths and it is easy to explain the algorithm and how they reached from input to output.
Hence, somewhere AI has not been able to create trust among people. And the only solution that seems to this problem is to let people see that this technology really works. However, the reality is somewhat different. And it shows that there is a lot of opportunities to make things better by having predictions that are more accurate.
This raises problems of government overstep. Suppose, a part of the regulation tells that citizens may have the right to ask an explanation for decisions that are made about them with the help of Artificial Intelligence.
4. One Track Minds
A big problem that should be taken into account is that most of the AI implementations are highly specialized. We also call specialized AI as “Applied AI”. And it is built just to perform a single task and keep learning to become better and better at it.
The process that it follows is to look at the inputs given and results produced. It looks at the best result produced and notes down those input values. Generalized AI is different and can jump to any task similar to a human being. However, it is yet to come in the future.
It simply means that AIs need to be trained just to make sure that their solutions do not cause other issues. Specifically, all those areas that are beyond those which they designed to consider.
5. Provability
Organizations working on AI-based products cannot demonstrate clearly about their vision and what they have achieved with the help of AI techniques. People are doubtful about this technology that how it takes decisions and whether all its decisions are perfect or not!
Moreover, such kind of confusion has surrounded the minds of people. And ultimately, a probability which is the mathematical uncertainty behind AI predictions still remain as an unclear region for organizations.
They cannot prove that the AI system’s decision-making process is fine. And its only remedy can lie in making AI explainable, provable and transparent. Organizations should implement explainable AI.
6. Data Privacy and security
Most of the AI applications are based on massive volumes of data to learn and make intelligent decisions. Machine learning systems depend on the data which is often sensitive and personal in nature.
These systems learn from the data and improve themselves. Due to this systematic learning, these ML systems can become prone to data breach and identity theft. European Union has implemented the General Data Protection Regulation (GDPR) that makes sure the complete protection of personal data.
This step is taken after taking a look at increasing awareness in customers regarding an increasing number of machine-made decisions. Moreover, there is a unique method known as Federated learning that is aimed to disrupt the AI paradigm.
This Federated learning will encourage data scientists to create AI without affecting users’ data security and confidentiality.
7. Algorithm bias
A big problem with AI systems is that their level of goodness or badness depends on the much data they are trained on. Bad data is often associated with, ethnic, communal, gender or racial biases.
Proprietary algorithms are used to find out things like who granted bail, whose loan is sanctioned etc. If in case, a bias hidden in the algorithms which take crucial decisions goes unrecognized, it could lead to unethical and unfair results.
In future, such biases will be more highlighted as many AI systems will continue to be trained to utilize bad data. Hence, the urgent need in front of organizations working on AI is to train these systems with unbiased data and create algorithms that can be easily explained.
8. Data Scarcity
It is the fact that organizations have access to more data in the present time than ever before. However, datasets that are applicable to AI applications to learn are really rare. However, the most powerful AI machines are those that are trained on supervised learning.
This kind of training requires labeled data. Labeled data is organized to make it understandable for machines to learn. One more thing about labeled data is that it has a limit. In future automated creation of increasingly difficult algorithms will only worsen the problem.
Still, there is a ray of hope. As time is passing, organizations are investing in design methodologies and focusing on how to create AI models learn despite the scarcity of labeled data.
Here is a youtube video that you can check in order to get a quick introduction to several risks of artificial intelligence in business. This YouTube video explains ten possible risks of artificial intelligence:
<iframe width=”560" height=”315" src=”https://www.youtube.com/embed/1oeoosMrJz4" frameborder=”0" allow=”accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture” allowfullscreen></iframe>
===================================
Yes, there are risks and challenges that are associated with AI implementation in Business. But, just like the two different faces of a coin, AI also has several opportunities for businesses. Due to opportunities associated with AI, many businesses hire dedicated Indian developers to have their own AI based apps. Let’s have a look at them one by one.
It is the dream of every small business to maximize its marketing budgets and focus on high achieving marketing strategies. Moreover, every business wants to learn about which marketing activities deliver the highest return on investment.
But it takes a lot of time to monitor and analyze data across all the media channels. Here, the role of AI marketing solutions comes in!
AI enabled platforms such as Acquisio can easily help in managing marketing operations across various channels like Google Adwords, Facebook, and Bing.
This machine learning enabled layer analyzes live campaign data with the help of sentiment analysis algorithms and suggests a distribution of marketing activities which results in the best results.
It automates regular bids and monitors overall marketing spend so that business owners can reduce the time spent on tracking marketing campaigns and pay attention to other important areas.
It is always crucial to keep track of what your competitors are doing. Unfortunately, most of the business owners are not able to review the competition due to busy schedules. Here, the role of AI comes in.
There are various competitive analysis tools like Crayon. They track competitors with the help of different channels like websites, social media, and apps. Moreover, they provide business owners with a close look into any changes in competitors’ marketing planning like price changes, subtle message modifications, and PR activities.
It is not a big surprise that small business owners are willing to take advantage of large amounts of online as well as offline information to make informed, data-driven decisions that will make their business grow.
The most interesting thing about AI-powered tools for business is that they can be fitted in every data producing workflow and provide close insights that are quite applicable as well as actionable.
AI business tools like Monkey Learn integrate and analyze data across various channels and achieve timesaving analytics and reporting like sentiment analysis in Google Sheets, CSV, etc.
Automated chat systems permit small businesses to scale their customer service efforts and free up resources needed for more difficult customer interactions.
AI customer service solutions like DigitalGenius or ChattyPeople suggest or automate answers to incoming customer questions, classify help tickets and direct inquiries or messages to the appropriate department.
When you use AI in customer support, a big reduction in average handling time is seen. Moreover, it enhances the overall responsiveness of your customer service team.
How would you feel if you find a way to take your CRM to the next level and to get valuable insights that can help managing interactions with present and prospective clients!
CRM platforms that are embedded with AI functionality can do real-time data analysis in order to provide predictions as well as recommendations based on your company’s unique business processes and customer data.
==================================
Conclusion
Hence, we found that AI’s time may have finally come, but more progress is required. And the adoption of AI is uneven across various companies and sectors.
Moreover, we looked at all the opportunities and challenges that businesses face while implementing AI. Now, I hope you are clear on whether you should go for Artificial Intelligence (AI) development in your company.
In case you wish to create AI-based applications, you can contact a reputed web development company that turns your dream come true. There are numerous firms that offer AI-based software to make customer service sector more efficient.
|
[
{
"code": null,
"e": 258,
"s": 172,
"text": "● Looking for opportunities and challenges that businesses face with implementing AI?"
},
{
"code": null,
"e": 338,
"s": 258,
"text": "● Confused about whether to start AI based development or not in your business?"
},
{
"code": null,
"e": 394,
"s": 338,
"text": "● How is AI imapacting your business growth and profit?"
},
{
"code": null,
"e": 472,
"s": 394,
"text": "Here, in this blog, you will find answers to all such questions. Let’s start!"
},
{
"code": null,
"e": 753,
"s": 472,
"text": "Artificial Intelligence is a technology for which even a layman is curious about! The reason lies in the strong tendency that it has to disrupt every aspect of life. Artificial intelligence seems to radiate enthusiasm and skepticism collectively. Obviously, in different measures!"
},
{
"code": null,
"e": 807,
"s": 753,
"text": "Before that let’s look at some stats and facts of AI:"
},
{
"code": null,
"e": 890,
"s": 807,
"text": "● AI technology can increase business productivity by up to 40 percent (Accenture)"
},
{
"code": null,
"e": 965,
"s": 890,
"text": "● The number of AI startups since 2000 has magnified to 14 times. (Forbes)"
},
{
"code": null,
"e": 1017,
"s": 965,
"text": "● AI will automate 16% of American jobs (Forrester)"
},
{
"code": null,
"e": 1141,
"s": 1017,
"text": "● 15 percent of enterprises are using AI, and 31 percent of them say that it is their agenda for the next 12 months (Adobe)"
},
{
"code": null,
"e": 1400,
"s": 1141,
"text": "It is quite true that AI is no more confined to innovation labs only. It is being praised for its amazing potential to transform businesses. However, businesses need to tackle certain challenges before they can find out the real potential of this technology."
},
{
"code": null,
"e": 1434,
"s": 1400,
"text": "1. Computing is not that Advanced"
},
{
"code": null,
"e": 1617,
"s": 1434,
"text": "Machine Learning and deep learning techniques that seem most beneficial require a series of calculations to made very quickly ( in microseconds or nanoseconds or slower than that! )."
},
{
"code": null,
"e": 1698,
"s": 1617,
"text": "It clearly indicates that these AI techniques utilize a lot of processing power."
},
{
"code": null,
"e": 1840,
"s": 1698,
"text": "AI has been in the expert discussion for a long time. And always it came out that there is not enough power to implement these AI techniques."
},
{
"code": null,
"e": 2116,
"s": 1840,
"text": "Cloud computing and massively parallel processing systems have created hope to implementation of these techniques for short term, but as data volumes go up, and deep learning moves towards automated creation of increasingly complex algorithms, cloud computing would not help!"
},
{
"code": null,
"e": 2140,
"s": 2116,
"text": "2. Fewer people support"
},
{
"code": null,
"e": 2435,
"s": 2140,
"text": "AI implementation does not have enough use cases in the market. And without it, no organization would be interested to invest money in AI-based projects. It clearly means that there have been comparatively few organizations interested in putting money into the development of AI-based products."
},
{
"code": null,
"e": 2698,
"s": 2435,
"text": "Moreover, there are not enough people who can make other businesses understand the vision of machine powered progress in the world. In simple words, we can say that there are not enough people who know how to operate machines which think and learn by themselves."
},
{
"code": null,
"e": 3057,
"s": 2698,
"text": "For a remedy to this problem, a mild cure is a citizen data scientist. But this is also not a permanent or real solution. Another alternative is a shift towards offering platforms and tools that permit AI driven work “as a service”. Rather than starting everything from scratch, organizations are able to take ready-made solutions and plug in their own data."
},
{
"code": null,
"e": 3075,
"s": 3057,
"text": "3. Creating Trust"
},
{
"code": null,
"e": 3378,
"s": 3075,
"text": "The problem with AI is that it is like a black box for people. People don’t feel comfortable when they don’t understand how the decision was made. For instance, banks use simple algorithms that are based on linear maths and it is easy to explain the algorithm and how they reached from input to output."
},
{
"code": null,
"e": 3713,
"s": 3378,
"text": "Hence, somewhere AI has not been able to create trust among people. And the only solution that seems to this problem is to let people see that this technology really works. However, the reality is somewhat different. And it shows that there is a lot of opportunities to make things better by having predictions that are more accurate."
},
{
"code": null,
"e": 3934,
"s": 3713,
"text": "This raises problems of government overstep. Suppose, a part of the regulation tells that citizens may have the right to ask an explanation for decisions that are made about them with the help of Artificial Intelligence."
},
{
"code": null,
"e": 3953,
"s": 3934,
"text": "4. One Track Minds"
},
{
"code": null,
"e": 4208,
"s": 3953,
"text": "A big problem that should be taken into account is that most of the AI implementations are highly specialized. We also call specialized AI as “Applied AI”. And it is built just to perform a single task and keep learning to become better and better at it."
},
{
"code": null,
"e": 4482,
"s": 4208,
"text": "The process that it follows is to look at the inputs given and results produced. It looks at the best result produced and notes down those input values. Generalized AI is different and can jump to any task similar to a human being. However, it is yet to come in the future."
},
{
"code": null,
"e": 4677,
"s": 4482,
"text": "It simply means that AIs need to be trained just to make sure that their solutions do not cause other issues. Specifically, all those areas that are beyond those which they designed to consider."
},
{
"code": null,
"e": 4692,
"s": 4677,
"text": "5. Provability"
},
{
"code": null,
"e": 4961,
"s": 4692,
"text": "Organizations working on AI-based products cannot demonstrate clearly about their vision and what they have achieved with the help of AI techniques. People are doubtful about this technology that how it takes decisions and whether all its decisions are perfect or not!"
},
{
"code": null,
"e": 5173,
"s": 4961,
"text": "Moreover, such kind of confusion has surrounded the minds of people. And ultimately, a probability which is the mathematical uncertainty behind AI predictions still remain as an unclear region for organizations."
},
{
"code": null,
"e": 5372,
"s": 5173,
"text": "They cannot prove that the AI system’s decision-making process is fine. And its only remedy can lie in making AI explainable, provable and transparent. Organizations should implement explainable AI."
},
{
"code": null,
"e": 5401,
"s": 5372,
"text": "6. Data Privacy and security"
},
{
"code": null,
"e": 5600,
"s": 5401,
"text": "Most of the AI applications are based on massive volumes of data to learn and make intelligent decisions. Machine learning systems depend on the data which is often sensitive and personal in nature."
},
{
"code": null,
"e": 5895,
"s": 5600,
"text": "These systems learn from the data and improve themselves. Due to this systematic learning, these ML systems can become prone to data breach and identity theft. European Union has implemented the General Data Protection Regulation (GDPR) that makes sure the complete protection of personal data."
},
{
"code": null,
"e": 6134,
"s": 5895,
"text": "This step is taken after taking a look at increasing awareness in customers regarding an increasing number of machine-made decisions. Moreover, there is a unique method known as Federated learning that is aimed to disrupt the AI paradigm."
},
{
"code": null,
"e": 6262,
"s": 6134,
"text": "This Federated learning will encourage data scientists to create AI without affecting users’ data security and confidentiality."
},
{
"code": null,
"e": 6280,
"s": 6262,
"text": "7. Algorithm bias"
},
{
"code": null,
"e": 6477,
"s": 6280,
"text": "A big problem with AI systems is that their level of goodness or badness depends on the much data they are trained on. Bad data is often associated with, ethnic, communal, gender or racial biases."
},
{
"code": null,
"e": 6720,
"s": 6477,
"text": "Proprietary algorithms are used to find out things like who granted bail, whose loan is sanctioned etc. If in case, a bias hidden in the algorithms which take crucial decisions goes unrecognized, it could lead to unethical and unfair results."
},
{
"code": null,
"e": 6996,
"s": 6720,
"text": "In future, such biases will be more highlighted as many AI systems will continue to be trained to utilize bad data. Hence, the urgent need in front of organizations working on AI is to train these systems with unbiased data and create algorithms that can be easily explained."
},
{
"code": null,
"e": 7013,
"s": 6996,
"text": "8. Data Scarcity"
},
{
"code": null,
"e": 7283,
"s": 7013,
"text": "It is the fact that organizations have access to more data in the present time than ever before. However, datasets that are applicable to AI applications to learn are really rare. However, the most powerful AI machines are those that are trained on supervised learning."
},
{
"code": null,
"e": 7557,
"s": 7283,
"text": "This kind of training requires labeled data. Labeled data is organized to make it understandable for machines to learn. One more thing about labeled data is that it has a limit. In future automated creation of increasingly difficult algorithms will only worsen the problem."
},
{
"code": null,
"e": 7744,
"s": 7557,
"text": "Still, there is a ray of hope. As time is passing, organizations are investing in design methodologies and focusing on how to create AI models learn despite the scarcity of labeled data."
},
{
"code": null,
"e": 7956,
"s": 7744,
"text": "Here is a youtube video that you can check in order to get a quick introduction to several risks of artificial intelligence in business. This YouTube video explains ten possible risks of artificial intelligence:"
},
{
"code": null,
"e": 8159,
"s": 7956,
"text": "<iframe width=”560\" height=”315\" src=”https://www.youtube.com/embed/1oeoosMrJz4\" frameborder=”0\" allow=”accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture” allowfullscreen></iframe>"
},
{
"code": null,
"e": 8195,
"s": 8159,
"text": "==================================="
},
{
"code": null,
"e": 8548,
"s": 8195,
"text": "Yes, there are risks and challenges that are associated with AI implementation in Business. But, just like the two different faces of a coin, AI also has several opportunities for businesses. Due to opportunities associated with AI, many businesses hire dedicated Indian developers to have their own AI based apps. Let’s have a look at them one by one."
},
{
"code": null,
"e": 8787,
"s": 8548,
"text": "It is the dream of every small business to maximize its marketing budgets and focus on high achieving marketing strategies. Moreover, every business wants to learn about which marketing activities deliver the highest return on investment."
},
{
"code": null,
"e": 8924,
"s": 8787,
"text": "But it takes a lot of time to monitor and analyze data across all the media channels. Here, the role of AI marketing solutions comes in!"
},
{
"code": null,
"e": 9076,
"s": 8924,
"text": "AI enabled platforms such as Acquisio can easily help in managing marketing operations across various channels like Google Adwords, Facebook, and Bing."
},
{
"code": null,
"e": 9274,
"s": 9076,
"text": "This machine learning enabled layer analyzes live campaign data with the help of sentiment analysis algorithms and suggests a distribution of marketing activities which results in the best results."
},
{
"code": null,
"e": 9463,
"s": 9274,
"text": "It automates regular bids and monitors overall marketing spend so that business owners can reduce the time spent on tracking marketing campaigns and pay attention to other important areas."
},
{
"code": null,
"e": 9670,
"s": 9463,
"text": "It is always crucial to keep track of what your competitors are doing. Unfortunately, most of the business owners are not able to review the competition due to busy schedules. Here, the role of AI comes in."
},
{
"code": null,
"e": 10004,
"s": 9670,
"text": "There are various competitive analysis tools like Crayon. They track competitors with the help of different channels like websites, social media, and apps. Moreover, they provide business owners with a close look into any changes in competitors’ marketing planning like price changes, subtle message modifications, and PR activities."
},
{
"code": null,
"e": 10220,
"s": 10004,
"text": "It is not a big surprise that small business owners are willing to take advantage of large amounts of online as well as offline information to make informed, data-driven decisions that will make their business grow."
},
{
"code": null,
"e": 10419,
"s": 10220,
"text": "The most interesting thing about AI-powered tools for business is that they can be fitted in every data producing workflow and provide close insights that are quite applicable as well as actionable."
},
{
"code": null,
"e": 10605,
"s": 10419,
"text": "AI business tools like Monkey Learn integrate and analyze data across various channels and achieve timesaving analytics and reporting like sentiment analysis in Google Sheets, CSV, etc."
},
{
"code": null,
"e": 10763,
"s": 10605,
"text": "Automated chat systems permit small businesses to scale their customer service efforts and free up resources needed for more difficult customer interactions."
},
{
"code": null,
"e": 10974,
"s": 10763,
"text": "AI customer service solutions like DigitalGenius or ChattyPeople suggest or automate answers to incoming customer questions, classify help tickets and direct inquiries or messages to the appropriate department."
},
{
"code": null,
"e": 11141,
"s": 10974,
"text": "When you use AI in customer support, a big reduction in average handling time is seen. Moreover, it enhances the overall responsiveness of your customer service team."
},
{
"code": null,
"e": 11316,
"s": 11141,
"text": "How would you feel if you find a way to take your CRM to the next level and to get valuable insights that can help managing interactions with present and prospective clients!"
},
{
"code": null,
"e": 11529,
"s": 11316,
"text": "CRM platforms that are embedded with AI functionality can do real-time data analysis in order to provide predictions as well as recommendations based on your company’s unique business processes and customer data."
},
{
"code": null,
"e": 11564,
"s": 11529,
"text": "=================================="
},
{
"code": null,
"e": 11575,
"s": 11564,
"text": "Conclusion"
},
{
"code": null,
"e": 11731,
"s": 11575,
"text": "Hence, we found that AI’s time may have finally come, but more progress is required. And the adoption of AI is uneven across various companies and sectors."
},
{
"code": null,
"e": 11948,
"s": 11731,
"text": "Moreover, we looked at all the opportunities and challenges that businesses face while implementing AI. Now, I hope you are clear on whether you should go for Artificial Intelligence (AI) development in your company."
}
] |
Python IMDbPY – Movie info set - GeeksforGeeks
|
22 Apr, 2020
IMDb data base have every information of the movie i.e when movie released, rating, locations etc but in order to retrieve them problem occur as there will be lots of web pages which can be both time-and bandwidth-consuming, especially if you’re interested in only a small part of the information.
If we want to fetch only specific information we can fetch it by passing an optional information parameter to the get_movie method. In order to get information set of IMDb data set we will use get_movie_infoset method.
Syntax : imdb_object.get_movie_infoset()
Argument : It takes no argument.
Return : It return list.
Below is the implementation
# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # getting the movie info set of data baseinfo = ia.get_movie_infoset() # printing the list for element in info: print(element)
Output :
airing
akas
alternate versions
awards
connections
crazy credits
critic reviews
episodes
external reviews
external sites
faqs
full credits
goofs
keywords
locations
main
misc sites
news
official sites
parents guide
photo sites
plot
quotes
release dates
release info
reviews
sound clips
soundtrack
synopsis
taglines
technical
trivia
tv schedule
video clips
vote details
Python IMDbPY-module
Python
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
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 25853,
"s": 25555,
"text": "IMDb data base have every information of the movie i.e when movie released, rating, locations etc but in order to retrieve them problem occur as there will be lots of web pages which can be both time-and bandwidth-consuming, especially if you’re interested in only a small part of the information."
},
{
"code": null,
"e": 26072,
"s": 25853,
"text": "If we want to fetch only specific information we can fetch it by passing an optional information parameter to the get_movie method. In order to get information set of IMDb data set we will use get_movie_infoset method."
},
{
"code": null,
"e": 26113,
"s": 26072,
"text": "Syntax : imdb_object.get_movie_infoset()"
},
{
"code": null,
"e": 26146,
"s": 26113,
"text": "Argument : It takes no argument."
},
{
"code": null,
"e": 26171,
"s": 26146,
"text": "Return : It return list."
},
{
"code": null,
"e": 26199,
"s": 26171,
"text": "Below is the implementation"
},
{
"code": "# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # getting the movie info set of data baseinfo = ia.get_movie_infoset() # printing the list for element in info: print(element)",
"e": 26413,
"s": 26199,
"text": null
},
{
"code": null,
"e": 26422,
"s": 26413,
"text": "Output :"
},
{
"code": null,
"e": 26790,
"s": 26422,
"text": "airing\nakas\nalternate versions\nawards\nconnections\ncrazy credits\ncritic reviews\nepisodes\nexternal reviews\nexternal sites\nfaqs\nfull credits\ngoofs\nkeywords\nlocations\nmain\nmisc sites\nnews\nofficial sites\nparents guide\nphoto sites\nplot\nquotes\nrelease dates\nrelease info\nreviews\nsound clips\nsoundtrack\nsynopsis\ntaglines\ntechnical\ntrivia\ntv schedule\nvideo clips\nvote details\n"
},
{
"code": null,
"e": 26811,
"s": 26790,
"text": "Python IMDbPY-module"
},
{
"code": null,
"e": 26818,
"s": 26811,
"text": "Python"
},
{
"code": null,
"e": 26916,
"s": 26818,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26948,
"s": 26916,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26990,
"s": 26948,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27032,
"s": 26990,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27088,
"s": 27032,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27115,
"s": 27088,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27146,
"s": 27115,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27185,
"s": 27146,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27214,
"s": 27185,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27236,
"s": 27214,
"text": "Defaultdict in Python"
}
] |
Python | Transpose elements of two dimensional list - GeeksforGeeks
|
19 Jan, 2021
Given a two-dimensional list of integers, write a Python program to get the transpose of given list of lists.In Python, a matrix can be interpreted as a list of lists. Each element is treated as a row of the matrix. For example m = [[10, 20], [40, 50], [30, 60]] represents a matrix of 3 rows and 2 columns. First element of the list – m[0] and element in first row, first column – m[0][0].
Example:
Input : l1 = [[4, 5, 3, 9],
[7, 1, 8, 2],
[5, 6, 4, 7]]
Output : lt = [[4, 7, 5],
[5, 1, 6],
[3, 8, 4],
[9, 2, 7]]
Method #1: Using loops
Python
# Python program to get transpose# elements of two dimension listdef transpose(l1, l2): # iterate over list l1 to the length of an item for i in range(len(l1[0])): # print(i) row =[] for item in l1: # appending to new list with values and index positions # i contains index position and item contains values row.append(item[i]) l2.append(row) return l2 # Driver codel1 = [[4, 5, 3, 9], [7, 1, 8, 2], [5, 6, 4, 7]]l2 = []print(transpose(l1, l2))
[[4, 7, 5], [5, 1, 6], [3, 8, 4], [9, 2, 7]]
Method #2: Using List comprehensions
Python
# Python program to get transpose# elements of two dimension listdef transpose(l1, l2): # we have nested loops in comprehensions # value of i is assigned using inner loop # then value of item is directed by row[i] # and appended to l2 l2 =[[row[i] for row in l1] for i in range(len(l1[0]))] return l2 # Driver codel1 = [[4, 5, 3, 9], [7, 1, 8, 2], [5, 6, 4, 7]]l2 = []print(transpose(l1, l2))
[[4, 7, 5], [5, 1, 6], [3, 8, 4], [9, 2, 7]]
Method #3: Using numpy
Python3
# Python program to get transpose# elements of two dimension listimport numpy l1= [[4, 5, 3, 9], [7, 1, 8, 2], [5, 6, 4, 7]]print(numpy.transpose(l1))
Output:
[[4 7 5]
[5 1 6]
[3 8 4]
[9 2 7]]
Method #4: Using zip function
Python
# Python program to get transpose# elements of two dimension listdef transpose(l1, l2): # star operator will first # unpack the values of 2D list # and then zip function will # pack them again in opposite manner l2 = list(map(list, zip(*l1))) return l2 # Driver codel1 = [[4, 5, 3, 9], [7, 1, 8, 2], [5, 6, 4, 7]]l2 = []print(transpose(l1, l2)) # code contributed by# chaudhary_19# Mayank Chaudhary# modified by Chirag Shilwant
[[4, 7, 5], [5, 1, 6], [3, 8, 4], [9, 2, 7]]
chaudhary_19
chirags_30
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 26565,
"s": 26537,
"text": "\n19 Jan, 2021"
},
{
"code": null,
"e": 26956,
"s": 26565,
"text": "Given a two-dimensional list of integers, write a Python program to get the transpose of given list of lists.In Python, a matrix can be interpreted as a list of lists. Each element is treated as a row of the matrix. For example m = [[10, 20], [40, 50], [30, 60]] represents a matrix of 3 rows and 2 columns. First element of the list – m[0] and element in first row, first column – m[0][0]."
},
{
"code": null,
"e": 26966,
"s": 26956,
"text": "Example: "
},
{
"code": null,
"e": 27158,
"s": 26966,
"text": "Input : l1 = [[4, 5, 3, 9],\n [7, 1, 8, 2],\n [5, 6, 4, 7]]\n\nOutput : lt = [[4, 7, 5],\n [5, 1, 6],\n [3, 8, 4],\n [9, 2, 7]]"
},
{
"code": null,
"e": 27183,
"s": 27158,
"text": " Method #1: Using loops "
},
{
"code": null,
"e": 27190,
"s": 27183,
"text": "Python"
},
{
"code": "# Python program to get transpose# elements of two dimension listdef transpose(l1, l2): # iterate over list l1 to the length of an item for i in range(len(l1[0])): # print(i) row =[] for item in l1: # appending to new list with values and index positions # i contains index position and item contains values row.append(item[i]) l2.append(row) return l2 # Driver codel1 = [[4, 5, 3, 9], [7, 1, 8, 2], [5, 6, 4, 7]]l2 = []print(transpose(l1, l2))",
"e": 27706,
"s": 27190,
"text": null
},
{
"code": null,
"e": 27752,
"s": 27706,
"text": "[[4, 7, 5], [5, 1, 6], [3, 8, 4], [9, 2, 7]]\n"
},
{
"code": null,
"e": 27791,
"s": 27752,
"text": " Method #2: Using List comprehensions "
},
{
"code": null,
"e": 27798,
"s": 27791,
"text": "Python"
},
{
"code": "# Python program to get transpose# elements of two dimension listdef transpose(l1, l2): # we have nested loops in comprehensions # value of i is assigned using inner loop # then value of item is directed by row[i] # and appended to l2 l2 =[[row[i] for row in l1] for i in range(len(l1[0]))] return l2 # Driver codel1 = [[4, 5, 3, 9], [7, 1, 8, 2], [5, 6, 4, 7]]l2 = []print(transpose(l1, l2))",
"e": 28210,
"s": 27798,
"text": null
},
{
"code": null,
"e": 28256,
"s": 28210,
"text": "[[4, 7, 5], [5, 1, 6], [3, 8, 4], [9, 2, 7]]\n"
},
{
"code": null,
"e": 28280,
"s": 28256,
"text": "Method #3: Using numpy "
},
{
"code": null,
"e": 28288,
"s": 28280,
"text": "Python3"
},
{
"code": "# Python program to get transpose# elements of two dimension listimport numpy l1= [[4, 5, 3, 9], [7, 1, 8, 2], [5, 6, 4, 7]]print(numpy.transpose(l1))",
"e": 28440,
"s": 28288,
"text": null
},
{
"code": null,
"e": 28448,
"s": 28440,
"text": "Output:"
},
{
"code": null,
"e": 28485,
"s": 28448,
"text": "[[4 7 5]\n [5 1 6]\n [3 8 4]\n [9 2 7]]"
},
{
"code": null,
"e": 28516,
"s": 28485,
"text": "Method #4: Using zip function "
},
{
"code": null,
"e": 28523,
"s": 28516,
"text": "Python"
},
{
"code": "# Python program to get transpose# elements of two dimension listdef transpose(l1, l2): # star operator will first # unpack the values of 2D list # and then zip function will # pack them again in opposite manner l2 = list(map(list, zip(*l1))) return l2 # Driver codel1 = [[4, 5, 3, 9], [7, 1, 8, 2], [5, 6, 4, 7]]l2 = []print(transpose(l1, l2)) # code contributed by# chaudhary_19# Mayank Chaudhary# modified by Chirag Shilwant",
"e": 28970,
"s": 28523,
"text": null
},
{
"code": null,
"e": 29016,
"s": 28970,
"text": "[[4, 7, 5], [5, 1, 6], [3, 8, 4], [9, 2, 7]]\n"
},
{
"code": null,
"e": 29029,
"s": 29016,
"text": "chaudhary_19"
},
{
"code": null,
"e": 29040,
"s": 29029,
"text": "chirags_30"
},
{
"code": null,
"e": 29061,
"s": 29040,
"text": "Python list-programs"
},
{
"code": null,
"e": 29068,
"s": 29061,
"text": "Python"
},
{
"code": null,
"e": 29084,
"s": 29068,
"text": "Python Programs"
},
{
"code": null,
"e": 29182,
"s": 29084,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29200,
"s": 29182,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29235,
"s": 29200,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29267,
"s": 29235,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29289,
"s": 29267,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29331,
"s": 29289,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29374,
"s": 29331,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 29396,
"s": 29374,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29435,
"s": 29396,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 29481,
"s": 29435,
"text": "Python | Split string into list of characters"
}
] |
NLP Part 3 | Exploratory Data Analysis of Text Data | by Kamil Mysiak | Towards Data Science
|
This is a continuation of a three part series on NLP using python. Feel free to check out my other articles. (Part 1, Part 2)
Let’s get a better understanding of our newly cleansed dataset.Exploratory Data Analysis (EDA) is the process by which the data analyst becomes acquainted with their data to drive intuition and begin to formulate testable hypotheses. This process typically makes use of descriptive statistics and visualizations.
Let’s begin, as always, by importing the necessary libraries and opening our dataset.
import pandas as pdimport numpy as npimport nltkimport pickleimport pyLDAvis.sklearnfrom collections import Counterfrom textblob import TextBlobfrom nltk.tokenize import word_tokenizefrom nltk.probability import FreqDistfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.decomposition import LatentDirichletAllocation, NMFfrom wordcloud import WordCloud, ImageColorGeneratorimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinepd.options.mode.chained_assignment = Nonepd.set_option('display.max_colwidth', 100)with open('indeed_scrape_clean.pkl', 'rb') as pickle_file: df = pickle.load(pickle_file)
If you recall from our previous tutorial, we went through a series of pre-processing steps to clean and prepare our data for analysis. Our final dataset contains numerous columns but the last column “lemmatized”, contained our final cleansed list of words. We are going to overwrite our existing dataframe because we are only interested in the “rating” and “lemmatized” columns.
df = df[['rating', 'lemmatized']]df.head()
Sentiment analysis is the process of determining the writer’s attitude or opinion ranging from -1 (negative attitude) to 1 (positive attitude). We’ll be using the TextBlob library to analyze sentiment. TextBlob’s Sentiment() function requires a string but our “lemmatized” column is currently a list. Let’s convert the list into a string.
df['lemma_str'] = [' '.join(map(str,l)) for l in df['lemmatized']]df.head()
Now we can pass the “lemma_str” column into the Sentiment() function to calculate sentiment. Since we have the “rating” column, we can validate how well the sentiment analysis was able to determine the writer’s attitude. That said, we do see obvious errors as rating #5 has a rating of 5but a fairly low sentiment.
df['sentiment'] = df['lemma_str'].apply(lambda x: TextBlob(x).sentiment.polarity)df.head()
When comparing a histogram of our sentiment, we can see that the vast majority of our derived sentiment rating is overwhelmingly positive. When we compare this against the “ratings” column, we can see a similar pattern emerge. Not only do we feel comfortable in the accuracy of the sentiment analysis but we can see that the overall employee attitude about the company is very positive. It is no wonder Google regularly makes the Forbes’s Best Places to Work list.
plt.figure(figsize=(50,30))plt.margins(0.02)plt.xlabel('Sentiment', fontsize=50)plt.xticks(fontsize=40)plt.ylabel('Frequency', fontsize=50)plt.yticks(fontsize=40)plt.hist(df['sentiment'], bins=50)plt.title('Sentiment Distribution', fontsize=60)plt.show()
x_rating = df.rating.value_counts()y_rating = x_rating.sort_index()plt.figure(figsize=(50,30))sns.barplot(x_rating.index, x_rating.values, alpha=0.8)plt.title("Rating Distribution", fontsize=50)plt.ylabel('Frequency', fontsize=50)plt.yticks(fontsize=40)plt.xlabel('Employee Ratings', fontsize=50)plt.xticks(fontsize=40)
plt.figure(figsize=(30,10))plt.title('Percentage of Ratings', fontsize=20)df.rating.value_counts().plot(kind='pie', labels=['Rating5', 'Rating4', 'Rating3', 'Rating2', 'Rating1'], wedgeprops=dict(width=.7), autopct='%1.0f%%', startangle= -20, textprops={'fontsize': 15})
polarity_avg = df.groupby('rating')['sentiment'].mean().plot(kind='bar', figsize=(50,30))plt.xlabel('Rating', fontsize=45)plt.ylabel('Average Sentiment', fontsize=45)plt.xticks(fontsize=40)plt.yticks(fontsize=40)plt.title('Average Sentiment per Rating Distribution', fontsize=50)plt.show()
Let’s create two additional features of “word_count” to determine the number of words per review and “review_len” to determine the number of letters per review.
df['word_count'] = df['lemmatized'].apply(lambda x: len(str(x).split()))df['review_len'] = df['lemma_str'].astype(str).apply(len)
Although the differences are not significantly large it seems the longest reviews based on the count of letters and words seem to be negative and neutral. It seems disgruntled employees typically provide significantly more detail in their reviews. This result is not uncommon as humans have a tendency to complain in detail but praise in brief. This can be further confirmed by examining the correlation matrix below. Both ratings and sentiment have a negative correlation with “review_len” and “word_count”. This would explain the inverse relationship as the count of letters and words per review increases the overall rating and sentiment decreases. However, once again the correlation is rather small nevertheless negative.
letter_avg = df.groupby('rating')['review_len'].mean().plot(kind='bar', figsize=(50,30))plt.xlabel('Rating', fontsize=35)plt.ylabel('Count of Letters in Rating', fontsize=35)plt.xticks(fontsize=40)plt.yticks(fontsize=40)plt.title('Average Number of Letters per Rating Distribution', fontsize=40)plt.show()
word_avg = df.groupby('rating')['word_count'].mean().plot(kind='bar', figsize=(50,30))plt.xlabel('Rating', fontsize=35)plt.ylabel('Count of Words in Rating', fontsize=35)plt.xticks(fontsize=40)plt.yticks(fontsize=40)plt.title('Average Number of Words per Rating Distribution', fontsize=40)plt.show()
correlation = df[['rating','sentiment', 'review_len', 'word_count']].corr()mask = np.zeros_like(correlation, dtype=np.bool)mask[np.triu_indices_from(mask)] = Trueplt.figure(figsize=(50,30))plt.xticks(fontsize=40)plt.yticks(fontsize=40)sns.heatmap(correlation, cmap='coolwarm', annot=True, annot_kws={"size": 40}, linewidths=10, vmin=-1.5, mask=mask)
Let’s take an in-depth look at the actual reviews themselves. What are the most common words? What are the most common words by rating? Answers to these questions will provide further insights into the opinions of Google’s employees.
NLTK has a great library named “FreqDist” which allows us to determine the count of the most common terms in our corpus. First, we need to convert our individual lists of tokenized reviews into a comprehensive list of iterable tokens which stores all the reviews together. Finally, we pass FreqDist() the “allwords” object and apply the “most_common(100)” function to obtain the 100 most common words.
words = df['lemmatized']allwords = []for wordlist in words: allwords += wordlistprint(allwords)
mostcommon = FreqDist(allwords).most_common(100)wordcloud = WordCloud(width=1600, height=800, background_color='white').generate(str(mostcommon))fig = plt.figure(figsize=(30,10), facecolor='white')plt.imshow(wordcloud, interpolation="bilinear")plt.axis('off')plt.title('Top 100 Most Common Words', fontsize=100)plt.tight_layout(pad=0)plt.show()
mostcommon_small = FreqDist(allwords).most_common(25)x, y = zip(*mostcommon_small)plt.figure(figsize=(50,30))plt.margins(0.02)plt.bar(x, y)plt.xlabel('Words', fontsize=50)plt.ylabel('Frequency of Words', fontsize=50)plt.yticks(fontsize=40)plt.xticks(rotation=60, fontsize=40)plt.title('Frequency of 25 Most Common Words', fontsize=60)plt.show()
The results of the term frequency analysis certainly supports the overall positive sentiment of the reviews. Terms such as “Great”, “Work”, “People”, “Team”, “Company” point to a positive company environment where employees enjoy working together.
Based on the fact terms such as “work”, “Google”, “job” and “company” have such a high frequency in the corpus it might be a good idea to remove them (ie. add them to our stopwords) prior to analysis.
That said, a company can always improve therefore, let’s examine the most common words for each review rating.
It seems the most common words for reviews where the rating = 1 had something to do with the “Management”, “Manager”, “People”. We have to be careful when interpreting these results as there are only (2%) reviews with a rating of 1 based on our pie chart printed above.
group_by = df.groupby('rating')['lemma_str'].apply(lambda x: Counter(' '.join(x).split()).most_common(25))group_by_0 = group_by.iloc[0]words0 = list(zip(*group_by_0))[0]freq0 = list(zip(*group_by_0))[1]plt.figure(figsize=(50,30))plt.bar(words0, freq0)plt.xlabel('Words', fontsize=50)plt.ylabel('Frequency of Words', fontsize=50)plt.yticks(fontsize=40)plt.xticks(rotation=60, fontsize=40)plt.title('Frequency of 25 Most Common Words for Rating=1', fontsize=60)plt.show()
Reviews with a rating of 2 had a common theme of “manager”, “management”. Once again the rating distribution is very skewed but this does give us some clues on ways to improve the organization.
group_by_1 = group_by.iloc[1]words1 = list(zip(*group_by_1))[0]freq1 = list(zip(*group_by_1))[1]plt.figure(figsize=(50,30))plt.bar(words1, freq1)plt.xlabel('Words', fontsize=50)plt.ylabel('Frequency of Words', fontsize=50)plt.yticks(fontsize=40)plt.xticks(rotation=60, fontsize=40)plt.title('Frequency of 25 Most Common Words for Rating=2', fontsize=60)plt.show()
It is difficult to derive accurate insights from a “neutral” rating as the employee didn’t have anything overly positive or negative to say about the company. That said, it is interesting that “Management” has once again crept into the top 10 words. So far roughly 14% of the employees had a negative or neutral (didn’t have anything good or bad to say) about the management at Google. Words like “work” and “Google” seem to be skewing the distribution for all ratings, it would be a good idea to remove these words from future analysis.
Notice the “...”, we have some more data processing to perform. 😞
group_by_2 = group_by.iloc[2]words2 = list(zip(*group_by_2))[0]freq2 = list(zip(*group_by_2))[1]plt.figure(figsize=(50,30))plt.bar(words2, freq2)plt.xlabel('Words', fontsize=50)plt.ylabel('Frequency of Words', fontsize=50)plt.yticks(fontsize=40)plt.xticks(rotation=60, fontsize=40)plt.title('Frequency of 25 Most Common Words for Rating=3', fontsize=60)plt.show()
Rating of 4 and 5 had very similar terms as it seems employees enjoy their work, the people with whom they work, and value the environment/culture at Google. For example, “design”, “learning opportunities”, “people”, “time” and “team” all made an appearance. That said, we don’t see “Management” or “Manager” anywhere in the top 10 words. This is very insightful as it helps to validate the results from ratings 1, 2, and 3. Last but not least, these word frequencies (ie. ratings 4 & 5) have been derived from a very large number of reviews which only adds to the validity of these results; management is certainly an area of improvement.
group_by_3 = group_by.iloc[3]words3 = list(zip(*group_by_3))[0]freq3 = list(zip(*group_by_3))[1]plt.figure(figsize=(50,30))plt.bar(words3, freq3)plt.xlabel('Words', fontsize=50)plt.ylabel('Frequency of Words', fontsize=50)plt.yticks(fontsize=40)plt.xticks(rotation=60, fontsize=40)plt.title('Frequency of 25 Most Common Words for Rating=4', fontsize=60)plt.show()
group_by_4 = group_by.iloc[4]words4 = list(zip(*group_by_4))[0]freq4 = list(zip(*group_by_4))[1]plt.figure(figsize=(50,30))plt.bar(words4, freq4)plt.xlabel('Words', fontsize=50)plt.ylabel('Frequency of Words', fontsize=50)plt.yticks(fontsize=40)plt.xticks(rotation=60, fontsize=40)plt.title('Frequency of 25 Most Common Words for Rating=5', fontsize=60)plt.show()
Finally, let’s apply a few topic modeling algorithms to help derive specific topics or themes for our reviews. Before we have determined the topics for each rating we have to perform one additional processing step. Right now our data/words are still readable to us human beings whereas computers only understand numbers. We need to convert our text into numbers or vectors.
The CountVectorizer method of vectorizing tokens transposes all the words/tokens into features and then provides a count of occurrence of each word. The result is called a document term matrix, which you can see below.
First, we create the vectorizer object. Max_df=0.9 will remove words that appear in more than 90% of the reviews. Min_df=25 will remove words that appear in less than 25 reviews. Next, we create the spare matrix as the result of fit_transform(). Finally, we create a list of all the words/features. The result is our document term matrix. Each row represents individual employee reviews and counts of how many times each word/feature occurs in each review.
tf_vectorizer = CountVectorizer(max_df=0.9, min_df=25, max_features=5000)tf = tf_vectorizer.fit_transform(df['lemma_str'].values.astype('U'))tf_feature_names = tf_vectorizer.get_feature_names()doc_term_matrix = pd.DataFrame(tf.toarray(), columns=list(tf_feature_names))doc_term_matrix
Now that we have prepared our data for topic modeling, we’ll be using the Latent Dirichlet Allocation (LDA) approach to determine the topics present in our corpus. In our model, we are going to produce 10 individual topics (ie. n_components). Once the model is created let’s create a function to display the identified topics. Each topic will consist of 10 words. The function will have three required parameters; the LDA model, feature names from the document term matrix, and the number of words per topic.
lda_model = LatentDirichletAllocation(n_components=10, learning_method='online', max_iter=500, random_state=0).fit(tf)no_top_words = 10def display_topics(model, feature_names, no_top_words): for topic_idx, topic in enumerate(model.components_): print("Topic %d:" % (topic_idx)) print(" ".join([feature_names[i] for i in topic.argsort()[:-no_top_words - 1:-1]])) display_topics(lda_model, tf_feature_names, no_top_words)
It certainly takes a little imagination to determine the topics produced by the LDA model. Since we know that “work”, “google” and “job” are very common works we can almost ignore them.
Topic 0: Good Design Processes
Topic 1: Great Work Environment
Topic 2: Flexible Work Hours
Topic 3: Skill Building
Topic 4: Difficult but Enjoyable Work
Topic 5: Great Company/Job
Topic 6: Care about Employees
Topic 7: Great Contractor Pay
Topic 8: Customer Service
Topic 9: ?
pyLDAvis is an interactive LDA visualization python library. Each circle represents a unique topic, the size of the circle represents the importance of the topic and finally, the distance between each circle represents how similar the topics are to each other. Selecting a topic/circle will reveal a horizontal bar chart displaying the 30 most relevant words for the topic along with the frequency of each word appearing in the topic and the overall corpus.
The relevance metric helps to distinguish words which are distinct/exclusive to the topic (λλ closer to 0.0) and words which have a high probability of being included in the selected topic (λλ closer to 1.0).
pyLDAvis.enable_notebook()panel = pyLDAvis.sklearn.prepare(lda_model, tf, tf_vectorizer, mds='tsne')panel
LDA isn’t the only approach to topic modeling. Let’s try another method named the Non-Negative Matrix Factorization (NMF) approach and see if our topics can be slightly more defined. Instead of using the simple CountVectorizer method to vectorize our words/tokens, we’ll use the TF-IDF (Term Frequency — Inverse Document Frequency) method. The TF-IDF method helps to bring down the weight/impact of high-frequency words (ie. “work”, “Google” and ‘job” in our case).
Much like the CountVectorizer method we first create the vectorizer object. Max_df=0.9 will remove words that appear in more than 90% of the reviews. Min_df=25 will remove words that appear in less than 25 reviews. Next, we create the spare matrix as the result of fit_transform(). Finally, we create a list of all the words/features.
tfidf_vectorizer = TfidfVectorizer(max_df=0.90, min_df =25, max_features=5000, use_idf=True)tfidf = tfidf_vectorizer.fit_transform(df['lemma_str'])tfidf_feature_names = tfidf_vectorizer.get_feature_names()doc_term_matrix_tfidf = pd.DataFrame(tfidf.toarray(), columns=list(tfidf_feature_names))doc_term_matrix_tfidf
nmf = NMF(n_components=10, random_state=0, alpha=.1, init='nndsvd').fit(tfidf)display_topics(nmf, tfidf_feature_names, no_top_words)
The topics produced via NMF seem to be much more distinct compared to LDA.
Topic 0: Fun Work Culture
Topic 1: Design Process
Topic 2: Enjoyable Job
Topic 3:
Topic 4: Great Experience
Topic 5: Perks
Topic 6: Learning Opportunities
Topic 7: Great Company/Job
Topic 8: Contractor Employee Experience
Topic 9: Management
Let’s add both the LDA and NMF topics into our dataframe for further analysis. Let’s also remap the integer topics into our subjectively derived topic labels.
nmf_topic_values = nmf.transform(tfidf)df['nmf_topics'] = nmf_topic_values.argmax(axis=1)lda_topic_values = lda_model.transform(tf)df['lda_topics'] = lda_topic_values.argmax(axis=1)lda_remap = {0: 'Good Design Processes', 1: 'Great Work Environment', 2: 'Flexible Work Hours', 3: 'Skill Building', 4: 'Difficult but Enjoyable Work', 5: 'Great Company/Job', 6: 'Care about Employees', 7: 'Great Contractor Pay', 8: 'Customer Service', 9: 'Unknown1'}df['lda_topics'] = df['lda_topics'].map(lda_remap)nmf_remap = {0: 'Fun Work Culture', 1: 'Design Process', 2: 'Enjoyable Job', 3: 'Difficult but Enjoyable Work', 4: 'Great Experience', 5: 'Perks', 6: 'Learning Opportunities', 7: 'Great Company/Job', 8: 'Contractor Employee Experience', 9: 'Management'}df['nmf_topics'] = df['nmf_topics'].map(nmf_remap)
Examining the frequency of topics produced by NMF we can see that the first 5 topics show up at a relatively similar frequency. Keep in mind these are the topics across all reviews (positive, neutral, and negative) and if you recall our dataset is negatively skewed as the majority of the reviews are positive.
nmf_x = df['nmf_topics'].value_counts()nmf_y = nmf_x.sort_index()plt.figure(figsize=(50,30))sns.barplot(nmf_x, nmf_y.index)plt.title("NMF Topic Distribution", fontsize=50)plt.ylabel('Review Topics', fontsize=50)plt.yticks(fontsize=40)plt.xlabel('Frequency', fontsize=50)plt.xticks(fontsize=40)
Let’s split our data and examine the topics for the negative reviews based on ratings of 1 and 2. It is interesting to see that despite the negative ratings the employees still overwhelmingly enjoyed their work, culture, and the company overall. It is very difficult to obtain an accurate perspective on the topics for negative reviews due to the skewness of our dataset (ie. the relatively small amount of negative reviews).
df_low_ratings = df.loc[(df['rating']==1) | (df['rating']==2)]nmf_low_x = df_low_ratings['nmf_topics'].value_counts()nmf_low_y = nmf_low_x.sort_index()plt.figure(figsize=(50,30))sns.barplot(nmf_low_x, nmf_low_y.index)plt.title("NMF Topic Distribution for Low Ratings (1 & 2)", fontsize=50)plt.ylabel('Frequency', fontsize=50)plt.yticks(fontsize=40)plt.xlabel('Review Topics', fontsize=50)plt.xticks(fontsize=40)
Since we have many more positive reviews the topics derived via NMF will be much more accurate. It seems contractor employees make up many of the reviews. Employees find an efficient design process, work which is difficult but enjoyable, and an overall happy sentiment towards Google.
df_high_ratings = df.loc[(df['rating']==4) | (df['rating']==5)]nmf_high_x = df_high_ratings['nmf_topics'].value_counts()nmf_high_y = nmf_high_x.sort_index()plt.figure(figsize=(50,30))sns.barplot(nmf_high_x, nmf_high_y.index)plt.title("NMF Topic Distribution for High Ratings (3 & 4)", fontsize=50)plt.ylabel('Frequency', fontsize=50)plt.yticks(fontsize=40)plt.xlabel('Review Topics', fontsize=50)plt.xticks(fontsize=40)
Based on the results obtained it seems Google’s employees are overwhelmingly happy working at Google. We see a negatively skewed distribution where 84% of employees had given Google a rating of 4 or 5 (out of a 1–5 Likert scale). A sentiment analysis confirmed these results even when employees who gave Google a rating between 2 and 3 had a positive average sentiment score.
As we dug a bit deeper into the data an interesting discovery was made which would need to be validated with additional data. When we observed the term/word frequencies per rating it seemed that terms around “managers/management” seemed to present themselves for ratings 1, 2, and 3. As mentioned earlier, the data was skewed as the majority of ratings were positive but it was interesting to see that employees who had a negative or a neutral rating seemed to mention “management” often.
On the other hand, employees who rated Google between 4 and 5 seemed to be using words such as “great”, “work”, “job”, “design”, “company”, “good”, “culture”, “people”, etc. These results were slightly confirmed with an examination of topics/themes in our corpus. An NMF analysis of topics determined that employees who rated Google with a 4 or 5 were eager to discuss the difficult but enjoyable work, great culture, design process. It was interesting to also see the absence of any mention of terms like “manager” and “management” which is also telling and helps to validate our previous insight.
Google continues to be a preferred employer of choice for many, as 84% of reviews were positive. That said, we identified a potential area of improvement which stemmed from Google’s managers and/or management techniques.
Can you think of any other EDA methods and/or strategies we could have explored? Posted them in the comments below. Also, if you have any constructive feedback or see a mistake I have made please call me out 😃
|
[
{
"code": null,
"e": 298,
"s": 172,
"text": "This is a continuation of a three part series on NLP using python. Feel free to check out my other articles. (Part 1, Part 2)"
},
{
"code": null,
"e": 611,
"s": 298,
"text": "Let’s get a better understanding of our newly cleansed dataset.Exploratory Data Analysis (EDA) is the process by which the data analyst becomes acquainted with their data to drive intuition and begin to formulate testable hypotheses. This process typically makes use of descriptive statistics and visualizations."
},
{
"code": null,
"e": 697,
"s": 611,
"text": "Let’s begin, as always, by importing the necessary libraries and opening our dataset."
},
{
"code": null,
"e": 1396,
"s": 697,
"text": "import pandas as pdimport numpy as npimport nltkimport pickleimport pyLDAvis.sklearnfrom collections import Counterfrom textblob import TextBlobfrom nltk.tokenize import word_tokenizefrom nltk.probability import FreqDistfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.decomposition import LatentDirichletAllocation, NMFfrom wordcloud import WordCloud, ImageColorGeneratorimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinepd.options.mode.chained_assignment = Nonepd.set_option('display.max_colwidth', 100)with open('indeed_scrape_clean.pkl', 'rb') as pickle_file: df = pickle.load(pickle_file)"
},
{
"code": null,
"e": 1775,
"s": 1396,
"text": "If you recall from our previous tutorial, we went through a series of pre-processing steps to clean and prepare our data for analysis. Our final dataset contains numerous columns but the last column “lemmatized”, contained our final cleansed list of words. We are going to overwrite our existing dataframe because we are only interested in the “rating” and “lemmatized” columns."
},
{
"code": null,
"e": 1818,
"s": 1775,
"text": "df = df[['rating', 'lemmatized']]df.head()"
},
{
"code": null,
"e": 2157,
"s": 1818,
"text": "Sentiment analysis is the process of determining the writer’s attitude or opinion ranging from -1 (negative attitude) to 1 (positive attitude). We’ll be using the TextBlob library to analyze sentiment. TextBlob’s Sentiment() function requires a string but our “lemmatized” column is currently a list. Let’s convert the list into a string."
},
{
"code": null,
"e": 2233,
"s": 2157,
"text": "df['lemma_str'] = [' '.join(map(str,l)) for l in df['lemmatized']]df.head()"
},
{
"code": null,
"e": 2548,
"s": 2233,
"text": "Now we can pass the “lemma_str” column into the Sentiment() function to calculate sentiment. Since we have the “rating” column, we can validate how well the sentiment analysis was able to determine the writer’s attitude. That said, we do see obvious errors as rating #5 has a rating of 5but a fairly low sentiment."
},
{
"code": null,
"e": 2639,
"s": 2548,
"text": "df['sentiment'] = df['lemma_str'].apply(lambda x: TextBlob(x).sentiment.polarity)df.head()"
},
{
"code": null,
"e": 3104,
"s": 2639,
"text": "When comparing a histogram of our sentiment, we can see that the vast majority of our derived sentiment rating is overwhelmingly positive. When we compare this against the “ratings” column, we can see a similar pattern emerge. Not only do we feel comfortable in the accuracy of the sentiment analysis but we can see that the overall employee attitude about the company is very positive. It is no wonder Google regularly makes the Forbes’s Best Places to Work list."
},
{
"code": null,
"e": 3359,
"s": 3104,
"text": "plt.figure(figsize=(50,30))plt.margins(0.02)plt.xlabel('Sentiment', fontsize=50)plt.xticks(fontsize=40)plt.ylabel('Frequency', fontsize=50)plt.yticks(fontsize=40)plt.hist(df['sentiment'], bins=50)plt.title('Sentiment Distribution', fontsize=60)plt.show()"
},
{
"code": null,
"e": 3679,
"s": 3359,
"text": "x_rating = df.rating.value_counts()y_rating = x_rating.sort_index()plt.figure(figsize=(50,30))sns.barplot(x_rating.index, x_rating.values, alpha=0.8)plt.title(\"Rating Distribution\", fontsize=50)plt.ylabel('Frequency', fontsize=50)plt.yticks(fontsize=40)plt.xlabel('Employee Ratings', fontsize=50)plt.xticks(fontsize=40)"
},
{
"code": null,
"e": 4009,
"s": 3679,
"text": "plt.figure(figsize=(30,10))plt.title('Percentage of Ratings', fontsize=20)df.rating.value_counts().plot(kind='pie', labels=['Rating5', 'Rating4', 'Rating3', 'Rating2', 'Rating1'], wedgeprops=dict(width=.7), autopct='%1.0f%%', startangle= -20, textprops={'fontsize': 15})"
},
{
"code": null,
"e": 4299,
"s": 4009,
"text": "polarity_avg = df.groupby('rating')['sentiment'].mean().plot(kind='bar', figsize=(50,30))plt.xlabel('Rating', fontsize=45)plt.ylabel('Average Sentiment', fontsize=45)plt.xticks(fontsize=40)plt.yticks(fontsize=40)plt.title('Average Sentiment per Rating Distribution', fontsize=50)plt.show()"
},
{
"code": null,
"e": 4460,
"s": 4299,
"text": "Let’s create two additional features of “word_count” to determine the number of words per review and “review_len” to determine the number of letters per review."
},
{
"code": null,
"e": 4590,
"s": 4460,
"text": "df['word_count'] = df['lemmatized'].apply(lambda x: len(str(x).split()))df['review_len'] = df['lemma_str'].astype(str).apply(len)"
},
{
"code": null,
"e": 5317,
"s": 4590,
"text": "Although the differences are not significantly large it seems the longest reviews based on the count of letters and words seem to be negative and neutral. It seems disgruntled employees typically provide significantly more detail in their reviews. This result is not uncommon as humans have a tendency to complain in detail but praise in brief. This can be further confirmed by examining the correlation matrix below. Both ratings and sentiment have a negative correlation with “review_len” and “word_count”. This would explain the inverse relationship as the count of letters and words per review increases the overall rating and sentiment decreases. However, once again the correlation is rather small nevertheless negative."
},
{
"code": null,
"e": 5623,
"s": 5317,
"text": "letter_avg = df.groupby('rating')['review_len'].mean().plot(kind='bar', figsize=(50,30))plt.xlabel('Rating', fontsize=35)plt.ylabel('Count of Letters in Rating', fontsize=35)plt.xticks(fontsize=40)plt.yticks(fontsize=40)plt.title('Average Number of Letters per Rating Distribution', fontsize=40)plt.show()"
},
{
"code": null,
"e": 5923,
"s": 5623,
"text": "word_avg = df.groupby('rating')['word_count'].mean().plot(kind='bar', figsize=(50,30))plt.xlabel('Rating', fontsize=35)plt.ylabel('Count of Words in Rating', fontsize=35)plt.xticks(fontsize=40)plt.yticks(fontsize=40)plt.title('Average Number of Words per Rating Distribution', fontsize=40)plt.show()"
},
{
"code": null,
"e": 6273,
"s": 5923,
"text": "correlation = df[['rating','sentiment', 'review_len', 'word_count']].corr()mask = np.zeros_like(correlation, dtype=np.bool)mask[np.triu_indices_from(mask)] = Trueplt.figure(figsize=(50,30))plt.xticks(fontsize=40)plt.yticks(fontsize=40)sns.heatmap(correlation, cmap='coolwarm', annot=True, annot_kws={\"size\": 40}, linewidths=10, vmin=-1.5, mask=mask)"
},
{
"code": null,
"e": 6507,
"s": 6273,
"text": "Let’s take an in-depth look at the actual reviews themselves. What are the most common words? What are the most common words by rating? Answers to these questions will provide further insights into the opinions of Google’s employees."
},
{
"code": null,
"e": 6909,
"s": 6507,
"text": "NLTK has a great library named “FreqDist” which allows us to determine the count of the most common terms in our corpus. First, we need to convert our individual lists of tokenized reviews into a comprehensive list of iterable tokens which stores all the reviews together. Finally, we pass FreqDist() the “allwords” object and apply the “most_common(100)” function to obtain the 100 most common words."
},
{
"code": null,
"e": 7008,
"s": 6909,
"text": "words = df['lemmatized']allwords = []for wordlist in words: allwords += wordlistprint(allwords)"
},
{
"code": null,
"e": 7353,
"s": 7008,
"text": "mostcommon = FreqDist(allwords).most_common(100)wordcloud = WordCloud(width=1600, height=800, background_color='white').generate(str(mostcommon))fig = plt.figure(figsize=(30,10), facecolor='white')plt.imshow(wordcloud, interpolation=\"bilinear\")plt.axis('off')plt.title('Top 100 Most Common Words', fontsize=100)plt.tight_layout(pad=0)plt.show()"
},
{
"code": null,
"e": 7698,
"s": 7353,
"text": "mostcommon_small = FreqDist(allwords).most_common(25)x, y = zip(*mostcommon_small)plt.figure(figsize=(50,30))plt.margins(0.02)plt.bar(x, y)plt.xlabel('Words', fontsize=50)plt.ylabel('Frequency of Words', fontsize=50)plt.yticks(fontsize=40)plt.xticks(rotation=60, fontsize=40)plt.title('Frequency of 25 Most Common Words', fontsize=60)plt.show()"
},
{
"code": null,
"e": 7946,
"s": 7698,
"text": "The results of the term frequency analysis certainly supports the overall positive sentiment of the reviews. Terms such as “Great”, “Work”, “People”, “Team”, “Company” point to a positive company environment where employees enjoy working together."
},
{
"code": null,
"e": 8147,
"s": 7946,
"text": "Based on the fact terms such as “work”, “Google”, “job” and “company” have such a high frequency in the corpus it might be a good idea to remove them (ie. add them to our stopwords) prior to analysis."
},
{
"code": null,
"e": 8258,
"s": 8147,
"text": "That said, a company can always improve therefore, let’s examine the most common words for each review rating."
},
{
"code": null,
"e": 8528,
"s": 8258,
"text": "It seems the most common words for reviews where the rating = 1 had something to do with the “Management”, “Manager”, “People”. We have to be careful when interpreting these results as there are only (2%) reviews with a rating of 1 based on our pie chart printed above."
},
{
"code": null,
"e": 8998,
"s": 8528,
"text": "group_by = df.groupby('rating')['lemma_str'].apply(lambda x: Counter(' '.join(x).split()).most_common(25))group_by_0 = group_by.iloc[0]words0 = list(zip(*group_by_0))[0]freq0 = list(zip(*group_by_0))[1]plt.figure(figsize=(50,30))plt.bar(words0, freq0)plt.xlabel('Words', fontsize=50)plt.ylabel('Frequency of Words', fontsize=50)plt.yticks(fontsize=40)plt.xticks(rotation=60, fontsize=40)plt.title('Frequency of 25 Most Common Words for Rating=1', fontsize=60)plt.show()"
},
{
"code": null,
"e": 9192,
"s": 8998,
"text": "Reviews with a rating of 2 had a common theme of “manager”, “management”. Once again the rating distribution is very skewed but this does give us some clues on ways to improve the organization."
},
{
"code": null,
"e": 9556,
"s": 9192,
"text": "group_by_1 = group_by.iloc[1]words1 = list(zip(*group_by_1))[0]freq1 = list(zip(*group_by_1))[1]plt.figure(figsize=(50,30))plt.bar(words1, freq1)plt.xlabel('Words', fontsize=50)plt.ylabel('Frequency of Words', fontsize=50)plt.yticks(fontsize=40)plt.xticks(rotation=60, fontsize=40)plt.title('Frequency of 25 Most Common Words for Rating=2', fontsize=60)plt.show()"
},
{
"code": null,
"e": 10094,
"s": 9556,
"text": "It is difficult to derive accurate insights from a “neutral” rating as the employee didn’t have anything overly positive or negative to say about the company. That said, it is interesting that “Management” has once again crept into the top 10 words. So far roughly 14% of the employees had a negative or neutral (didn’t have anything good or bad to say) about the management at Google. Words like “work” and “Google” seem to be skewing the distribution for all ratings, it would be a good idea to remove these words from future analysis."
},
{
"code": null,
"e": 10160,
"s": 10094,
"text": "Notice the “...”, we have some more data processing to perform. 😞"
},
{
"code": null,
"e": 10524,
"s": 10160,
"text": "group_by_2 = group_by.iloc[2]words2 = list(zip(*group_by_2))[0]freq2 = list(zip(*group_by_2))[1]plt.figure(figsize=(50,30))plt.bar(words2, freq2)plt.xlabel('Words', fontsize=50)plt.ylabel('Frequency of Words', fontsize=50)plt.yticks(fontsize=40)plt.xticks(rotation=60, fontsize=40)plt.title('Frequency of 25 Most Common Words for Rating=3', fontsize=60)plt.show()"
},
{
"code": null,
"e": 11164,
"s": 10524,
"text": "Rating of 4 and 5 had very similar terms as it seems employees enjoy their work, the people with whom they work, and value the environment/culture at Google. For example, “design”, “learning opportunities”, “people”, “time” and “team” all made an appearance. That said, we don’t see “Management” or “Manager” anywhere in the top 10 words. This is very insightful as it helps to validate the results from ratings 1, 2, and 3. Last but not least, these word frequencies (ie. ratings 4 & 5) have been derived from a very large number of reviews which only adds to the validity of these results; management is certainly an area of improvement."
},
{
"code": null,
"e": 11528,
"s": 11164,
"text": "group_by_3 = group_by.iloc[3]words3 = list(zip(*group_by_3))[0]freq3 = list(zip(*group_by_3))[1]plt.figure(figsize=(50,30))plt.bar(words3, freq3)plt.xlabel('Words', fontsize=50)plt.ylabel('Frequency of Words', fontsize=50)plt.yticks(fontsize=40)plt.xticks(rotation=60, fontsize=40)plt.title('Frequency of 25 Most Common Words for Rating=4', fontsize=60)plt.show()"
},
{
"code": null,
"e": 11892,
"s": 11528,
"text": "group_by_4 = group_by.iloc[4]words4 = list(zip(*group_by_4))[0]freq4 = list(zip(*group_by_4))[1]plt.figure(figsize=(50,30))plt.bar(words4, freq4)plt.xlabel('Words', fontsize=50)plt.ylabel('Frequency of Words', fontsize=50)plt.yticks(fontsize=40)plt.xticks(rotation=60, fontsize=40)plt.title('Frequency of 25 Most Common Words for Rating=5', fontsize=60)plt.show()"
},
{
"code": null,
"e": 12266,
"s": 11892,
"text": "Finally, let’s apply a few topic modeling algorithms to help derive specific topics or themes for our reviews. Before we have determined the topics for each rating we have to perform one additional processing step. Right now our data/words are still readable to us human beings whereas computers only understand numbers. We need to convert our text into numbers or vectors."
},
{
"code": null,
"e": 12485,
"s": 12266,
"text": "The CountVectorizer method of vectorizing tokens transposes all the words/tokens into features and then provides a count of occurrence of each word. The result is called a document term matrix, which you can see below."
},
{
"code": null,
"e": 12942,
"s": 12485,
"text": "First, we create the vectorizer object. Max_df=0.9 will remove words that appear in more than 90% of the reviews. Min_df=25 will remove words that appear in less than 25 reviews. Next, we create the spare matrix as the result of fit_transform(). Finally, we create a list of all the words/features. The result is our document term matrix. Each row represents individual employee reviews and counts of how many times each word/feature occurs in each review."
},
{
"code": null,
"e": 13227,
"s": 12942,
"text": "tf_vectorizer = CountVectorizer(max_df=0.9, min_df=25, max_features=5000)tf = tf_vectorizer.fit_transform(df['lemma_str'].values.astype('U'))tf_feature_names = tf_vectorizer.get_feature_names()doc_term_matrix = pd.DataFrame(tf.toarray(), columns=list(tf_feature_names))doc_term_matrix"
},
{
"code": null,
"e": 13736,
"s": 13227,
"text": "Now that we have prepared our data for topic modeling, we’ll be using the Latent Dirichlet Allocation (LDA) approach to determine the topics present in our corpus. In our model, we are going to produce 10 individual topics (ie. n_components). Once the model is created let’s create a function to display the identified topics. Each topic will consist of 10 words. The function will have three required parameters; the LDA model, feature names from the document term matrix, and the number of words per topic."
},
{
"code": null,
"e": 14211,
"s": 13736,
"text": "lda_model = LatentDirichletAllocation(n_components=10, learning_method='online', max_iter=500, random_state=0).fit(tf)no_top_words = 10def display_topics(model, feature_names, no_top_words): for topic_idx, topic in enumerate(model.components_): print(\"Topic %d:\" % (topic_idx)) print(\" \".join([feature_names[i] for i in topic.argsort()[:-no_top_words - 1:-1]])) display_topics(lda_model, tf_feature_names, no_top_words)"
},
{
"code": null,
"e": 14397,
"s": 14211,
"text": "It certainly takes a little imagination to determine the topics produced by the LDA model. Since we know that “work”, “google” and “job” are very common works we can almost ignore them."
},
{
"code": null,
"e": 14428,
"s": 14397,
"text": "Topic 0: Good Design Processes"
},
{
"code": null,
"e": 14460,
"s": 14428,
"text": "Topic 1: Great Work Environment"
},
{
"code": null,
"e": 14489,
"s": 14460,
"text": "Topic 2: Flexible Work Hours"
},
{
"code": null,
"e": 14513,
"s": 14489,
"text": "Topic 3: Skill Building"
},
{
"code": null,
"e": 14551,
"s": 14513,
"text": "Topic 4: Difficult but Enjoyable Work"
},
{
"code": null,
"e": 14578,
"s": 14551,
"text": "Topic 5: Great Company/Job"
},
{
"code": null,
"e": 14608,
"s": 14578,
"text": "Topic 6: Care about Employees"
},
{
"code": null,
"e": 14638,
"s": 14608,
"text": "Topic 7: Great Contractor Pay"
},
{
"code": null,
"e": 14664,
"s": 14638,
"text": "Topic 8: Customer Service"
},
{
"code": null,
"e": 14675,
"s": 14664,
"text": "Topic 9: ?"
},
{
"code": null,
"e": 15133,
"s": 14675,
"text": "pyLDAvis is an interactive LDA visualization python library. Each circle represents a unique topic, the size of the circle represents the importance of the topic and finally, the distance between each circle represents how similar the topics are to each other. Selecting a topic/circle will reveal a horizontal bar chart displaying the 30 most relevant words for the topic along with the frequency of each word appearing in the topic and the overall corpus."
},
{
"code": null,
"e": 15342,
"s": 15133,
"text": "The relevance metric helps to distinguish words which are distinct/exclusive to the topic (λλ closer to 0.0) and words which have a high probability of being included in the selected topic (λλ closer to 1.0)."
},
{
"code": null,
"e": 15448,
"s": 15342,
"text": "pyLDAvis.enable_notebook()panel = pyLDAvis.sklearn.prepare(lda_model, tf, tf_vectorizer, mds='tsne')panel"
},
{
"code": null,
"e": 15914,
"s": 15448,
"text": "LDA isn’t the only approach to topic modeling. Let’s try another method named the Non-Negative Matrix Factorization (NMF) approach and see if our topics can be slightly more defined. Instead of using the simple CountVectorizer method to vectorize our words/tokens, we’ll use the TF-IDF (Term Frequency — Inverse Document Frequency) method. The TF-IDF method helps to bring down the weight/impact of high-frequency words (ie. “work”, “Google” and ‘job” in our case)."
},
{
"code": null,
"e": 16249,
"s": 15914,
"text": "Much like the CountVectorizer method we first create the vectorizer object. Max_df=0.9 will remove words that appear in more than 90% of the reviews. Min_df=25 will remove words that appear in less than 25 reviews. Next, we create the spare matrix as the result of fit_transform(). Finally, we create a list of all the words/features."
},
{
"code": null,
"e": 16564,
"s": 16249,
"text": "tfidf_vectorizer = TfidfVectorizer(max_df=0.90, min_df =25, max_features=5000, use_idf=True)tfidf = tfidf_vectorizer.fit_transform(df['lemma_str'])tfidf_feature_names = tfidf_vectorizer.get_feature_names()doc_term_matrix_tfidf = pd.DataFrame(tfidf.toarray(), columns=list(tfidf_feature_names))doc_term_matrix_tfidf"
},
{
"code": null,
"e": 16697,
"s": 16564,
"text": "nmf = NMF(n_components=10, random_state=0, alpha=.1, init='nndsvd').fit(tfidf)display_topics(nmf, tfidf_feature_names, no_top_words)"
},
{
"code": null,
"e": 16772,
"s": 16697,
"text": "The topics produced via NMF seem to be much more distinct compared to LDA."
},
{
"code": null,
"e": 16798,
"s": 16772,
"text": "Topic 0: Fun Work Culture"
},
{
"code": null,
"e": 16822,
"s": 16798,
"text": "Topic 1: Design Process"
},
{
"code": null,
"e": 16845,
"s": 16822,
"text": "Topic 2: Enjoyable Job"
},
{
"code": null,
"e": 16854,
"s": 16845,
"text": "Topic 3:"
},
{
"code": null,
"e": 16880,
"s": 16854,
"text": "Topic 4: Great Experience"
},
{
"code": null,
"e": 16895,
"s": 16880,
"text": "Topic 5: Perks"
},
{
"code": null,
"e": 16927,
"s": 16895,
"text": "Topic 6: Learning Opportunities"
},
{
"code": null,
"e": 16954,
"s": 16927,
"text": "Topic 7: Great Company/Job"
},
{
"code": null,
"e": 16994,
"s": 16954,
"text": "Topic 8: Contractor Employee Experience"
},
{
"code": null,
"e": 17014,
"s": 16994,
"text": "Topic 9: Management"
},
{
"code": null,
"e": 17173,
"s": 17014,
"text": "Let’s add both the LDA and NMF topics into our dataframe for further analysis. Let’s also remap the integer topics into our subjectively derived topic labels."
},
{
"code": null,
"e": 18001,
"s": 17173,
"text": "nmf_topic_values = nmf.transform(tfidf)df['nmf_topics'] = nmf_topic_values.argmax(axis=1)lda_topic_values = lda_model.transform(tf)df['lda_topics'] = lda_topic_values.argmax(axis=1)lda_remap = {0: 'Good Design Processes', 1: 'Great Work Environment', 2: 'Flexible Work Hours', 3: 'Skill Building', 4: 'Difficult but Enjoyable Work', 5: 'Great Company/Job', 6: 'Care about Employees', 7: 'Great Contractor Pay', 8: 'Customer Service', 9: 'Unknown1'}df['lda_topics'] = df['lda_topics'].map(lda_remap)nmf_remap = {0: 'Fun Work Culture', 1: 'Design Process', 2: 'Enjoyable Job', 3: 'Difficult but Enjoyable Work', 4: 'Great Experience', 5: 'Perks', 6: 'Learning Opportunities', 7: 'Great Company/Job', 8: 'Contractor Employee Experience', 9: 'Management'}df['nmf_topics'] = df['nmf_topics'].map(nmf_remap)"
},
{
"code": null,
"e": 18312,
"s": 18001,
"text": "Examining the frequency of topics produced by NMF we can see that the first 5 topics show up at a relatively similar frequency. Keep in mind these are the topics across all reviews (positive, neutral, and negative) and if you recall our dataset is negatively skewed as the majority of the reviews are positive."
},
{
"code": null,
"e": 18606,
"s": 18312,
"text": "nmf_x = df['nmf_topics'].value_counts()nmf_y = nmf_x.sort_index()plt.figure(figsize=(50,30))sns.barplot(nmf_x, nmf_y.index)plt.title(\"NMF Topic Distribution\", fontsize=50)plt.ylabel('Review Topics', fontsize=50)plt.yticks(fontsize=40)plt.xlabel('Frequency', fontsize=50)plt.xticks(fontsize=40)"
},
{
"code": null,
"e": 19032,
"s": 18606,
"text": "Let’s split our data and examine the topics for the negative reviews based on ratings of 1 and 2. It is interesting to see that despite the negative ratings the employees still overwhelmingly enjoyed their work, culture, and the company overall. It is very difficult to obtain an accurate perspective on the topics for negative reviews due to the skewness of our dataset (ie. the relatively small amount of negative reviews)."
},
{
"code": null,
"e": 19444,
"s": 19032,
"text": "df_low_ratings = df.loc[(df['rating']==1) | (df['rating']==2)]nmf_low_x = df_low_ratings['nmf_topics'].value_counts()nmf_low_y = nmf_low_x.sort_index()plt.figure(figsize=(50,30))sns.barplot(nmf_low_x, nmf_low_y.index)plt.title(\"NMF Topic Distribution for Low Ratings (1 & 2)\", fontsize=50)plt.ylabel('Frequency', fontsize=50)plt.yticks(fontsize=40)plt.xlabel('Review Topics', fontsize=50)plt.xticks(fontsize=40)"
},
{
"code": null,
"e": 19729,
"s": 19444,
"text": "Since we have many more positive reviews the topics derived via NMF will be much more accurate. It seems contractor employees make up many of the reviews. Employees find an efficient design process, work which is difficult but enjoyable, and an overall happy sentiment towards Google."
},
{
"code": null,
"e": 20149,
"s": 19729,
"text": "df_high_ratings = df.loc[(df['rating']==4) | (df['rating']==5)]nmf_high_x = df_high_ratings['nmf_topics'].value_counts()nmf_high_y = nmf_high_x.sort_index()plt.figure(figsize=(50,30))sns.barplot(nmf_high_x, nmf_high_y.index)plt.title(\"NMF Topic Distribution for High Ratings (3 & 4)\", fontsize=50)plt.ylabel('Frequency', fontsize=50)plt.yticks(fontsize=40)plt.xlabel('Review Topics', fontsize=50)plt.xticks(fontsize=40)"
},
{
"code": null,
"e": 20525,
"s": 20149,
"text": "Based on the results obtained it seems Google’s employees are overwhelmingly happy working at Google. We see a negatively skewed distribution where 84% of employees had given Google a rating of 4 or 5 (out of a 1–5 Likert scale). A sentiment analysis confirmed these results even when employees who gave Google a rating between 2 and 3 had a positive average sentiment score."
},
{
"code": null,
"e": 21014,
"s": 20525,
"text": "As we dug a bit deeper into the data an interesting discovery was made which would need to be validated with additional data. When we observed the term/word frequencies per rating it seemed that terms around “managers/management” seemed to present themselves for ratings 1, 2, and 3. As mentioned earlier, the data was skewed as the majority of ratings were positive but it was interesting to see that employees who had a negative or a neutral rating seemed to mention “management” often."
},
{
"code": null,
"e": 21613,
"s": 21014,
"text": "On the other hand, employees who rated Google between 4 and 5 seemed to be using words such as “great”, “work”, “job”, “design”, “company”, “good”, “culture”, “people”, etc. These results were slightly confirmed with an examination of topics/themes in our corpus. An NMF analysis of topics determined that employees who rated Google with a 4 or 5 were eager to discuss the difficult but enjoyable work, great culture, design process. It was interesting to also see the absence of any mention of terms like “manager” and “management” which is also telling and helps to validate our previous insight."
},
{
"code": null,
"e": 21834,
"s": 21613,
"text": "Google continues to be a preferred employer of choice for many, as 84% of reviews were positive. That said, we identified a potential area of improvement which stemmed from Google’s managers and/or management techniques."
}
] |
Comparing the Performance of Fully-Connected, Simple CNN, and ResNet50 for Binary Image Classification in TensorFlow | by Binh Phan | Towards Data Science
|
In the world of machine learning, there are three models that you can use to perform binary image classification: a fully-connected network, a convolutional neural network, or a pre-trained network like MobileNet with transfer learning applied to it. In my previous stories, I showed how to implement these models to build an image classifier that can classify dandelions and grass and evaluate their performance by computing their accuracy, ROC curves, and AUC score. In this story, I will compare these models side-by-side and compare their performances. If you’d like to follow along the entire training, evaluation, and comparison of these models, follow this notebook. You can run the code by saving your own copy by going to File -> Save a copy.
Which model do you think will perform best?
Firstly, let’s take a look at the three model architectures and see how they differ:
FULLY-CONNECTED MODELLayer (type) Output Shape Param # ================================================================= flatten (Flatten) (None, 120000) 0 _________________________________________________________________ dense (Dense) (None, 128) 15360128 _________________________________________________________________ dense_1 (Dense) (None, 1) 129 ================================================================= Total params: 15,360,257 Trainable params: 15,360,257 Non-trainable params: 0CONVOLUTIONAL NEURAL NETWORK MODELLayer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 198, 198, 16) 448 _________________________________________________________________ max_pooling2d (MaxPooling2D) (None, 99, 99, 16) 0 _________________________________________________________________ conv2d_1 (Conv2D) (None, 97, 97, 32) 4640 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 48, 48, 32) 0 _________________________________________________________________ conv2d_2 (Conv2D) (None, 46, 46, 64) 18496 _________________________________________________________________ max_pooling2d_2 (MaxPooling2 (None, 23, 23, 64) 0 _________________________________________________________________ conv2d_3 (Conv2D) (None, 21, 21, 64) 36928 _________________________________________________________________ max_pooling2d_3 (MaxPooling2 (None, 10, 10, 64) 0 _________________________________________________________________ conv2d_4 (Conv2D) (None, 8, 8, 64) 36928 _________________________________________________________________ max_pooling2d_4 (MaxPooling2 (None, 4, 4, 64) 0 _________________________________________________________________ flatten (Flatten) (None, 1024) 0 _________________________________________________________________ dense (Dense) (None, 512) 524800 _________________________________________________________________ dense_1 (Dense) (None, 1) 513 ================================================================= Total params: 622,753 Trainable params: 622,753 Non-trainable params: 0MOBILENET w/ TRANSFER LEARNINGLayer (type) Output Shape Param # ================================================================= mobilenetv2_1.00_224 (Model) (None, 7, 7, 1280) 2257984 _________________________________________________________________ global_average_pooling2d (Gl (None, 1280) 0 _________________________________________________________________ dense (Dense) (None, 1) 1281 ================================================================= Total params: 2,259,265 Trainable params: 1,281 Non-trainable params: 2,257,984
Notice how the fully-connected model has the highest number of trainable parameters, followed by the CNN model, followed by the MobileNet model. In the FC model, every connection in the Flatten layer is connected to every connection in the Dense layer, resulting in a higher number of parameters. In the CNN, fewer parameters are needed because every convolutional layer reduces the dimensions of the input through the convolution operation. And in contrast to those two models, the MobileNet model uses what is called transfer learning: it doesn’t train on the pre-trained layers and only trains a final Dense layer. It takes advantage of the feature extraction capabilities of the pre-trained layers for training that last layer, so only few parameters are needed to train the model.
For each model, I used the same dataset and trained the model with 15 epochs. Let’s bring the results together and compare them side-by-side, starting with the accuracies :
FC accuracy: 0.5987CNN accuracy: 0.7197MobileNet accuracy: 0.8917
The MobileNet model has the highest accuracy, followed by the CNN model, followed by the fully-connected model.
Accuracy isn’t the best way to compare model performance. Better metrics for classification tasks include ROC curves and AUC, which measure how much our model is capable of distinguishing between our two classes, dandelions and grass. The higher the AUC, the better our model is at classification. In the plot above, MobileNet scores highest in AUC, followed by CNN, followed by FC.
Here are the takeaways from these comparisons:
The MobileNet model is a superior model in terms of accuracy and ROC curve/AUC, even though it doesn’t have the most parameters. This shows the power of transfer learning over a powerful trained model.
The CNN model comes in 2nd. Convolutional Neural Networks perform better than fully-connected networks on binary image classification, with a lot less parameters, because of their shared-weights architecture and translation invariance characteristics.
The fully-connected model performs better than chance at binary image classification, but it isn’t the optimal model to do so.
|
[
{
"code": null,
"e": 924,
"s": 172,
"text": "In the world of machine learning, there are three models that you can use to perform binary image classification: a fully-connected network, a convolutional neural network, or a pre-trained network like MobileNet with transfer learning applied to it. In my previous stories, I showed how to implement these models to build an image classifier that can classify dandelions and grass and evaluate their performance by computing their accuracy, ROC curves, and AUC score. In this story, I will compare these models side-by-side and compare their performances. If you’d like to follow along the entire training, evaluation, and comparison of these models, follow this notebook. You can run the code by saving your own copy by going to File -> Save a copy."
},
{
"code": null,
"e": 968,
"s": 924,
"text": "Which model do you think will perform best?"
},
{
"code": null,
"e": 1053,
"s": 968,
"text": "Firstly, let’s take a look at the three model architectures and see how they differ:"
},
{
"code": null,
"e": 4270,
"s": 1053,
"text": "FULLY-CONNECTED MODELLayer (type) Output Shape Param # ================================================================= flatten (Flatten) (None, 120000) 0 _________________________________________________________________ dense (Dense) (None, 128) 15360128 _________________________________________________________________ dense_1 (Dense) (None, 1) 129 ================================================================= Total params: 15,360,257 Trainable params: 15,360,257 Non-trainable params: 0CONVOLUTIONAL NEURAL NETWORK MODELLayer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 198, 198, 16) 448 _________________________________________________________________ max_pooling2d (MaxPooling2D) (None, 99, 99, 16) 0 _________________________________________________________________ conv2d_1 (Conv2D) (None, 97, 97, 32) 4640 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 48, 48, 32) 0 _________________________________________________________________ conv2d_2 (Conv2D) (None, 46, 46, 64) 18496 _________________________________________________________________ max_pooling2d_2 (MaxPooling2 (None, 23, 23, 64) 0 _________________________________________________________________ conv2d_3 (Conv2D) (None, 21, 21, 64) 36928 _________________________________________________________________ max_pooling2d_3 (MaxPooling2 (None, 10, 10, 64) 0 _________________________________________________________________ conv2d_4 (Conv2D) (None, 8, 8, 64) 36928 _________________________________________________________________ max_pooling2d_4 (MaxPooling2 (None, 4, 4, 64) 0 _________________________________________________________________ flatten (Flatten) (None, 1024) 0 _________________________________________________________________ dense (Dense) (None, 512) 524800 _________________________________________________________________ dense_1 (Dense) (None, 1) 513 ================================================================= Total params: 622,753 Trainable params: 622,753 Non-trainable params: 0MOBILENET w/ TRANSFER LEARNINGLayer (type) Output Shape Param # ================================================================= mobilenetv2_1.00_224 (Model) (None, 7, 7, 1280) 2257984 _________________________________________________________________ global_average_pooling2d (Gl (None, 1280) 0 _________________________________________________________________ dense (Dense) (None, 1) 1281 ================================================================= Total params: 2,259,265 Trainable params: 1,281 Non-trainable params: 2,257,984"
},
{
"code": null,
"e": 5056,
"s": 4270,
"text": "Notice how the fully-connected model has the highest number of trainable parameters, followed by the CNN model, followed by the MobileNet model. In the FC model, every connection in the Flatten layer is connected to every connection in the Dense layer, resulting in a higher number of parameters. In the CNN, fewer parameters are needed because every convolutional layer reduces the dimensions of the input through the convolution operation. And in contrast to those two models, the MobileNet model uses what is called transfer learning: it doesn’t train on the pre-trained layers and only trains a final Dense layer. It takes advantage of the feature extraction capabilities of the pre-trained layers for training that last layer, so only few parameters are needed to train the model."
},
{
"code": null,
"e": 5229,
"s": 5056,
"text": "For each model, I used the same dataset and trained the model with 15 epochs. Let’s bring the results together and compare them side-by-side, starting with the accuracies :"
},
{
"code": null,
"e": 5295,
"s": 5229,
"text": "FC accuracy: 0.5987CNN accuracy: 0.7197MobileNet accuracy: 0.8917"
},
{
"code": null,
"e": 5407,
"s": 5295,
"text": "The MobileNet model has the highest accuracy, followed by the CNN model, followed by the fully-connected model."
},
{
"code": null,
"e": 5790,
"s": 5407,
"text": "Accuracy isn’t the best way to compare model performance. Better metrics for classification tasks include ROC curves and AUC, which measure how much our model is capable of distinguishing between our two classes, dandelions and grass. The higher the AUC, the better our model is at classification. In the plot above, MobileNet scores highest in AUC, followed by CNN, followed by FC."
},
{
"code": null,
"e": 5837,
"s": 5790,
"text": "Here are the takeaways from these comparisons:"
},
{
"code": null,
"e": 6039,
"s": 5837,
"text": "The MobileNet model is a superior model in terms of accuracy and ROC curve/AUC, even though it doesn’t have the most parameters. This shows the power of transfer learning over a powerful trained model."
},
{
"code": null,
"e": 6291,
"s": 6039,
"text": "The CNN model comes in 2nd. Convolutional Neural Networks perform better than fully-connected networks on binary image classification, with a lot less parameters, because of their shared-weights architecture and translation invariance characteristics."
}
] |
Python program to print all distinct elements of a given integer array.
|
Given an integer array. The elements of the array may be duplicate.Our task is to display the distinct values.
Input::A=[1,2,3,4,2,3,5,6]
Output [1,2,3,4,5,6]
Step 1: input Array element.
Step 2: Then pick all the elements one by one.
Step 3: then check if the picked element is already displayed or not.
Step 4: use one flag variable which initialized by 0.if the element is displayed earlier flag variable is 1 and if the element is not displayed earlier flag variable is 0.
Step 5: Display distinct elements.
# Python program to print all distinct
# elements in a given array
def distinctelement(A, n1):
print("Distinct Elements are ::>")
for i in range(0, n1):
c = 0
for j in range(0, i):
if (A[i] == A[j]):
c = 1
break
if (c == 0):
print(A[i])
# Driver code
A=list()
n1=int(input("Enter the size of the List ::"))
print("Enter the Element of List ::")
for i in range(int(n1)):
k=int(input(""))
A.append(k)
distinctelement(A, n1)
Enter the size of the List ::4
Enter the Element of List ::
1
2
2
4
Distinct Elements are ::>
1
2
4
|
[
{
"code": null,
"e": 1173,
"s": 1062,
"text": "Given an integer array. The elements of the array may be duplicate.Our task is to display the distinct values."
},
{
"code": null,
"e": 1222,
"s": 1173,
"text": "Input::A=[1,2,3,4,2,3,5,6]\nOutput [1,2,3,4,5,6]\n"
},
{
"code": null,
"e": 1579,
"s": 1222,
"text": "Step 1: input Array element.\nStep 2: Then pick all the elements one by one.\nStep 3: then check if the picked element is already displayed or not.\nStep 4: use one flag variable which initialized by 0.if the element is displayed earlier flag variable is 1 and if the element is not displayed earlier flag variable is 0.\nStep 5: Display distinct elements. \n"
},
{
"code": null,
"e": 2097,
"s": 1579,
"text": "# Python program to print all distinct\n# elements in a given array\ndef distinctelement(A, n1):\n print(\"Distinct Elements are ::>\")\n for i in range(0, n1):\n c = 0\n for j in range(0, i):\n if (A[i] == A[j]):\n c = 1\n break\n if (c == 0):\n print(A[i])\n# Driver code\nA=list()\nn1=int(input(\"Enter the size of the List ::\"))\nprint(\"Enter the Element of List ::\")\nfor i in range(int(n1)):\n k=int(input(\"\"))\n A.append(k)\ndistinctelement(A, n1)"
},
{
"code": null,
"e": 2198,
"s": 2097,
"text": "Enter the size of the List ::4\nEnter the Element of List ::\n1\n2\n2\n4\nDistinct Elements are ::>\n1\n2\n4\n"
}
] |
What is the JLink tool in Java 9?
|
JLink is a new linker tool that has been used to create our own customized JRE. Usually, we can run our program using default JRE provided by Oracle. If we need to create our own JRE then use this tool. JLink tool can help to create its own JRE with only the required class to run the application. It can reduce the size of the API developed and the dependency of using full JRE.
In Java 9, we have a new phase between compiling the code and its execution link time. Link time is an optional phase between the phases of compile-time and runtime.
jlink --module-path --add-modules --limit-modules --output
module-path is the path where observable modules have discovered by the linker. It can be modular JAR files, JMOD files, and modules.
add-modules names the modules to add to the run-time image, these modules can, via transitive dependencies, cause additional modules to be added.
limit-modules limits the universe of observable modules.
the output is the directory that contains the resulting run-time image.
jlink --module-path $JAVA_HOME/jmods:mlib --add-modules com.greetings --output greetingsapp
In the above command, the value to module-path is a PATH of directories containing the packaged modules. JAVA_HOME/jmods is a directory containing java.base.jmod, other standards, and JDK modules. The directory mlib on the module path containing the artifact for module com.greetings.
|
[
{
"code": null,
"e": 1442,
"s": 1062,
"text": "JLink is a new linker tool that has been used to create our own customized JRE. Usually, we can run our program using default JRE provided by Oracle. If we need to create our own JRE then use this tool. JLink tool can help to create its own JRE with only the required class to run the application. It can reduce the size of the API developed and the dependency of using full JRE."
},
{
"code": null,
"e": 1608,
"s": 1442,
"text": "In Java 9, we have a new phase between compiling the code and its execution link time. Link time is an optional phase between the phases of compile-time and runtime."
},
{
"code": null,
"e": 1667,
"s": 1608,
"text": "jlink --module-path --add-modules --limit-modules --output"
},
{
"code": null,
"e": 1801,
"s": 1667,
"text": "module-path is the path where observable modules have discovered by the linker. It can be modular JAR files, JMOD files, and modules."
},
{
"code": null,
"e": 1947,
"s": 1801,
"text": "add-modules names the modules to add to the run-time image, these modules can, via transitive dependencies, cause additional modules to be added."
},
{
"code": null,
"e": 2004,
"s": 1947,
"text": "limit-modules limits the universe of observable modules."
},
{
"code": null,
"e": 2076,
"s": 2004,
"text": "the output is the directory that contains the resulting run-time image."
},
{
"code": null,
"e": 2168,
"s": 2076,
"text": "jlink --module-path $JAVA_HOME/jmods:mlib --add-modules com.greetings --output greetingsapp"
},
{
"code": null,
"e": 2453,
"s": 2168,
"text": "In the above command, the value to module-path is a PATH of directories containing the packaged modules. JAVA_HOME/jmods is a directory containing java.base.jmod, other standards, and JDK modules. The directory mlib on the module path containing the artifact for module com.greetings."
}
] |
How to print a page using JavaScript?
|
To print a page in JavaScript, use the print() method. It opens up the standard dialog box, through which you can easily set the printing options like which printer to select for printing.
Here’s an example −
You can try to run the following code to learn how to print a page −
Live Demo
<!DOCTYPE html>
<html>
<body>
<button onclick="display()">Click to Print</button>
<script>
function display() {
window.print();
}
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1251,
"s": 1062,
"text": "To print a page in JavaScript, use the print() method. It opens up the standard dialog box, through which you can easily set the printing options like which printer to select for printing."
},
{
"code": null,
"e": 1271,
"s": 1251,
"text": "Here’s an example −"
},
{
"code": null,
"e": 1340,
"s": 1271,
"text": "You can try to run the following code to learn how to print a page −"
},
{
"code": null,
"e": 1350,
"s": 1340,
"text": "Live Demo"
},
{
"code": null,
"e": 1560,
"s": 1350,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <button onclick=\"display()\">Click to Print</button>\n <script>\n function display() {\n window.print();\n }\n </script>\n </body>\n</html>"
}
] |
GATE CS 2010 - GeeksforGeeks
|
10 Nov, 2021
a
/ | \
b c d
Newton-Raphson method is used to compute a root of the equation x2-13=0 with 3.5 as the initial value. The approximation after one iteration is
3.607
3.667
3.676
3.575
In Newton-Raphson's method, We use the following formula to get the next value of f(x). f'(x) is derivative of f(x).
f(x) = x2-13
f'(x) = 2x
Applying the above formula, we get
Next x = 3.5 - (3.5*3.5 - 13)/2*3.5
Next x = 3.607
What is the possible number of reflexive relations on a set of 5 elements?
225
220
215
210
Number of reflexive relations is 2n2-n which is 220 for n = 5
What is the value of Limn->∞(1-1/n)2n ?
e-1/2
1
e-2
0
= PQ + QR’ + PR’
= PQ(R+R’) + (P+P’)QR’ + P(Q+Q’)R’
= PQR + PQR’ +PQR’ +P’QR’ + PQR’ + PQ’R’
= PQR(m7) + PQR'(m6)+P’QR'(m2) +PQ’R'(m4)
= m2 + m4 + m6 + m7
P is a 16-bit signed integer. The 2's complement representation of P is (F87B)16.The 2's complement representation of 8*P
(C3D8)16
(187B)16
(F878)16
(987B)16
P = (F87B)16 is -1111 1000 0111 1011 in binary Note that most significant bit in the binary representation is 1, which implies that the number is negative. To get the value of the number performs the 2's complement of the number. We get P as -1925 and 8P as -15400 Since 8P is also negative, we need to find 2's complement of it (-15400) Binary of 15400 = 0011 1100 0010 1000 2's Complement = 1100 0011 1101 1000 = (C3D8)16
What does the following program print?
C
2 2
2 1
0 1
0 2
See below comments for explanation.
/* p points to i and q points to j */
void f(int *p, int *q)
{
p = q; /* p also points to j now */
*p = 2; /* Value of j is changed to 2 now */
}
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Difference Between Skewness and Kurtosis
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
How to Replace Values in a List in Python?
How to Select Data Between Two Dates and Times in SQL Server?
Spring - REST Controller
Difference between Information Retrieval and Information Extraction
How to Read Text Files with Pandas?
|
[
{
"code": null,
"e": 28855,
"s": 28827,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 28879,
"s": 28855,
"text": " a \n / | \\\n b c d"
},
{
"code": null,
"e": 29024,
"s": 28879,
"text": "Newton-Raphson method is used to compute a root of the equation x2-13=0 with 3.5 as the initial value. The approximation after one iteration is "
},
{
"code": null,
"e": 29031,
"s": 29024,
"text": "3.607 "
},
{
"code": null,
"e": 29038,
"s": 29031,
"text": "3.667 "
},
{
"code": null,
"e": 29045,
"s": 29038,
"text": "3.676 "
},
{
"code": null,
"e": 29052,
"s": 29045,
"text": "3.575 "
},
{
"code": null,
"e": 29171,
"s": 29052,
"text": "In Newton-Raphson's method, We use the following formula to get the next value of f(x). f'(x) is derivative of f(x). "
},
{
"code": null,
"e": 29285,
"s": 29171,
"text": "f(x) = x2-13\nf'(x) = 2x\n\nApplying the above formula, we get\nNext x = 3.5 - (3.5*3.5 - 13)/2*3.5\nNext x = 3.607"
},
{
"code": null,
"e": 29363,
"s": 29287,
"text": "What is the possible number of reflexive relations on a set of 5 elements? "
},
{
"code": null,
"e": 29368,
"s": 29363,
"text": "225 "
},
{
"code": null,
"e": 29373,
"s": 29368,
"text": "220 "
},
{
"code": null,
"e": 29378,
"s": 29373,
"text": "215 "
},
{
"code": null,
"e": 29383,
"s": 29378,
"text": "210 "
},
{
"code": null,
"e": 29446,
"s": 29383,
"text": "Number of reflexive relations is 2n2-n which is 220 for n = 5 "
},
{
"code": null,
"e": 29487,
"s": 29446,
"text": "What is the value of Limn->∞(1-1/n)2n ? "
},
{
"code": null,
"e": 29494,
"s": 29487,
"text": "e-1/2 "
},
{
"code": null,
"e": 29497,
"s": 29494,
"text": "1 "
},
{
"code": null,
"e": 29502,
"s": 29497,
"text": "e-2 "
},
{
"code": null,
"e": 29505,
"s": 29502,
"text": "0 "
},
{
"code": null,
"e": 29664,
"s": 29505,
"text": "= PQ + QR’ + PR’ \n= PQ(R+R’) + (P+P’)QR’ + P(Q+Q’)R’\n= PQR + PQR’ +PQR’ +P’QR’ + PQR’ + PQ’R’ \n= PQR(m7) + PQR'(m6)+P’QR'(m2) +PQ’R'(m4) \n= m2 + m4 + m6 + m7 "
},
{
"code": null,
"e": 29787,
"s": 29664,
"text": "P is a 16-bit signed integer. The 2's complement representation of P is (F87B)16.The 2's complement representation of 8*P "
},
{
"code": null,
"e": 29797,
"s": 29787,
"text": "(C3D8)16 "
},
{
"code": null,
"e": 29807,
"s": 29797,
"text": "(187B)16 "
},
{
"code": null,
"e": 29817,
"s": 29807,
"text": "(F878)16 "
},
{
"code": null,
"e": 29827,
"s": 29817,
"text": "(987B)16 "
},
{
"code": null,
"e": 30252,
"s": 29827,
"text": "P = (F87B)16 is -1111 1000 0111 1011 in binary Note that most significant bit in the binary representation is 1, which implies that the number is negative. To get the value of the number performs the 2's complement of the number. We get P as -1925 and 8P as -15400 Since 8P is also negative, we need to find 2's complement of it (-15400) Binary of 15400 = 0011 1100 0010 1000 2's Complement = 1100 0011 1101 1000 = (C3D8)16 "
},
{
"code": null,
"e": 30292,
"s": 30252,
"text": "What does the following program print? "
},
{
"code": null,
"e": 30294,
"s": 30292,
"text": "C"
},
{
"code": null,
"e": 30299,
"s": 30294,
"text": "2 2 "
},
{
"code": null,
"e": 30304,
"s": 30299,
"text": "2 1 "
},
{
"code": null,
"e": 30309,
"s": 30304,
"text": "0 1 "
},
{
"code": null,
"e": 30315,
"s": 30309,
"text": "0 2 "
},
{
"code": null,
"e": 30353,
"s": 30315,
"text": "See below comments for explanation. "
},
{
"code": null,
"e": 30507,
"s": 30353,
"text": "/* p points to i and q points to j */\nvoid f(int *p, int *q)\n{\n p = q; /* p also points to j now */\n *p = 2; /* Value of j is changed to 2 now */\n}"
},
{
"code": null,
"e": 30607,
"s": 30509,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 30660,
"s": 30607,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 30701,
"s": 30660,
"text": "Difference Between Skewness and Kurtosis"
},
{
"code": null,
"e": 30763,
"s": 30701,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 30804,
"s": 30763,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 30884,
"s": 30804,
"text": "How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?"
},
{
"code": null,
"e": 30927,
"s": 30884,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 30989,
"s": 30927,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
},
{
"code": null,
"e": 31014,
"s": 30989,
"text": "Spring - REST Controller"
},
{
"code": null,
"e": 31082,
"s": 31014,
"text": "Difference between Information Retrieval and Information Extraction"
}
] |
Cypress - Mouse Actions
|
Cypress can handle hidden elements. There are occasions when submenus get displayed only on hovering over the main menu. These submenus are initially made hidden with the CSS property display:none.
For handling hidden elements, Cypress takes the help of the jQuery method show. It has to be invoked with the help of the Cypress command (invoke['show']).
For example, on hovering over the Mouse Hover button, the Top and Reload buttons get displayed, as shown below −
On moving the mouse out of the Mouse Hover button, the Top and Reload buttons get hidden, as shown below −
Given below is the implementation with jQuery show method in Cypress −
describe('Tutorialspoint Test', function () {
// test case
it('Scenario 1', function (){
// launch URL
cy.visit("https://learn.letskodeit.com/p/practice");
// show hidden element with invoke
cy.get('div.mouse-hover-content').invoke('show');
//click hidden element
cy.contains('Top').click();
});
});
Execution Results
The output is as follows −
The execution logs show the hidden element – Top button represented by an icon at the right of the steps.
73 Lectures
12 hours
Rahul Shetty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2695,
"s": 2497,
"text": "Cypress can handle hidden elements. There are occasions when submenus get displayed only on hovering over the main menu. These submenus are initially made hidden with the CSS property display:none."
},
{
"code": null,
"e": 2851,
"s": 2695,
"text": "For handling hidden elements, Cypress takes the help of the jQuery method show. It has to be invoked with the help of the Cypress command (invoke['show'])."
},
{
"code": null,
"e": 2964,
"s": 2851,
"text": "For example, on hovering over the Mouse Hover button, the Top and Reload buttons get displayed, as shown below −"
},
{
"code": null,
"e": 3071,
"s": 2964,
"text": "On moving the mouse out of the Mouse Hover button, the Top and Reload buttons get hidden, as shown below −"
},
{
"code": null,
"e": 3142,
"s": 3071,
"text": "Given below is the implementation with jQuery show method in Cypress −"
},
{
"code": null,
"e": 3487,
"s": 3142,
"text": "describe('Tutorialspoint Test', function () {\n // test case\n it('Scenario 1', function (){\n // launch URL\n cy.visit(\"https://learn.letskodeit.com/p/practice\");\n // show hidden element with invoke\n cy.get('div.mouse-hover-content').invoke('show');\n //click hidden element\n cy.contains('Top').click();\n });\n});"
},
{
"code": null,
"e": 3505,
"s": 3487,
"text": "Execution Results"
},
{
"code": null,
"e": 3532,
"s": 3505,
"text": "The output is as follows −"
},
{
"code": null,
"e": 3638,
"s": 3532,
"text": "The execution logs show the hidden element – Top button represented by an icon at the right of the steps."
},
{
"code": null,
"e": 3672,
"s": 3638,
"text": "\n 73 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 3686,
"s": 3672,
"text": " Rahul Shetty"
},
{
"code": null,
"e": 3693,
"s": 3686,
"text": " Print"
},
{
"code": null,
"e": 3704,
"s": 3693,
"text": " Add Notes"
}
] |
How to Install Go Project Dependencies? - GeeksforGeeks
|
22 Nov, 2021
We all know that project management is the most essential key for the setup of any project and in the same way, installing dependencies is also one of the important parts of project management.
For installing the go project dependencies, we use go get command, which automatically updates the go.mod file. You can also install go project dependencies by following a few steps, but remember as the package is still not used anywhere in the project it will be marked as indirect. And once you have configured the project for the use of go modules then you can introduce some more new dependencies into your codebase.
Below are all the steps that one needs to follow in order to install go dependencies.
First of all, we are going to create a workspace for the project, which will involve the below-mentioned steps:
Firstly we need to create a workspace or project folder and then inside that workspace, we need to create three subdirectories.
mkdir myproject
cd myproject
Names of the three subdirectories will be BIN, SRC, and PKG respectively.
mkdir bin
mkdir src
mkdir pkg
Now after doing all this the structure of our workspace is ready and now next we need to export the location of this workspace so that we can use the Go path variable.
pwd
export GOPATH=$HOME/golang_tutor/myproject
Now we need to export the BIN directory which we created inside the workspace so that we can use the path variable.
export PATH=$GOPATH/bin:$PATH
Now our workspace is ready to work and here are some simple steps to install go project dependencies into your workspace.
Step 2: Choose the package you want to install using the go get command. Suppose, you are installing one package named mux from github.com using the go get command. You can also use any other package from any other medium also.
go get github.com/gorilla/mux
ls
Now in your workspace, you can see your source file inside src folder and inside pkg folder you can see the package object. And the bin directory is empty.
ls src/
ls pkg/
ls bin/
So this is all that it takes to install a dependency in a go project using go get command.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Create and Setup Spring Boot Project in Eclipse IDE?
How to Install Jupyter Notebook on MacOS?
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": 24952,
"s": 24924,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 25146,
"s": 24952,
"text": "We all know that project management is the most essential key for the setup of any project and in the same way, installing dependencies is also one of the important parts of project management."
},
{
"code": null,
"e": 25567,
"s": 25146,
"text": "For installing the go project dependencies, we use go get command, which automatically updates the go.mod file. You can also install go project dependencies by following a few steps, but remember as the package is still not used anywhere in the project it will be marked as indirect. And once you have configured the project for the use of go modules then you can introduce some more new dependencies into your codebase."
},
{
"code": null,
"e": 25653,
"s": 25567,
"text": "Below are all the steps that one needs to follow in order to install go dependencies."
},
{
"code": null,
"e": 25766,
"s": 25653,
"text": " First of all, we are going to create a workspace for the project, which will involve the below-mentioned steps:"
},
{
"code": null,
"e": 25895,
"s": 25766,
"text": " Firstly we need to create a workspace or project folder and then inside that workspace, we need to create three subdirectories."
},
{
"code": null,
"e": 25911,
"s": 25895,
"text": "mkdir myproject"
},
{
"code": null,
"e": 25924,
"s": 25911,
"text": "cd myproject"
},
{
"code": null,
"e": 25998,
"s": 25924,
"text": "Names of the three subdirectories will be BIN, SRC, and PKG respectively."
},
{
"code": null,
"e": 26028,
"s": 25998,
"text": "mkdir bin\nmkdir src\nmkdir pkg"
},
{
"code": null,
"e": 26196,
"s": 26028,
"text": "Now after doing all this the structure of our workspace is ready and now next we need to export the location of this workspace so that we can use the Go path variable."
},
{
"code": null,
"e": 26200,
"s": 26196,
"text": "pwd"
},
{
"code": null,
"e": 26243,
"s": 26200,
"text": "export GOPATH=$HOME/golang_tutor/myproject"
},
{
"code": null,
"e": 26359,
"s": 26243,
"text": "Now we need to export the BIN directory which we created inside the workspace so that we can use the path variable."
},
{
"code": null,
"e": 26389,
"s": 26359,
"text": "export PATH=$GOPATH/bin:$PATH"
},
{
"code": null,
"e": 26511,
"s": 26389,
"text": "Now our workspace is ready to work and here are some simple steps to install go project dependencies into your workspace."
},
{
"code": null,
"e": 26739,
"s": 26511,
"text": "Step 2: Choose the package you want to install using the go get command. Suppose, you are installing one package named mux from github.com using the go get command. You can also use any other package from any other medium also."
},
{
"code": null,
"e": 26769,
"s": 26739,
"text": "go get github.com/gorilla/mux"
},
{
"code": null,
"e": 26772,
"s": 26769,
"text": "ls"
},
{
"code": null,
"e": 26928,
"s": 26772,
"text": "Now in your workspace, you can see your source file inside src folder and inside pkg folder you can see the package object. And the bin directory is empty."
},
{
"code": null,
"e": 26936,
"s": 26928,
"text": "ls src/"
},
{
"code": null,
"e": 26944,
"s": 26936,
"text": "ls pkg/"
},
{
"code": null,
"e": 26952,
"s": 26944,
"text": "ls bin/"
},
{
"code": null,
"e": 27043,
"s": 26952,
"text": "So this is all that it takes to install a dependency in a go project using go get command."
},
{
"code": null,
"e": 27058,
"s": 27043,
"text": "how-to-install"
},
{
"code": null,
"e": 27065,
"s": 27058,
"text": "Picked"
},
{
"code": null,
"e": 27072,
"s": 27065,
"text": "How To"
},
{
"code": null,
"e": 27091,
"s": 27072,
"text": "Installation Guide"
},
{
"code": null,
"e": 27189,
"s": 27091,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27198,
"s": 27189,
"text": "Comments"
},
{
"code": null,
"e": 27211,
"s": 27198,
"text": "Old Comments"
},
{
"code": null,
"e": 27245,
"s": 27211,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 27294,
"s": 27245,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 27352,
"s": 27294,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 27412,
"s": 27352,
"text": "How to Create and Setup Spring Boot Project in Eclipse IDE?"
},
{
"code": null,
"e": 27454,
"s": 27412,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 27487,
"s": 27454,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27521,
"s": 27487,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 27556,
"s": 27521,
"text": "How to Install Pygame on Windows ?"
},
{
"code": null,
"e": 27614,
"s": 27556,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
}
] |
Getting Started with End-to-End Speech Translation | by Mattia Di Gangi | Towards Data Science
|
With Pytorch you can translate English speech in only a few steps
Update 24–05–2021: The github repository used in this tutorial is no longer developed. If interested you should refer to this fork that is actively developed.
Speech-to-text translation is the task of translating a speech given in a source language into text written in a different, target language. It is a task with a history that dates back to a demo given in 1983. The classic approach to tackle this task consists in training a cascade of systems including automatic speech recognition (ASR) and machine translation (MT). You can see it in your Google Translate app, where your speech is first transcribed and then translated (although the translation appear to be real-time)
Both tasks of ASR and MT have been studied for long time and the systems’ quality has experienced significant leaps with the adoption of deep learning techniques. Indeed, the availability of big data (at least for some languages), large computing power and clear evaluation, made these two tasks perfect targets for big companies like Google that invested a lot in research. See as a reference the papers about Transformer[1] and SpecAugment [2]. As this blog post is not about cascaded systems, I refer the interested reader to the system that won the last IWSLT competition [3].
IWSLT is the main yearly workshop devoted to spoken language translation. Every edition hosts a “shared task”, a kind of competition, with the goal of recording the progress in spoken language technologies. Since 2018, the shared task started a separate evaluation for “end-to-end” systems, that are those systems consisting of a single model that learns to translate directly from audio to text in the target language, without intermediate steps. Our group has been participating to this new evaluation since its first edition, and I reported our first participation in a previous story.
medium.com
The quality of end-to-end models is still discussed, when compared to the cascaded approach, but it is a growing research topic and quality improvements are reported quite frequently. The goal of this tutorial is to lower the entry barriers to this field by providing the reader with a step-to-step guide to train an end-to-end system. In particular, we will focus on a system that can translate English speech into Italian, but it can be easily extended to additional seven languages: Dutch, French, German, Spanish, Portuguese, Romanian or Russian.
The minimum requirement is the access to at least one GPU, which you can get for free with Colab and Pytorch 0.4 installed.
medium.com
However, the K80 GPUs are quite slow and will require several days of training. Accessing to better or more GPUs will be of great help.
We will use MuST-C, the largest multilingual corpus available for the direct speech translation task. You can find a detailed description in the paper that introduced it [4] or in the following Medium story:
medium.com
To get the corpus, go to https://mustc.fbk.eu/, click on the button “Click here to download the corpus”, then fill the form and you will soon be able to download it.
MuST-C is divided in 8 portions, one for each target language, feel free to download one or all of them, but for this tutorial we will use the Italian target (it) as an example. Each portion contains TED talks given in English and translated in the target language (the translations are provided by the Ted website). The size of the training set depends on the availability of translations for the given language, while the validation and test sets are extracted from a common pool of talks.
Each portion of MuST-C is divided into train, dev, tst-COMMON and tst-HE. Train, dev and tst-COMMON represent our split into training, validation and test set, while you can safely ignore tst-HE. In each of the three directories you will find three sub-directories: wav/, txt/, and h5/. wav/ contains the audio side of the set in the form of .wav files, one for each talk. txt contains the transcripts and translations, for our example with Italian you will find, under the train/txt directory, the files train.it, train.en, train.yaml. The first two are, respectively, the textual translation and trascript. train.yaml is a file containing the audio segmentation in a way that it is aligned with the textual files. As a bonus, the .en and .it files are parallel and, as such, they can be used to train MT systems. If you don’t know what to do with the segmentation provided by the yaml file, don’t be afraid! In the h5/ directory there is a single .h5 file that contains the audio already segmented and transformed to extract 40 Mel Filterbanks features.
NOTE: The dataset will be downloaded from Google Drive, if you want to download it from a machine with no GUI, you can try to use the tool gdown. However, it does not work always correctly. If you are unable to download with gdown, please try again after a few hours.
We will use FBK-Fairseq-ST, that is the fairseq tool by Facebook for MT adapted for the direct speech translation task. Clone the repository from github:
git clone https://github.com/mattiadg/FBK-Fairseq-ST.git
Then, clone also mosesdecoder, which contains useful scripts for text preprocessing.
git clone https://github.com/moses-smt/mosesdecoder.git
The audio side of the data is already preprocessed in the .h5 file, so we only have to care about the textual side.
Let us first create a directory where to put the tokenized data.
> mkdir mustc-tokenized> cd mustc-tokenized
Then, we can proceed to tokenize our Italian texts (an analogous process is needed for the other target languages):
> for file in $MUSTC/en-it/data/{train,dev,tst-COMMON}/txt/*.it; do $mosesdecoder/scripts/tokenizer/tokenizer.perl -l it < $file | $mosesdecoder/scripts/tokenizer/deescape-special-chars.perl > $filedone> mkdir tokenized> for file in *.it; do cp $file tokenized/$file.char sh word_level2char_level.sh tokenized/$filedone
The second for-loop splits the words in characters, as done in our paper that sets baselines for all the MuST-C languages [5].
Now, we have to binarize the data to make audio and text in a single format for fairseq. First, link the h5 files in the data directory.
> cd tokenized> for file in $MUSTC/en-it/data/{train,dev,tst-COMMON}/h5/*.h5; do ln -s $filedone
Then, we can move to the actual binarization
> python $FBK-Fairseq-ST/preprocess.py --trainpref train --validpref dev --testpref tst-COMMON -s h5 -t it --inputtype audio --format h5 --destdir bin
This will require some minutes, and in the end you should get something like this:
> ls bin/dict.it.txt train.h5-it.it.bin valid.h5-it.it.idxtest.h5-it.it.bin train.h5-it.it.idx valid.h5-it.h5.bintest.h5-it.it.idx train.h5-it.h5.bin valid.h5-it.h5.idxtest.h5-it.h5.bin train.h5-it.h5.idxtest.h5-it.h5.idx valid.h5-it.it.bin
We have a dictionary for the target language (dict.it.txt), and for each split of the data, an index and a content file for the source side (*.h5.idx and *.h5.bin) and the same for the target side (*.it.idx and *.it.bin).
With this, we have finished with the data preprocessing and can move on the training!
NOTE: Before training, I strongly recommend you to pre-train the encoder with an ASR system using the same architecture. The training script is the same as here, but follow the instructions at the end of this post first. Without encoder pre-training these models are unstable and may not converge.
For training, we are going to replicate the one reported in [5]. You just need to run the following command:
> mkdir models> CUDA_VISIBLE_DEVICES=$GPUS python $FBK-Fairseq-ST/train.py bin/ \ --clip-norm 20 \ --max-sentences 8 \ --max-tokens 12000 \ --save-dir models/ \ --max-epoch 50 \ --lr 5e-3 \ --dropout 0.1 \ --lr-schedule inverse_sqrt \ --warmup-updates 4000 --warmup-init-lr 3e-4 \ --optimizer adam \ --arch speechconvtransformer_big \ --distance-penalty log \ --task translation \ --audio-input \ --max-source-positions 1400 --max-target-positions 300 \ --update-freq 16 \ --skip-invalid-size-inputs-valid-test \ --sentence-avg \ --criterion label_smoothed_cross_entropy \ --label-smoothing 0.1
Let me explain it step by step. bin/ is the directory containing the binarized data, as above, while models/ is the directory where the checkpoints will be saved (one at the end of each epoch). --clip-norm refers to gradient clipping, and --dropout should be clear if you are familiar with deep learning.--max-tokens is the maximum number of audio frames that can be loaded in a single GPU for every iteration, and --max-sentences is the maximum batch size, which is limited also by max-tokens. --update-freq also affects the batch size, as here we are saying that the weights have to be updated after 16 iterations. It basically emulates the training with 16x GPUs. Now, the optimization policy: --optimizer adam is for using the Adam optimizer, --lr-schedule inverse_sqrt uses the schedule introduced by the Transformer paper [1]: the learning rate grows linearly in --warmup-updates step (4000) from --warmup-init-lr(0.0003) to --lr (0.005) and then decreases following the square root of the number of steps. The loss to optimize is cross entropy with label smoothing (--criterion) using a --label-smoothingof 0.1 . The loss is averaged among the sentences and not the tokens with--sentence-avg. --arch defines the architecture to use and the hyperparameters, these can be changed when running the training, but speechconvtransformer_big uses the same hyperparameters as in our paper, except for the distance penalty that is specified in our command.
The deep learning architecture is an adaptation of the Transformer to the speech translation task, which modifies the encoder to work with spectrograms in input. I will describe it in a future blog post.
During training, one checkpoint will be saved at the end of each epoch and called accordingly checkpoint1.pt, checkpoint2.pt, etc. Additionally, two more checkpoints will be updated at the end of every epoch: checkpoint_best.pt and checkpoint_last.pt. The former is a copy of the checkpoint with the best validation loss, the latter a copy of the last saved checkpoint.
When you are ready to run a translation from audio (actually, preprocessed spectrograms), you can run the following command:
python $FBK-Fairseq-ST/generate.py tokenized/bin/ --path models/checkpoint_best.pt --audio-input \ [--gen-subset valid] [--beam 5] [--batch 32] \[--skip-invalid-size-inputs-valid-test] [--max-source-positions N] [--max-target-positions N] > test.raw.txt
What is absolutely needed here is the directory with binarized data bin/, the path to the checkpoint --path models/checkpoint_best.pt, but it can be any of the saved checkpoints, --audio-inputand to inform the software that it has to expect audio (and not text) in input.
By design, this command will look for the “test” portion of the dataset within the given directory. If you want to translate another, valid or train, you can do it with --gen-subset {valid,train}. The beam size and the batch size can modified, respectively, with --beam and --batch . --skip-invalid-size-inputs-valid-test let the software skip the segments that are longer than the limits set by --max-source-positions and --max-target-positions.
The output will be something like this:
It starts with a list of the arguments used for translation, followed by some information on data: dictionaries first, then the dataset, and finally the model’s path.
After the preamble, we have the list of translations sorted by source length. This length is not evident from the translation, but it is partially reflected in the translation length. Each segment is identified by its original position, and there are four lines for each segment. The source segment S, here always AUDIO, the reference sentence T, the translation hypothesis H and the log probability of each word P.
The last line prints the BLEU score, but here it is computed at character level and it is not very significant for us.
In order to extract the translations, sort them by position id and bring the translations at word level, you can use the following scripts
> python $FBK-Fairseq-ST/scripts/sort-sentences.py test.raw.txt 5 > test.lines.txt> bash $FBK-Fairseq-ST/scripts/extract_words.sh test.lines.txt
This will create the word-level file test.lines.txt.word that you can use to measure the BLEU score, for example with the script in the mosesdecoder repository:
> $mosesdecoder/scripts/generic/multi-bleu.perl test.it < test.lines.txt.word
It is known in speech translation literature that initializing the encoder of our model with the weights of a model trained on the ASR task is beneficial for the final translation quality and speeds up training. This is also easy to replicate with our software and data. First, preprocess the data as above using the same audio but the English portion of the text. The audio segments and the English texts are already aligned, this means that you can use exactly the same binarized data for the audio side, and process the text to produce the remaining binaries. For ASR, you may want to remove punctuation and only predict words to make the task easier. The punctuation can be removed with:
sed "s/[[:punct:]]//g" $file.tok > $file.depunct
Follow the steps listed above for training an ASR system in a new directory models-asr. Then, once the training is over, run
$FBK-Fairseq-ST/strip_modules.py --model-path models-asr/checkpoint_best.pt --new-model-path models/pretrain_encoder.pt --strip-what decoder
This command will create a new checkpoint file with the same encoder as models-asr/checkpoint_best.pt but deprived of its decoder. Finally, in order to use it to initialize the new decoder, simply run the training command as above, but copy the checkpoint with the new
cp models/pretrain_encoder.pt models/checkpoint_last.pt
By default, the training script checks if there is a checkpoint named checkpoint_last.pt in the checkpoint directory, and if it exists it is used to initialize the model’s weights. Simple as that!
The recent research in direct speech-to-text translation made available software and data resources that can be easily used for kick-starting your work in this field. I hope that this tutorial is useful to get your hands “dirty” and familiarize with the tools. The next step is to research how to improve the existing methods!
towardsdatascience.com
[1] Vaswani, A., et al. “Attention is all you need.” Advances in neural information processing systems. (2017)[2] Park, DS., et al. “SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition.” Proc. Interspeech 2019 (2019)[3] Pham, NQ, et al. “The IWSLT 2019 KIT Speech Translation System.” Zenodo. http://doi.org/10.5281/zenodo.3525564 (2019)[4] Di Gangi, MA., et al. “MuST-C: a multilingual speech translation corpus.” HLT-NAACL 2019 (2019)[5] Di Gangi, MA., et al. “Adapting transformer to end-to-end spoken language translation.” INTERSPEECH 2019 (2019)
|
[
{
"code": null,
"e": 238,
"s": 172,
"text": "With Pytorch you can translate English speech in only a few steps"
},
{
"code": null,
"e": 397,
"s": 238,
"text": "Update 24–05–2021: The github repository used in this tutorial is no longer developed. If interested you should refer to this fork that is actively developed."
},
{
"code": null,
"e": 919,
"s": 397,
"text": "Speech-to-text translation is the task of translating a speech given in a source language into text written in a different, target language. It is a task with a history that dates back to a demo given in 1983. The classic approach to tackle this task consists in training a cascade of systems including automatic speech recognition (ASR) and machine translation (MT). You can see it in your Google Translate app, where your speech is first transcribed and then translated (although the translation appear to be real-time)"
},
{
"code": null,
"e": 1500,
"s": 919,
"text": "Both tasks of ASR and MT have been studied for long time and the systems’ quality has experienced significant leaps with the adoption of deep learning techniques. Indeed, the availability of big data (at least for some languages), large computing power and clear evaluation, made these two tasks perfect targets for big companies like Google that invested a lot in research. See as a reference the papers about Transformer[1] and SpecAugment [2]. As this blog post is not about cascaded systems, I refer the interested reader to the system that won the last IWSLT competition [3]."
},
{
"code": null,
"e": 2089,
"s": 1500,
"text": "IWSLT is the main yearly workshop devoted to spoken language translation. Every edition hosts a “shared task”, a kind of competition, with the goal of recording the progress in spoken language technologies. Since 2018, the shared task started a separate evaluation for “end-to-end” systems, that are those systems consisting of a single model that learns to translate directly from audio to text in the target language, without intermediate steps. Our group has been participating to this new evaluation since its first edition, and I reported our first participation in a previous story."
},
{
"code": null,
"e": 2100,
"s": 2089,
"text": "medium.com"
},
{
"code": null,
"e": 2651,
"s": 2100,
"text": "The quality of end-to-end models is still discussed, when compared to the cascaded approach, but it is a growing research topic and quality improvements are reported quite frequently. The goal of this tutorial is to lower the entry barriers to this field by providing the reader with a step-to-step guide to train an end-to-end system. In particular, we will focus on a system that can translate English speech into Italian, but it can be easily extended to additional seven languages: Dutch, French, German, Spanish, Portuguese, Romanian or Russian."
},
{
"code": null,
"e": 2775,
"s": 2651,
"text": "The minimum requirement is the access to at least one GPU, which you can get for free with Colab and Pytorch 0.4 installed."
},
{
"code": null,
"e": 2786,
"s": 2775,
"text": "medium.com"
},
{
"code": null,
"e": 2922,
"s": 2786,
"text": "However, the K80 GPUs are quite slow and will require several days of training. Accessing to better or more GPUs will be of great help."
},
{
"code": null,
"e": 3130,
"s": 2922,
"text": "We will use MuST-C, the largest multilingual corpus available for the direct speech translation task. You can find a detailed description in the paper that introduced it [4] or in the following Medium story:"
},
{
"code": null,
"e": 3141,
"s": 3130,
"text": "medium.com"
},
{
"code": null,
"e": 3307,
"s": 3141,
"text": "To get the corpus, go to https://mustc.fbk.eu/, click on the button “Click here to download the corpus”, then fill the form and you will soon be able to download it."
},
{
"code": null,
"e": 3799,
"s": 3307,
"text": "MuST-C is divided in 8 portions, one for each target language, feel free to download one or all of them, but for this tutorial we will use the Italian target (it) as an example. Each portion contains TED talks given in English and translated in the target language (the translations are provided by the Ted website). The size of the training set depends on the availability of translations for the given language, while the validation and test sets are extracted from a common pool of talks."
},
{
"code": null,
"e": 4855,
"s": 3799,
"text": "Each portion of MuST-C is divided into train, dev, tst-COMMON and tst-HE. Train, dev and tst-COMMON represent our split into training, validation and test set, while you can safely ignore tst-HE. In each of the three directories you will find three sub-directories: wav/, txt/, and h5/. wav/ contains the audio side of the set in the form of .wav files, one for each talk. txt contains the transcripts and translations, for our example with Italian you will find, under the train/txt directory, the files train.it, train.en, train.yaml. The first two are, respectively, the textual translation and trascript. train.yaml is a file containing the audio segmentation in a way that it is aligned with the textual files. As a bonus, the .en and .it files are parallel and, as such, they can be used to train MT systems. If you don’t know what to do with the segmentation provided by the yaml file, don’t be afraid! In the h5/ directory there is a single .h5 file that contains the audio already segmented and transformed to extract 40 Mel Filterbanks features."
},
{
"code": null,
"e": 5123,
"s": 4855,
"text": "NOTE: The dataset will be downloaded from Google Drive, if you want to download it from a machine with no GUI, you can try to use the tool gdown. However, it does not work always correctly. If you are unable to download with gdown, please try again after a few hours."
},
{
"code": null,
"e": 5277,
"s": 5123,
"text": "We will use FBK-Fairseq-ST, that is the fairseq tool by Facebook for MT adapted for the direct speech translation task. Clone the repository from github:"
},
{
"code": null,
"e": 5334,
"s": 5277,
"text": "git clone https://github.com/mattiadg/FBK-Fairseq-ST.git"
},
{
"code": null,
"e": 5419,
"s": 5334,
"text": "Then, clone also mosesdecoder, which contains useful scripts for text preprocessing."
},
{
"code": null,
"e": 5475,
"s": 5419,
"text": "git clone https://github.com/moses-smt/mosesdecoder.git"
},
{
"code": null,
"e": 5591,
"s": 5475,
"text": "The audio side of the data is already preprocessed in the .h5 file, so we only have to care about the textual side."
},
{
"code": null,
"e": 5656,
"s": 5591,
"text": "Let us first create a directory where to put the tokenized data."
},
{
"code": null,
"e": 5700,
"s": 5656,
"text": "> mkdir mustc-tokenized> cd mustc-tokenized"
},
{
"code": null,
"e": 5816,
"s": 5700,
"text": "Then, we can proceed to tokenize our Italian texts (an analogous process is needed for the other target languages):"
},
{
"code": null,
"e": 6147,
"s": 5816,
"text": "> for file in $MUSTC/en-it/data/{train,dev,tst-COMMON}/txt/*.it; do $mosesdecoder/scripts/tokenizer/tokenizer.perl -l it < $file | $mosesdecoder/scripts/tokenizer/deescape-special-chars.perl > $filedone> mkdir tokenized> for file in *.it; do cp $file tokenized/$file.char sh word_level2char_level.sh tokenized/$filedone"
},
{
"code": null,
"e": 6274,
"s": 6147,
"text": "The second for-loop splits the words in characters, as done in our paper that sets baselines for all the MuST-C languages [5]."
},
{
"code": null,
"e": 6411,
"s": 6274,
"text": "Now, we have to binarize the data to make audio and text in a single format for fairseq. First, link the h5 files in the data directory."
},
{
"code": null,
"e": 6511,
"s": 6411,
"text": "> cd tokenized> for file in $MUSTC/en-it/data/{train,dev,tst-COMMON}/h5/*.h5; do ln -s $filedone"
},
{
"code": null,
"e": 6556,
"s": 6511,
"text": "Then, we can move to the actual binarization"
},
{
"code": null,
"e": 6707,
"s": 6556,
"text": "> python $FBK-Fairseq-ST/preprocess.py --trainpref train --validpref dev --testpref tst-COMMON -s h5 -t it --inputtype audio --format h5 --destdir bin"
},
{
"code": null,
"e": 6790,
"s": 6707,
"text": "This will require some minutes, and in the end you should get something like this:"
},
{
"code": null,
"e": 7050,
"s": 6790,
"text": "> ls bin/dict.it.txt train.h5-it.it.bin valid.h5-it.it.idxtest.h5-it.it.bin train.h5-it.it.idx valid.h5-it.h5.bintest.h5-it.it.idx train.h5-it.h5.bin valid.h5-it.h5.idxtest.h5-it.h5.bin train.h5-it.h5.idxtest.h5-it.h5.idx valid.h5-it.it.bin"
},
{
"code": null,
"e": 7272,
"s": 7050,
"text": "We have a dictionary for the target language (dict.it.txt), and for each split of the data, an index and a content file for the source side (*.h5.idx and *.h5.bin) and the same for the target side (*.it.idx and *.it.bin)."
},
{
"code": null,
"e": 7358,
"s": 7272,
"text": "With this, we have finished with the data preprocessing and can move on the training!"
},
{
"code": null,
"e": 7656,
"s": 7358,
"text": "NOTE: Before training, I strongly recommend you to pre-train the encoder with an ASR system using the same architecture. The training script is the same as here, but follow the instructions at the end of this post first. Without encoder pre-training these models are unstable and may not converge."
},
{
"code": null,
"e": 7765,
"s": 7656,
"text": "For training, we are going to replicate the one reported in [5]. You just need to run the following command:"
},
{
"code": null,
"e": 8424,
"s": 7765,
"text": "> mkdir models> CUDA_VISIBLE_DEVICES=$GPUS python $FBK-Fairseq-ST/train.py bin/ \\ --clip-norm 20 \\ --max-sentences 8 \\ --max-tokens 12000 \\ --save-dir models/ \\ --max-epoch 50 \\ --lr 5e-3 \\ --dropout 0.1 \\ --lr-schedule inverse_sqrt \\ --warmup-updates 4000 --warmup-init-lr 3e-4 \\ --optimizer adam \\ --arch speechconvtransformer_big \\ --distance-penalty log \\ --task translation \\ --audio-input \\ --max-source-positions 1400 --max-target-positions 300 \\ --update-freq 16 \\ --skip-invalid-size-inputs-valid-test \\ --sentence-avg \\ --criterion label_smoothed_cross_entropy \\ --label-smoothing 0.1"
},
{
"code": null,
"e": 9879,
"s": 8424,
"text": "Let me explain it step by step. bin/ is the directory containing the binarized data, as above, while models/ is the directory where the checkpoints will be saved (one at the end of each epoch). --clip-norm refers to gradient clipping, and --dropout should be clear if you are familiar with deep learning.--max-tokens is the maximum number of audio frames that can be loaded in a single GPU for every iteration, and --max-sentences is the maximum batch size, which is limited also by max-tokens. --update-freq also affects the batch size, as here we are saying that the weights have to be updated after 16 iterations. It basically emulates the training with 16x GPUs. Now, the optimization policy: --optimizer adam is for using the Adam optimizer, --lr-schedule inverse_sqrt uses the schedule introduced by the Transformer paper [1]: the learning rate grows linearly in --warmup-updates step (4000) from --warmup-init-lr(0.0003) to --lr (0.005) and then decreases following the square root of the number of steps. The loss to optimize is cross entropy with label smoothing (--criterion) using a --label-smoothingof 0.1 . The loss is averaged among the sentences and not the tokens with--sentence-avg. --arch defines the architecture to use and the hyperparameters, these can be changed when running the training, but speechconvtransformer_big uses the same hyperparameters as in our paper, except for the distance penalty that is specified in our command."
},
{
"code": null,
"e": 10083,
"s": 9879,
"text": "The deep learning architecture is an adaptation of the Transformer to the speech translation task, which modifies the encoder to work with spectrograms in input. I will describe it in a future blog post."
},
{
"code": null,
"e": 10453,
"s": 10083,
"text": "During training, one checkpoint will be saved at the end of each epoch and called accordingly checkpoint1.pt, checkpoint2.pt, etc. Additionally, two more checkpoints will be updated at the end of every epoch: checkpoint_best.pt and checkpoint_last.pt. The former is a copy of the checkpoint with the best validation loss, the latter a copy of the last saved checkpoint."
},
{
"code": null,
"e": 10578,
"s": 10453,
"text": "When you are ready to run a translation from audio (actually, preprocessed spectrograms), you can run the following command:"
},
{
"code": null,
"e": 10832,
"s": 10578,
"text": "python $FBK-Fairseq-ST/generate.py tokenized/bin/ --path models/checkpoint_best.pt --audio-input \\ [--gen-subset valid] [--beam 5] [--batch 32] \\[--skip-invalid-size-inputs-valid-test] [--max-source-positions N] [--max-target-positions N] > test.raw.txt"
},
{
"code": null,
"e": 11104,
"s": 10832,
"text": "What is absolutely needed here is the directory with binarized data bin/, the path to the checkpoint --path models/checkpoint_best.pt, but it can be any of the saved checkpoints, --audio-inputand to inform the software that it has to expect audio (and not text) in input."
},
{
"code": null,
"e": 11551,
"s": 11104,
"text": "By design, this command will look for the “test” portion of the dataset within the given directory. If you want to translate another, valid or train, you can do it with --gen-subset {valid,train}. The beam size and the batch size can modified, respectively, with --beam and --batch . --skip-invalid-size-inputs-valid-test let the software skip the segments that are longer than the limits set by --max-source-positions and --max-target-positions."
},
{
"code": null,
"e": 11591,
"s": 11551,
"text": "The output will be something like this:"
},
{
"code": null,
"e": 11758,
"s": 11591,
"text": "It starts with a list of the arguments used for translation, followed by some information on data: dictionaries first, then the dataset, and finally the model’s path."
},
{
"code": null,
"e": 12174,
"s": 11758,
"text": "After the preamble, we have the list of translations sorted by source length. This length is not evident from the translation, but it is partially reflected in the translation length. Each segment is identified by its original position, and there are four lines for each segment. The source segment S, here always AUDIO, the reference sentence T, the translation hypothesis H and the log probability of each word P."
},
{
"code": null,
"e": 12293,
"s": 12174,
"text": "The last line prints the BLEU score, but here it is computed at character level and it is not very significant for us."
},
{
"code": null,
"e": 12432,
"s": 12293,
"text": "In order to extract the translations, sort them by position id and bring the translations at word level, you can use the following scripts"
},
{
"code": null,
"e": 12581,
"s": 12432,
"text": "> python $FBK-Fairseq-ST/scripts/sort-sentences.py test.raw.txt 5 > test.lines.txt> bash $FBK-Fairseq-ST/scripts/extract_words.sh test.lines.txt"
},
{
"code": null,
"e": 12742,
"s": 12581,
"text": "This will create the word-level file test.lines.txt.word that you can use to measure the BLEU score, for example with the script in the mosesdecoder repository:"
},
{
"code": null,
"e": 12820,
"s": 12742,
"text": "> $mosesdecoder/scripts/generic/multi-bleu.perl test.it < test.lines.txt.word"
},
{
"code": null,
"e": 13512,
"s": 12820,
"text": "It is known in speech translation literature that initializing the encoder of our model with the weights of a model trained on the ASR task is beneficial for the final translation quality and speeds up training. This is also easy to replicate with our software and data. First, preprocess the data as above using the same audio but the English portion of the text. The audio segments and the English texts are already aligned, this means that you can use exactly the same binarized data for the audio side, and process the text to produce the remaining binaries. For ASR, you may want to remove punctuation and only predict words to make the task easier. The punctuation can be removed with:"
},
{
"code": null,
"e": 13561,
"s": 13512,
"text": "sed \"s/[[:punct:]]//g\" $file.tok > $file.depunct"
},
{
"code": null,
"e": 13686,
"s": 13561,
"text": "Follow the steps listed above for training an ASR system in a new directory models-asr. Then, once the training is over, run"
},
{
"code": null,
"e": 13827,
"s": 13686,
"text": "$FBK-Fairseq-ST/strip_modules.py --model-path models-asr/checkpoint_best.pt --new-model-path models/pretrain_encoder.pt --strip-what decoder"
},
{
"code": null,
"e": 14096,
"s": 13827,
"text": "This command will create a new checkpoint file with the same encoder as models-asr/checkpoint_best.pt but deprived of its decoder. Finally, in order to use it to initialize the new decoder, simply run the training command as above, but copy the checkpoint with the new"
},
{
"code": null,
"e": 14152,
"s": 14096,
"text": "cp models/pretrain_encoder.pt models/checkpoint_last.pt"
},
{
"code": null,
"e": 14349,
"s": 14152,
"text": "By default, the training script checks if there is a checkpoint named checkpoint_last.pt in the checkpoint directory, and if it exists it is used to initialize the model’s weights. Simple as that!"
},
{
"code": null,
"e": 14676,
"s": 14349,
"text": "The recent research in direct speech-to-text translation made available software and data resources that can be easily used for kick-starting your work in this field. I hope that this tutorial is useful to get your hands “dirty” and familiarize with the tools. The next step is to research how to improve the existing methods!"
},
{
"code": null,
"e": 14699,
"s": 14676,
"text": "towardsdatascience.com"
}
] |
Mercari price recommendation for online retail sellers using Machine learning | by Debayan Mitra | Towards Data Science
|
Business problemUse of Machine learning / Deep learning to solve the business problemEvaluation metric (RMSLE)Exploratory data analysisFeature engineering (Generating 19 new features)Existing solutionsMy Experiments with models for improvementsSummary, results and conclusionsFuture workLink to my profile — Github code and LinkedinReferences
Business problem
Use of Machine learning / Deep learning to solve the business problem
Evaluation metric (RMSLE)
Exploratory data analysis
Feature engineering (Generating 19 new features)
Existing solutions
My Experiments with models for improvements
Summary, results and conclusions
Future work
Link to my profile — Github code and Linkedin
References
This case study is based on a Kaggle competition conducted in 2018 by Mercari which is an online shopping app. Link to the kaggle Competition — https://www.kaggle.com/c/mercari-price-suggestion-challenge.
You can find my entire code in my github profile (link at the end of this blog).
Mercari is an online selling app (quite similar to Quikr in India). Sellers upload used/refurbished products on the store that they want to sell. When they upload the product on the Mercari App, they want to know how much price they should be selling at. This helps the sellers in pricing/valuating their products before actually selling it.
Sellers upload product information like Item name (text format), Item description (text format), Item brand, Item category, Item condition, shipping status. When they upload these product information on the Mercari app, they in return get back the recommended price that would be sold at.
The goal in this case study is to predict this price of a product listing given the product attributes.
This problem can be best solved using Machine learning techniques, which is basically a regression modelling task which basically looks at historical product information/attributes which were similar and also the price in which that was sold and suggests prices accordingly.
Let us look at one row of the training data and understand its fields. (The entire training data contains ~1.4 million item listings)
The dataset comprises of the following fields —
name — This is the item name/product Name of the product that is being listed by the seller. (Text format)item condition id — Contains values one of (1,2,3,4,5). Basically its a number that represents the condition of the Item from a scale of 1–5.Category — Contains the product category taxonomy of the item as a 3-level hierarchy (seperated by ‘/’ delimiter). In the above example, It is electronics as Level 1 , computers & tablets as Level 2, components & parts as Level 3.Brand — The brand of the item being listed. 60% of rows are empty.Shipping — Contains Boolean — 1,0. ‘1’ indicates that the shipping fee is paid by the seller, ‘0’ indicates not paid by the seller.item description — This contains the detailed text description of the item. This contains as much information as possible about the condition, features and all other information relevant to the product. Naturally, we could imagine that this information would be quite relevant to us because price would depend on features, working condition of certain features etc. This would be an interesting Deep NLP task to solve.Price (to be predicted) — This is the price to be predicted in our case. contains float values between 0 and 2009.
name — This is the item name/product Name of the product that is being listed by the seller. (Text format)
item condition id — Contains values one of (1,2,3,4,5). Basically its a number that represents the condition of the Item from a scale of 1–5.
Category — Contains the product category taxonomy of the item as a 3-level hierarchy (seperated by ‘/’ delimiter). In the above example, It is electronics as Level 1 , computers & tablets as Level 2, components & parts as Level 3.
Brand — The brand of the item being listed. 60% of rows are empty.
Shipping — Contains Boolean — 1,0. ‘1’ indicates that the shipping fee is paid by the seller, ‘0’ indicates not paid by the seller.
item description — This contains the detailed text description of the item. This contains as much information as possible about the condition, features and all other information relevant to the product. Naturally, we could imagine that this information would be quite relevant to us because price would depend on features, working condition of certain features etc. This would be an interesting Deep NLP task to solve.
Price (to be predicted) — This is the price to be predicted in our case. contains float values between 0 and 2009.
(Note — This is not RMSE. It is RMSLE)
The evaluation metric that the competition used was basically a score. RMSLE stands for Root Mean Squared Logarithm Error. Here is a great blog post that I found which explains the differences between RMSE and RMSLE and in what cases RMSLE is more relevant in using as an evalation metric for regression tasks — https://medium.com/analytics-vidhya/root-mean-square-log-error-rmse-vs-rmlse-935c6cc1802a
Summarizing a couple of points from the blogpost about why RMSLE is used as a metric here :-
RMSLE penalizes more when you are under-estimating rather than over-estimating — In other words, RMSLE is used in this project ,it is saying that it’s okay if you give a higher price suggestion for certain Items but if you under predict than the actual, it is not acceptable . RMSLE will increase significantly if we under predict as compared to if we over predict by the same amount.I think this makes business sense for this case study, because we would probably be okay to give a higher price estimate for certain listings than actual, but if we underestimate an item’s price, its not okay because the buyer would probably not want to sell in that case.RMSLE can cushion out the effect of Outliers in the Data — Certain items in the dataset which would have a very high price value can actually skew the model if you evaluate on RMSE because of the squared error penalty in RMSE , whereas the RMSLE would only incur a slightly higher penalty for high value cars compared to low value cars because RMSLE has a logarithm term in the metric that cushions this effect.RMSLE considers only relative error and not the absolute error (because of the logarithm term), so a prediction of 9 against 10 and a prediction of 900 against 1000 are both having same relative errors.
RMSLE penalizes more when you are under-estimating rather than over-estimating — In other words, RMSLE is used in this project ,it is saying that it’s okay if you give a higher price suggestion for certain Items but if you under predict than the actual, it is not acceptable . RMSLE will increase significantly if we under predict as compared to if we over predict by the same amount.I think this makes business sense for this case study, because we would probably be okay to give a higher price estimate for certain listings than actual, but if we underestimate an item’s price, its not okay because the buyer would probably not want to sell in that case.
RMSLE can cushion out the effect of Outliers in the Data — Certain items in the dataset which would have a very high price value can actually skew the model if you evaluate on RMSE because of the squared error penalty in RMSE , whereas the RMSLE would only incur a slightly higher penalty for high value cars compared to low value cars because RMSLE has a logarithm term in the metric that cushions this effect.
RMSLE considers only relative error and not the absolute error (because of the logarithm term), so a prediction of 9 against 10 and a prediction of 900 against 1000 are both having same relative errors.
It is always recommended that we first understand the data very well before starting on predictive modelling. This is an extremely crucial task. Let us run through the data and gain some info and insights :
The prices follow a Log Normal Distribution here. From one of the existing Kaggle kernels, I found out that Mercari allows price listings between 3 and 2000 only. So we will filter for these item listings. If you see the graphs below, even the 99.9 percentile value is around 400. The inflection point occurs beyond that. We can build price slabs (according to 5 percentile slabs) to better analyze the distribution of prices of the item listings.
The shipping status is a binary — (1,0). 1 represents shipping fee is paid by seller. 0 represents if shipping fee is not paid by seller. We can check the violin plot plotted below. We can see that ‘0’ has a slightly higher price than ‘1’ (although I expected to be other way around because my assumption was that if the seller is already paying for shipping the item, then the price is expected to be slightly higher). But is the difference statistically significant ?— we can conduct a one way ANOVA test to do this at 5% significance — and this told that the difference in prices in the shipping status is indeed statistically significant.
Similar analysis for item condition has been done below. The differences in prices here are statistically significant too. No missing values have been found in these 2 features.
Categories feature here appear in ‘/’ seperated values . Most categories have 3 level seperators. (See image below). So the nomenclature here is cat1/cat2/cat3 where cat1 is the high level category followed by cat2 & cat3 which are sub level categories.
import seaborn as snssns.set(rc={'figure.figsize':(8,6)}, style = 'whitegrid')sns.barplot(x = "count", y="cat1", data=df_cat1_counts,palette="Blues_d")
Let us look at what types of words occur in this column using a wordcloud. Also, lets analyze price distributions across categories using violin plots.
sns.set(rc={'figure.figsize':(19,7)})sns.violinplot(x="cat1", y="log_price", data = df_train)plt.title('Violin Plots - Price variation in cat1')plt.show()
import matplotlib.pyplot as pltfrom wordcloud import WordCloudwordcloud = WordCloud(collocations=False).generate(text_cat)plt.figure(figsize = (12,6))plt.imshow(wordcloud, interpolation='bilinear')plt.axis("off")plt.title('WordCloud for Category Name')plt.show()
This feature contains ~4800 brands (with 60% of rows are missing). Top brands (by count)are listed below in dataframe. We can see that top 1000 brands (~ 25% top brands) account for about 97% of the product listings. (close to a power law distribution)
Different brands have different price distributions (as expected ). Brand should occur for one of the most relevant features since prices of products are a very heavy function of the brand of the Item. Follows a long tail skewed distribution as we can see below graph.
Let us understand by plotting their wordclouds. (But after some text preprocessing)
# reference - Applied AI Course (Code for Text Preprocessing)import refrom tqdm import tqdm_notebookdef decontracted(phrase): phrase = re.sub(r"won't", "will not", phrase) phrase = re.sub(r"can\'t", "can not", phrase) phrase = re.sub(r"n\'t", " not", phrase) phrase = re.sub(r"\'re", " are", phrase) phrase = re.sub(r"\'s", " is", phrase) phrase = re.sub(r"\'d", " would", phrase) phrase = re.sub(r"\'ll", " will", phrase) phrase = re.sub(r"\'t", " not", phrase) phrase = re.sub(r"\'ve", " have", phrase) phrase = re.sub(r"\'m", " am", phrase) return phrasedef text_preprocess(data): preprocessed = [] for sentance in tqdm_notebook(data): sent = decontracted(sentance) sent = sent.replace('\\r', ' ') sent = sent.replace('\\"', ' ') sent = sent.replace('\\n', ' ') sent = re.sub('[^A-Za-z0-9]+', ' ', sent) # https://gist.github.com/sebleier/554280 sent = ' '.join(e for e in sent.split() if e not in stopwords) preprocessed.append(sent.lower().strip()) return preprocessed
Above plot looks good — it gives an information about most frequently occuring words.
Let us also do some Topic Modelling using Latent Dirichlet Allocation. Without getting into details, What this does is basically a unsupervised algorithm that finds topics that the sentences are talking about in the entire text corpus. This analysis was inspired from this Kaggle kernel — link.
Let us look at some of the topics generated (by grouping similar words/sentences into topics- which the LDA algorithm does). LDA does a pretty decent job here in our case when applied to the item descriptions feature.
Topic 0 is most likely referring to Jewellery— (necklace,bracelet,chain,gold). Similarly topic 3 is referring to Apparel— (shirt, nike, men,women). Topic 7 is referring to Accessories— (leather,bag,wallet) etc. So we get a good sense of what the item descriptions column is talking about and a summary of the various topics present in it. This feature would be a very important predictor of price as it contains information related to item condition, newness, detailed features of the product etc.
My first hunch intuition is that this would be a Deep NLP task and needs to be solved using some form of LSTM Neural Network.
This was one of the most important parts in the ML system. Inspired by this Kaggle kernel link. Some new features were generated.
The hypotheses here was that the better sentiment an item is conveyed with in item description, the higher the buyers are willing to pay for the Item. I expected a positive co-relation between sentiment scores of item description and price.
from nltk.sentiment.vader import SentimentIntensityAnalyzerdef generate_sentiment_scores(data): sid = SentimentIntensityAnalyzer() scores = [] for sentence in tqdm_notebook(data): sentence_sentiment_score = sid.polarity_scores(sentence) scores.append(sentence_sentiment_score['compound']) return scores
I borrowed this code snippet from this Kaggle kernel — link . This basically gets the price statistics by grouping the (Category, Brand, Shipping) features together and generating price statistics — Mean, Median, Std. Deviation, Coefficient of variation, Expected price ranges based on 2 Std. deviations from mean etc. This makes sense because we are basically looking at historical prices of a group of items and feeding them in the feature set to assume that they might be well co-related to the current Prices.
I’m again borrowing this code snippet from the same Kaggle kernel link again as posted above. The code basically creates new features from the item description column like word counts, number of special characters, number of numerics etc.
The most important question is do these new features co-relate well to price — for this we can plot a correlation heatmap.
#ref = https://datatofish.com/correlation-matrix-pandas/# df_corr contains all the newly generated featurescorrMatrix = df_corr.corr()plt.figure(figsize = (18,9))sns.heatmap(corrMatrix, annot=True)plt.show()
As we can see from the heatmap above, 3 features have a strong co-relation to price output with corelation > 0.5 . The mean, min expected, max expected price features generated seem to be most significant. We shall keep only these 3 new features.
There are many kernels on different approaches, some of them include —
CNN with GloVE for word embeddings — kernel link. This uses CNN model over word embeddings on item name, item description concatenated along with the categorical features to pass it through a Dense MLP. Model gives an RMSLE score of 0.41 (35th place)Sparse MLP — kernel link. This uses a sparse MLP to generate output over Tfidf Vectorizations of text and One Hot Encoding of categorical features. Model gives an RMSLE of 0.38 (1st place)Ridge Model — kernel link. Uses a simple Ridge Regression over Tfidf Text features to generate predictions. Model gives an RMSLE of 0.47LGBM Model — kernel link . Uses LightGBM Regressor to give output score of 0.44.
CNN with GloVE for word embeddings — kernel link. This uses CNN model over word embeddings on item name, item description concatenated along with the categorical features to pass it through a Dense MLP. Model gives an RMSLE score of 0.41 (35th place)
Sparse MLP — kernel link. This uses a sparse MLP to generate output over Tfidf Vectorizations of text and One Hot Encoding of categorical features. Model gives an RMSLE of 0.38 (1st place)
Ridge Model — kernel link. Uses a simple Ridge Regression over Tfidf Text features to generate predictions. Model gives an RMSLE of 0.47
LGBM Model — kernel link . Uses LightGBM Regressor to give output score of 0.44.
We can use the original training data to split into train/test with test data size of 25%.
from sklearn.model_selection import train_test_splitdf_train = pd.read_csv('train.tsv',sep = '\t')df_train_model,df_test_model = train_test_split(df_train,test_size = 0.25)
The input features consisted of categorical and text features, along with the 3 newly generated numeric features. Categorical encodings involved One Hot Encoders, LabelBinarizers. Text encodings involved Tfidf and Count (BOW) Vectorizers. Numeric encodings involved normalization using StandardScaler.
The output variable — price involved a log transform as discussed in EDA section.
import numpy as npy_train = np.log1p(df_train['price'])
We can start by building a simple linear model with L2 Regularizer which is basically called Ridge Regression. This Model gave a RMSLE of 0.474 on test data. Note that solver = ‘lsqr’ is used for faster training — takes less than a minute to train this model.
%%timefrom sklearn.linear_model import Ridgeridge_model = Ridge(solver = "lsqr", fit_intercept=False)ridge_model.fit(X_train, y_train)preds = np.expm1(ridge_model.predict(X_test))
We can try using GridSearchCV on this model to see if we can improve the score.
from sklearn.model_selection import GridSearchCVparameters = {'alpha':[0.0001,0.001,0.01,0.1,1,10,100,1000,10000], 'fit_intercept' : [False], 'solver' : ['lsqr']}gs_ridge = GridSearchCV(estimator = Ridge(), param_grid = parameters, cv = 3, scoring = 'neg_mean_squared_error', verbose = 100, return_train_score = True, n_jobs = -2)gs_ridge.fit(X_train, y_train)
As we can see below, alpha=10 gives lowest cross validation score when using a 3 fold cross validation. But when using this model. the RMSLE reduced only from 0.474 to 0.472 which is not very significant improvement. Note below in graph, Log Scale of 10 is used since all hyperparameter alpha values were in powers of 10 in conducitng the Grid Search.
lgbm_params_1 = {'n_estimators': 900, 'learning_rate': 0.15, 'max_depth': 5, 'num_leaves': 31, 'subsample': 0.9, 'colsample_bytree': 0.8, 'min_child_samples': 50, 'n_jobs': -2}
We can improve the Model by Tuning the hyperparameters to slightly overfit by increasing the estimators, reducing learning rate, not limiting max depth, Increasing Num Leaves etc. By tuning these, model improved from 0.50 to 0.47 which is indeed a significant improvement especially in Kaggle competitions and also that scoring is in log scale (RMSLE). Although this model is slightly overfit, we can reduce the model variance by building an ensemble towards the end as we shall see. Main issue with LightGBM is training time — took nearly 2–3 hrs to run on my desktop with 16 GB RAM.
lgbm_params_2 = {'n_estimators': 1500, 'learning_rate': 0.05, 'max_depth': -1, 'num_leaves': 50, 'subsample': 0.8, 'colsample_bytree': 0.8, 'min_child_samples': 50, 'n_jobs': -1}
This was the first hunch where we can assume safely that the model would work well since most of our data is present in the form of text in item names and item descriptions. Also, all the numeric newly generated 17 features have been passed as input to the numeric features. My hypotheses was that the neural network would learn by itself if these features were relevant or not — so shouldn’t harm the model.
Attached below is the 1st LSTM model — As you can see below, the text and categorical features are first passed through embedding layers and then flattened to concatenate into a Dense NN architecutre.
from tensorflow.keras.utils import plot_modelfrom IPython.display import Imageplot_model(baseline_lstm_model, to_file='baseline_lstm_model.png', show_shapes=True, show_layer_names=True)Image(filename='baseline_lstm_model.png')
This model above gave a RMSLE of 0.48 after 60 epochs and val loss failed to improve significantly when used with adam optimizer. Attached below is the code to generate the above LSTM model 1.
We can select the sentence length by plotting the distribution of sentence lengths.
As we can see from the code, only 0.59% of rows in the item description column have sentence length more than 125. Which means nearly all sentence lengths fall in this category and we can use this for sentence length selection.
>>>select_padding(train_desc,tokenizer_desc,"Item Descriptions",125)Output :Total number of words in the document are 1384190.5927708414700212 % of rows have sentence length > 125
In this model, We have concatenated the texts from name, description, brand, category and created a text feature. I also selected the 3 numeric features which were highly co-related with price as numeric inputs. This model gave an RMSLE of 0.47
The winner’s solution Model used a simple MLP model with sparse input representation of features with only 4 layers . This model gave good results as it was able to learn feature interactions in a better way as compared to LSTM/LGBM models. I added a few layers in my experiment on top of this along with dropouts and BatchNormalization to avoid overfitting. After building 2 such models, We can combine them using some form of ensembling.
As you can see above, the model is as simple as it can be. The 3 MLP models gave RMSLE scores of 0.415, 0.411 respectively.
After building many such models, We can combine them in a way to give better performance. We can use cross validation methods to get the best ensemble model combination. For my final model, However I decided to use only the Ridge Models and MLP models because they were faster to train (< 15 mins), whereas LSTM and LGBM models individually took >3 hrs to train.
What we are doing here in the above method is taking the predictions of the 2 models that we want to ensemble and assign weights to each of them in a way that gives best RMSLE — we can find this using cross validation. When we do this for an ensemble of (2 Ridge Models + 2 MLP Models) -> gives an RMSLE of 0.408 which is significantly lower than all individual models.
preds_final=ensemble_generator(preds_final_ridges,preds_final_mlps)
Roughly 0.1 weightage to Ridge Models and remaining 0.9 weightage to MLP models gives the best Score.
preds_f = 0.1*preds_ridge + 0.9*preds_mlps
Below is the summary of all the models trained and the RMSLE scores obtained. As we can see, the ensemble model is the winner.
Making the final submission on the unseen test dataset in Kaggle gave an RMSLE score of 0.39 which would be in top 1% leaderboard.
As you can see from the graph below, ~55% of points have errors < 5 and ~76% of points have errors < 10. This is one of the way we can visualize the distribution of errors. Here error = (actual — predicted).
Another plot that we can do is plot the Log(Absolute Error) because we have done the price modelling in the log Scale. In the plot below, x-axis is the Log(Abs Error), left y-axis represents the number of points (blue histgoram) against that error. The orange line gives the cumulative points in the right y-axis. We can see that, ~ 99% points have Log(Abs Error) < 4.
We could experiment more on this to further improve predictions —
Using hyperas library to fine tune the neural network architectures to further improve performance
Using other Vectorizations like DictVectorizer() on the text data to generate text features
Use Convolution layers on word embeddings on text data
You can find my complete code here on github link. You can connect me on my linkedin profile link if you want to discuss. You can also connect me on [email protected].
|
[
{
"code": null,
"e": 514,
"s": 171,
"text": "Business problemUse of Machine learning / Deep learning to solve the business problemEvaluation metric (RMSLE)Exploratory data analysisFeature engineering (Generating 19 new features)Existing solutionsMy Experiments with models for improvementsSummary, results and conclusionsFuture workLink to my profile — Github code and LinkedinReferences"
},
{
"code": null,
"e": 531,
"s": 514,
"text": "Business problem"
},
{
"code": null,
"e": 601,
"s": 531,
"text": "Use of Machine learning / Deep learning to solve the business problem"
},
{
"code": null,
"e": 627,
"s": 601,
"text": "Evaluation metric (RMSLE)"
},
{
"code": null,
"e": 653,
"s": 627,
"text": "Exploratory data analysis"
},
{
"code": null,
"e": 702,
"s": 653,
"text": "Feature engineering (Generating 19 new features)"
},
{
"code": null,
"e": 721,
"s": 702,
"text": "Existing solutions"
},
{
"code": null,
"e": 765,
"s": 721,
"text": "My Experiments with models for improvements"
},
{
"code": null,
"e": 798,
"s": 765,
"text": "Summary, results and conclusions"
},
{
"code": null,
"e": 810,
"s": 798,
"text": "Future work"
},
{
"code": null,
"e": 856,
"s": 810,
"text": "Link to my profile — Github code and Linkedin"
},
{
"code": null,
"e": 867,
"s": 856,
"text": "References"
},
{
"code": null,
"e": 1072,
"s": 867,
"text": "This case study is based on a Kaggle competition conducted in 2018 by Mercari which is an online shopping app. Link to the kaggle Competition — https://www.kaggle.com/c/mercari-price-suggestion-challenge."
},
{
"code": null,
"e": 1153,
"s": 1072,
"text": "You can find my entire code in my github profile (link at the end of this blog)."
},
{
"code": null,
"e": 1495,
"s": 1153,
"text": "Mercari is an online selling app (quite similar to Quikr in India). Sellers upload used/refurbished products on the store that they want to sell. When they upload the product on the Mercari App, they want to know how much price they should be selling at. This helps the sellers in pricing/valuating their products before actually selling it."
},
{
"code": null,
"e": 1784,
"s": 1495,
"text": "Sellers upload product information like Item name (text format), Item description (text format), Item brand, Item category, Item condition, shipping status. When they upload these product information on the Mercari app, they in return get back the recommended price that would be sold at."
},
{
"code": null,
"e": 1888,
"s": 1784,
"text": "The goal in this case study is to predict this price of a product listing given the product attributes."
},
{
"code": null,
"e": 2163,
"s": 1888,
"text": "This problem can be best solved using Machine learning techniques, which is basically a regression modelling task which basically looks at historical product information/attributes which were similar and also the price in which that was sold and suggests prices accordingly."
},
{
"code": null,
"e": 2297,
"s": 2163,
"text": "Let us look at one row of the training data and understand its fields. (The entire training data contains ~1.4 million item listings)"
},
{
"code": null,
"e": 2345,
"s": 2297,
"text": "The dataset comprises of the following fields —"
},
{
"code": null,
"e": 3552,
"s": 2345,
"text": "name — This is the item name/product Name of the product that is being listed by the seller. (Text format)item condition id — Contains values one of (1,2,3,4,5). Basically its a number that represents the condition of the Item from a scale of 1–5.Category — Contains the product category taxonomy of the item as a 3-level hierarchy (seperated by ‘/’ delimiter). In the above example, It is electronics as Level 1 , computers & tablets as Level 2, components & parts as Level 3.Brand — The brand of the item being listed. 60% of rows are empty.Shipping — Contains Boolean — 1,0. ‘1’ indicates that the shipping fee is paid by the seller, ‘0’ indicates not paid by the seller.item description — This contains the detailed text description of the item. This contains as much information as possible about the condition, features and all other information relevant to the product. Naturally, we could imagine that this information would be quite relevant to us because price would depend on features, working condition of certain features etc. This would be an interesting Deep NLP task to solve.Price (to be predicted) — This is the price to be predicted in our case. contains float values between 0 and 2009."
},
{
"code": null,
"e": 3659,
"s": 3552,
"text": "name — This is the item name/product Name of the product that is being listed by the seller. (Text format)"
},
{
"code": null,
"e": 3801,
"s": 3659,
"text": "item condition id — Contains values one of (1,2,3,4,5). Basically its a number that represents the condition of the Item from a scale of 1–5."
},
{
"code": null,
"e": 4032,
"s": 3801,
"text": "Category — Contains the product category taxonomy of the item as a 3-level hierarchy (seperated by ‘/’ delimiter). In the above example, It is electronics as Level 1 , computers & tablets as Level 2, components & parts as Level 3."
},
{
"code": null,
"e": 4099,
"s": 4032,
"text": "Brand — The brand of the item being listed. 60% of rows are empty."
},
{
"code": null,
"e": 4231,
"s": 4099,
"text": "Shipping — Contains Boolean — 1,0. ‘1’ indicates that the shipping fee is paid by the seller, ‘0’ indicates not paid by the seller."
},
{
"code": null,
"e": 4650,
"s": 4231,
"text": "item description — This contains the detailed text description of the item. This contains as much information as possible about the condition, features and all other information relevant to the product. Naturally, we could imagine that this information would be quite relevant to us because price would depend on features, working condition of certain features etc. This would be an interesting Deep NLP task to solve."
},
{
"code": null,
"e": 4765,
"s": 4650,
"text": "Price (to be predicted) — This is the price to be predicted in our case. contains float values between 0 and 2009."
},
{
"code": null,
"e": 4804,
"s": 4765,
"text": "(Note — This is not RMSE. It is RMSLE)"
},
{
"code": null,
"e": 5206,
"s": 4804,
"text": "The evaluation metric that the competition used was basically a score. RMSLE stands for Root Mean Squared Logarithm Error. Here is a great blog post that I found which explains the differences between RMSE and RMSLE and in what cases RMSLE is more relevant in using as an evalation metric for regression tasks — https://medium.com/analytics-vidhya/root-mean-square-log-error-rmse-vs-rmlse-935c6cc1802a"
},
{
"code": null,
"e": 5299,
"s": 5206,
"text": "Summarizing a couple of points from the blogpost about why RMSLE is used as a metric here :-"
},
{
"code": null,
"e": 6569,
"s": 5299,
"text": "RMSLE penalizes more when you are under-estimating rather than over-estimating — In other words, RMSLE is used in this project ,it is saying that it’s okay if you give a higher price suggestion for certain Items but if you under predict than the actual, it is not acceptable . RMSLE will increase significantly if we under predict as compared to if we over predict by the same amount.I think this makes business sense for this case study, because we would probably be okay to give a higher price estimate for certain listings than actual, but if we underestimate an item’s price, its not okay because the buyer would probably not want to sell in that case.RMSLE can cushion out the effect of Outliers in the Data — Certain items in the dataset which would have a very high price value can actually skew the model if you evaluate on RMSE because of the squared error penalty in RMSE , whereas the RMSLE would only incur a slightly higher penalty for high value cars compared to low value cars because RMSLE has a logarithm term in the metric that cushions this effect.RMSLE considers only relative error and not the absolute error (because of the logarithm term), so a prediction of 9 against 10 and a prediction of 900 against 1000 are both having same relative errors."
},
{
"code": null,
"e": 7226,
"s": 6569,
"text": "RMSLE penalizes more when you are under-estimating rather than over-estimating — In other words, RMSLE is used in this project ,it is saying that it’s okay if you give a higher price suggestion for certain Items but if you under predict than the actual, it is not acceptable . RMSLE will increase significantly if we under predict as compared to if we over predict by the same amount.I think this makes business sense for this case study, because we would probably be okay to give a higher price estimate for certain listings than actual, but if we underestimate an item’s price, its not okay because the buyer would probably not want to sell in that case."
},
{
"code": null,
"e": 7638,
"s": 7226,
"text": "RMSLE can cushion out the effect of Outliers in the Data — Certain items in the dataset which would have a very high price value can actually skew the model if you evaluate on RMSE because of the squared error penalty in RMSE , whereas the RMSLE would only incur a slightly higher penalty for high value cars compared to low value cars because RMSLE has a logarithm term in the metric that cushions this effect."
},
{
"code": null,
"e": 7841,
"s": 7638,
"text": "RMSLE considers only relative error and not the absolute error (because of the logarithm term), so a prediction of 9 against 10 and a prediction of 900 against 1000 are both having same relative errors."
},
{
"code": null,
"e": 8048,
"s": 7841,
"text": "It is always recommended that we first understand the data very well before starting on predictive modelling. This is an extremely crucial task. Let us run through the data and gain some info and insights :"
},
{
"code": null,
"e": 8496,
"s": 8048,
"text": "The prices follow a Log Normal Distribution here. From one of the existing Kaggle kernels, I found out that Mercari allows price listings between 3 and 2000 only. So we will filter for these item listings. If you see the graphs below, even the 99.9 percentile value is around 400. The inflection point occurs beyond that. We can build price slabs (according to 5 percentile slabs) to better analyze the distribution of prices of the item listings."
},
{
"code": null,
"e": 9139,
"s": 8496,
"text": "The shipping status is a binary — (1,0). 1 represents shipping fee is paid by seller. 0 represents if shipping fee is not paid by seller. We can check the violin plot plotted below. We can see that ‘0’ has a slightly higher price than ‘1’ (although I expected to be other way around because my assumption was that if the seller is already paying for shipping the item, then the price is expected to be slightly higher). But is the difference statistically significant ?— we can conduct a one way ANOVA test to do this at 5% significance — and this told that the difference in prices in the shipping status is indeed statistically significant."
},
{
"code": null,
"e": 9317,
"s": 9139,
"text": "Similar analysis for item condition has been done below. The differences in prices here are statistically significant too. No missing values have been found in these 2 features."
},
{
"code": null,
"e": 9571,
"s": 9317,
"text": "Categories feature here appear in ‘/’ seperated values . Most categories have 3 level seperators. (See image below). So the nomenclature here is cat1/cat2/cat3 where cat1 is the high level category followed by cat2 & cat3 which are sub level categories."
},
{
"code": null,
"e": 9723,
"s": 9571,
"text": "import seaborn as snssns.set(rc={'figure.figsize':(8,6)}, style = 'whitegrid')sns.barplot(x = \"count\", y=\"cat1\", data=df_cat1_counts,palette=\"Blues_d\")"
},
{
"code": null,
"e": 9875,
"s": 9723,
"text": "Let us look at what types of words occur in this column using a wordcloud. Also, lets analyze price distributions across categories using violin plots."
},
{
"code": null,
"e": 10030,
"s": 9875,
"text": "sns.set(rc={'figure.figsize':(19,7)})sns.violinplot(x=\"cat1\", y=\"log_price\", data = df_train)plt.title('Violin Plots - Price variation in cat1')plt.show()"
},
{
"code": null,
"e": 10293,
"s": 10030,
"text": "import matplotlib.pyplot as pltfrom wordcloud import WordCloudwordcloud = WordCloud(collocations=False).generate(text_cat)plt.figure(figsize = (12,6))plt.imshow(wordcloud, interpolation='bilinear')plt.axis(\"off\")plt.title('WordCloud for Category Name')plt.show()"
},
{
"code": null,
"e": 10546,
"s": 10293,
"text": "This feature contains ~4800 brands (with 60% of rows are missing). Top brands (by count)are listed below in dataframe. We can see that top 1000 brands (~ 25% top brands) account for about 97% of the product listings. (close to a power law distribution)"
},
{
"code": null,
"e": 10815,
"s": 10546,
"text": "Different brands have different price distributions (as expected ). Brand should occur for one of the most relevant features since prices of products are a very heavy function of the brand of the Item. Follows a long tail skewed distribution as we can see below graph."
},
{
"code": null,
"e": 10899,
"s": 10815,
"text": "Let us understand by plotting their wordclouds. (But after some text preprocessing)"
},
{
"code": null,
"e": 11971,
"s": 10899,
"text": "# reference - Applied AI Course (Code for Text Preprocessing)import refrom tqdm import tqdm_notebookdef decontracted(phrase): phrase = re.sub(r\"won't\", \"will not\", phrase) phrase = re.sub(r\"can\\'t\", \"can not\", phrase) phrase = re.sub(r\"n\\'t\", \" not\", phrase) phrase = re.sub(r\"\\'re\", \" are\", phrase) phrase = re.sub(r\"\\'s\", \" is\", phrase) phrase = re.sub(r\"\\'d\", \" would\", phrase) phrase = re.sub(r\"\\'ll\", \" will\", phrase) phrase = re.sub(r\"\\'t\", \" not\", phrase) phrase = re.sub(r\"\\'ve\", \" have\", phrase) phrase = re.sub(r\"\\'m\", \" am\", phrase) return phrasedef text_preprocess(data): preprocessed = [] for sentance in tqdm_notebook(data): sent = decontracted(sentance) sent = sent.replace('\\\\r', ' ') sent = sent.replace('\\\\\"', ' ') sent = sent.replace('\\\\n', ' ') sent = re.sub('[^A-Za-z0-9]+', ' ', sent) # https://gist.github.com/sebleier/554280 sent = ' '.join(e for e in sent.split() if e not in stopwords) preprocessed.append(sent.lower().strip()) return preprocessed"
},
{
"code": null,
"e": 12057,
"s": 11971,
"text": "Above plot looks good — it gives an information about most frequently occuring words."
},
{
"code": null,
"e": 12352,
"s": 12057,
"text": "Let us also do some Topic Modelling using Latent Dirichlet Allocation. Without getting into details, What this does is basically a unsupervised algorithm that finds topics that the sentences are talking about in the entire text corpus. This analysis was inspired from this Kaggle kernel — link."
},
{
"code": null,
"e": 12570,
"s": 12352,
"text": "Let us look at some of the topics generated (by grouping similar words/sentences into topics- which the LDA algorithm does). LDA does a pretty decent job here in our case when applied to the item descriptions feature."
},
{
"code": null,
"e": 13068,
"s": 12570,
"text": "Topic 0 is most likely referring to Jewellery— (necklace,bracelet,chain,gold). Similarly topic 3 is referring to Apparel— (shirt, nike, men,women). Topic 7 is referring to Accessories— (leather,bag,wallet) etc. So we get a good sense of what the item descriptions column is talking about and a summary of the various topics present in it. This feature would be a very important predictor of price as it contains information related to item condition, newness, detailed features of the product etc."
},
{
"code": null,
"e": 13194,
"s": 13068,
"text": "My first hunch intuition is that this would be a Deep NLP task and needs to be solved using some form of LSTM Neural Network."
},
{
"code": null,
"e": 13324,
"s": 13194,
"text": "This was one of the most important parts in the ML system. Inspired by this Kaggle kernel link. Some new features were generated."
},
{
"code": null,
"e": 13565,
"s": 13324,
"text": "The hypotheses here was that the better sentiment an item is conveyed with in item description, the higher the buyers are willing to pay for the Item. I expected a positive co-relation between sentiment scores of item description and price."
},
{
"code": null,
"e": 13895,
"s": 13565,
"text": "from nltk.sentiment.vader import SentimentIntensityAnalyzerdef generate_sentiment_scores(data): sid = SentimentIntensityAnalyzer() scores = [] for sentence in tqdm_notebook(data): sentence_sentiment_score = sid.polarity_scores(sentence) scores.append(sentence_sentiment_score['compound']) return scores"
},
{
"code": null,
"e": 14409,
"s": 13895,
"text": "I borrowed this code snippet from this Kaggle kernel — link . This basically gets the price statistics by grouping the (Category, Brand, Shipping) features together and generating price statistics — Mean, Median, Std. Deviation, Coefficient of variation, Expected price ranges based on 2 Std. deviations from mean etc. This makes sense because we are basically looking at historical prices of a group of items and feeding them in the feature set to assume that they might be well co-related to the current Prices."
},
{
"code": null,
"e": 14648,
"s": 14409,
"text": "I’m again borrowing this code snippet from the same Kaggle kernel link again as posted above. The code basically creates new features from the item description column like word counts, number of special characters, number of numerics etc."
},
{
"code": null,
"e": 14771,
"s": 14648,
"text": "The most important question is do these new features co-relate well to price — for this we can plot a correlation heatmap."
},
{
"code": null,
"e": 14980,
"s": 14771,
"text": "#ref = https://datatofish.com/correlation-matrix-pandas/# df_corr contains all the newly generated featurescorrMatrix = df_corr.corr()plt.figure(figsize = (18,9))sns.heatmap(corrMatrix, annot=True)plt.show()"
},
{
"code": null,
"e": 15227,
"s": 14980,
"text": "As we can see from the heatmap above, 3 features have a strong co-relation to price output with corelation > 0.5 . The mean, min expected, max expected price features generated seem to be most significant. We shall keep only these 3 new features."
},
{
"code": null,
"e": 15298,
"s": 15227,
"text": "There are many kernels on different approaches, some of them include —"
},
{
"code": null,
"e": 15953,
"s": 15298,
"text": "CNN with GloVE for word embeddings — kernel link. This uses CNN model over word embeddings on item name, item description concatenated along with the categorical features to pass it through a Dense MLP. Model gives an RMSLE score of 0.41 (35th place)Sparse MLP — kernel link. This uses a sparse MLP to generate output over Tfidf Vectorizations of text and One Hot Encoding of categorical features. Model gives an RMSLE of 0.38 (1st place)Ridge Model — kernel link. Uses a simple Ridge Regression over Tfidf Text features to generate predictions. Model gives an RMSLE of 0.47LGBM Model — kernel link . Uses LightGBM Regressor to give output score of 0.44."
},
{
"code": null,
"e": 16204,
"s": 15953,
"text": "CNN with GloVE for word embeddings — kernel link. This uses CNN model over word embeddings on item name, item description concatenated along with the categorical features to pass it through a Dense MLP. Model gives an RMSLE score of 0.41 (35th place)"
},
{
"code": null,
"e": 16393,
"s": 16204,
"text": "Sparse MLP — kernel link. This uses a sparse MLP to generate output over Tfidf Vectorizations of text and One Hot Encoding of categorical features. Model gives an RMSLE of 0.38 (1st place)"
},
{
"code": null,
"e": 16530,
"s": 16393,
"text": "Ridge Model — kernel link. Uses a simple Ridge Regression over Tfidf Text features to generate predictions. Model gives an RMSLE of 0.47"
},
{
"code": null,
"e": 16611,
"s": 16530,
"text": "LGBM Model — kernel link . Uses LightGBM Regressor to give output score of 0.44."
},
{
"code": null,
"e": 16702,
"s": 16611,
"text": "We can use the original training data to split into train/test with test data size of 25%."
},
{
"code": null,
"e": 16875,
"s": 16702,
"text": "from sklearn.model_selection import train_test_splitdf_train = pd.read_csv('train.tsv',sep = '\\t')df_train_model,df_test_model = train_test_split(df_train,test_size = 0.25)"
},
{
"code": null,
"e": 17177,
"s": 16875,
"text": "The input features consisted of categorical and text features, along with the 3 newly generated numeric features. Categorical encodings involved One Hot Encoders, LabelBinarizers. Text encodings involved Tfidf and Count (BOW) Vectorizers. Numeric encodings involved normalization using StandardScaler."
},
{
"code": null,
"e": 17259,
"s": 17177,
"text": "The output variable — price involved a log transform as discussed in EDA section."
},
{
"code": null,
"e": 17316,
"s": 17259,
"text": "import numpy as npy_train = np.log1p(df_train['price'])"
},
{
"code": null,
"e": 17576,
"s": 17316,
"text": "We can start by building a simple linear model with L2 Regularizer which is basically called Ridge Regression. This Model gave a RMSLE of 0.474 on test data. Note that solver = ‘lsqr’ is used for faster training — takes less than a minute to train this model."
},
{
"code": null,
"e": 17756,
"s": 17576,
"text": "%%timefrom sklearn.linear_model import Ridgeridge_model = Ridge(solver = \"lsqr\", fit_intercept=False)ridge_model.fit(X_train, y_train)preds = np.expm1(ridge_model.predict(X_test))"
},
{
"code": null,
"e": 17836,
"s": 17756,
"text": "We can try using GridSearchCV on this model to see if we can improve the score."
},
{
"code": null,
"e": 18362,
"s": 17836,
"text": "from sklearn.model_selection import GridSearchCVparameters = {'alpha':[0.0001,0.001,0.01,0.1,1,10,100,1000,10000], 'fit_intercept' : [False], 'solver' : ['lsqr']}gs_ridge = GridSearchCV(estimator = Ridge(), param_grid = parameters, cv = 3, scoring = 'neg_mean_squared_error', verbose = 100, return_train_score = True, n_jobs = -2)gs_ridge.fit(X_train, y_train)"
},
{
"code": null,
"e": 18714,
"s": 18362,
"text": "As we can see below, alpha=10 gives lowest cross validation score when using a 3 fold cross validation. But when using this model. the RMSLE reduced only from 0.474 to 0.472 which is not very significant improvement. Note below in graph, Log Scale of 10 is used since all hyperparameter alpha values were in powers of 10 in conducitng the Grid Search."
},
{
"code": null,
"e": 19005,
"s": 18714,
"text": "lgbm_params_1 = {'n_estimators': 900, 'learning_rate': 0.15, 'max_depth': 5, 'num_leaves': 31, 'subsample': 0.9, 'colsample_bytree': 0.8, 'min_child_samples': 50, 'n_jobs': -2}"
},
{
"code": null,
"e": 19590,
"s": 19005,
"text": "We can improve the Model by Tuning the hyperparameters to slightly overfit by increasing the estimators, reducing learning rate, not limiting max depth, Increasing Num Leaves etc. By tuning these, model improved from 0.50 to 0.47 which is indeed a significant improvement especially in Kaggle competitions and also that scoring is in log scale (RMSLE). Although this model is slightly overfit, we can reduce the model variance by building an ensemble towards the end as we shall see. Main issue with LightGBM is training time — took nearly 2–3 hrs to run on my desktop with 16 GB RAM."
},
{
"code": null,
"e": 19881,
"s": 19590,
"text": "lgbm_params_2 = {'n_estimators': 1500, 'learning_rate': 0.05, 'max_depth': -1, 'num_leaves': 50, 'subsample': 0.8, 'colsample_bytree': 0.8, 'min_child_samples': 50, 'n_jobs': -1}"
},
{
"code": null,
"e": 20290,
"s": 19881,
"text": "This was the first hunch where we can assume safely that the model would work well since most of our data is present in the form of text in item names and item descriptions. Also, all the numeric newly generated 17 features have been passed as input to the numeric features. My hypotheses was that the neural network would learn by itself if these features were relevant or not — so shouldn’t harm the model."
},
{
"code": null,
"e": 20491,
"s": 20290,
"text": "Attached below is the 1st LSTM model — As you can see below, the text and categorical features are first passed through embedding layers and then flattened to concatenate into a Dense NN architecutre."
},
{
"code": null,
"e": 20718,
"s": 20491,
"text": "from tensorflow.keras.utils import plot_modelfrom IPython.display import Imageplot_model(baseline_lstm_model, to_file='baseline_lstm_model.png', show_shapes=True, show_layer_names=True)Image(filename='baseline_lstm_model.png')"
},
{
"code": null,
"e": 20911,
"s": 20718,
"text": "This model above gave a RMSLE of 0.48 after 60 epochs and val loss failed to improve significantly when used with adam optimizer. Attached below is the code to generate the above LSTM model 1."
},
{
"code": null,
"e": 20995,
"s": 20911,
"text": "We can select the sentence length by plotting the distribution of sentence lengths."
},
{
"code": null,
"e": 21223,
"s": 20995,
"text": "As we can see from the code, only 0.59% of rows in the item description column have sentence length more than 125. Which means nearly all sentence lengths fall in this category and we can use this for sentence length selection."
},
{
"code": null,
"e": 21406,
"s": 21223,
"text": ">>>select_padding(train_desc,tokenizer_desc,\"Item Descriptions\",125)Output :Total number of words in the document are 1384190.5927708414700212 % of rows have sentence length > 125"
},
{
"code": null,
"e": 21651,
"s": 21406,
"text": "In this model, We have concatenated the texts from name, description, brand, category and created a text feature. I also selected the 3 numeric features which were highly co-related with price as numeric inputs. This model gave an RMSLE of 0.47"
},
{
"code": null,
"e": 22091,
"s": 21651,
"text": "The winner’s solution Model used a simple MLP model with sparse input representation of features with only 4 layers . This model gave good results as it was able to learn feature interactions in a better way as compared to LSTM/LGBM models. I added a few layers in my experiment on top of this along with dropouts and BatchNormalization to avoid overfitting. After building 2 such models, We can combine them using some form of ensembling."
},
{
"code": null,
"e": 22215,
"s": 22091,
"text": "As you can see above, the model is as simple as it can be. The 3 MLP models gave RMSLE scores of 0.415, 0.411 respectively."
},
{
"code": null,
"e": 22578,
"s": 22215,
"text": "After building many such models, We can combine them in a way to give better performance. We can use cross validation methods to get the best ensemble model combination. For my final model, However I decided to use only the Ridge Models and MLP models because they were faster to train (< 15 mins), whereas LSTM and LGBM models individually took >3 hrs to train."
},
{
"code": null,
"e": 22948,
"s": 22578,
"text": "What we are doing here in the above method is taking the predictions of the 2 models that we want to ensemble and assign weights to each of them in a way that gives best RMSLE — we can find this using cross validation. When we do this for an ensemble of (2 Ridge Models + 2 MLP Models) -> gives an RMSLE of 0.408 which is significantly lower than all individual models."
},
{
"code": null,
"e": 23016,
"s": 22948,
"text": "preds_final=ensemble_generator(preds_final_ridges,preds_final_mlps)"
},
{
"code": null,
"e": 23118,
"s": 23016,
"text": "Roughly 0.1 weightage to Ridge Models and remaining 0.9 weightage to MLP models gives the best Score."
},
{
"code": null,
"e": 23161,
"s": 23118,
"text": "preds_f = 0.1*preds_ridge + 0.9*preds_mlps"
},
{
"code": null,
"e": 23288,
"s": 23161,
"text": "Below is the summary of all the models trained and the RMSLE scores obtained. As we can see, the ensemble model is the winner."
},
{
"code": null,
"e": 23419,
"s": 23288,
"text": "Making the final submission on the unseen test dataset in Kaggle gave an RMSLE score of 0.39 which would be in top 1% leaderboard."
},
{
"code": null,
"e": 23627,
"s": 23419,
"text": "As you can see from the graph below, ~55% of points have errors < 5 and ~76% of points have errors < 10. This is one of the way we can visualize the distribution of errors. Here error = (actual — predicted)."
},
{
"code": null,
"e": 23996,
"s": 23627,
"text": "Another plot that we can do is plot the Log(Absolute Error) because we have done the price modelling in the log Scale. In the plot below, x-axis is the Log(Abs Error), left y-axis represents the number of points (blue histgoram) against that error. The orange line gives the cumulative points in the right y-axis. We can see that, ~ 99% points have Log(Abs Error) < 4."
},
{
"code": null,
"e": 24062,
"s": 23996,
"text": "We could experiment more on this to further improve predictions —"
},
{
"code": null,
"e": 24161,
"s": 24062,
"text": "Using hyperas library to fine tune the neural network architectures to further improve performance"
},
{
"code": null,
"e": 24253,
"s": 24161,
"text": "Using other Vectorizations like DictVectorizer() on the text data to generate text features"
},
{
"code": null,
"e": 24308,
"s": 24253,
"text": "Use Convolution layers on word embeddings on text data"
}
] |
How To Install and Configure Webmin on Ubuntu 16.04
|
In this article, we will learn – How we can install Webmin on Ubuntu 16.04. Webmin is a web-based control panel with dashboards for any Linux server machines, which allows you to control your server with a simple interface, where we can change the settings of common application packages with simple clicks. Webmin can also be used to add new users accounts and update the packages on the server from the Webmin dashboard itself.
Ubuntu 16.04 machine with a non-root user with Sudo permissions.
Apache, PHP, and MySQL Installed on the Ubuntu 16.04 machine.
Assuming that we have all the pre-requisites, First, we need to add the Webmin official repository to the sources.list so that we can get the updates and install the Webmin using the package manager.
$ sudo vi /etc/apt/sources.list
Once we open the file we needed to add the following lines to the bottom of the files.
deb http://download.webmin.com/download/repository sarge contrib
...
...
...
# deb-src http://security.ubuntu.com/ubuntu xenial-security universe
deb http://security.ubuntu.com/ubuntu xenial-security multiverse
# deb-src http://security.ubuntu.com/ubuntu xenial-security multiverse
deb [arch=amd64,i386] https://cran.rstudio.com/bin/linux/ubuntu xenial/
# deb-src [arch=amd64,i386] https://cran.rstudio.com/bin/linux/ubuntu xenial/
# deb-src [arch=amd64,i386] https://cran.rstudio.com/bin/linux/ubuntu xenial/
# deb-src [arch=i386,amd64] https://cran.rstudio.com/bin/linux/ubuntu xenial/
deb http://download.webmin.com/download/repository sarge contrib
Once we add the line we needed to get the PGP key to the Ubuntu 16.04 machine so that our system get trust from the new repository.
$ wget http://www.webmin.com/jcameron-key.asc
--2017-05-10 15:33:27-- http://www.webmin.com/jcameron-key.asc
Resolving www.webmin.com (www.webmin.com)... 216.34.181.97
Connecting to www.webmin.com (www.webmin.com)|216.34.181.97|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1320 (1.3K) [text/plain]
Saving to: ‘jcameron-key.asc’
jcameron-key.asc 100%[======================>] 1.29K --.-KB/s in 0s
2017-05-10 15:33:28 (169 MB/s) - ‘jcameron-key.asc’ saved [1320/1320]
$ sudo apt-key add jcameron-key.asc
OK
We need to update the Ubuntu 16.04 machine with the below command –.
$sudo apt-get update.
Once the machine is updated below is the command to install the Webmin.
$ sudo apt-get install webmin
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and which are no longer required:
libapr1-dev libaprutil1-dev libexpat1-dev libldap2-dev libsctp-dev libsctp1
linux-headers-4.4.0-21 linux-headers-4.4.0-21-generic linux-headers-4.4.0-42
linux-headers-4.4.0-42-generic linux-image-4.4.0-21-generic
linux-image-4.4.0-42-generic linux-image-extra-4.4.0-21-generic
linux-image-extra-4.4.0-42-generic uuid-dev
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
apt-show-versions libapt-pkg-perl libauthen-pam-perl libio-pty-perl
The following NEW packages will be installed:
apt-show-versions libapt-pkg-perl libauthen-pam-perl libio-pty-perl Webmin
0 upgraded, 5 newly installed, 0 to remove and 187 not upgraded.
Need to get 15.6 MB of archives.
After this operation, 262 MB of additional disk space will be used.
Do you want to continue? [Y/n]
...
...
...
Preparing to unpack .../libapt-pkg-perl_0.1.29build7_amd64.deb ...
Unpacking libapt-pkg-perl (0.1.29build7) ...
Selecting previously unselected package apt-show-versions.
Preparing to unpack .../apt-show-versions_0.22.7_all.deb ...
Unpacking apt-show-versions (0.22.7) ...
Selecting previously unselected package Webmin.
Preparing to unpack .../archives/webmin_1.840_all.deb ...
Unpacking webmin (1.840) ...
...
...
...
Setting up libauthen-pam-perl (0.16-3build2) ...
Setting up libio-pty-perl (1:1.08-1.1build1) ...
Setting up libapt-pkg-perl (0.1.29build7) ...
Setting up apt-show-versions (0.22.7) ...
** initializing cache. This may take a while **
Setting up Webmin (1.840) ...
Webmin install completely. You can now log in to https://ubuntu-16:10000/
as root with your root password, or as any user who can use sudo
to run commands as root.
Processing triggers for systemd (229-4ubuntu10) ...
Processing triggers for ureadahead (0.100.0-19) ...
Once the installation is completed we will just open https://your-system-ip:10000.
First, we will see the login screen where we can give the root user and password of the root user, here I am using Ubuntu as username and password.
Once, we log-in using the root username and password the dashboard looks like this –.
Once we click on the Dashboard from the Webmin Main menu we can update all the packages, here we can see Packages updates, Click on the Package Updates –.
Once we click on the Packages Updates we can see all the list of packages, here default all the packages are selected we can remove or select the packages we want to update and click on Update Selected Packages.
We can manage users and groups on the server using the Webmin.
First, we will click on the System tab, and click on the Users and Groups, where we can add, manage users and groups.
Here we will create one user using the Webmin. We needed to provide the following information on the Webmin.
Username
Real Name (Means the users First name and Last name)
Home Directory.
Shell
Password
Primary Group
Secondary Group
When we creating a user we can set options like password expiry, whether we are allowing to his home directory, First name, Last name(Real Name), Password, Belongs to a Primary group or Secondary Group.
In the above article we have learned how to install the Webmin using the official repository once the installation completed we have learned how to update the packages on the machine, also we have learned how to create users and groups, now only these we can also manage Apache Webserver, MySQL database and lots more.
|
[
{
"code": null,
"e": 1492,
"s": 1062,
"text": "In this article, we will learn – How we can install Webmin on Ubuntu 16.04. Webmin is a web-based control panel with dashboards for any Linux server machines, which allows you to control your server with a simple interface, where we can change the settings of common application packages with simple clicks. Webmin can also be used to add new users accounts and update the packages on the server from the Webmin dashboard itself."
},
{
"code": null,
"e": 1557,
"s": 1492,
"text": "Ubuntu 16.04 machine with a non-root user with Sudo permissions."
},
{
"code": null,
"e": 1619,
"s": 1557,
"text": "Apache, PHP, and MySQL Installed on the Ubuntu 16.04 machine."
},
{
"code": null,
"e": 1819,
"s": 1619,
"text": "Assuming that we have all the pre-requisites, First, we need to add the Webmin official repository to the sources.list so that we can get the updates and install the Webmin using the package manager."
},
{
"code": null,
"e": 1851,
"s": 1819,
"text": "$ sudo vi /etc/apt/sources.list"
},
{
"code": null,
"e": 1938,
"s": 1851,
"text": "Once we open the file we needed to add the following lines to the bottom of the files."
},
{
"code": null,
"e": 2591,
"s": 1938,
"text": "deb http://download.webmin.com/download/repository sarge contrib\n...\n...\n...\n# deb-src http://security.ubuntu.com/ubuntu xenial-security universe\ndeb http://security.ubuntu.com/ubuntu xenial-security multiverse\n# deb-src http://security.ubuntu.com/ubuntu xenial-security multiverse\ndeb [arch=amd64,i386] https://cran.rstudio.com/bin/linux/ubuntu xenial/\n# deb-src [arch=amd64,i386] https://cran.rstudio.com/bin/linux/ubuntu xenial/\n# deb-src [arch=amd64,i386] https://cran.rstudio.com/bin/linux/ubuntu xenial/\n# deb-src [arch=i386,amd64] https://cran.rstudio.com/bin/linux/ubuntu xenial/\ndeb http://download.webmin.com/download/repository sarge contrib"
},
{
"code": null,
"e": 2723,
"s": 2591,
"text": "Once we add the line we needed to get the PGP key to the Ubuntu 16.04 machine so that our system get trust from the new repository."
},
{
"code": null,
"e": 3256,
"s": 2723,
"text": "$ wget http://www.webmin.com/jcameron-key.asc\n--2017-05-10 15:33:27-- http://www.webmin.com/jcameron-key.asc\nResolving www.webmin.com (www.webmin.com)... 216.34.181.97\nConnecting to www.webmin.com (www.webmin.com)|216.34.181.97|:80... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 1320 (1.3K) [text/plain]\nSaving to: ‘jcameron-key.asc’\njcameron-key.asc 100%[======================>] 1.29K --.-KB/s in 0s\n2017-05-10 15:33:28 (169 MB/s) - ‘jcameron-key.asc’ saved [1320/1320]\n$ sudo apt-key add jcameron-key.asc\nOK"
},
{
"code": null,
"e": 3325,
"s": 3256,
"text": "We need to update the Ubuntu 16.04 machine with the below command –."
},
{
"code": null,
"e": 3347,
"s": 3325,
"text": "$sudo apt-get update."
},
{
"code": null,
"e": 3419,
"s": 3347,
"text": "Once the machine is updated below is the command to install the Webmin."
},
{
"code": null,
"e": 5390,
"s": 3419,
"text": "$ sudo apt-get install webmin\nReading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following packages were automatically installed and which are no longer required:\nlibapr1-dev libaprutil1-dev libexpat1-dev libldap2-dev libsctp-dev libsctp1\nlinux-headers-4.4.0-21 linux-headers-4.4.0-21-generic linux-headers-4.4.0-42\nlinux-headers-4.4.0-42-generic linux-image-4.4.0-21-generic\nlinux-image-4.4.0-42-generic linux-image-extra-4.4.0-21-generic\nlinux-image-extra-4.4.0-42-generic uuid-dev\nUse 'sudo apt autoremove' to remove them.\nThe following additional packages will be installed:\napt-show-versions libapt-pkg-perl libauthen-pam-perl libio-pty-perl\nThe following NEW packages will be installed:\napt-show-versions libapt-pkg-perl libauthen-pam-perl libio-pty-perl Webmin\n0 upgraded, 5 newly installed, 0 to remove and 187 not upgraded.\nNeed to get 15.6 MB of archives.\nAfter this operation, 262 MB of additional disk space will be used.\nDo you want to continue? [Y/n]\n...\n...\n...\nPreparing to unpack .../libapt-pkg-perl_0.1.29build7_amd64.deb ...\nUnpacking libapt-pkg-perl (0.1.29build7) ...\nSelecting previously unselected package apt-show-versions.\nPreparing to unpack .../apt-show-versions_0.22.7_all.deb ...\nUnpacking apt-show-versions (0.22.7) ...\nSelecting previously unselected package Webmin.\nPreparing to unpack .../archives/webmin_1.840_all.deb ...\nUnpacking webmin (1.840) ...\n...\n...\n...\nSetting up libauthen-pam-perl (0.16-3build2) ...\nSetting up libio-pty-perl (1:1.08-1.1build1) ...\nSetting up libapt-pkg-perl (0.1.29build7) ...\nSetting up apt-show-versions (0.22.7) ...\n** initializing cache. This may take a while **\nSetting up Webmin (1.840) ...\nWebmin install completely. You can now log in to https://ubuntu-16:10000/\nas root with your root password, or as any user who can use sudo\nto run commands as root.\nProcessing triggers for systemd (229-4ubuntu10) ...\nProcessing triggers for ureadahead (0.100.0-19) ..."
},
{
"code": null,
"e": 5473,
"s": 5390,
"text": "Once the installation is completed we will just open https://your-system-ip:10000."
},
{
"code": null,
"e": 5621,
"s": 5473,
"text": "First, we will see the login screen where we can give the root user and password of the root user, here I am using Ubuntu as username and password."
},
{
"code": null,
"e": 5707,
"s": 5621,
"text": "Once, we log-in using the root username and password the dashboard looks like this –."
},
{
"code": null,
"e": 5862,
"s": 5707,
"text": "Once we click on the Dashboard from the Webmin Main menu we can update all the packages, here we can see Packages updates, Click on the Package Updates –."
},
{
"code": null,
"e": 6074,
"s": 5862,
"text": "Once we click on the Packages Updates we can see all the list of packages, here default all the packages are selected we can remove or select the packages we want to update and click on Update Selected Packages."
},
{
"code": null,
"e": 6137,
"s": 6074,
"text": "We can manage users and groups on the server using the Webmin."
},
{
"code": null,
"e": 6255,
"s": 6137,
"text": "First, we will click on the System tab, and click on the Users and Groups, where we can add, manage users and groups."
},
{
"code": null,
"e": 6364,
"s": 6255,
"text": "Here we will create one user using the Webmin. We needed to provide the following information on the Webmin."
},
{
"code": null,
"e": 6373,
"s": 6364,
"text": "Username"
},
{
"code": null,
"e": 6426,
"s": 6373,
"text": "Real Name (Means the users First name and Last name)"
},
{
"code": null,
"e": 6442,
"s": 6426,
"text": "Home Directory."
},
{
"code": null,
"e": 6448,
"s": 6442,
"text": "Shell"
},
{
"code": null,
"e": 6457,
"s": 6448,
"text": "Password"
},
{
"code": null,
"e": 6471,
"s": 6457,
"text": "Primary Group"
},
{
"code": null,
"e": 6487,
"s": 6471,
"text": "Secondary Group"
},
{
"code": null,
"e": 6690,
"s": 6487,
"text": "When we creating a user we can set options like password expiry, whether we are allowing to his home directory, First name, Last name(Real Name), Password, Belongs to a Primary group or Secondary Group."
},
{
"code": null,
"e": 7009,
"s": 6690,
"text": "In the above article we have learned how to install the Webmin using the official repository once the installation completed we have learned how to update the packages on the machine, also we have learned how to create users and groups, now only these we can also manage Apache Webserver, MySQL database and lots more."
}
] |
Instruction type INR R in 8085 Microprocessor
|
In 8085 Instruction set, INR is a mnemonic that stands for ‘INcRement’ and ‘R’ stands for any of the following registers or memory location M pointed by HL pair.
R = A, B, C, D, E, H, L, or M
This instruction is used to add 1 with the contents of R. So the previous value in R will get increased by amount 1 only. The result of increment will be stored in R updating its previous content. All flags, except Cy flag, are affected depending on the result thus produced. In different assembly language core, this instruction is used for looping or as a count. As R can have any of the eight values as mentioned, so there are eight opcodes possible for this type of instruction. It requires only 1-Byte in memory.
Let us consider INR M as a sample instruction of this category. It is a 1-Byte instruction. Let us consider that HL register pair is holding the 16-bit value 4050H as 16-bit address. And 4050H location is holding value 05H. So after execution of the instruction INR M, the current content of location 4050H will become 06H. The tracing table of this instruction is as follows
(HL)
(4050H)
Flag Register (F)
Here is the timing diagram of the execution of the instruction INR M
Summary − So this instruction INR M requires 1-Byte, 3-Machine Cycles (Opcode Fetch, Memory Read, Memory Write) and 10 T-States for execution as shown in the timing diagram.
|
[
{
"code": null,
"e": 1224,
"s": 1062,
"text": "In 8085 Instruction set, INR is a mnemonic that stands for ‘INcRement’ and ‘R’ stands for any of the following registers or memory location M pointed by HL pair."
},
{
"code": null,
"e": 1255,
"s": 1224,
"text": "R = A, B, C, D, E, H, L, or M\n"
},
{
"code": null,
"e": 1773,
"s": 1255,
"text": "This instruction is used to add 1 with the contents of R. So the previous value in R will get increased by amount 1 only. The result of increment will be stored in R updating its previous content. All flags, except Cy flag, are affected depending on the result thus produced. In different assembly language core, this instruction is used for looping or as a count. As R can have any of the eight values as mentioned, so there are eight opcodes possible for this type of instruction. It requires only 1-Byte in memory."
},
{
"code": null,
"e": 2149,
"s": 1773,
"text": "Let us consider INR M as a sample instruction of this category. It is a 1-Byte instruction. Let us consider that HL register pair is holding the 16-bit value 4050H as 16-bit address. And 4050H location is holding value 05H. So after execution of the instruction INR M, the current content of location 4050H will become 06H. The tracing table of this instruction is as follows"
},
{
"code": null,
"e": 2154,
"s": 2149,
"text": "(HL)"
},
{
"code": null,
"e": 2162,
"s": 2154,
"text": "(4050H)"
},
{
"code": null,
"e": 2180,
"s": 2162,
"text": "Flag Register (F)"
},
{
"code": null,
"e": 2249,
"s": 2180,
"text": "Here is the timing diagram of the execution of the instruction INR M"
},
{
"code": null,
"e": 2423,
"s": 2249,
"text": "Summary − So this instruction INR M requires 1-Byte, 3-Machine Cycles (Opcode Fetch, Memory Read, Memory Write) and 10 T-States for execution as shown in the timing diagram."
}
] |
CSS - Flash Effect
|
A sudden brief burst of bright light of an element.
@keyframes flash {
0%, 50%, 100% {
opacity: 1;
}
25%, 75% {
opacity: 0;
}
}
Opacity − Opacity applies to an element to make translucence.
Opacity − Opacity applies to an element to make translucence.
<html>
<head>
<style>
.animated {
background-image: url(/css/images/logo.png);
background-repeat: no-repeat;
background-position: left top;
padding-top:95px;
margin-bottom:60px;
-webkit-animation-duration: 1s;
animation-duration: 1s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
@keyframes flash {
0%, 50%, 100% {
opacity: 1;
}
25%, 75% {
opacity: 0;
}
}
.flash {
animation-name: flash;
}
</style>
</head>
<body>
<div id = "animated-example" class = "animated flash"></div>
<button onclick = "myFunction()">Reload page</button>
<script>
function myFunction() {
location.reload();
}
</script>
</body>
</html>
It will produce the following result −
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
Selected Reading
UPSC IAS Exams Notes
Developer's Best Practices
Questions and Answers
Effective Resume Writing
HR Interview Questions
Computer Glossary
Who is Who
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2678,
"s": 2626,
"text": "A sudden brief burst of bright light of an element."
},
{
"code": null,
"e": 2778,
"s": 2678,
"text": "@keyframes flash {\n 0%, 50%, 100% {\n opacity: 1;\n }\n 25%, 75% {\n opacity: 0;\n }\n}"
},
{
"code": null,
"e": 2840,
"s": 2778,
"text": "Opacity − Opacity applies to an element to make translucence."
},
{
"code": null,
"e": 2902,
"s": 2840,
"text": "Opacity − Opacity applies to an element to make translucence."
},
{
"code": null,
"e": 3898,
"s": 2902,
"text": "<html>\n <head>\n <style>\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 1s;\n animation-duration: 1s;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n \n @keyframes flash {\n 0%, 50%, 100% {\n opacity: 1;\n }\n 25%, 75% {\n opacity: 0;\n }\n }\n \n .flash {\n animation-name: flash;\n }\n </style>\n </head>\n\n <body>\n \n <div id = \"animated-example\" class = \"animated flash\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n \n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 3937,
"s": 3898,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 4584,
"s": 3937,
"text": "\n\n Academic Tutorials\n Big Data & Analytics \n Computer Programming \n Computer Science \n Databases \n DevOps \n Digital Marketing \n Engineering Tutorials \n Exams Syllabus \n Famous Monuments \n GATE Exams Tutorials\n Latest Technologies \n Machine Learning \n Mainframe Development \n Management Tutorials \n Mathematics Tutorials\n Microsoft Technologies \n Misc tutorials \n Mobile Development \n Java Technologies \n Python Technologies \n SAP Tutorials \nProgramming Scripts \n Selected Reading \n Software Quality \n Soft Skills \n Telecom Tutorials \n UPSC IAS Exams \n Web Development \n Sports Tutorials \n XML Technologies \n Multi-Language\n Interview Questions\n\n"
},
{
"code": null,
"e": 4604,
"s": 4584,
"text": " Academic Tutorials"
},
{
"code": null,
"e": 4627,
"s": 4604,
"text": " Big Data & Analytics "
},
{
"code": null,
"e": 4650,
"s": 4627,
"text": " Computer Programming "
},
{
"code": null,
"e": 4669,
"s": 4650,
"text": " Computer Science "
},
{
"code": null,
"e": 4681,
"s": 4669,
"text": " Databases "
},
{
"code": null,
"e": 4690,
"s": 4681,
"text": " DevOps "
},
{
"code": null,
"e": 4710,
"s": 4690,
"text": " Digital Marketing "
},
{
"code": null,
"e": 4734,
"s": 4710,
"text": " Engineering Tutorials "
},
{
"code": null,
"e": 4751,
"s": 4734,
"text": " Exams Syllabus "
},
{
"code": null,
"e": 4770,
"s": 4751,
"text": " Famous Monuments "
},
{
"code": null,
"e": 4792,
"s": 4770,
"text": " GATE Exams Tutorials"
},
{
"code": null,
"e": 4814,
"s": 4792,
"text": " Latest Technologies "
},
{
"code": null,
"e": 4833,
"s": 4814,
"text": " Machine Learning "
},
{
"code": null,
"e": 4857,
"s": 4833,
"text": " Mainframe Development "
},
{
"code": null,
"e": 4880,
"s": 4857,
"text": " Management Tutorials "
},
{
"code": null,
"e": 4903,
"s": 4880,
"text": " Mathematics Tutorials"
},
{
"code": null,
"e": 4928,
"s": 4903,
"text": " Microsoft Technologies "
},
{
"code": null,
"e": 4945,
"s": 4928,
"text": " Misc tutorials "
},
{
"code": null,
"e": 4966,
"s": 4945,
"text": " Mobile Development "
},
{
"code": null,
"e": 4986,
"s": 4966,
"text": " Java Technologies "
},
{
"code": null,
"e": 5008,
"s": 4986,
"text": " Python Technologies "
},
{
"code": null,
"e": 5024,
"s": 5008,
"text": " SAP Tutorials "
},
{
"code": null,
"e": 5045,
"s": 5024,
"text": "Programming Scripts "
},
{
"code": null,
"e": 5064,
"s": 5045,
"text": " Selected Reading "
},
{
"code": null,
"e": 5083,
"s": 5064,
"text": " Software Quality "
},
{
"code": null,
"e": 5097,
"s": 5083,
"text": " Soft Skills "
},
{
"code": null,
"e": 5117,
"s": 5097,
"text": " Telecom Tutorials "
},
{
"code": null,
"e": 5134,
"s": 5117,
"text": " UPSC IAS Exams "
},
{
"code": null,
"e": 5152,
"s": 5134,
"text": " Web Development "
},
{
"code": null,
"e": 5171,
"s": 5152,
"text": " Sports Tutorials "
},
{
"code": null,
"e": 5190,
"s": 5171,
"text": " XML Technologies "
},
{
"code": null,
"e": 5206,
"s": 5190,
"text": " Multi-Language"
},
{
"code": null,
"e": 5227,
"s": 5206,
"text": " Interview Questions"
},
{
"code": null,
"e": 5244,
"s": 5227,
"text": "Selected Reading"
},
{
"code": null,
"e": 5265,
"s": 5244,
"text": "UPSC IAS Exams Notes"
},
{
"code": null,
"e": 5292,
"s": 5265,
"text": "Developer's Best Practices"
},
{
"code": null,
"e": 5314,
"s": 5292,
"text": "Questions and Answers"
},
{
"code": null,
"e": 5339,
"s": 5314,
"text": "Effective Resume Writing"
},
{
"code": null,
"e": 5362,
"s": 5339,
"text": "HR Interview Questions"
},
{
"code": null,
"e": 5380,
"s": 5362,
"text": "Computer Glossary"
},
{
"code": null,
"e": 5391,
"s": 5380,
"text": "Who is Who"
},
{
"code": null,
"e": 5398,
"s": 5391,
"text": " Print"
},
{
"code": null,
"e": 5409,
"s": 5398,
"text": " Add Notes"
}
] |
Get the Names of all Collections using PyMongo - GeeksforGeeks
|
17 May, 2020
PyMongo is the module used for establishing a connection to the MongoDB using Python and perform all the operations like insertion, deletion, updating, etc. PyMongo is the recommended way to work with MongoDB and Python.
Note: For detailed information about Python and MongoDB visit MongoDB and Python.
Let’s begin with the Get Names of all Collections using PyMongo
Importing PyMongo Module: Import the PyMongo module using the command:from pymongo import MongoClientIf MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with PythonCreating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number).client = MongoClient(‘localhost’, 27017)Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database.mydatabase = client.name_of_the_databaseIn our case the name of the database is GeeksForGeeksmydatabase = client.GeeksForGeeksList the name of all the Collections in the Database: To list the name of all the collection in the database.mydatabase.collection_names()The collection_names() is deprecated in the version 3.7.0. Instead usemydatabase.list_collection_names()This method return the list of the collections in the Database.
Importing PyMongo Module: Import the PyMongo module using the command:from pymongo import MongoClientIf MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with Python
from pymongo import MongoClient
If MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with Python
Creating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number).client = MongoClient(‘localhost’, 27017)
client = MongoClient(‘localhost’, 27017)
Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database.mydatabase = client.name_of_the_databaseIn our case the name of the database is GeeksForGeeksmydatabase = client.GeeksForGeeks
mydatabase = client.name_of_the_database
In our case the name of the database is GeeksForGeeks
mydatabase = client.GeeksForGeeks
List the name of all the Collections in the Database: To list the name of all the collection in the database.mydatabase.collection_names()The collection_names() is deprecated in the version 3.7.0. Instead usemydatabase.list_collection_names()This method return the list of the collections in the Database.
mydatabase.collection_names()
The collection_names() is deprecated in the version 3.7.0. Instead use
mydatabase.list_collection_names()
This method return the list of the collections in the Database.
Example:
Sample Database:
# Python Program to demonstrate# List name of all collections using PyMongo # Importing required librariesfrom pymongo import MongoClient # Connecting to MongoDB server# client = MongoClient('host_name', 'port_number')client = MongoClient(‘localhost’, 27017) # Connecting to the database named# GeeksForGeeksmydatabase = client.GeeksForGeeks # Getting the names of all the collections# in GeeksForGeeks Database.collections = mydatabase.list_collection_names() # Printing the name of the collections to the console.print(collections)
Output:
['Geeks']
Python-mongoDB
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 ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
|
[
{
"code": null,
"e": 24237,
"s": 24209,
"text": "\n17 May, 2020"
},
{
"code": null,
"e": 24458,
"s": 24237,
"text": "PyMongo is the module used for establishing a connection to the MongoDB using Python and perform all the operations like insertion, deletion, updating, etc. PyMongo is the recommended way to work with MongoDB and Python."
},
{
"code": null,
"e": 24540,
"s": 24458,
"text": "Note: For detailed information about Python and MongoDB visit MongoDB and Python."
},
{
"code": null,
"e": 24604,
"s": 24540,
"text": "Let’s begin with the Get Names of all Collections using PyMongo"
},
{
"code": null,
"e": 25625,
"s": 24604,
"text": "Importing PyMongo Module: Import the PyMongo module using the command:from pymongo import MongoClientIf MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with PythonCreating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number).client = MongoClient(‘localhost’, 27017)Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database.mydatabase = client.name_of_the_databaseIn our case the name of the database is GeeksForGeeksmydatabase = client.GeeksForGeeksList the name of all the Collections in the Database: To list the name of all the collection in the database.mydatabase.collection_names()The collection_names() is deprecated in the version 3.7.0. Instead usemydatabase.list_collection_names()This method return the list of the collections in the Database."
},
{
"code": null,
"e": 25843,
"s": 25625,
"text": "Importing PyMongo Module: Import the PyMongo module using the command:from pymongo import MongoClientIf MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with Python"
},
{
"code": null,
"e": 25875,
"s": 25843,
"text": "from pymongo import MongoClient"
},
{
"code": null,
"e": 25992,
"s": 25875,
"text": "If MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with Python"
},
{
"code": null,
"e": 26235,
"s": 25992,
"text": "Creating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number).client = MongoClient(‘localhost’, 27017)"
},
{
"code": null,
"e": 26276,
"s": 26235,
"text": "client = MongoClient(‘localhost’, 27017)"
},
{
"code": null,
"e": 26533,
"s": 26276,
"text": "Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database.mydatabase = client.name_of_the_databaseIn our case the name of the database is GeeksForGeeksmydatabase = client.GeeksForGeeks"
},
{
"code": null,
"e": 26574,
"s": 26533,
"text": "mydatabase = client.name_of_the_database"
},
{
"code": null,
"e": 26628,
"s": 26574,
"text": "In our case the name of the database is GeeksForGeeks"
},
{
"code": null,
"e": 26662,
"s": 26628,
"text": "mydatabase = client.GeeksForGeeks"
},
{
"code": null,
"e": 26968,
"s": 26662,
"text": "List the name of all the Collections in the Database: To list the name of all the collection in the database.mydatabase.collection_names()The collection_names() is deprecated in the version 3.7.0. Instead usemydatabase.list_collection_names()This method return the list of the collections in the Database."
},
{
"code": null,
"e": 26998,
"s": 26968,
"text": "mydatabase.collection_names()"
},
{
"code": null,
"e": 27069,
"s": 26998,
"text": "The collection_names() is deprecated in the version 3.7.0. Instead use"
},
{
"code": null,
"e": 27104,
"s": 27069,
"text": "mydatabase.list_collection_names()"
},
{
"code": null,
"e": 27168,
"s": 27104,
"text": "This method return the list of the collections in the Database."
},
{
"code": null,
"e": 27177,
"s": 27168,
"text": "Example:"
},
{
"code": null,
"e": 27194,
"s": 27177,
"text": "Sample Database:"
},
{
"code": "# Python Program to demonstrate# List name of all collections using PyMongo # Importing required librariesfrom pymongo import MongoClient # Connecting to MongoDB server# client = MongoClient('host_name', 'port_number')client = MongoClient(‘localhost’, 27017) # Connecting to the database named# GeeksForGeeksmydatabase = client.GeeksForGeeks # Getting the names of all the collections# in GeeksForGeeks Database.collections = mydatabase.list_collection_names() # Printing the name of the collections to the console.print(collections)",
"e": 27745,
"s": 27194,
"text": null
},
{
"code": null,
"e": 27753,
"s": 27745,
"text": "Output:"
},
{
"code": null,
"e": 27763,
"s": 27753,
"text": "['Geeks']"
},
{
"code": null,
"e": 27778,
"s": 27763,
"text": "Python-mongoDB"
},
{
"code": null,
"e": 27785,
"s": 27778,
"text": "Python"
},
{
"code": null,
"e": 27883,
"s": 27785,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27892,
"s": 27883,
"text": "Comments"
},
{
"code": null,
"e": 27905,
"s": 27892,
"text": "Old Comments"
},
{
"code": null,
"e": 27937,
"s": 27905,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27993,
"s": 27937,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28014,
"s": 27993,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 28053,
"s": 28014,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28095,
"s": 28053,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28122,
"s": 28095,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28153,
"s": 28122,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28195,
"s": 28153,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28231,
"s": 28195,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Difference between sum of the squares of and square of sum first n natural numbers.
|
With a given number n, write a program to find the difference between sum of the squares of and square of sum first n natural numbers.
n = 3
Squares of first three numbers
= 3x3 + 2x2 + 1x1
= 9 + 4 + 1
= 14
Squares of sum of first three numbers
= (3 + 2 + 1)x(3 + 2 + 1)
= 6x6
= 36
Difference
= 36 - 14
= 22
Live Demo
Following is the program in Java to find the required difference.
public class JavaTester {
public static int difference(int n){
//sum of squares of n natural numbers
int sumSquareN = (n * (n + 1) * (2 * n + 1)) / 6;
//sum of n natural numbers
int sumN = (n * (n + 1)) / 2;
//square of sum of n natural numbers
int squareSumN = sumN * sumN;
//difference
return Math.abs(sumSquareN - squareSumN);
}
public static void main(String args[]){
int n = 3;
System.out.println("Number: " + n);
System.out.println("Difference: " + difference(n));
}
}
Number : 3
Difference: 22
|
[
{
"code": null,
"e": 1197,
"s": 1062,
"text": "With a given number n, write a program to find the difference between sum of the squares of and square of sum first n natural numbers."
},
{
"code": null,
"e": 1372,
"s": 1197,
"text": "n = 3\nSquares of first three numbers\n= 3x3 + 2x2 + 1x1\n= 9 + 4 + 1\n= 14\n\nSquares of sum of first three numbers\n= (3 + 2 + 1)x(3 + 2 + 1)\n= 6x6\n= 36\n\nDifference\n= 36 - 14\n= 22"
},
{
"code": null,
"e": 1383,
"s": 1372,
"text": " Live Demo"
},
{
"code": null,
"e": 1449,
"s": 1383,
"text": "Following is the program in Java to find the required difference."
},
{
"code": null,
"e": 2002,
"s": 1449,
"text": "public class JavaTester {\n public static int difference(int n){\n //sum of squares of n natural numbers\n int sumSquareN = (n * (n + 1) * (2 * n + 1)) / 6;\n //sum of n natural numbers\n int sumN = (n * (n + 1)) / 2;\n //square of sum of n natural numbers\n int squareSumN = sumN * sumN;\n //difference\n return Math.abs(sumSquareN - squareSumN);\n }\n public static void main(String args[]){\n int n = 3;\n System.out.println(\"Number: \" + n);\n System.out.println(\"Difference: \" + difference(n));\n }\n}"
},
{
"code": null,
"e": 2028,
"s": 2002,
"text": "Number : 3\nDifference: 22"
}
] |
Deploying a Web App with Streamlit Sharing | by Aren Carpenter | Towards Data Science
|
You may remember a previous post with instructions on how to host a web app created with Streamlit using Heroku. But now it’s even easier!
Streamlit has recently unveiled their new native solution for hosting web apps, Streamlit Sharing! It’s currently in beta, but you can message the developers to get access for hosting up to three apps (this is just the beta limit for now). Once you have access, deploying the app is incredibly straightfoward!
Let’s work through the steps!
You’ll need a Streamlit account using the same email as your GitHub account. This is because Streamlit will automatically populate later fields using information from your repositories to make deploying as simple as possible.
You can find the primary email address for your account by going to your GitHub settings and finding the ‘Email’ tab.
Just as in the previous guide, you’ll need a requirements.txt file that tells Streamlit what versions of your packages it will need to run with stability.
Here’s the entirety of my file, just defining the version of Streamlit and Scikit-Learn I need for my model on the backend.
streamlit==0.71.0scikit-learn==0.23.2
It’s time to deploy! You’ll see a page that looks like this.
So we’ll specify a few things here. But you’ll notice that these fields auto-populate from your GitHub, including all public repositories, any branches therein, and .py files to be deployed (this will default to ‘streamlit_app.py’ but the dropdown will include your actual file names).
I’ll select my Diabetes_Hospitalizations repo that includes a requirements.txt file already from my Heroku deployment. I’m only using my Master branch at the moment, but I’d recommend putting the deployment in its own branch.
You can see my ‘web_app.py’ in the main file path dropdown.
NOTE: you should remove the leading ‘/’ from your main file path. This is a small bug at the moment because the repo dropdown will end with a ‘/’ and then the file will have two ‘//’ causing an error.
Once hosted, you’ll see something like this during initialization. The left half will have your web app and the right is the backend deployment. You can collapse this field with the bottom arrow (and end-users will never see it anyway). If there is an issue in the deployment, this is where any errors will be reported and you can download the log.
This will also auto-generate a URL where the project is hosted so you can share it!
Each app has 1 CPU, 800 MB of RAM, and 800 MB of storage.
Once you login to Streamlit, you’ll now have this dashboard showing your deployed apps. You can reboot or delete an instance, or deploy a new app (again, there’s a current limit of 3 projects for the beta). The stable URL is also listed here if you lose it.
As with all Streamlit apps, you can continuously update your app by altering the .py file on GitHub. Once the changes are pushed, you can manually update the hosted app from the menu on the site.
For the full documentation on sharing, visit the developer docs.
Streamlit has made deploying web apps even easier with their native Streamlit Sharing solution. No longer must you turn to 3rd party solutions like Heroku for hosting simple apps. Again, the feature is still in beta, so if you want to try it out, get in touch with the developers on the Streamlit website.
You can check out my hosted app, and you can use my GitHub repo as a guide so you don’t need to start from scratch! Furthermore, the Streamlit forums are a great resource and the developers are usually very quick to respond.
I’m always looking to connect and explore other projects!
LinkedIn | Medium | GitHub
|
[
{
"code": null,
"e": 311,
"s": 172,
"text": "You may remember a previous post with instructions on how to host a web app created with Streamlit using Heroku. But now it’s even easier!"
},
{
"code": null,
"e": 621,
"s": 311,
"text": "Streamlit has recently unveiled their new native solution for hosting web apps, Streamlit Sharing! It’s currently in beta, but you can message the developers to get access for hosting up to three apps (this is just the beta limit for now). Once you have access, deploying the app is incredibly straightfoward!"
},
{
"code": null,
"e": 651,
"s": 621,
"text": "Let’s work through the steps!"
},
{
"code": null,
"e": 877,
"s": 651,
"text": "You’ll need a Streamlit account using the same email as your GitHub account. This is because Streamlit will automatically populate later fields using information from your repositories to make deploying as simple as possible."
},
{
"code": null,
"e": 995,
"s": 877,
"text": "You can find the primary email address for your account by going to your GitHub settings and finding the ‘Email’ tab."
},
{
"code": null,
"e": 1150,
"s": 995,
"text": "Just as in the previous guide, you’ll need a requirements.txt file that tells Streamlit what versions of your packages it will need to run with stability."
},
{
"code": null,
"e": 1274,
"s": 1150,
"text": "Here’s the entirety of my file, just defining the version of Streamlit and Scikit-Learn I need for my model on the backend."
},
{
"code": null,
"e": 1312,
"s": 1274,
"text": "streamlit==0.71.0scikit-learn==0.23.2"
},
{
"code": null,
"e": 1373,
"s": 1312,
"text": "It’s time to deploy! You’ll see a page that looks like this."
},
{
"code": null,
"e": 1659,
"s": 1373,
"text": "So we’ll specify a few things here. But you’ll notice that these fields auto-populate from your GitHub, including all public repositories, any branches therein, and .py files to be deployed (this will default to ‘streamlit_app.py’ but the dropdown will include your actual file names)."
},
{
"code": null,
"e": 1885,
"s": 1659,
"text": "I’ll select my Diabetes_Hospitalizations repo that includes a requirements.txt file already from my Heroku deployment. I’m only using my Master branch at the moment, but I’d recommend putting the deployment in its own branch."
},
{
"code": null,
"e": 1945,
"s": 1885,
"text": "You can see my ‘web_app.py’ in the main file path dropdown."
},
{
"code": null,
"e": 2146,
"s": 1945,
"text": "NOTE: you should remove the leading ‘/’ from your main file path. This is a small bug at the moment because the repo dropdown will end with a ‘/’ and then the file will have two ‘//’ causing an error."
},
{
"code": null,
"e": 2495,
"s": 2146,
"text": "Once hosted, you’ll see something like this during initialization. The left half will have your web app and the right is the backend deployment. You can collapse this field with the bottom arrow (and end-users will never see it anyway). If there is an issue in the deployment, this is where any errors will be reported and you can download the log."
},
{
"code": null,
"e": 2579,
"s": 2495,
"text": "This will also auto-generate a URL where the project is hosted so you can share it!"
},
{
"code": null,
"e": 2637,
"s": 2579,
"text": "Each app has 1 CPU, 800 MB of RAM, and 800 MB of storage."
},
{
"code": null,
"e": 2895,
"s": 2637,
"text": "Once you login to Streamlit, you’ll now have this dashboard showing your deployed apps. You can reboot or delete an instance, or deploy a new app (again, there’s a current limit of 3 projects for the beta). The stable URL is also listed here if you lose it."
},
{
"code": null,
"e": 3091,
"s": 2895,
"text": "As with all Streamlit apps, you can continuously update your app by altering the .py file on GitHub. Once the changes are pushed, you can manually update the hosted app from the menu on the site."
},
{
"code": null,
"e": 3156,
"s": 3091,
"text": "For the full documentation on sharing, visit the developer docs."
},
{
"code": null,
"e": 3462,
"s": 3156,
"text": "Streamlit has made deploying web apps even easier with their native Streamlit Sharing solution. No longer must you turn to 3rd party solutions like Heroku for hosting simple apps. Again, the feature is still in beta, so if you want to try it out, get in touch with the developers on the Streamlit website."
},
{
"code": null,
"e": 3687,
"s": 3462,
"text": "You can check out my hosted app, and you can use my GitHub repo as a guide so you don’t need to start from scratch! Furthermore, the Streamlit forums are a great resource and the developers are usually very quick to respond."
},
{
"code": null,
"e": 3745,
"s": 3687,
"text": "I’m always looking to connect and explore other projects!"
}
] |
Binary list to integer in Python
|
We can convert a list of 0s and 1s representing a binary number to a decimal number in python using various approaches. In the below examples we use the int() method as well as bitwise left shift operator.
The int() method takes in two arguments and changes the base of the input as per the below syntax.
int(x, base=10)
Return an integer object constructed from a number or string x.
In the below example we use the int() method to take each element of the list as a string and join them to form a final string which gets converted to integer with base 10.
Live Demo
List = [0, 1, 0, 1, 0, 1]
print ("The List is : " + str(List))
# binary list to integer conversion
result = int("".join(str(i) for i in List),2)
# result
print ("The value is : " + str(result))
Running the above code gives us the following result −
The List is : [1, 1, 0, 1, 0, 1]
The value is : 53
The bitwise left shift operator converts the given list of digits to an integer after adding to zeros to the binary form. Then bitwise or is used to add to this result. We use a for loop to iterate through each of the digits in the list.
Live Demo
List = [1, 0, 0, 1, 1, 0]
print ("The values in list is : " + str(List))
# binary list to integer conversion
result = 0
for digits in List:
result = (result << 1) | digits
# result
print ("The value is : " + str(result))
Running the above code gives us the following result −
The values in list is : [1, 0, 0, 1, 1, 0]
The value is : 38
|
[
{
"code": null,
"e": 1268,
"s": 1062,
"text": "We can convert a list of 0s and 1s representing a binary number to a decimal number in python using various approaches. In the below examples we use the int() method as well as bitwise left shift operator."
},
{
"code": null,
"e": 1367,
"s": 1268,
"text": "The int() method takes in two arguments and changes the base of the input as per the below syntax."
},
{
"code": null,
"e": 1447,
"s": 1367,
"text": "int(x, base=10)\nReturn an integer object constructed from a number or string x."
},
{
"code": null,
"e": 1620,
"s": 1447,
"text": "In the below example we use the int() method to take each element of the list as a string and join them to form a final string which gets converted to integer with base 10."
},
{
"code": null,
"e": 1631,
"s": 1620,
"text": " Live Demo"
},
{
"code": null,
"e": 1825,
"s": 1631,
"text": "List = [0, 1, 0, 1, 0, 1]\nprint (\"The List is : \" + str(List))\n# binary list to integer conversion\nresult = int(\"\".join(str(i) for i in List),2)\n# result\nprint (\"The value is : \" + str(result))"
},
{
"code": null,
"e": 1880,
"s": 1825,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1931,
"s": 1880,
"text": "The List is : [1, 1, 0, 1, 0, 1]\nThe value is : 53"
},
{
"code": null,
"e": 2169,
"s": 1931,
"text": "The bitwise left shift operator converts the given list of digits to an integer after adding to zeros to the binary form. Then bitwise or is used to add to this result. We use a for loop to iterate through each of the digits in the list."
},
{
"code": null,
"e": 2180,
"s": 2169,
"text": " Live Demo"
},
{
"code": null,
"e": 2403,
"s": 2180,
"text": "List = [1, 0, 0, 1, 1, 0]\nprint (\"The values in list is : \" + str(List))\n\n# binary list to integer conversion\nresult = 0\nfor digits in List:\nresult = (result << 1) | digits\n\n# result\nprint (\"The value is : \" + str(result))"
},
{
"code": null,
"e": 2458,
"s": 2403,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2519,
"s": 2458,
"text": "The values in list is : [1, 0, 0, 1, 1, 0]\nThe value is : 38"
}
] |
Collect Your Own Fitbit Data with Python | by Stephen Hsu | Towards Data Science
|
So you’ve got your Fitbit over the Christmas break and you’ve got some New Years Resolutions. You go online and see the graphs on your dashboard but you’re still not pleased. You want more data, more graphs, and more information. Well say no more, because I’m going to teach you how to collect your own Fitbit data using nothing but a little Python code. With this tutorial, you can get your elusive minute by minute data (also known as intraday data), which is not readily available when you first get your Fitbit.
Step 1: Set up your account and create the app
The first thing you’ll need to do is create a Fitbit account. Once you’ve done that, you can go to dev.fitbit.com. Under “Manage”, go to “Register An App”. This will lead you to a page that looks like:
For the application website and organization website, name it anything starting with “http://” or “https://”. Secondly, make sure the OAuth 2.0 Application Type is “Personal” as this is key to allowing us to download our intraday data. Lastly, make sure the Callback URL is “http://127.0.0.1:8080/” in order to get our Fitbit API to connect properly. After that, click on the agreement box and submit.
NOTE: depending on the app, we may need an additional step to fill out a form in order to gain permission to our intraday data at this link. Fitbit is supportive of personal projects and any other non profit research, so these should already be callable, but commercial apps might take longer to be approved.
After that, you’ll be redirected to a page looking like this:
The parts we will need from this page are the OAuth 2.0 Client ID and the Client Secret.
Step 2: The API
Once Step 1 is completed, our next step is to use a Fitbit unofficial API. Click the green button on the right side to download the repo and afterwards unzip the file. After that, open up the command line to change directories to the directory containing the unzipped files and run a quick ‘sudo pip install -r requirements/base.txt’ .
Now we’re finally ready to start coding. First things first, we will need to import the necessary packages and bring in our Client_ID and Client_Secret from earlier to authorize ourselves.
import fitbitimport gather_keys_oauth2 as Oauth2import pandas as pd import datetimeCLIENT_ID = '22CPDQ'CLIENT_SECRET = '56662aa8bf31823e4137dfbf48a1b5f1'
Using the ID and Secret, we can obtain the access and refresh tokens that authorize us to get our data.
server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)server.browser_authorize()ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])auth2_client = fitbit.Fitbit(CLIENT_ID, CLIENT_SECRET, oauth2=True, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)
We’re in! ... but not so fast. We’ve authenticated ourselves but we still haven’t gotten our data. Before jumping in, I have one handy trick that will save a lot of manual typing: many of the calls require a date format of (YYYY-MM-DD) as a string format. So if you were to collect your data daily, we’ll have to change this string manually everyday. Instead, we can import the useful ‘datetime’ package and let it do the formatting for us instead.
yesterday = str((datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y%m%d"))yesterday2 = str((datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y-%m-%d"))today = str(datetime.datetime.now().strftime("%Y%m%d"))
Step 3: Acquire the data
We can finally now call for our data.
fit_statsHR = auth2_client.intraday_time_series('activities/heart', base_date=yesterday2, detail_level='1sec')
While this data looks readable to us, it’s not yet ready to be saved on our computer. The following bit of code reads the dictionary format and iterates through the dictionary values — saving the respective time and value values as lists before combining both into a pandas data frame.
time_list = []val_list = []for i in fit_statsHR['activities-heart-intraday']['dataset']: val_list.append(i['value']) time_list.append(i['time'])heartdf = pd.DataFrame({'Heart Rate':val_list,'Time':time_list})
Now to finally save our data locally. Thinking ahead, we’ll be calling our data about once a data (1 file = 1 day), so we’ll want to have a good naming convention that prevents any future mixups or overriding data. My preferred format is to go with heartYYYMMDD.csv. The following code takes our heart data frame and saves them as a CSV in the /Downloads/python-fitbit-master/Heart/ directory.
heartdf.to_csv('/Users/shsu/Downloads/python-fitbit-master/Heart/heart'+ \ yesterday+'.csv', \ columns=['Time','Heart Rate'], header=True, \ index = False)
But wait! There’s still more!
Reading the documentation, there’s plenty of other data we can still collect like:
Our sleep log data:
"""Sleep data on the night of ...."""fit_statsSl = auth2_client.sleep(date='today')stime_list = []sval_list = []for i in fit_statsSl['sleep'][0]['minuteData']: stime_list.append(i['dateTime']) sval_list.append(i['value'])sleepdf = pd.DataFrame({'State':sval_list, 'Time':stime_list})sleepdf['Interpreted'] = sleepdf['State'].map({'2':'Awake','3':'Very Awake','1':'Asleep'})sleepdf.to_csv('/Users/shsu/Downloads/python-fitbit-master/Sleep/sleep' + \ today+'.csv', \ columns = ['Time','State','Interpreted'],header=True, index = False)
Or our sleep summary:
"""Sleep Summary on the night of ...."""fit_statsSum = auth2_client.sleep(date='today')['sleep'][0]ssummarydf = pd.DataFrame({'Date':fit_statsSum['dateOfSleep'], 'MainSleep':fit_statsSum['isMainSleep'], 'Efficiency':fit_statsSum['efficiency'], 'Duration':fit_statsSum['duration'], 'Minutes Asleep':fit_statsSum['minutesAsleep'], 'Minutes Awake':fit_statsSum['minutesAwake'], 'Awakenings':fit_statsSum['awakeCount'], 'Restless Count':fit_statsSum['restlessCount'], 'Restless Duration':fit_statsSum['restlessDuration'], 'Time in Bed':fit_statsSum['timeInBed'] } ,index=[0])
And that’s all you need to get started on collecting all your Fitbit data! So play around some more, read the Python Fitbit documentation, get lost in it for a whole, find your way out, and see overall how nifty your heart data is. In case you wanted a feel for what you can make with that data, here is a link to one of my analyses of my own heart data.
Thanks for taking the time to read my tutorial and feel free to leave a comment or connect on LinkedIn as I’ll be posting more tutorials on data mining and data science.
References:
Orcas Fitbit API GithubPython-Fitbit documentationOfficial Fitbit API documentationFitbit Intraday Access FormPersonal Github with all the codePandas data frame documentation
Orcas Fitbit API Github
Python-Fitbit documentation
Official Fitbit API documentation
Fitbit Intraday Access Form
Personal Github with all the code
Pandas data frame documentation
|
[
{
"code": null,
"e": 687,
"s": 171,
"text": "So you’ve got your Fitbit over the Christmas break and you’ve got some New Years Resolutions. You go online and see the graphs on your dashboard but you’re still not pleased. You want more data, more graphs, and more information. Well say no more, because I’m going to teach you how to collect your own Fitbit data using nothing but a little Python code. With this tutorial, you can get your elusive minute by minute data (also known as intraday data), which is not readily available when you first get your Fitbit."
},
{
"code": null,
"e": 734,
"s": 687,
"text": "Step 1: Set up your account and create the app"
},
{
"code": null,
"e": 936,
"s": 734,
"text": "The first thing you’ll need to do is create a Fitbit account. Once you’ve done that, you can go to dev.fitbit.com. Under “Manage”, go to “Register An App”. This will lead you to a page that looks like:"
},
{
"code": null,
"e": 1338,
"s": 936,
"text": "For the application website and organization website, name it anything starting with “http://” or “https://”. Secondly, make sure the OAuth 2.0 Application Type is “Personal” as this is key to allowing us to download our intraday data. Lastly, make sure the Callback URL is “http://127.0.0.1:8080/” in order to get our Fitbit API to connect properly. After that, click on the agreement box and submit."
},
{
"code": null,
"e": 1647,
"s": 1338,
"text": "NOTE: depending on the app, we may need an additional step to fill out a form in order to gain permission to our intraday data at this link. Fitbit is supportive of personal projects and any other non profit research, so these should already be callable, but commercial apps might take longer to be approved."
},
{
"code": null,
"e": 1709,
"s": 1647,
"text": "After that, you’ll be redirected to a page looking like this:"
},
{
"code": null,
"e": 1798,
"s": 1709,
"text": "The parts we will need from this page are the OAuth 2.0 Client ID and the Client Secret."
},
{
"code": null,
"e": 1814,
"s": 1798,
"text": "Step 2: The API"
},
{
"code": null,
"e": 2150,
"s": 1814,
"text": "Once Step 1 is completed, our next step is to use a Fitbit unofficial API. Click the green button on the right side to download the repo and afterwards unzip the file. After that, open up the command line to change directories to the directory containing the unzipped files and run a quick ‘sudo pip install -r requirements/base.txt’ ."
},
{
"code": null,
"e": 2339,
"s": 2150,
"text": "Now we’re finally ready to start coding. First things first, we will need to import the necessary packages and bring in our Client_ID and Client_Secret from earlier to authorize ourselves."
},
{
"code": null,
"e": 2493,
"s": 2339,
"text": "import fitbitimport gather_keys_oauth2 as Oauth2import pandas as pd import datetimeCLIENT_ID = '22CPDQ'CLIENT_SECRET = '56662aa8bf31823e4137dfbf48a1b5f1'"
},
{
"code": null,
"e": 2597,
"s": 2493,
"text": "Using the ID and Secret, we can obtain the access and refresh tokens that authorize us to get our data."
},
{
"code": null,
"e": 2943,
"s": 2597,
"text": "server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)server.browser_authorize()ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])auth2_client = fitbit.Fitbit(CLIENT_ID, CLIENT_SECRET, oauth2=True, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)"
},
{
"code": null,
"e": 3392,
"s": 2943,
"text": "We’re in! ... but not so fast. We’ve authenticated ourselves but we still haven’t gotten our data. Before jumping in, I have one handy trick that will save a lot of manual typing: many of the calls require a date format of (YYYY-MM-DD) as a string format. So if you were to collect your data daily, we’ll have to change this string manually everyday. Instead, we can import the useful ‘datetime’ package and let it do the formatting for us instead."
},
{
"code": null,
"e": 3631,
"s": 3392,
"text": "yesterday = str((datetime.datetime.now() - datetime.timedelta(days=1)).strftime(\"%Y%m%d\"))yesterday2 = str((datetime.datetime.now() - datetime.timedelta(days=1)).strftime(\"%Y-%m-%d\"))today = str(datetime.datetime.now().strftime(\"%Y%m%d\"))"
},
{
"code": null,
"e": 3656,
"s": 3631,
"text": "Step 3: Acquire the data"
},
{
"code": null,
"e": 3694,
"s": 3656,
"text": "We can finally now call for our data."
},
{
"code": null,
"e": 3805,
"s": 3694,
"text": "fit_statsHR = auth2_client.intraday_time_series('activities/heart', base_date=yesterday2, detail_level='1sec')"
},
{
"code": null,
"e": 4091,
"s": 3805,
"text": "While this data looks readable to us, it’s not yet ready to be saved on our computer. The following bit of code reads the dictionary format and iterates through the dictionary values — saving the respective time and value values as lists before combining both into a pandas data frame."
},
{
"code": null,
"e": 4306,
"s": 4091,
"text": "time_list = []val_list = []for i in fit_statsHR['activities-heart-intraday']['dataset']: val_list.append(i['value']) time_list.append(i['time'])heartdf = pd.DataFrame({'Heart Rate':val_list,'Time':time_list})"
},
{
"code": null,
"e": 4700,
"s": 4306,
"text": "Now to finally save our data locally. Thinking ahead, we’ll be calling our data about once a data (1 file = 1 day), so we’ll want to have a good naming convention that prevents any future mixups or overriding data. My preferred format is to go with heartYYYMMDD.csv. The following code takes our heart data frame and saves them as a CSV in the /Downloads/python-fitbit-master/Heart/ directory."
},
{
"code": null,
"e": 4898,
"s": 4700,
"text": "heartdf.to_csv('/Users/shsu/Downloads/python-fitbit-master/Heart/heart'+ \\ yesterday+'.csv', \\ columns=['Time','Heart Rate'], header=True, \\ index = False)"
},
{
"code": null,
"e": 4928,
"s": 4898,
"text": "But wait! There’s still more!"
},
{
"code": null,
"e": 5011,
"s": 4928,
"text": "Reading the documentation, there’s plenty of other data we can still collect like:"
},
{
"code": null,
"e": 5031,
"s": 5011,
"text": "Our sleep log data:"
},
{
"code": null,
"e": 5634,
"s": 5031,
"text": "\"\"\"Sleep data on the night of ....\"\"\"fit_statsSl = auth2_client.sleep(date='today')stime_list = []sval_list = []for i in fit_statsSl['sleep'][0]['minuteData']: stime_list.append(i['dateTime']) sval_list.append(i['value'])sleepdf = pd.DataFrame({'State':sval_list, 'Time':stime_list})sleepdf['Interpreted'] = sleepdf['State'].map({'2':'Awake','3':'Very Awake','1':'Asleep'})sleepdf.to_csv('/Users/shsu/Downloads/python-fitbit-master/Sleep/sleep' + \\ today+'.csv', \\ columns = ['Time','State','Interpreted'],header=True, index = False)"
},
{
"code": null,
"e": 5656,
"s": 5634,
"text": "Or our sleep summary:"
},
{
"code": null,
"e": 6378,
"s": 5656,
"text": "\"\"\"Sleep Summary on the night of ....\"\"\"fit_statsSum = auth2_client.sleep(date='today')['sleep'][0]ssummarydf = pd.DataFrame({'Date':fit_statsSum['dateOfSleep'], 'MainSleep':fit_statsSum['isMainSleep'], 'Efficiency':fit_statsSum['efficiency'], 'Duration':fit_statsSum['duration'], 'Minutes Asleep':fit_statsSum['minutesAsleep'], 'Minutes Awake':fit_statsSum['minutesAwake'], 'Awakenings':fit_statsSum['awakeCount'], 'Restless Count':fit_statsSum['restlessCount'], 'Restless Duration':fit_statsSum['restlessDuration'], 'Time in Bed':fit_statsSum['timeInBed'] } ,index=[0])"
},
{
"code": null,
"e": 6733,
"s": 6378,
"text": "And that’s all you need to get started on collecting all your Fitbit data! So play around some more, read the Python Fitbit documentation, get lost in it for a whole, find your way out, and see overall how nifty your heart data is. In case you wanted a feel for what you can make with that data, here is a link to one of my analyses of my own heart data."
},
{
"code": null,
"e": 6903,
"s": 6733,
"text": "Thanks for taking the time to read my tutorial and feel free to leave a comment or connect on LinkedIn as I’ll be posting more tutorials on data mining and data science."
},
{
"code": null,
"e": 6915,
"s": 6903,
"text": "References:"
},
{
"code": null,
"e": 7090,
"s": 6915,
"text": "Orcas Fitbit API GithubPython-Fitbit documentationOfficial Fitbit API documentationFitbit Intraday Access FormPersonal Github with all the codePandas data frame documentation"
},
{
"code": null,
"e": 7114,
"s": 7090,
"text": "Orcas Fitbit API Github"
},
{
"code": null,
"e": 7142,
"s": 7114,
"text": "Python-Fitbit documentation"
},
{
"code": null,
"e": 7176,
"s": 7142,
"text": "Official Fitbit API documentation"
},
{
"code": null,
"e": 7204,
"s": 7176,
"text": "Fitbit Intraday Access Form"
},
{
"code": null,
"e": 7238,
"s": 7204,
"text": "Personal Github with all the code"
}
] |
Express.js res.redirect() Function - GeeksforGeeks
|
29 Mar, 2022
The res.redirect() function redirects to the URL derived from the specified path, with specified status, a integer (positive) which corresponds to an HTTP status code. The default status is “302 Found”.
Syntax:
res.redirect([status, ] path)
Parameter: This function accepts two parameters as mentioned above and described below:
status: This parameter holds the HTTP status code
path: This parameter describes the path.
Return Value: It returns an Object.
Type of path’s we can enter
We can enter the whole global URL
e.g : https://www.geeksforgeeks.org/
Path can be relative to root of the host name
e.g : /user with relative to http://hostname/user/cart will redirect to http://hostname/user
Path can be to relative to current URL
e.g : /addtocart with relative to http://hostname/user/ will redirect to http://hostname/user/addtocart
Installation of express module:
You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install express module. You can install this package by using this command.npm install express
npm install express
After installing the express module, you can check your express version in command prompt using the command.npm version express
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
Example 1: Filename: index.js
var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ res.redirect('/user');}); app.get('/user', function(req, res){ res.send("Redirected to User Page");}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Steps to run the program:
The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000
Now open browser and go to http://localhost:3000/, now on your screen you will see the following output:Redirected to User Page
The project structure will look like this:
Make sure you have installed express module using the following command:npm install express
npm install express
Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000
node index.js
Output:
Server listening on PORT 3000
Now open browser and go to http://localhost:3000/, now on your screen you will see the following output:Redirected to User Page
Redirected to User Page
Example 2: Filename: index.js
var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/verify', function(req, res, next){ console.log("Authenticate and Redirect") res.redirect('/user'); next();}); app.get('/user', function(req, res){ res.send("User Page");}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Run index.js file using below command:
node index.js
Now open the browser and go to http://localhost:3000/verify, now check your console and you will see the following output:
Server listening on PORT 3000
Authenticate and Redirect
And you will see the following output on your browser:
User Page
Reference: https://expressjs.com/en/5x/api.html#res.redirect
manikarora059
nachiketmh7
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
Node.js fs.writeFile() Method
Difference between promise and async await in Node.js
JWT Authentication with Node.js
How to use an ES6 import in Node.js?
Roadmap to Become a Web Developer in 2022
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?
Top 10 Angular Libraries For Web Developers
|
[
{
"code": null,
"e": 24509,
"s": 24481,
"text": "\n29 Mar, 2022"
},
{
"code": null,
"e": 24712,
"s": 24509,
"text": "The res.redirect() function redirects to the URL derived from the specified path, with specified status, a integer (positive) which corresponds to an HTTP status code. The default status is “302 Found”."
},
{
"code": null,
"e": 24720,
"s": 24712,
"text": "Syntax:"
},
{
"code": null,
"e": 24750,
"s": 24720,
"text": "res.redirect([status, ] path)"
},
{
"code": null,
"e": 24838,
"s": 24750,
"text": "Parameter: This function accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 24888,
"s": 24838,
"text": "status: This parameter holds the HTTP status code"
},
{
"code": null,
"e": 24929,
"s": 24888,
"text": "path: This parameter describes the path."
},
{
"code": null,
"e": 24965,
"s": 24929,
"text": "Return Value: It returns an Object."
},
{
"code": null,
"e": 24993,
"s": 24965,
"text": "Type of path’s we can enter"
},
{
"code": null,
"e": 25027,
"s": 24993,
"text": "We can enter the whole global URL"
},
{
"code": null,
"e": 25064,
"s": 25027,
"text": "e.g : https://www.geeksforgeeks.org/"
},
{
"code": null,
"e": 25110,
"s": 25064,
"text": "Path can be relative to root of the host name"
},
{
"code": null,
"e": 25203,
"s": 25110,
"text": "e.g : /user with relative to http://hostname/user/cart will redirect to http://hostname/user"
},
{
"code": null,
"e": 25242,
"s": 25203,
"text": "Path can be to relative to current URL"
},
{
"code": null,
"e": 25346,
"s": 25242,
"text": "e.g : /addtocart with relative to http://hostname/user/ will redirect to http://hostname/user/addtocart"
},
{
"code": null,
"e": 25378,
"s": 25346,
"text": "Installation of express module:"
},
{
"code": null,
"e": 25773,
"s": 25378,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 25894,
"s": 25773,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install express"
},
{
"code": null,
"e": 25914,
"s": 25894,
"text": "npm install express"
},
{
"code": null,
"e": 26042,
"s": 25914,
"text": "After installing the express module, you can check your express version in command prompt using the command.npm version express"
},
{
"code": null,
"e": 26062,
"s": 26042,
"text": "npm version express"
},
{
"code": null,
"e": 26210,
"s": 26062,
"text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 26224,
"s": 26210,
"text": "node index.js"
},
{
"code": null,
"e": 26254,
"s": 26224,
"text": "Example 1: Filename: index.js"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ res.redirect('/user');}); app.get('/user', function(req, res){ res.send(\"Redirected to User Page\");}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 26605,
"s": 26254,
"text": null
},
{
"code": null,
"e": 26631,
"s": 26605,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 26980,
"s": 26631,
"text": "The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000\nNow open browser and go to http://localhost:3000/, now on your screen you will see the following output:Redirected to User Page"
},
{
"code": null,
"e": 27023,
"s": 26980,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 27115,
"s": 27023,
"text": "Make sure you have installed express module using the following command:npm install express"
},
{
"code": null,
"e": 27135,
"s": 27115,
"text": "npm install express"
},
{
"code": null,
"e": 27224,
"s": 27135,
"text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000\n"
},
{
"code": null,
"e": 27238,
"s": 27224,
"text": "node index.js"
},
{
"code": null,
"e": 27246,
"s": 27238,
"text": "Output:"
},
{
"code": null,
"e": 27277,
"s": 27246,
"text": "Server listening on PORT 3000\n"
},
{
"code": null,
"e": 27405,
"s": 27277,
"text": "Now open browser and go to http://localhost:3000/, now on your screen you will see the following output:Redirected to User Page"
},
{
"code": null,
"e": 27429,
"s": 27405,
"text": "Redirected to User Page"
},
{
"code": null,
"e": 27459,
"s": 27429,
"text": "Example 2: Filename: index.js"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/verify', function(req, res, next){ console.log(\"Authenticate and Redirect\") res.redirect('/user'); next();}); app.get('/user', function(req, res){ res.send(\"User Page\");}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 27860,
"s": 27459,
"text": null
},
{
"code": null,
"e": 27899,
"s": 27860,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 27913,
"s": 27899,
"text": "node index.js"
},
{
"code": null,
"e": 28036,
"s": 27913,
"text": "Now open the browser and go to http://localhost:3000/verify, now check your console and you will see the following output:"
},
{
"code": null,
"e": 28093,
"s": 28036,
"text": "Server listening on PORT 3000\nAuthenticate and Redirect\n"
},
{
"code": null,
"e": 28148,
"s": 28093,
"text": "And you will see the following output on your browser:"
},
{
"code": null,
"e": 28159,
"s": 28148,
"text": "User Page\n"
},
{
"code": null,
"e": 28220,
"s": 28159,
"text": "Reference: https://expressjs.com/en/5x/api.html#res.redirect"
},
{
"code": null,
"e": 28234,
"s": 28220,
"text": "manikarora059"
},
{
"code": null,
"e": 28246,
"s": 28234,
"text": "nachiketmh7"
},
{
"code": null,
"e": 28257,
"s": 28246,
"text": "Express.js"
},
{
"code": null,
"e": 28265,
"s": 28257,
"text": "Node.js"
},
{
"code": null,
"e": 28282,
"s": 28265,
"text": "Web Technologies"
},
{
"code": null,
"e": 28380,
"s": 28282,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28389,
"s": 28380,
"text": "Comments"
},
{
"code": null,
"e": 28402,
"s": 28389,
"text": "Old Comments"
},
{
"code": null,
"e": 28439,
"s": 28402,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 28469,
"s": 28439,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 28523,
"s": 28469,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 28555,
"s": 28523,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 28592,
"s": 28555,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 28634,
"s": 28592,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28696,
"s": 28634,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28739,
"s": 28696,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28789,
"s": 28739,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
What is the role of IWebHostEnvironment interface in C# ASP.NET Core?
|
IWebHostEnvironment Provides information about the web hosting environment an
application is running in.
belongs to namespace Microsoft.AspNetCore.Hosting
The IWebHostEnvironment interface need to be injected as dependency in the
Controller and then later used throughout the Controller.
The IWebHostEnvironment interface have two properties.
WebRootPath − Path of the www folder(Gets or sets the absolute path to the directory that contains the web-servable application content files)
ContentRootPath − Path of the root folder which contains all the Application files(Gets or sets an IFileProvider pointing at WebRootPath.)
We need to import namesace
using Microsoft.AspNetCore.Hosting;
In the below example, the IWebHostEnvironment is injected in the Controller and
assigned to the private property Environment and later used to get the WebRootPath
and ContentRootPath.
public class HomeController : Controller{
private IWebHostEnvironment Environment;
public HomeController(IWebHostEnvironment _environment){
Environment = _environment;
}
public IActionResult Index(){
string wwwPath = this.Environment.WebRootPath;
string contentPath = this.Environment.ContentRootPath;
return View();
}
}
|
[
{
"code": null,
"e": 1167,
"s": 1062,
"text": "IWebHostEnvironment Provides information about the web hosting environment an\napplication is running in."
},
{
"code": null,
"e": 1217,
"s": 1167,
"text": "belongs to namespace Microsoft.AspNetCore.Hosting"
},
{
"code": null,
"e": 1350,
"s": 1217,
"text": "The IWebHostEnvironment interface need to be injected as dependency in the\nController and then later used throughout the Controller."
},
{
"code": null,
"e": 1405,
"s": 1350,
"text": "The IWebHostEnvironment interface have two properties."
},
{
"code": null,
"e": 1548,
"s": 1405,
"text": "WebRootPath − Path of the www folder(Gets or sets the absolute path to the directory that contains the web-servable application content files)"
},
{
"code": null,
"e": 1687,
"s": 1548,
"text": "ContentRootPath − Path of the root folder which contains all the Application files(Gets or sets an IFileProvider pointing at WebRootPath.)"
},
{
"code": null,
"e": 1714,
"s": 1687,
"text": "We need to import namesace"
},
{
"code": null,
"e": 1750,
"s": 1714,
"text": "using Microsoft.AspNetCore.Hosting;"
},
{
"code": null,
"e": 1934,
"s": 1750,
"text": "In the below example, the IWebHostEnvironment is injected in the Controller and\nassigned to the private property Environment and later used to get the WebRootPath\nand ContentRootPath."
},
{
"code": null,
"e": 2294,
"s": 1934,
"text": "public class HomeController : Controller{\n private IWebHostEnvironment Environment;\n public HomeController(IWebHostEnvironment _environment){\n Environment = _environment;\n }\n public IActionResult Index(){\n string wwwPath = this.Environment.WebRootPath;\n string contentPath = this.Environment.ContentRootPath;\n return View();\n }\n}"
}
] |
A single neuron neural network in Python
|
Neural networks are very important core of deep learning; it has many practical applications in many different areas. Now a days these networks are used for image classification, speech recognition, object detection etc.
Let’s do understand what is this and how does it work?
This network has different components. They are as follows −
An input layer, x
An arbitrary amount of hidden layers
An output layer, ŷ
A set of weights and biases between each layer which is defined by W and b
Next is a choice of activation function for each hidden layer, σ.
In this diagram 2-layer Neural Network is presented (the input layer is typically excluded when counting the number of layers in a Neural Network)
In this graph, circles are representing neurons and the lines are representing synapses. The synapses are used to multiply the inputs and weights. We think weights as the “strength” of the connection between neurons. Weights define the output of a neural network.
Here’s a brief overview of how a simple feed forward neural network works −
When we use feed forward neural network, we have to follow some steps.
First take input as a matrix (2D array of numbers)
First take input as a matrix (2D array of numbers)
Next is multiplies the input by a set weights.
Next is multiplies the input by a set weights.
Next applies an activation function.
Next applies an activation function.
Return an output.
Return an output.
Next error is calculated, it is the difference between desired output from the data and the predicted output.
Next error is calculated, it is the difference between desired output from the data and the predicted output.
And the weights are little bit changes according to the error.
And the weights are little bit changes according to the error.
To train, this process is repeated 1,000+ times and the more data is trained upon, the more accurate our outputs will be.
To train, this process is repeated 1,000+ times and the more data is trained upon, the more accurate our outputs will be.
HOURS STUDIED, HOURS SLEPT (INPUT)TEST SCORE (OUTPUT)
2, 992
1, 586
3, 689
4, 8?
from numpy import exp, array, random, dot, tanh
class my_network():
def __init__(self):
random.seed(1)
# 3x1 Weight matrix
self.weight_matrix = 2 * random.random((3, 1)) - 1
defmy_tanh(self, x):
return tanh(x)
defmy_tanh_derivative(self, x):
return 1.0 - tanh(x) ** 2
# forward propagation
defmy_forward_propagation(self, inputs):
return self.my_tanh(dot(inputs, self.weight_matrix))
# training the neural network.
deftrain(self, train_inputs, train_outputs,
num_train_iterations):
for iteration in range(num_train_iterations):
output = self.my_forward_propagation(train_inputs)
# Calculate the error in the output.
error = train_outputs - output
adjustment = dot(train_inputs.T, error *self.my_tanh_derivative(output))
# Adjust the weight matrix
self.weight_matrix += adjustment
# Driver Code
if __name__ == "__main__":
my_neural = my_network()
print ('Random weights when training has started')
print (my_neural.weight_matrix)
train_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
train_outputs = array([[0, 1, 1, 0]]).T
my_neural.train(train_inputs, train_outputs, 10000)
print ('Displaying new weights after training')
print (my_neural.weight_matrix)
# Test the neural network with a new situation.
print ("Testing network on new examples ->")
print (my_neural.my_forward_propagation(array([1, 0, 0])))
Random weights when training has started
[[-0.16595599]
[ 0.44064899]
[-0.99977125]]
Displaying new weights after training
[[5.39428067]
[0.19482422]
[0.34317086]]
Testing network on new examples ->
[0.99995873]
|
[
{
"code": null,
"e": 1283,
"s": 1062,
"text": "Neural networks are very important core of deep learning; it has many practical applications in many different areas. Now a days these networks are used for image classification, speech recognition, object detection etc."
},
{
"code": null,
"e": 1338,
"s": 1283,
"text": "Let’s do understand what is this and how does it work?"
},
{
"code": null,
"e": 1399,
"s": 1338,
"text": "This network has different components. They are as follows −"
},
{
"code": null,
"e": 1417,
"s": 1399,
"text": "An input layer, x"
},
{
"code": null,
"e": 1454,
"s": 1417,
"text": "An arbitrary amount of hidden layers"
},
{
"code": null,
"e": 1474,
"s": 1454,
"text": "An output layer, ŷ"
},
{
"code": null,
"e": 1549,
"s": 1474,
"text": "A set of weights and biases between each layer which is defined by W and b"
},
{
"code": null,
"e": 1615,
"s": 1549,
"text": "Next is a choice of activation function for each hidden layer, σ."
},
{
"code": null,
"e": 1762,
"s": 1615,
"text": "In this diagram 2-layer Neural Network is presented (the input layer is typically excluded when counting the number of layers in a Neural Network)"
},
{
"code": null,
"e": 2026,
"s": 1762,
"text": "In this graph, circles are representing neurons and the lines are representing synapses. The synapses are used to multiply the inputs and weights. We think weights as the “strength” of the connection between neurons. Weights define the output of a neural network."
},
{
"code": null,
"e": 2102,
"s": 2026,
"text": "Here’s a brief overview of how a simple feed forward neural network works −"
},
{
"code": null,
"e": 2173,
"s": 2102,
"text": "When we use feed forward neural network, we have to follow some steps."
},
{
"code": null,
"e": 2224,
"s": 2173,
"text": "First take input as a matrix (2D array of numbers)"
},
{
"code": null,
"e": 2275,
"s": 2224,
"text": "First take input as a matrix (2D array of numbers)"
},
{
"code": null,
"e": 2322,
"s": 2275,
"text": "Next is multiplies the input by a set weights."
},
{
"code": null,
"e": 2369,
"s": 2322,
"text": "Next is multiplies the input by a set weights."
},
{
"code": null,
"e": 2406,
"s": 2369,
"text": "Next applies an activation function."
},
{
"code": null,
"e": 2443,
"s": 2406,
"text": "Next applies an activation function."
},
{
"code": null,
"e": 2461,
"s": 2443,
"text": "Return an output."
},
{
"code": null,
"e": 2479,
"s": 2461,
"text": "Return an output."
},
{
"code": null,
"e": 2589,
"s": 2479,
"text": "Next error is calculated, it is the difference between desired output from the data and the predicted output."
},
{
"code": null,
"e": 2699,
"s": 2589,
"text": "Next error is calculated, it is the difference between desired output from the data and the predicted output."
},
{
"code": null,
"e": 2762,
"s": 2699,
"text": "And the weights are little bit changes according to the error."
},
{
"code": null,
"e": 2825,
"s": 2762,
"text": "And the weights are little bit changes according to the error."
},
{
"code": null,
"e": 2947,
"s": 2825,
"text": "To train, this process is repeated 1,000+ times and the more data is trained upon, the more accurate our outputs will be."
},
{
"code": null,
"e": 3069,
"s": 2947,
"text": "To train, this process is repeated 1,000+ times and the more data is trained upon, the more accurate our outputs will be."
},
{
"code": null,
"e": 3123,
"s": 3069,
"text": "HOURS STUDIED, HOURS SLEPT (INPUT)TEST SCORE (OUTPUT)"
},
{
"code": null,
"e": 3150,
"s": 3123,
"text": "2, 992\n1, 586\n3, 689\n4, 8?"
},
{
"code": null,
"e": 4653,
"s": 3150,
"text": "from numpy import exp, array, random, dot, tanh\nclass my_network():\n def __init__(self):\n random.seed(1)\n # 3x1 Weight matrix\n self.weight_matrix = 2 * random.random((3, 1)) - 1\n defmy_tanh(self, x):\n return tanh(x)\n defmy_tanh_derivative(self, x):\n return 1.0 - tanh(x) ** 2\n # forward propagation\n defmy_forward_propagation(self, inputs):\n return self.my_tanh(dot(inputs, self.weight_matrix))\n # training the neural network.\n deftrain(self, train_inputs, train_outputs,\n num_train_iterations):\n for iteration in range(num_train_iterations):\n output = self.my_forward_propagation(train_inputs)\n # Calculate the error in the output.\n error = train_outputs - output\n adjustment = dot(train_inputs.T, error *self.my_tanh_derivative(output))\n # Adjust the weight matrix\n self.weight_matrix += adjustment\n # Driver Code\n if __name__ == \"__main__\":\n my_neural = my_network()\n print ('Random weights when training has started')\n print (my_neural.weight_matrix)\n train_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])\n train_outputs = array([[0, 1, 1, 0]]).T\n my_neural.train(train_inputs, train_outputs, 10000)\n print ('Displaying new weights after training')\n print (my_neural.weight_matrix)\n # Test the neural network with a new situation.\n print (\"Testing network on new examples ->\")\nprint (my_neural.my_forward_propagation(array([1, 0, 0])))"
},
{
"code": null,
"e": 4865,
"s": 4653,
"text": "Random weights when training has started\n[[-0.16595599]\n[ 0.44064899]\n[-0.99977125]]\nDisplaying new weights after training\n[[5.39428067]\n[0.19482422]\n[0.34317086]]\nTesting network on new examples ->\n[0.99995873]"
}
] |
Constructor Delegation in C++ - GeeksforGeeks
|
23 Jul, 2021
Sometimes it is useful for a constructor to be able to call another constructor of the same class. This feature, called Constructor Delegation, was introduced in C++ 11.An example program without delegation :
CPP
// A C++ program to demonstrate need of// constructor delegation.#include <iostream>using namespace std; class A { int x, y, z; public: A() { x = 0; y = 0; z = 0; } A(int z) { // The below two lines are redundant x = 0; y = 0; /* Only initialize z by passing an argument, while all the other arguments are initialized the same way they were, as in the previous constructor*/ this->z = z; } void show() { cout << x << '\n' << y << '\n' << z; }}; int main(){ A obj(3); obj.show(); return 0;}
0
0
3
Solving above redundant code problem using init() We can see in the above example that the constructors of the above class, despite having different signatures, have first two lines of code common between them, leading to code duplication. One solution to avoid this situation would have been the creation of an init function that can be called from both the constructors.
CPP
// Program to demonstrate use of init() to// avoid redundant code.#include <iostream>using namespace std; class A { int x, y, z; // init function to initialize x and y void init() { x = 0; y = 0; } public: A() { init(); z = 0; } A(int z) { init(); this->z = z; } void show() { cout << x << '\n' << y << '\n' << z; }}; int main(){ A obj(3); obj.show(); return 0;}
0
0
3
Solving above redundant code problem using constructor delegation() While the usage of an init() function eliminates duplicate code, it still has its own drawbacks. First, it’s not quite as readable, as it adds a new function and several new function calls. Second, because init() is not a constructor, it can be called during the normal program flow, where member variables may already be set and dynamically allocated memory may already be allocated. This means init() needs to be additionally complex in order to handle both the new initialization and re-initialization cases properly.However, C++ Constructor delegation provides an elegant solution to handle this problem, by allowing us to call a constructor by placing it in the initializer list of other constructors. The following program demonstrates how it is done:
CPP
// Program to demonstrate constructor delegation// in C++#include <iostream>using namespace std;class A { int x, y, z; public: A() { x = 0; y = 0; z = 0; } // Constructor delegation A(int z) : A() { this->z = z; // Only update z } void show() { cout << x << '\n' << y << '\n' << z; }};int main(){ A obj(3); obj.show(); return 0;}
0
0
3
It is very important to note that constructor delegation is different from calling a constructor from inside the body of another constructor, which is not recommended because doing so creates another object and initializes it, without doing anything to the object created by the constructor that called it.
vineet kumar 14
cpp-constructor
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Convert string to char array in C++
List in C++ Standard Template Library (STL)
Iterators in C++ STL
Inline Functions in C++
std::string class in C++
|
[
{
"code": null,
"e": 24122,
"s": 24094,
"text": "\n23 Jul, 2021"
},
{
"code": null,
"e": 24333,
"s": 24122,
"text": "Sometimes it is useful for a constructor to be able to call another constructor of the same class. This feature, called Constructor Delegation, was introduced in C++ 11.An example program without delegation : "
},
{
"code": null,
"e": 24337,
"s": 24333,
"text": "CPP"
},
{
"code": "// A C++ program to demonstrate need of// constructor delegation.#include <iostream>using namespace std; class A { int x, y, z; public: A() { x = 0; y = 0; z = 0; } A(int z) { // The below two lines are redundant x = 0; y = 0; /* Only initialize z by passing an argument, while all the other arguments are initialized the same way they were, as in the previous constructor*/ this->z = z; } void show() { cout << x << '\\n' << y << '\\n' << z; }}; int main(){ A obj(3); obj.show(); return 0;}",
"e": 24985,
"s": 24337,
"text": null
},
{
"code": null,
"e": 24991,
"s": 24985,
"text": "0\n0\n3"
},
{
"code": null,
"e": 25368,
"s": 24993,
"text": "Solving above redundant code problem using init() We can see in the above example that the constructors of the above class, despite having different signatures, have first two lines of code common between them, leading to code duplication. One solution to avoid this situation would have been the creation of an init function that can be called from both the constructors. "
},
{
"code": null,
"e": 25372,
"s": 25368,
"text": "CPP"
},
{
"code": "// Program to demonstrate use of init() to// avoid redundant code.#include <iostream>using namespace std; class A { int x, y, z; // init function to initialize x and y void init() { x = 0; y = 0; } public: A() { init(); z = 0; } A(int z) { init(); this->z = z; } void show() { cout << x << '\\n' << y << '\\n' << z; }}; int main(){ A obj(3); obj.show(); return 0;}",
"e": 25861,
"s": 25372,
"text": null
},
{
"code": null,
"e": 25867,
"s": 25861,
"text": "0\n0\n3"
},
{
"code": null,
"e": 26696,
"s": 25869,
"text": "Solving above redundant code problem using constructor delegation() While the usage of an init() function eliminates duplicate code, it still has its own drawbacks. First, it’s not quite as readable, as it adds a new function and several new function calls. Second, because init() is not a constructor, it can be called during the normal program flow, where member variables may already be set and dynamically allocated memory may already be allocated. This means init() needs to be additionally complex in order to handle both the new initialization and re-initialization cases properly.However, C++ Constructor delegation provides an elegant solution to handle this problem, by allowing us to call a constructor by placing it in the initializer list of other constructors. The following program demonstrates how it is done: "
},
{
"code": null,
"e": 26700,
"s": 26696,
"text": "CPP"
},
{
"code": "// Program to demonstrate constructor delegation// in C++#include <iostream>using namespace std;class A { int x, y, z; public: A() { x = 0; y = 0; z = 0; } // Constructor delegation A(int z) : A() { this->z = z; // Only update z } void show() { cout << x << '\\n' << y << '\\n' << z; }};int main(){ A obj(3); obj.show(); return 0;}",
"e": 27133,
"s": 26700,
"text": null
},
{
"code": null,
"e": 27139,
"s": 27133,
"text": "0\n0\n3"
},
{
"code": null,
"e": 27449,
"s": 27141,
"text": "It is very important to note that constructor delegation is different from calling a constructor from inside the body of another constructor, which is not recommended because doing so creates another object and initializes it, without doing anything to the object created by the constructor that called it. "
},
{
"code": null,
"e": 27465,
"s": 27449,
"text": "vineet kumar 14"
},
{
"code": null,
"e": 27481,
"s": 27465,
"text": "cpp-constructor"
},
{
"code": null,
"e": 27485,
"s": 27481,
"text": "C++"
},
{
"code": null,
"e": 27489,
"s": 27485,
"text": "CPP"
},
{
"code": null,
"e": 27587,
"s": 27489,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27615,
"s": 27587,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27635,
"s": 27615,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27659,
"s": 27635,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27692,
"s": 27659,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27736,
"s": 27692,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27772,
"s": 27736,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 27816,
"s": 27772,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27837,
"s": 27816,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 27861,
"s": 27837,
"text": "Inline Functions in C++"
}
] |
wxPython - HTMLWindow Class
|
wxHTML library contains classes for parsing and displaying HTML content. Although this is not intended to be a full-featured browser, wx.HtmlWindow object is a generic HTML viewer.
HtmlWindow class constructor takes a familiar look −
(Parent, id, pos, size, style)
This class supports the following styles −
wxHW_SCROLLBAR_NEVER
Never display scrollbars, not even when the page is larger than the window
wxHW_SCROLLBAR_AUTO
Display scrollbars only if the page size exceeds window's size
wxHW_NO_SELECTION
Don't allow the user to select text
Following event binders are available for this class −
EVT_HTML_CELL_CLICKED
A wxHtmlCell was clicked
EVT_HTML_CELL_HOVER
The mouse passed over a wxHtmlCell
EVT_HTML_LINK_CLICKED
A wxHtmlCell which contains an hyperlink was clicked
Following member functions of this class are frequently used −
AppendToPage()
Appends HTML fragment to currently displayed text and refreshes the window
HistoryBack()
Goes back to the previously visited page
HistoryForward()
Goes to the next page in history
LoadPage()
Loads a HTML file
OnLinkClicked()
Called when a hyperlink is clicked
SetPage()
Sets text tagged with HTML tags as page contents
The following code displays a simple HTML browser. On running the code, a TextEntry Dialog pops up asking a URL to be entered. LoadPage() method of wx.HtmlWindow class displays the contents in the window.
import wx
import wx.html
class MyHtmlFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title, size = (600,400))
html = wx.html.HtmlWindow(self)
if "gtk2" in wx.PlatformInfo:
html.SetStandardFonts()
dlg = wx.TextEntryDialog(self, 'Enter a URL', 'HTMLWindow')
if dlg.ShowModal() == wx.ID_OK:
html.LoadPage(dlg.GetValue())
app = wx.App()
frm = MyHtmlFrame(None, "Simple HTML Browser")
frm.Show()
app.MainLoop()
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2063,
"s": 1882,
"text": "wxHTML library contains classes for parsing and displaying HTML content. Although this is not intended to be a full-featured browser, wx.HtmlWindow object is a generic HTML viewer."
},
{
"code": null,
"e": 2116,
"s": 2063,
"text": "HtmlWindow class constructor takes a familiar look −"
},
{
"code": null,
"e": 2148,
"s": 2116,
"text": "(Parent, id, pos, size, style)\n"
},
{
"code": null,
"e": 2191,
"s": 2148,
"text": "This class supports the following styles −"
},
{
"code": null,
"e": 2212,
"s": 2191,
"text": "wxHW_SCROLLBAR_NEVER"
},
{
"code": null,
"e": 2287,
"s": 2212,
"text": "Never display scrollbars, not even when the page is larger than the window"
},
{
"code": null,
"e": 2307,
"s": 2287,
"text": "wxHW_SCROLLBAR_AUTO"
},
{
"code": null,
"e": 2370,
"s": 2307,
"text": "Display scrollbars only if the page size exceeds window's size"
},
{
"code": null,
"e": 2388,
"s": 2370,
"text": "wxHW_NO_SELECTION"
},
{
"code": null,
"e": 2424,
"s": 2388,
"text": "Don't allow the user to select text"
},
{
"code": null,
"e": 2479,
"s": 2424,
"text": "Following event binders are available for this class −"
},
{
"code": null,
"e": 2501,
"s": 2479,
"text": "EVT_HTML_CELL_CLICKED"
},
{
"code": null,
"e": 2526,
"s": 2501,
"text": "A wxHtmlCell was clicked"
},
{
"code": null,
"e": 2546,
"s": 2526,
"text": "EVT_HTML_CELL_HOVER"
},
{
"code": null,
"e": 2581,
"s": 2546,
"text": "The mouse passed over a wxHtmlCell"
},
{
"code": null,
"e": 2603,
"s": 2581,
"text": "EVT_HTML_LINK_CLICKED"
},
{
"code": null,
"e": 2656,
"s": 2603,
"text": "A wxHtmlCell which contains an hyperlink was clicked"
},
{
"code": null,
"e": 2719,
"s": 2656,
"text": "Following member functions of this class are frequently used −"
},
{
"code": null,
"e": 2734,
"s": 2719,
"text": "AppendToPage()"
},
{
"code": null,
"e": 2809,
"s": 2734,
"text": "Appends HTML fragment to currently displayed text and refreshes the window"
},
{
"code": null,
"e": 2823,
"s": 2809,
"text": "HistoryBack()"
},
{
"code": null,
"e": 2864,
"s": 2823,
"text": "Goes back to the previously visited page"
},
{
"code": null,
"e": 2881,
"s": 2864,
"text": "HistoryForward()"
},
{
"code": null,
"e": 2914,
"s": 2881,
"text": "Goes to the next page in history"
},
{
"code": null,
"e": 2925,
"s": 2914,
"text": "LoadPage()"
},
{
"code": null,
"e": 2943,
"s": 2925,
"text": "Loads a HTML file"
},
{
"code": null,
"e": 2959,
"s": 2943,
"text": "OnLinkClicked()"
},
{
"code": null,
"e": 2994,
"s": 2959,
"text": "Called when a hyperlink is clicked"
},
{
"code": null,
"e": 3004,
"s": 2994,
"text": "SetPage()"
},
{
"code": null,
"e": 3053,
"s": 3004,
"text": "Sets text tagged with HTML tags as page contents"
},
{
"code": null,
"e": 3258,
"s": 3053,
"text": "The following code displays a simple HTML browser. On running the code, a TextEntry Dialog pops up asking a URL to be entered. LoadPage() method of wx.HtmlWindow class displays the contents in the window."
},
{
"code": null,
"e": 3791,
"s": 3258,
"text": "import wx \nimport wx.html \n \nclass MyHtmlFrame(wx.Frame): \n def __init__(self, parent, title): \n wx.Frame.__init__(self, parent, -1, title, size = (600,400)) \n html = wx.html.HtmlWindow(self) \n\t\t\n if \"gtk2\" in wx.PlatformInfo: \n html.SetStandardFonts() \n\t\t\t\n dlg = wx.TextEntryDialog(self, 'Enter a URL', 'HTMLWindow') \n\t\t\n if dlg.ShowModal() == wx.ID_OK: \n html.LoadPage(dlg.GetValue()) \n\t\t\t\napp = wx.App() \nfrm = MyHtmlFrame(None, \"Simple HTML Browser\") \nfrm.Show() \napp.MainLoop()"
},
{
"code": null,
"e": 3798,
"s": 3791,
"text": " Print"
},
{
"code": null,
"e": 3809,
"s": 3798,
"text": " Add Notes"
}
] |
Draw Composition of Plots Using the patchwork Package in R - GeeksforGeeks
|
28 Jul, 2021
In this article, we will discuss how to draw a composition of plots using the patchwork package in R programming language. The patchwork package makes it easier to plot different ggplots in a single graph. We will require both ggplot2 packages for plotting our data and the patchwork package to combine the different ggplots.
Let us first draw all the plots normally and independently.
Example: Plotting the dataset in a bar plot
R
library(ggplot2)library(patchwork) data(iris) head(iris) # Plotting the bar chartgfg1 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_bar(stat = "identity") gfg1
Output :
Bar plot
Example: Plotting the dataset in a scatterplot
R
library(ggplot2)library(patchwork) data(iris) head(iris) # Scatterplotgfg2 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_point() gfg2
Output :
Scatterplot
Example: Plotting the dataset in a line plot
R
library(ggplot2)library(patchwork) data(iris) head(iris) # Line plotgfg3 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_line() gfg3
Output :
Line plot
Now let us look at how these three plots can be combined in various orientations.
The vertical orientation combines the plots and these plots are placed side by side with each other. We will take the above ggplot2 plots and add them to arrange them vertically. The + operator is used to arrange these plots side by side in the same graph.
Example: Vertically arrange plots in the same frame
R
library(ggplot2)library(patchwork) data(iris) head(iris) gfg1 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_bar(stat = "identity") gfg2 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_point() gfg3 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_line() # Combination of plots by arranging them side by sidegfg_comb_1 <- gfg1 + gfg2 + gfg3 gfg_comb_1
Output :
Vertical orientation
The second combination of these plots would be arranging them in different widths in multiple rows and columns in the same graph window. The different width orientation arranges the plots in different lines according to widths. Basically, the first plot is placed on the first line and the other two plots are placed on the next line horizontally.
We use a slash(/) operator at that position where we want to start a new line. So we placed it after the first plot. Then, we use add(+) operator to arrange the other two plots horizontally on the next new line.
Example: Arranging plots with different widths
R
library(ggplot2)library(patchwork) data(iris) head(iris) gfg1 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_bar(stat = "identity") gfg2 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) +geom_point() gfg3 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) +geom_line() # Arranging the plots in different widthsgfg_comb_2 <- gfg1 / (gfg2 + gfg3) gfg_comb_2
Output :
Different widths orientation
The third combination of these plots would be arranging them in different heights in multiple rows and columns in the same graph window. The different height orientation arranges the plots in different lines according to heights. Basically, the first two plots are arranged horizontally and the last plot here is placed below the second plot.
We use the add(+) operator to arrange the first two plots horizontally. Then we use the slash (/) operator for the third plot to place it on a new line below the second plot.
Example: Arranging plots with different heights
R
library(ggplot2)library(patchwork) data(iris) head(iris) gfg1 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_bar(stat = "identity") gfg2 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) +geom_point() gfg3 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_line() # Arrangement of plots according to # different heightsgfg_comb_3 <- gfg1 + gfg2 / gfg3 gfg_comb_3
Output :
Different heights orientation
The last combination of plots is to arrange them horizontally. These plots are placed one below the other. We will use the slash(/) operator to place these plots in a new line, one below the other plot.
Example: Arranging plots vertically
R
library(ggplot2)library(patchwork) data(iris) head(iris) gfg1 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_bar(stat = "identity") gfg2 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_point() gfg3 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_line() # Combination of plots by arranging them # horizontallygfg_comb_4 <- gfg1 / gfg2 / gfg3 gfg_comb_4
Output :
Horizontal orientation
Picked
R-Packages
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
R - if statement
Replace Specific Characters in String in R
Time Series Analysis in R
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 25569,
"s": 25242,
"text": "In this article, we will discuss how to draw a composition of plots using the patchwork package in R programming language. The patchwork package makes it easier to plot different ggplots in a single graph. We will require both ggplot2 packages for plotting our data and the patchwork package to combine the different ggplots. "
},
{
"code": null,
"e": 25629,
"s": 25569,
"text": "Let us first draw all the plots normally and independently."
},
{
"code": null,
"e": 25673,
"s": 25629,
"text": "Example: Plotting the dataset in a bar plot"
},
{
"code": null,
"e": 25675,
"s": 25673,
"text": "R"
},
{
"code": "library(ggplot2)library(patchwork) data(iris) head(iris) # Plotting the bar chartgfg1 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_bar(stat = \"identity\") gfg1",
"e": 25866,
"s": 25675,
"text": null
},
{
"code": null,
"e": 25875,
"s": 25866,
"text": "Output :"
},
{
"code": null,
"e": 25884,
"s": 25875,
"text": "Bar plot"
},
{
"code": null,
"e": 25931,
"s": 25884,
"text": "Example: Plotting the dataset in a scatterplot"
},
{
"code": null,
"e": 25933,
"s": 25931,
"text": "R"
},
{
"code": "library(ggplot2)library(patchwork) data(iris) head(iris) # Scatterplotgfg2 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_point() gfg2",
"e": 26123,
"s": 25933,
"text": null
},
{
"code": null,
"e": 26132,
"s": 26123,
"text": "Output :"
},
{
"code": null,
"e": 26144,
"s": 26132,
"text": "Scatterplot"
},
{
"code": null,
"e": 26189,
"s": 26144,
"text": "Example: Plotting the dataset in a line plot"
},
{
"code": null,
"e": 26191,
"s": 26189,
"text": "R"
},
{
"code": "library(ggplot2)library(patchwork) data(iris) head(iris) # Line plotgfg3 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_line() gfg3",
"e": 26378,
"s": 26191,
"text": null
},
{
"code": null,
"e": 26387,
"s": 26378,
"text": "Output :"
},
{
"code": null,
"e": 26397,
"s": 26387,
"text": "Line plot"
},
{
"code": null,
"e": 26479,
"s": 26397,
"text": "Now let us look at how these three plots can be combined in various orientations."
},
{
"code": null,
"e": 26736,
"s": 26479,
"text": "The vertical orientation combines the plots and these plots are placed side by side with each other. We will take the above ggplot2 plots and add them to arrange them vertically. The + operator is used to arrange these plots side by side in the same graph."
},
{
"code": null,
"e": 26788,
"s": 26736,
"text": "Example: Vertically arrange plots in the same frame"
},
{
"code": null,
"e": 26790,
"s": 26788,
"text": "R"
},
{
"code": "library(ggplot2)library(patchwork) data(iris) head(iris) gfg1 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_bar(stat = \"identity\") gfg2 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_point() gfg3 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_line() # Combination of plots by arranging them side by sidegfg_comb_1 <- gfg1 + gfg2 + gfg3 gfg_comb_1",
"e": 27298,
"s": 26790,
"text": null
},
{
"code": null,
"e": 27307,
"s": 27298,
"text": "Output :"
},
{
"code": null,
"e": 27328,
"s": 27307,
"text": "Vertical orientation"
},
{
"code": null,
"e": 27676,
"s": 27328,
"text": "The second combination of these plots would be arranging them in different widths in multiple rows and columns in the same graph window. The different width orientation arranges the plots in different lines according to widths. Basically, the first plot is placed on the first line and the other two plots are placed on the next line horizontally."
},
{
"code": null,
"e": 27888,
"s": 27676,
"text": "We use a slash(/) operator at that position where we want to start a new line. So we placed it after the first plot. Then, we use add(+) operator to arrange the other two plots horizontally on the next new line."
},
{
"code": null,
"e": 27935,
"s": 27888,
"text": "Example: Arranging plots with different widths"
},
{
"code": null,
"e": 27937,
"s": 27935,
"text": "R"
},
{
"code": "library(ggplot2)library(patchwork) data(iris) head(iris) gfg1 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_bar(stat = \"identity\") gfg2 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) +geom_point() gfg3 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) +geom_line() # Arranging the plots in different widthsgfg_comb_2 <- gfg1 / (gfg2 + gfg3) gfg_comb_2",
"e": 28432,
"s": 27937,
"text": null
},
{
"code": null,
"e": 28441,
"s": 28432,
"text": "Output :"
},
{
"code": null,
"e": 28470,
"s": 28441,
"text": "Different widths orientation"
},
{
"code": null,
"e": 28813,
"s": 28470,
"text": "The third combination of these plots would be arranging them in different heights in multiple rows and columns in the same graph window. The different height orientation arranges the plots in different lines according to heights. Basically, the first two plots are arranged horizontally and the last plot here is placed below the second plot."
},
{
"code": null,
"e": 28988,
"s": 28813,
"text": "We use the add(+) operator to arrange the first two plots horizontally. Then we use the slash (/) operator for the third plot to place it on a new line below the second plot."
},
{
"code": null,
"e": 29036,
"s": 28988,
"text": "Example: Arranging plots with different heights"
},
{
"code": null,
"e": 29038,
"s": 29036,
"text": "R"
},
{
"code": "library(ggplot2)library(patchwork) data(iris) head(iris) gfg1 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_bar(stat = \"identity\") gfg2 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) +geom_point() gfg3 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_line() # Arrangement of plots according to # different heightsgfg_comb_3 <- gfg1 + gfg2 / gfg3 gfg_comb_3",
"e": 29544,
"s": 29038,
"text": null
},
{
"code": null,
"e": 29553,
"s": 29544,
"text": "Output :"
},
{
"code": null,
"e": 29583,
"s": 29553,
"text": "Different heights orientation"
},
{
"code": null,
"e": 29786,
"s": 29583,
"text": "The last combination of plots is to arrange them horizontally. These plots are placed one below the other. We will use the slash(/) operator to place these plots in a new line, one below the other plot."
},
{
"code": null,
"e": 29822,
"s": 29786,
"text": "Example: Arranging plots vertically"
},
{
"code": null,
"e": 29824,
"s": 29822,
"text": "R"
},
{
"code": "library(ggplot2)library(patchwork) data(iris) head(iris) gfg1 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_bar(stat = \"identity\") gfg2 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_point() gfg3 <- ggplot(iris, aes(Sepal.Length, Petal.Length, color = Species)) + geom_line() # Combination of plots by arranging them # horizontallygfg_comb_4 <- gfg1 / gfg2 / gfg3 gfg_comb_4",
"e": 30259,
"s": 29824,
"text": null
},
{
"code": null,
"e": 30268,
"s": 30259,
"text": "Output :"
},
{
"code": null,
"e": 30291,
"s": 30268,
"text": "Horizontal orientation"
},
{
"code": null,
"e": 30298,
"s": 30291,
"text": "Picked"
},
{
"code": null,
"e": 30309,
"s": 30298,
"text": "R-Packages"
},
{
"code": null,
"e": 30320,
"s": 30309,
"text": "R Language"
},
{
"code": null,
"e": 30418,
"s": 30320,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30427,
"s": 30418,
"text": "Comments"
},
{
"code": null,
"e": 30440,
"s": 30427,
"text": "Old Comments"
},
{
"code": null,
"e": 30492,
"s": 30440,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 30530,
"s": 30492,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 30565,
"s": 30530,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 30623,
"s": 30565,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30672,
"s": 30623,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 30709,
"s": 30672,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 30759,
"s": 30709,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 30776,
"s": 30759,
"text": "R - if statement"
},
{
"code": null,
"e": 30819,
"s": 30776,
"text": "Replace Specific Characters in String in R"
}
] |
Extract key value from a nested object in JavaScript?
|
Let us first create a nested object −
var details = {
"teacherDetails":
{
"teacherName": ["John", "David"]
},
"subjectDetails":
{
"subjectName": ["MongoDB", "Java"]
}
}
Let us now extract the keys. Following is the code −
var details = {
"teacherDetails":
{
"teacherName": ["John", "David"]
},
"subjectDetails":
{
"subjectName": ["MongoDB", "Java"]
}
}
var objectName, nestedObject;
var name = "Java";
for(var key in details){
for(var secondKey in details[key]){
if(details[key][secondKey].includes(name)){
objectName = key;
nestedObject = secondKey;
}
}
}
console.log(objectName + ', ' + nestedObject);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo96.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo96.js
subjectDetails, subjectName
|
[
{
"code": null,
"e": 1100,
"s": 1062,
"text": "Let us first create a nested object −"
},
{
"code": null,
"e": 1261,
"s": 1100,
"text": "var details = {\n \"teacherDetails\":\n {\n \"teacherName\": [\"John\", \"David\"]\n },\n \"subjectDetails\":\n {\n \"subjectName\": [\"MongoDB\", \"Java\"]\n }\n}"
},
{
"code": null,
"e": 1314,
"s": 1261,
"text": "Let us now extract the keys. Following is the code −"
},
{
"code": null,
"e": 1762,
"s": 1314,
"text": "var details = {\n \"teacherDetails\":\n {\n \"teacherName\": [\"John\", \"David\"]\n },\n \"subjectDetails\":\n {\n \"subjectName\": [\"MongoDB\", \"Java\"]\n }\n}\nvar objectName, nestedObject;\nvar name = \"Java\";\nfor(var key in details){\n for(var secondKey in details[key]){\n if(details[key][secondKey].includes(name)){\n objectName = key;\n nestedObject = secondKey;\n }\n }\n}\nconsole.log(objectName + ', ' + nestedObject);"
},
{
"code": null,
"e": 1828,
"s": 1762,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1846,
"s": 1828,
"text": "node fileName.js."
},
{
"code": null,
"e": 1879,
"s": 1846,
"text": "Here, my file name is demo96.js."
},
{
"code": null,
"e": 1920,
"s": 1879,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1997,
"s": 1920,
"text": "PS C:\\Users\\Amit\\JavaScript-code> node demo96.js\nsubjectDetails, subjectName"
}
] |
Finding two closest elements to a specific number in an array using JavaScript
|
We are required to write a JavaScript function that takes in an array of sorted integers, arr, as the first argument and a target number, as the second argument.
Our function should return an array of exactly two numbers that exists in the array arr and are closest to target. The output array should also be sorted in increasing order.
For example, if the input to the function is
Input
const arr = [1, 2, 3, 4, 5];
const target = 3;
Output
const output = [2, 3];
Following is the code −
Live Demo
const arr = [1, 2, 3, 4, 5];
const target = 3;
const findClosest = (arr = [], target = 1) => {
const size = 2;
return arr.sort((a, b) => {
const distanceA = Math.abs(a - target)
const distanceB = Math.abs(b - target)
if (distanceA === distanceB) {
return a - b
}
return distanceA - distanceB
}).slice(0, size)
.sort((a, b) => a - b);
};
console.log(findClosest(arr, target));
[2, 3]
|
[
{
"code": null,
"e": 1224,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in an array of sorted integers, arr, as the first argument and a target number, as the second argument."
},
{
"code": null,
"e": 1399,
"s": 1224,
"text": "Our function should return an array of exactly two numbers that exists in the array arr and are closest to target. The output array should also be sorted in increasing order."
},
{
"code": null,
"e": 1444,
"s": 1399,
"text": "For example, if the input to the function is"
},
{
"code": null,
"e": 1450,
"s": 1444,
"text": "Input"
},
{
"code": null,
"e": 1497,
"s": 1450,
"text": "const arr = [1, 2, 3, 4, 5];\nconst target = 3;"
},
{
"code": null,
"e": 1504,
"s": 1497,
"text": "Output"
},
{
"code": null,
"e": 1527,
"s": 1504,
"text": "const output = [2, 3];"
},
{
"code": null,
"e": 1551,
"s": 1527,
"text": "Following is the code −"
},
{
"code": null,
"e": 1562,
"s": 1551,
"text": " Live Demo"
},
{
"code": null,
"e": 1989,
"s": 1562,
"text": "const arr = [1, 2, 3, 4, 5];\nconst target = 3;\nconst findClosest = (arr = [], target = 1) => {\n const size = 2;\n return arr.sort((a, b) => {\n const distanceA = Math.abs(a - target)\n const distanceB = Math.abs(b - target)\n if (distanceA === distanceB) {\n return a - b\n }\n return distanceA - distanceB\n }).slice(0, size)\n .sort((a, b) => a - b);\n};\nconsole.log(findClosest(arr, target));"
},
{
"code": null,
"e": 1996,
"s": 1989,
"text": "[2, 3]"
}
] |
How to create arrays dynamically in C#?
|
Dynamic arrays are growable arrays and have an advantage over static arrays. This is because the size of an array is fixed.
To create arrays dynamically in C#, use the ArrayList collection. It represents ordered collection of an object that can be indexed individually. It also allows dynamic memory allocation, adding, searching and sorting items in the list.
The following is an example showing how to create arrays in dynamically in C#.
Live Demo
using System;
using System.Collections;
namespace CollectionApplication {
class Program {
static void Main(string[] args) {
ArrayList al = new ArrayList();
al.Add(99);
al.Add(47);
al.Add(64);
Console.WriteLine("Count: {0}", al.Count);
Console.Write("List: ");
foreach (int i in al) {
Console.Write(i + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}
Count: 3
List: 99 47 64
|
[
{
"code": null,
"e": 1186,
"s": 1062,
"text": "Dynamic arrays are growable arrays and have an advantage over static arrays. This is because the size of an array is fixed."
},
{
"code": null,
"e": 1423,
"s": 1186,
"text": "To create arrays dynamically in C#, use the ArrayList collection. It represents ordered collection of an object that can be indexed individually. It also allows dynamic memory allocation, adding, searching and sorting items in the list."
},
{
"code": null,
"e": 1502,
"s": 1423,
"text": "The following is an example showing how to create arrays in dynamically in C#."
},
{
"code": null,
"e": 1513,
"s": 1502,
"text": " Live Demo"
},
{
"code": null,
"e": 1989,
"s": 1513,
"text": "using System;\nusing System.Collections;\nnamespace CollectionApplication {\n class Program {\n static void Main(string[] args) {\n ArrayList al = new ArrayList();\n al.Add(99);\n al.Add(47);\n al.Add(64);\n Console.WriteLine(\"Count: {0}\", al.Count);\n Console.Write(\"List: \");\n foreach (int i in al) {\n Console.Write(i + \" \");\n }\n Console.WriteLine();\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 2013,
"s": 1989,
"text": "Count: 3\nList: 99 47 64"
}
] |
Python - Itertools.zip_longest() - GeeksforGeeks
|
27 Feb, 2020
Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.
Iterators in Python is an object that can iterate like sequence data types such as list, tuple, str and so on.
Note: For more information, refer to Python Itertools
This iterator falls under the category of Terminating Iterators. It prints the values of iterables alternatively in sequence. If one of the iterables is printed fully, the remaining values are filled by the values assigned to fillvalue parameter.
Syntax:
zip_longest( iterable1, iterable2, fillval)
Example 1:
# Python code to demonstrate the working of # zip_longest() import itertools # using zip_longest() to combine two iterables. print ("The combined values of iterables is : ") print (*(itertools.zip_longest('GesoGes', 'ekfrek', fillvalue ='_' )))
Output:
The combined values of iterables is :
('G', 'e') ('e', 'k') ('s', 'f') ('o', 'r') ('G', 'e') ('e', 'k') ('s', '_')
Example 2:
from itertools import zip_longest x =[1, 2, 3, 4, 5, 6, 7]y =[8, 9, 10]z = list(zip_longest(x, y))print(z)
Output:
[(1, 8), (2, 9), (3, 10), (4, None), (5, None), (6, None), (7, None)]
Python-itertools
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?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 24536,
"s": 24292,
"text": "Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra."
},
{
"code": null,
"e": 24647,
"s": 24536,
"text": "Iterators in Python is an object that can iterate like sequence data types such as list, tuple, str and so on."
},
{
"code": null,
"e": 24701,
"s": 24647,
"text": "Note: For more information, refer to Python Itertools"
},
{
"code": null,
"e": 24948,
"s": 24701,
"text": "This iterator falls under the category of Terminating Iterators. It prints the values of iterables alternatively in sequence. If one of the iterables is printed fully, the remaining values are filled by the values assigned to fillvalue parameter."
},
{
"code": null,
"e": 24956,
"s": 24948,
"text": "Syntax:"
},
{
"code": null,
"e": 25000,
"s": 24956,
"text": "zip_longest( iterable1, iterable2, fillval)"
},
{
"code": null,
"e": 25011,
"s": 25000,
"text": "Example 1:"
},
{
"code": "# Python code to demonstrate the working of # zip_longest() import itertools # using zip_longest() to combine two iterables. print (\"The combined values of iterables is : \") print (*(itertools.zip_longest('GesoGes', 'ekfrek', fillvalue ='_' ))) ",
"e": 25281,
"s": 25011,
"text": null
},
{
"code": null,
"e": 25289,
"s": 25281,
"text": "Output:"
},
{
"code": null,
"e": 25406,
"s": 25289,
"text": "The combined values of iterables is : \n('G', 'e') ('e', 'k') ('s', 'f') ('o', 'r') ('G', 'e') ('e', 'k') ('s', '_')"
},
{
"code": null,
"e": 25417,
"s": 25406,
"text": "Example 2:"
},
{
"code": "from itertools import zip_longest x =[1, 2, 3, 4, 5, 6, 7]y =[8, 9, 10]z = list(zip_longest(x, y))print(z)",
"e": 25527,
"s": 25417,
"text": null
},
{
"code": null,
"e": 25535,
"s": 25527,
"text": "Output:"
},
{
"code": null,
"e": 25605,
"s": 25535,
"text": "[(1, 8), (2, 9), (3, 10), (4, None), (5, None), (6, None), (7, None)]"
},
{
"code": null,
"e": 25622,
"s": 25605,
"text": "Python-itertools"
},
{
"code": null,
"e": 25629,
"s": 25622,
"text": "Python"
},
{
"code": null,
"e": 25727,
"s": 25629,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25759,
"s": 25727,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25801,
"s": 25759,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25857,
"s": 25801,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25899,
"s": 25857,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25930,
"s": 25899,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25985,
"s": 25930,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26007,
"s": 25985,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26046,
"s": 26007,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26075,
"s": 26046,
"text": "Create a directory in Python"
}
] |
MySQL command for display current configuration variables?
|
You can use SHOW VARIABLES command to display current configuration variables. The syntax is as follows −
SHOW VARIABLES;
If you want any specific information, then implement the LIKE operator. The syntax is as follows −
SHOW VARIABLES LIKE ‘%AnySpecificInformation%’;
Now we will implement the above syntax −
mysql> show variables like '%variable%';
The following is the output −
+--------------------------------+------------------------------------------------------------------------------------------+
| Variable_name | Value |
+--------------------------------+------------------------------------------------------------------------------------------+
| session_track_system_variables | time_zone,autocommit,character_set_client,character_set_results,character_set_connection |
+--------------------------------+------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)
You can also get the host information. The query is as follows −
mysql> show variables like '%host%';
The following is the output −
+-------------------------------+-----------------+
| Variable_name | Value |
+-------------------------------+-----------------+
| host_cache_size | 279 |
| hostname | DESKTOP-QN2RB3H |
| performance_schema_hosts_size | -1 |
| report_host | |
+-------------------------------+-----------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1168,
"s": 1062,
"text": "You can use SHOW VARIABLES command to display current configuration variables. The syntax is as follows −"
},
{
"code": null,
"e": 1184,
"s": 1168,
"text": "SHOW VARIABLES;"
},
{
"code": null,
"e": 1283,
"s": 1184,
"text": "If you want any specific information, then implement the LIKE operator. The syntax is as follows −"
},
{
"code": null,
"e": 1331,
"s": 1283,
"text": "SHOW VARIABLES LIKE ‘%AnySpecificInformation%’;"
},
{
"code": null,
"e": 1372,
"s": 1331,
"text": "Now we will implement the above syntax −"
},
{
"code": null,
"e": 1413,
"s": 1372,
"text": "mysql> show variables like '%variable%';"
},
{
"code": null,
"e": 1443,
"s": 1413,
"text": "The following is the output −"
},
{
"code": null,
"e": 2097,
"s": 1443,
"text": "+--------------------------------+------------------------------------------------------------------------------------------+\n| Variable_name | Value |\n+--------------------------------+------------------------------------------------------------------------------------------+\n| session_track_system_variables | time_zone,autocommit,character_set_client,character_set_results,character_set_connection |\n+--------------------------------+------------------------------------------------------------------------------------------+\n1 row in set (0.01 sec)"
},
{
"code": null,
"e": 2162,
"s": 2097,
"text": "You can also get the host information. The query is as follows −"
},
{
"code": null,
"e": 2199,
"s": 2162,
"text": "mysql> show variables like '%host%';"
},
{
"code": null,
"e": 2229,
"s": 2199,
"text": "The following is the output −"
},
{
"code": null,
"e": 2670,
"s": 2229,
"text": "+-------------------------------+-----------------+\n| Variable_name | Value |\n+-------------------------------+-----------------+\n| host_cache_size | 279 |\n| hostname | DESKTOP-QN2RB3H |\n| performance_schema_hosts_size | -1 |\n| report_host | |\n+-------------------------------+-----------------+\n4 rows in set (0.00 sec)"
}
] |
Multiplicative Congruence method for generating Pseudo Random Numbers - GeeksforGeeks
|
08 Feb, 2022
Multiplicative Congruential Method (Lehmer Method) is a type of linear congruential generator for generating pseudorandom numbers in a specific range. This method can be defined as:
where, X, the sequence of pseudo-random numbersm ( > 0), the modulusa (0, m), the multiplierX0 [0, m), initial value of the sequence – termed as seed
m, a, and X0 should be chosen appropriately to get a period almost equal to m.
Approach:
Choose the seed value ( X0 ), modulus parameter ( m ), and multiplier term ( a ).
Initialize the required amount of random numbers to generate (say, an integer variable noOfRandomNums).
Define storage to keep the generated random numbers (here, the vector is considered) of size noOfRandomNums.
Initialize the 0th index of the vector with the seed value.
For the rest of the indexes follow the Multiplicative Congruential Method to generate the random numbers.
randomNums[i] = (randomNums[i – 1] * a) % m
Finally, return the random numbers.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the// above approach#include <bits/stdc++.h>using namespace std; // Function to generate random numbersvoid multiplicativeCongruentialMethod( int Xo, int m, int a, vector<int>& randomNums, int noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for (int i = 1; i < noOfRandomNums; i++) { // Follow the multiplicative // congruential method randomNums[i] = (randomNums[i - 1] * a) % m; }} // Driver Codeint main(){ int Xo = 3; // seed value int m = 15; // modulus parameter int a = 7; // multiplier term // Number of Random numbers // to be generated int noOfRandomNums = 10; // To store random numbers vector<int> randomNums(noOfRandomNums); // Function Call multiplicativeCongruentialMethod( Xo, m, a, randomNums, noOfRandomNums); // Print the generated random numbers for (int i = 0; i < noOfRandomNums; i++) { cout << randomNums[i] << " "; } return 0;}
// Java implementation of the above approachimport java.util.*; class GFG{ // Function to generate random numbersstatic void multiplicativeCongruentialMethod( int Xo, int m, int a, int[] randomNums, int noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for(int i = 1; i < noOfRandomNums; i++) { // Follow the multiplicative // congruential method randomNums[i] = (randomNums[i - 1] * a) % m; }} // Driver codepublic static void main(String[] args){ // Seed value int Xo = 3; // Modulus parameter int m = 15; // Multiplier term int a = 7; // Number of Random numbers // to be generated int noOfRandomNums = 10; // To store random numbers int[] randomNums = new int[noOfRandomNums]; // Function Call multiplicativeCongruentialMethod(Xo, m, a, randomNums, noOfRandomNums); // Print the generated random numbers for(int i = 0; i < noOfRandomNums; i++) { System.out.print(randomNums[i] + " "); }}} // This code is contributed by offbeat
# Python3 implementation of the# above approach # Function to generate random numbersdef multiplicativeCongruentialMethod(Xo, m, a, randomNums, noOfRandomNums): # Initialize the seed state randomNums[0] = Xo # Traverse to generate required # numbers of random numbers for i in range(1, noOfRandomNums): # Follow the linear congruential method randomNums[i] = (randomNums[i - 1] * a) % m # Driver Codeif __name__ == '__main__': # Seed value Xo = 3 # Modulus parameter m = 15 # Multiplier term a = 7 # Number of Random numbers # to be generated noOfRandomNums = 10 # To store random numbers randomNums = [0] * (noOfRandomNums) # Function Call multiplicativeCongruentialMethod(Xo, m, a, randomNums, noOfRandomNums) # Print the generated random numbers for i in randomNums: print(i, end = " ") # This code is contributed by mohit kumar 29
// C# implementation of the above approachusing System; class GFG{ // Function to generate random numbersstatic void multiplicativeCongruentialMethod( int Xo, int m, int a, int[] randomNums, int noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for(int i = 1; i < noOfRandomNums; i++) { // Follow the multiplicative // congruential method randomNums[i] = (randomNums[i - 1] * a) % m; }} // Driver codepublic static void Main(String[] args){ // Seed value int Xo = 3; // Modulus parameter int m = 15; // Multiplier term int a = 7; // Number of Random numbers // to be generated int noOfRandomNums = 10; // To store random numbers int[] randomNums = new int[noOfRandomNums]; // Function call multiplicativeCongruentialMethod(Xo, m, a, randomNums, noOfRandomNums); // Print the generated random numbers for(int i = 0; i < noOfRandomNums; i++) { Console.Write(randomNums[i] + " "); }}} // This code is contributed by sapnasingh4991
<script> // Javascript program to implement// the above approach // Function to generate random numbersfunction multiplicativeCongruentialMethod( Xo, m, a, randomNums, noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for(let i = 1; i < noOfRandomNums; i++) { // Follow the multiplicative // congruential method randomNums[i] = (randomNums[i - 1] * a) % m; }} // Driver Code // Seed value let Xo = 3; // Modulus parameter let m = 15; // Multiplier term let a = 7; // Number of Random numbers // to be generated let noOfRandomNums = 10; // To store random numbers let randomNums = new Array(noOfRandomNums).fill(0); // Function Call multiplicativeCongruentialMethod(Xo, m, a, randomNums, noOfRandomNums); // Print the generated random numbers for(let i = 0; i < noOfRandomNums; i++) { document.write(randomNums[i] + " "); } </script>
3 6 12 9 3 6 12 9 3 6
Time Complexity: O(N), where N is the total number of random numbers we need to generate.Auxiliary Space: O(1)The literal meaning of pseudo is false. These random numbers are called pseudo because some known arithmetic procedure is utilized to generate. Even the generated sequence forms a pattern hence the generated number seems to be random but may not be truly random.
mohit kumar 29
offbeat
sapnasingh4991
avijitmondal1998
pankajsharmagfg
surinderdawra388
Algorithms
Engineering Mathematics
Mathematical
Mathematical
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
How to write a Pseudo Code?
Relationship between number of nodes and height of binary tree
Inequalities in LaTeX
Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph
Arrow Symbols in LaTeX
Newton's Divided Difference Interpolation Formula
|
[
{
"code": null,
"e": 25126,
"s": 25098,
"text": "\n08 Feb, 2022"
},
{
"code": null,
"e": 25309,
"s": 25126,
"text": "Multiplicative Congruential Method (Lehmer Method) is a type of linear congruential generator for generating pseudorandom numbers in a specific range. This method can be defined as: "
},
{
"code": null,
"e": 25466,
"s": 25316,
"text": "where, X, the sequence of pseudo-random numbersm ( > 0), the modulusa (0, m), the multiplierX0 [0, m), initial value of the sequence – termed as seed"
},
{
"code": null,
"e": 25547,
"s": 25468,
"text": "m, a, and X0 should be chosen appropriately to get a period almost equal to m."
},
{
"code": null,
"e": 25560,
"s": 25549,
"text": "Approach: "
},
{
"code": null,
"e": 25642,
"s": 25560,
"text": "Choose the seed value ( X0 ), modulus parameter ( m ), and multiplier term ( a )."
},
{
"code": null,
"e": 25746,
"s": 25642,
"text": "Initialize the required amount of random numbers to generate (say, an integer variable noOfRandomNums)."
},
{
"code": null,
"e": 25855,
"s": 25746,
"text": "Define storage to keep the generated random numbers (here, the vector is considered) of size noOfRandomNums."
},
{
"code": null,
"e": 25915,
"s": 25855,
"text": "Initialize the 0th index of the vector with the seed value."
},
{
"code": null,
"e": 26021,
"s": 25915,
"text": "For the rest of the indexes follow the Multiplicative Congruential Method to generate the random numbers."
},
{
"code": null,
"e": 26066,
"s": 26021,
"text": "randomNums[i] = (randomNums[i – 1] * a) % m "
},
{
"code": null,
"e": 26152,
"s": 26066,
"text": "Finally, return the random numbers.Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26156,
"s": 26152,
"text": "C++"
},
{
"code": null,
"e": 26161,
"s": 26156,
"text": "Java"
},
{
"code": null,
"e": 26169,
"s": 26161,
"text": "Python3"
},
{
"code": null,
"e": 26172,
"s": 26169,
"text": "C#"
},
{
"code": null,
"e": 26183,
"s": 26172,
"text": "Javascript"
},
{
"code": "// C++ implementation of the// above approach#include <bits/stdc++.h>using namespace std; // Function to generate random numbersvoid multiplicativeCongruentialMethod( int Xo, int m, int a, vector<int>& randomNums, int noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for (int i = 1; i < noOfRandomNums; i++) { // Follow the multiplicative // congruential method randomNums[i] = (randomNums[i - 1] * a) % m; }} // Driver Codeint main(){ int Xo = 3; // seed value int m = 15; // modulus parameter int a = 7; // multiplier term // Number of Random numbers // to be generated int noOfRandomNums = 10; // To store random numbers vector<int> randomNums(noOfRandomNums); // Function Call multiplicativeCongruentialMethod( Xo, m, a, randomNums, noOfRandomNums); // Print the generated random numbers for (int i = 0; i < noOfRandomNums; i++) { cout << randomNums[i] << \" \"; } return 0;}",
"e": 27269,
"s": 26183,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.util.*; class GFG{ // Function to generate random numbersstatic void multiplicativeCongruentialMethod( int Xo, int m, int a, int[] randomNums, int noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for(int i = 1; i < noOfRandomNums; i++) { // Follow the multiplicative // congruential method randomNums[i] = (randomNums[i - 1] * a) % m; }} // Driver codepublic static void main(String[] args){ // Seed value int Xo = 3; // Modulus parameter int m = 15; // Multiplier term int a = 7; // Number of Random numbers // to be generated int noOfRandomNums = 10; // To store random numbers int[] randomNums = new int[noOfRandomNums]; // Function Call multiplicativeCongruentialMethod(Xo, m, a, randomNums, noOfRandomNums); // Print the generated random numbers for(int i = 0; i < noOfRandomNums; i++) { System.out.print(randomNums[i] + \" \"); }}} // This code is contributed by offbeat",
"e": 28514,
"s": 27269,
"text": null
},
{
"code": "# Python3 implementation of the# above approach # Function to generate random numbersdef multiplicativeCongruentialMethod(Xo, m, a, randomNums, noOfRandomNums): # Initialize the seed state randomNums[0] = Xo # Traverse to generate required # numbers of random numbers for i in range(1, noOfRandomNums): # Follow the linear congruential method randomNums[i] = (randomNums[i - 1] * a) % m # Driver Codeif __name__ == '__main__': # Seed value Xo = 3 # Modulus parameter m = 15 # Multiplier term a = 7 # Number of Random numbers # to be generated noOfRandomNums = 10 # To store random numbers randomNums = [0] * (noOfRandomNums) # Function Call multiplicativeCongruentialMethod(Xo, m, a, randomNums, noOfRandomNums) # Print the generated random numbers for i in randomNums: print(i, end = \" \") # This code is contributed by mohit kumar 29",
"e": 29604,
"s": 28514,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to generate random numbersstatic void multiplicativeCongruentialMethod( int Xo, int m, int a, int[] randomNums, int noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for(int i = 1; i < noOfRandomNums; i++) { // Follow the multiplicative // congruential method randomNums[i] = (randomNums[i - 1] * a) % m; }} // Driver codepublic static void Main(String[] args){ // Seed value int Xo = 3; // Modulus parameter int m = 15; // Multiplier term int a = 7; // Number of Random numbers // to be generated int noOfRandomNums = 10; // To store random numbers int[] randomNums = new int[noOfRandomNums]; // Function call multiplicativeCongruentialMethod(Xo, m, a, randomNums, noOfRandomNums); // Print the generated random numbers for(int i = 0; i < noOfRandomNums; i++) { Console.Write(randomNums[i] + \" \"); }}} // This code is contributed by sapnasingh4991",
"e": 30845,
"s": 29604,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Function to generate random numbersfunction multiplicativeCongruentialMethod( Xo, m, a, randomNums, noOfRandomNums){ // Initialize the seed state randomNums[0] = Xo; // Traverse to generate required // numbers of random numbers for(let i = 1; i < noOfRandomNums; i++) { // Follow the multiplicative // congruential method randomNums[i] = (randomNums[i - 1] * a) % m; }} // Driver Code // Seed value let Xo = 3; // Modulus parameter let m = 15; // Multiplier term let a = 7; // Number of Random numbers // to be generated let noOfRandomNums = 10; // To store random numbers let randomNums = new Array(noOfRandomNums).fill(0); // Function Call multiplicativeCongruentialMethod(Xo, m, a, randomNums, noOfRandomNums); // Print the generated random numbers for(let i = 0; i < noOfRandomNums; i++) { document.write(randomNums[i] + \" \"); } </script>",
"e": 32016,
"s": 30845,
"text": null
},
{
"code": null,
"e": 32038,
"s": 32016,
"text": "3 6 12 9 3 6 12 9 3 6"
},
{
"code": null,
"e": 32414,
"s": 32040,
"text": "Time Complexity: O(N), where N is the total number of random numbers we need to generate.Auxiliary Space: O(1)The literal meaning of pseudo is false. These random numbers are called pseudo because some known arithmetic procedure is utilized to generate. Even the generated sequence forms a pattern hence the generated number seems to be random but may not be truly random. "
},
{
"code": null,
"e": 32429,
"s": 32414,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 32437,
"s": 32429,
"text": "offbeat"
},
{
"code": null,
"e": 32452,
"s": 32437,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 32469,
"s": 32452,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 32485,
"s": 32469,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 32502,
"s": 32485,
"text": "surinderdawra388"
},
{
"code": null,
"e": 32513,
"s": 32502,
"text": "Algorithms"
},
{
"code": null,
"e": 32537,
"s": 32513,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 32550,
"s": 32537,
"text": "Mathematical"
},
{
"code": null,
"e": 32563,
"s": 32550,
"text": "Mathematical"
},
{
"code": null,
"e": 32574,
"s": 32563,
"text": "Algorithms"
},
{
"code": null,
"e": 32672,
"s": 32574,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32721,
"s": 32672,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 32746,
"s": 32721,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32797,
"s": 32746,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 32824,
"s": 32797,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 32852,
"s": 32824,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 32915,
"s": 32852,
"text": "Relationship between number of nodes and height of binary tree"
},
{
"code": null,
"e": 32937,
"s": 32915,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 33002,
"s": 32937,
"text": "Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph"
},
{
"code": null,
"e": 33025,
"s": 33002,
"text": "Arrow Symbols in LaTeX"
}
] |
Batch Script - Remove All Spaces
|
This is used to remove all spaces in a string via substitution.
@echo off
set str = This string has a lot of spaces
echo %str%
set str=%str:=%
echo %str%
The key thing to note about the above program is, the : = operator is used to remove all spaces from a string.
The above command produces the following output.
This string has a lot of spaces
Thisstringhasalotofspaces
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2233,
"s": 2169,
"text": "This is used to remove all spaces in a string via substitution."
},
{
"code": null,
"e": 2336,
"s": 2233,
"text": "@echo off \nset str = This string has a lot of spaces \necho %str% \n\nset str=%str:=% \necho %str%"
},
{
"code": null,
"e": 2447,
"s": 2336,
"text": "The key thing to note about the above program is, the : = operator is used to remove all spaces from a string."
},
{
"code": null,
"e": 2496,
"s": 2447,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 2563,
"s": 2496,
"text": "This string has a lot of spaces\nThisstringhasalotofspaces\n"
},
{
"code": null,
"e": 2570,
"s": 2563,
"text": " Print"
},
{
"code": null,
"e": 2581,
"s": 2570,
"text": " Add Notes"
}
] |
Puppet - Manifest Files
|
In Puppet, all the programs which are written using Ruby programming language and saved with an extension of .pp are called manifests. In general terms, all Puppet programs which are built with an intension of creating or managing any target host machine is called a manifest. All the programs written in Puppet follow Puppet coding style.
The core of Puppet is the way resources are declared and how these resources are representing their state. In any manifest, the user can have a collection of different kind of resources which are grouped together using class and definition.
In some cases, Puppet manifest can even have a conditional statement in order to achieve a desired state. However, ultimately it all comes down to make sure that all the resources are defined and used in the right way and the defined manifest when applied after getting converted to a catalog is capable of performing the task for which it was designed.
Puppet manifest consists of the following components −
Files (these are plain files where Puppet has nothing to do with them, just to pick them up and place them in the target location)
Files (these are plain files where Puppet has nothing to do with them, just to pick them up and place them in the target location)
Resources
Resources
Templates (these can be used to construct configuration files on the node).
Templates (these can be used to construct configuration files on the node).
Nodes (all the definition related to a client node is defined here)
Nodes (all the definition related to a client node is defined here)
Classes
Classes
In Puppet, all manifest files use Ruby as their encoding language and get saved with .pp extension.
In Puppet, all manifest files use Ruby as their encoding language and get saved with .pp extension.
"Import" statement in many manifest are used for loading files when Puppet starts.
"Import" statement in many manifest are used for loading files when Puppet starts.
In order to import all files contained in a directory, you can use the import statement in another way like import 'clients/*'. This will import all .pp files inside that directory.
In order to import all files contained in a directory, you can use the import statement in another way like import 'clients/*'. This will import all .pp files inside that directory.
While writing a manifest, the user can define a new variable or use an existing variable at any point in a manifest. Puppet supports different kind of variables but few of them are frequently used such as strings and array of string. Apart from them, other formats are also supported.
$package = "vim"
package { $package:
ensure => "installed"
}
Loops are used when one wishes to go through multiple iterations on a same set of code till a defined condition is met. They are also used to do repetitive tasks with different set of values. Creating 10 tasks for 10 different things. One can create a single task and use a loop to repeat the task with different packages one wants to install.
Most commonly an array is used to repeat a test with different values.
$packages = ['vim', 'git', 'curl']
package { $packages:
ensure => "installed"
}
Puppet supports most of the conditional structure which can be found in traditional programming languages. Condition can be used to dynamically define whether to perform a particular task or a set of code should get executed. Like if/else and case statements. Additionally, conditions like execute will also support attributes that works like condition, but only accepts a command output as a condition.
if $OperatingSystem != 'Linux' {
warning('This manifest is not supported on this other OS apart from linux.')
} else {
notify { 'the OS is Linux. We are good to go!': }
}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2513,
"s": 2173,
"text": "In Puppet, all the programs which are written using Ruby programming language and saved with an extension of .pp are called manifests. In general terms, all Puppet programs which are built with an intension of creating or managing any target host machine is called a manifest. All the programs written in Puppet follow Puppet coding style."
},
{
"code": null,
"e": 2754,
"s": 2513,
"text": "The core of Puppet is the way resources are declared and how these resources are representing their state. In any manifest, the user can have a collection of different kind of resources which are grouped together using class and definition."
},
{
"code": null,
"e": 3108,
"s": 2754,
"text": "In some cases, Puppet manifest can even have a conditional statement in order to achieve a desired state. However, ultimately it all comes down to make sure that all the resources are defined and used in the right way and the defined manifest when applied after getting converted to a catalog is capable of performing the task for which it was designed."
},
{
"code": null,
"e": 3163,
"s": 3108,
"text": "Puppet manifest consists of the following components −"
},
{
"code": null,
"e": 3294,
"s": 3163,
"text": "Files (these are plain files where Puppet has nothing to do with them, just to pick them up and place them in the target location)"
},
{
"code": null,
"e": 3425,
"s": 3294,
"text": "Files (these are plain files where Puppet has nothing to do with them, just to pick them up and place them in the target location)"
},
{
"code": null,
"e": 3435,
"s": 3425,
"text": "Resources"
},
{
"code": null,
"e": 3445,
"s": 3435,
"text": "Resources"
},
{
"code": null,
"e": 3521,
"s": 3445,
"text": "Templates (these can be used to construct configuration files on the node)."
},
{
"code": null,
"e": 3597,
"s": 3521,
"text": "Templates (these can be used to construct configuration files on the node)."
},
{
"code": null,
"e": 3665,
"s": 3597,
"text": "Nodes (all the definition related to a client node is defined here)"
},
{
"code": null,
"e": 3733,
"s": 3665,
"text": "Nodes (all the definition related to a client node is defined here)"
},
{
"code": null,
"e": 3741,
"s": 3733,
"text": "Classes"
},
{
"code": null,
"e": 3749,
"s": 3741,
"text": "Classes"
},
{
"code": null,
"e": 3849,
"s": 3749,
"text": "In Puppet, all manifest files use Ruby as their encoding language and get saved with .pp extension."
},
{
"code": null,
"e": 3949,
"s": 3849,
"text": "In Puppet, all manifest files use Ruby as their encoding language and get saved with .pp extension."
},
{
"code": null,
"e": 4032,
"s": 3949,
"text": "\"Import\" statement in many manifest are used for loading files when Puppet starts."
},
{
"code": null,
"e": 4115,
"s": 4032,
"text": "\"Import\" statement in many manifest are used for loading files when Puppet starts."
},
{
"code": null,
"e": 4297,
"s": 4115,
"text": "In order to import all files contained in a directory, you can use the import statement in another way like import 'clients/*'. This will import all .pp files inside that directory."
},
{
"code": null,
"e": 4479,
"s": 4297,
"text": "In order to import all files contained in a directory, you can use the import statement in another way like import 'clients/*'. This will import all .pp files inside that directory."
},
{
"code": null,
"e": 4764,
"s": 4479,
"text": "While writing a manifest, the user can define a new variable or use an existing variable at any point in a manifest. Puppet supports different kind of variables but few of them are frequently used such as strings and array of string. Apart from them, other formats are also supported."
},
{
"code": null,
"e": 4834,
"s": 4764,
"text": "$package = \"vim\" \n\npackage { $package: \n ensure => \"installed\" \n}"
},
{
"code": null,
"e": 5178,
"s": 4834,
"text": "Loops are used when one wishes to go through multiple iterations on a same set of code till a defined condition is met. They are also used to do repetitive tasks with different set of values. Creating 10 tasks for 10 different things. One can create a single task and use a loop to repeat the task with different packages one wants to install."
},
{
"code": null,
"e": 5249,
"s": 5178,
"text": "Most commonly an array is used to repeat a test with different values."
},
{
"code": null,
"e": 5337,
"s": 5249,
"text": "$packages = ['vim', 'git', 'curl'] \n\npackage { $packages: \n ensure => \"installed\" \n}"
},
{
"code": null,
"e": 5741,
"s": 5337,
"text": "Puppet supports most of the conditional structure which can be found in traditional programming languages. Condition can be used to dynamically define whether to perform a particular task or a set of code should get executed. Like if/else and case statements. Additionally, conditions like execute will also support attributes that works like condition, but only accepts a command output as a condition."
},
{
"code": null,
"e": 5922,
"s": 5741,
"text": "if $OperatingSystem != 'Linux' { \n warning('This manifest is not supported on this other OS apart from linux.') \n} else { \n notify { 'the OS is Linux. We are good to go!': }\n} "
},
{
"code": null,
"e": 5929,
"s": 5922,
"text": " Print"
},
{
"code": null,
"e": 5940,
"s": 5929,
"text": " Add Notes"
}
] |
From Data Analyst to Data Storyteller in 3 Steps | by Max Hilsdorf | Towards Data Science
|
Why you need to learn this
It is widely known that various forms of data preparation make up more than 80% of a data scientists job. This is a valuable piece of information given that new people getting into the field seem to think it is all about expensive computers and complex deep learning models. You might be able to impress your coworkers in the data team with those things, but your managers and customers generally don’t care much about technical details. However, it is crucial to get your work noticed and understood correctly by exactly these people. This is why you need to learn data visualization!
To some, data visualization is just bothering with annoying stakeholders. This is an unproductive way of thinking, and it is also wrong! Think about it this way instead:
If you can’t visualize your results, you don’t know your results.
Everyone and their grandmother can create some one-liner scatterplot and call it data visualization. It takes a passionate and skilled data scientist, however, to transform basic visualizations into a story, that your managers and customers will not only understand, but be excited about and inspired by. In this article, I am going to help you take your skillset to the next level! All it takes is to follow a simple three step procedure that you can apply to every single one of your visualizations. Your managers, customers and future employers will be thankful for your effort to read this story!
What does a bad visualization look like?
Try to imagine some of your first matplotlib visualizations. Chances are, they might look like Figure 1. What I tried to do here is visualize the popularity of various musical genres in different age groups.
This lineplot is produced by the following code:
fig, ax = plt.subplots(figsize =(10,6))# Loop through the genresfor i, g in enumerate(genres): # Define x and y x = np.arange(7) y = music_pref_2019[g] # Plot lines ax.plot(x, y, label = g) # X axis ax.set_xticks(x) ax.set_xticklabels([“14–19”, “20–29”, “30–39”, “40–49”, “50–59”, “60–69”, “70+”]) ax.legend()plt.show()
There’s a lot of things wrong with this plot. We are going to improve it in these three steps:
Add InformationReduce InformationEmphasize Information
Add Information
Reduce Information
Emphasize Information
The signal/noise ratio describes the amount of valuable information compared to the amount of unnecessary information. In any creative product (articles, visualizations, musical compositions), we should aim to maximize this ratio.
We can improve the signal/noise ratio by adding useful information, but also by removing useless information. In an ideal visualization, all of the important information arepresent and emphasized while everything that does not add any real value is removed.
Let’s brainstorm what the plot in Figure 1 is missing. Here are the observations I made. We need to add:
a titleaxis labelsticks and ticklabels for the y-axisa way to read single values for different age groups directly from the lines
a title
axis labels
ticks and ticklabels for the y-axis
a way to read single values for different age groups directly from the lines
We can do this by including the following lines of code to our full visualization code:
# 1ax.set_title("Popularity of Different Genres by Age Groups")# 2ax.set_xlabel("Age")ax.set_ylabel("Amount of people with preference (%)")# 3ax.set_ylim(0,1)ax.set_yticklabels(int(i*100) for i in ax.get_yticks()) # Turns the # decimals into percent values# 4ax.scatter(x, y) # adds points at every tick of x
On top of this, I selected different colors for our lines. The matplotlib standard colors are hard to deal with for colorblind people (like myself). Therefore, I have used only colors from the tableau colorblind palette in the plot below.
We can clearly see an improvement from Figure 1 to Figure 2 in terms of the amount of information given! Through adding relevant information, we have improved our signal/noise ratio. We need to protect the relevant information at all costs! It would be easy to just leave it at that since everything we need is included in the visualization in some form. However, this is where the magic can happen. Step 2 and 3 are going to keep all the relevant information, but use certain techniques to make the whole chart more clear and easier to read.
Reducing information doesn’t always mean actually deleting information like labels, legends or ticks. Sometimes, it just means reducing the extent to which the information is an obstacle to the reader. Here are some ideas on what to do with this plot:
We can:
remove ticksremove spinesremove the big legend and write the labels on each line directlyleave only 4 ticks on the y axisremove the x and y labels and indicate them on the last tick directly
remove ticks
remove spines
remove the big legend and write the labels on each line directly
leave only 4 ticks on the y axis
remove the x and y labels and indicate them on the last tick directly
# 1ax.tick_params(bottom = False, top = False, left = False, right = False)# 2for key, spine in ax.spines.items(): spine.set_visible(False)# 3ax.text(0,.875, "Rock/Pop", rotation = -1.5)ax.text(0,.144, "Classical", rotation = 16)ax.text(0,.395, "Hardrock/Metal", rotation = 4.5)ax.text(0,.679, "Hip Hop/Rap", rotation = -31)ax.text(0,.592, "Techno/House", rotation = -15)# 4ax.set_yticks([0,0.25,0.5,0.75,1])# 5ax.set_xticklabels(["14-19", "20-29", "30-39", "40-49", "50-59", "60-69", "70+ years"])ax.set_yticklabels([0, 25, 50, 75, "100%"])
Now that we have added all the relevant information and removed everything that is not, we can still optimize our visualization. Maybe there is something we can do to emphasize certain aspects. Here is a couple of ideas for this specific plot:
Change font, fontsize, and weight of the titleEmphasize the continuous quality of the data
Change font, fontsize, and weight of the title
Emphasize the continuous quality of the data
To change the title font, we can create a font_dict and call it in the ax.set_title() function.
title_font= {"family" : "Cambria", "size" : 16, "color" : "black", "weight" : "roman"}# LATER IN THE CODEax.set_title("Popularity of Different Genres by Age Groups", fontdict = title_font)
To emphasize the continuous quality of the data, we need to get rid of the category label and use the mean age instead. For classed variables, we don’t know what the mean age of participants in any age category was. We can use the rounded mean of the possible ages in the category, however. Our mean age m for any category c would be:
m = int(c_start + c_end)
Now, we can use these mean ages as your y axis labels:
ax.set_xticklabels(["17", "25", "35", "45", "55", "65", "70+ years"])
To further emphasize the continuous features of our data, we can decrease the dot sizes and transparencies while increasing line sizes:
ax.scatter(x, y, c = cb_colors[i], label = mapping_dict[g], marker = ".", linewidth = 3, alpha = 0.8)ax.plot(x,y, c = cb_colors[i], linestyle = "-", linewidth = 2.5, alpha = 0.8) # lowering alpha is also good here, as it gives more attention to the annotations and labels
I have also increased the annotation sizes to 12pt.
This will give us our final output (Figure 4).
Here, we can clearly see that the lines start to make sense. While this is not exactly what the data tells us (it’s categorical after all), our mean ages allow us to tell an actual story. With this visualization, we can predict how preferences change with age, not only compare how they are different between ages. The dots still allow us to target a specific age and see the exact values for it, while also revealing that the connections between dots are linear predictions, not actual data.
We could also go the other route and emphasize the categorical features of our data. Figure 5 is an example of that approach.
Here, I emphasized the points and added a grid in the background. I also kept the original category labels.
In this article, I showed you how you can use a three-step formula to improve your matplotlib visualizations. One key thing to take home from this post is that the magic lies not within the information you add, but within the information you remove or transform. Look at Figure 1 and compare it to our final results. Then check your own recent visualizations and see if you can make use of the three-step formula to make them even better!
Thanks for reading!
|
[
{
"code": null,
"e": 199,
"s": 172,
"text": "Why you need to learn this"
},
{
"code": null,
"e": 785,
"s": 199,
"text": "It is widely known that various forms of data preparation make up more than 80% of a data scientists job. This is a valuable piece of information given that new people getting into the field seem to think it is all about expensive computers and complex deep learning models. You might be able to impress your coworkers in the data team with those things, but your managers and customers generally don’t care much about technical details. However, it is crucial to get your work noticed and understood correctly by exactly these people. This is why you need to learn data visualization!"
},
{
"code": null,
"e": 955,
"s": 785,
"text": "To some, data visualization is just bothering with annoying stakeholders. This is an unproductive way of thinking, and it is also wrong! Think about it this way instead:"
},
{
"code": null,
"e": 1021,
"s": 955,
"text": "If you can’t visualize your results, you don’t know your results."
},
{
"code": null,
"e": 1622,
"s": 1021,
"text": "Everyone and their grandmother can create some one-liner scatterplot and call it data visualization. It takes a passionate and skilled data scientist, however, to transform basic visualizations into a story, that your managers and customers will not only understand, but be excited about and inspired by. In this article, I am going to help you take your skillset to the next level! All it takes is to follow a simple three step procedure that you can apply to every single one of your visualizations. Your managers, customers and future employers will be thankful for your effort to read this story!"
},
{
"code": null,
"e": 1663,
"s": 1622,
"text": "What does a bad visualization look like?"
},
{
"code": null,
"e": 1871,
"s": 1663,
"text": "Try to imagine some of your first matplotlib visualizations. Chances are, they might look like Figure 1. What I tried to do here is visualize the popularity of various musical genres in different age groups."
},
{
"code": null,
"e": 1920,
"s": 1871,
"text": "This lineplot is produced by the following code:"
},
{
"code": null,
"e": 2243,
"s": 1920,
"text": "fig, ax = plt.subplots(figsize =(10,6))# Loop through the genresfor i, g in enumerate(genres): # Define x and y x = np.arange(7) y = music_pref_2019[g] # Plot lines ax.plot(x, y, label = g) # X axis ax.set_xticks(x) ax.set_xticklabels([“14–19”, “20–29”, “30–39”, “40–49”, “50–59”, “60–69”, “70+”]) ax.legend()plt.show()"
},
{
"code": null,
"e": 2338,
"s": 2243,
"text": "There’s a lot of things wrong with this plot. We are going to improve it in these three steps:"
},
{
"code": null,
"e": 2393,
"s": 2338,
"text": "Add InformationReduce InformationEmphasize Information"
},
{
"code": null,
"e": 2409,
"s": 2393,
"text": "Add Information"
},
{
"code": null,
"e": 2428,
"s": 2409,
"text": "Reduce Information"
},
{
"code": null,
"e": 2450,
"s": 2428,
"text": "Emphasize Information"
},
{
"code": null,
"e": 2681,
"s": 2450,
"text": "The signal/noise ratio describes the amount of valuable information compared to the amount of unnecessary information. In any creative product (articles, visualizations, musical compositions), we should aim to maximize this ratio."
},
{
"code": null,
"e": 2939,
"s": 2681,
"text": "We can improve the signal/noise ratio by adding useful information, but also by removing useless information. In an ideal visualization, all of the important information arepresent and emphasized while everything that does not add any real value is removed."
},
{
"code": null,
"e": 3044,
"s": 2939,
"text": "Let’s brainstorm what the plot in Figure 1 is missing. Here are the observations I made. We need to add:"
},
{
"code": null,
"e": 3174,
"s": 3044,
"text": "a titleaxis labelsticks and ticklabels for the y-axisa way to read single values for different age groups directly from the lines"
},
{
"code": null,
"e": 3182,
"s": 3174,
"text": "a title"
},
{
"code": null,
"e": 3194,
"s": 3182,
"text": "axis labels"
},
{
"code": null,
"e": 3230,
"s": 3194,
"text": "ticks and ticklabels for the y-axis"
},
{
"code": null,
"e": 3307,
"s": 3230,
"text": "a way to read single values for different age groups directly from the lines"
},
{
"code": null,
"e": 3395,
"s": 3307,
"text": "We can do this by including the following lines of code to our full visualization code:"
},
{
"code": null,
"e": 3704,
"s": 3395,
"text": "# 1ax.set_title(\"Popularity of Different Genres by Age Groups\")# 2ax.set_xlabel(\"Age\")ax.set_ylabel(\"Amount of people with preference (%)\")# 3ax.set_ylim(0,1)ax.set_yticklabels(int(i*100) for i in ax.get_yticks()) # Turns the # decimals into percent values# 4ax.scatter(x, y) # adds points at every tick of x"
},
{
"code": null,
"e": 3943,
"s": 3704,
"text": "On top of this, I selected different colors for our lines. The matplotlib standard colors are hard to deal with for colorblind people (like myself). Therefore, I have used only colors from the tableau colorblind palette in the plot below."
},
{
"code": null,
"e": 4486,
"s": 3943,
"text": "We can clearly see an improvement from Figure 1 to Figure 2 in terms of the amount of information given! Through adding relevant information, we have improved our signal/noise ratio. We need to protect the relevant information at all costs! It would be easy to just leave it at that since everything we need is included in the visualization in some form. However, this is where the magic can happen. Step 2 and 3 are going to keep all the relevant information, but use certain techniques to make the whole chart more clear and easier to read."
},
{
"code": null,
"e": 4738,
"s": 4486,
"text": "Reducing information doesn’t always mean actually deleting information like labels, legends or ticks. Sometimes, it just means reducing the extent to which the information is an obstacle to the reader. Here are some ideas on what to do with this plot:"
},
{
"code": null,
"e": 4746,
"s": 4738,
"text": "We can:"
},
{
"code": null,
"e": 4937,
"s": 4746,
"text": "remove ticksremove spinesremove the big legend and write the labels on each line directlyleave only 4 ticks on the y axisremove the x and y labels and indicate them on the last tick directly"
},
{
"code": null,
"e": 4950,
"s": 4937,
"text": "remove ticks"
},
{
"code": null,
"e": 4964,
"s": 4950,
"text": "remove spines"
},
{
"code": null,
"e": 5029,
"s": 4964,
"text": "remove the big legend and write the labels on each line directly"
},
{
"code": null,
"e": 5062,
"s": 5029,
"text": "leave only 4 ticks on the y axis"
},
{
"code": null,
"e": 5132,
"s": 5062,
"text": "remove the x and y labels and indicate them on the last tick directly"
},
{
"code": null,
"e": 5694,
"s": 5132,
"text": "# 1ax.tick_params(bottom = False, top = False, left = False, right = False)# 2for key, spine in ax.spines.items(): spine.set_visible(False)# 3ax.text(0,.875, \"Rock/Pop\", rotation = -1.5)ax.text(0,.144, \"Classical\", rotation = 16)ax.text(0,.395, \"Hardrock/Metal\", rotation = 4.5)ax.text(0,.679, \"Hip Hop/Rap\", rotation = -31)ax.text(0,.592, \"Techno/House\", rotation = -15)# 4ax.set_yticks([0,0.25,0.5,0.75,1])# 5ax.set_xticklabels([\"14-19\", \"20-29\", \"30-39\", \"40-49\", \"50-59\", \"60-69\", \"70+ years\"])ax.set_yticklabels([0, 25, 50, 75, \"100%\"])"
},
{
"code": null,
"e": 5938,
"s": 5694,
"text": "Now that we have added all the relevant information and removed everything that is not, we can still optimize our visualization. Maybe there is something we can do to emphasize certain aspects. Here is a couple of ideas for this specific plot:"
},
{
"code": null,
"e": 6029,
"s": 5938,
"text": "Change font, fontsize, and weight of the titleEmphasize the continuous quality of the data"
},
{
"code": null,
"e": 6076,
"s": 6029,
"text": "Change font, fontsize, and weight of the title"
},
{
"code": null,
"e": 6121,
"s": 6076,
"text": "Emphasize the continuous quality of the data"
},
{
"code": null,
"e": 6217,
"s": 6121,
"text": "To change the title font, we can create a font_dict and call it in the ax.set_title() function."
},
{
"code": null,
"e": 6442,
"s": 6217,
"text": "title_font= {\"family\" : \"Cambria\", \"size\" : 16, \"color\" : \"black\", \"weight\" : \"roman\"}# LATER IN THE CODEax.set_title(\"Popularity of Different Genres by Age Groups\", fontdict = title_font)"
},
{
"code": null,
"e": 6777,
"s": 6442,
"text": "To emphasize the continuous quality of the data, we need to get rid of the category label and use the mean age instead. For classed variables, we don’t know what the mean age of participants in any age category was. We can use the rounded mean of the possible ages in the category, however. Our mean age m for any category c would be:"
},
{
"code": null,
"e": 6802,
"s": 6777,
"text": "m = int(c_start + c_end)"
},
{
"code": null,
"e": 6857,
"s": 6802,
"text": "Now, we can use these mean ages as your y axis labels:"
},
{
"code": null,
"e": 6927,
"s": 6857,
"text": "ax.set_xticklabels([\"17\", \"25\", \"35\", \"45\", \"55\", \"65\", \"70+ years\"])"
},
{
"code": null,
"e": 7063,
"s": 6927,
"text": "To further emphasize the continuous features of our data, we can decrease the dot sizes and transparencies while increasing line sizes:"
},
{
"code": null,
"e": 7335,
"s": 7063,
"text": "ax.scatter(x, y, c = cb_colors[i], label = mapping_dict[g], marker = \".\", linewidth = 3, alpha = 0.8)ax.plot(x,y, c = cb_colors[i], linestyle = \"-\", linewidth = 2.5, alpha = 0.8) # lowering alpha is also good here, as it gives more attention to the annotations and labels"
},
{
"code": null,
"e": 7387,
"s": 7335,
"text": "I have also increased the annotation sizes to 12pt."
},
{
"code": null,
"e": 7434,
"s": 7387,
"text": "This will give us our final output (Figure 4)."
},
{
"code": null,
"e": 7927,
"s": 7434,
"text": "Here, we can clearly see that the lines start to make sense. While this is not exactly what the data tells us (it’s categorical after all), our mean ages allow us to tell an actual story. With this visualization, we can predict how preferences change with age, not only compare how they are different between ages. The dots still allow us to target a specific age and see the exact values for it, while also revealing that the connections between dots are linear predictions, not actual data."
},
{
"code": null,
"e": 8053,
"s": 7927,
"text": "We could also go the other route and emphasize the categorical features of our data. Figure 5 is an example of that approach."
},
{
"code": null,
"e": 8161,
"s": 8053,
"text": "Here, I emphasized the points and added a grid in the background. I also kept the original category labels."
},
{
"code": null,
"e": 8600,
"s": 8161,
"text": "In this article, I showed you how you can use a three-step formula to improve your matplotlib visualizations. One key thing to take home from this post is that the magic lies not within the information you add, but within the information you remove or transform. Look at Figure 1 and compare it to our final results. Then check your own recent visualizations and see if you can make use of the three-step formula to make them even better!"
}
] |
Azure Machine Learning : Run Python Script Experiment | Towards Data Science
|
In Part 1 of this series I mostly covered an overview and introduction about Azure Machine Learning (AML) Service, in that post I covered setup, configuration, and various OOB capabilities on the offering by this cloud-managed service. I also discussed AML Workspace, AML Experiment, and AML service experiment’s dashboard in detail.
In this Part 2, I will discuss how we can create an independent experiment script to encapsulate the core implementation of an ML model on the cloud, i.e. by training and tracking through repetitive experiment run. Also, I will demonstrate how to set up a prerequisite environment and configurations required to execute an experiment script.
This particular post is extracted from the Kaggle notebook hosted — here. Use the link to setup and execute the experiment
Once connected to the Azure Machine Learning workspace, the next step is to define a model experiment script, this is a very general python script which is loaded and executed form the experiment’s ‘workspace’ compute context. This also requires that the data files’ root (folder) has to be at the same location where this script is loaded, as shown below —
Experiment Output Folder — Mostly, Run of an experiment generates some output files, e.g. a saved model, that are saved in the workspace’s outputs folder as shown below —
os.makedirs("outputs", exist_ok=True)joblib.dump(value=model, filename='outputs/iris_simple_model.pkl')# Complete the runrun.complete()
One can also use the Run object’s upload_file method in the experiment file code as shown below, this enables that any files written to the outputs folder in the compute context are automatically uploaded to the run’s outputs folder when the run completed, e.g. —
run.upload_file(name='outputs/IRIS.csv', path_or_stream='./sample.csv') # upload from local
After the script for implementing the ML model is ready, the next step is to define RunConfiguration object — which defines the Python environment in which the script will run, and ScriptRunConfig object— which associates the run environment with the script. The below code snippet instantiates the Python environment by calling the RunConfiguration() method and ScriptRunConfig() encapsulate the same environment for the script’s execution:
from azureml.core import Experiment, RunConfiguration, ScriptRunConfig# create a new RunConfig objectexperiment_run_config = RunConfiguration()experiment_run_config.environment.python.user_managed_dependencies = True# Create a script configsrc = ScriptRunConfig(source_directory=experiment_folder, script='iris_simple_experiment.py', run_config=experiment_run_config)
The RunConfig object also allows to additionally include the Python packages which are necessary for script execution.
Access the Azure Machine Learning Studio to navigate for the sample experiment run and verify the results in results on the dashboard. Here, the entire details of the experiment’s run history is displayed, as shown below — the details of run stats, history, results, metrics, logs, outputs, errors, diagnostics, etc.. are readily available from the dashboard:
In this part of the series, I tried to cover the most fundamental concept of Azure Machine Learning Service, i.e., to prepare and execute a machine learning experiment and generate a model binary. In the next article, I will cover a slightly more advanced way to set up and control the script’s execution environment, install or update the required dependencies & packages. So please stay tuned!
This is a series of blog posts encompassing a detailed overview of various Azure Machine Learning capabilities, the URLs for other posts are as follows:
Post 1: Azure Machine Learning Service: Part 1 — An Introduction
Post 2 (this): Azure Machine Learning Service — Run a Simple Experiment
Post 3: Azure Machine Learning Service — Train a model
Post 4: Azure Machine Learning Service — Where is My Data?
Post 5: Azure Machine Learning Service — What is the Target Environment?
Connect with me on LinkedIn to discuss further
[1] Notebook & Code — Azure Machine Learning — Introduction, Kaggle.[2] Azure Machine Learning Service Official Documentation, Microsoft Azure.
|
[
{
"code": null,
"e": 506,
"s": 172,
"text": "In Part 1 of this series I mostly covered an overview and introduction about Azure Machine Learning (AML) Service, in that post I covered setup, configuration, and various OOB capabilities on the offering by this cloud-managed service. I also discussed AML Workspace, AML Experiment, and AML service experiment’s dashboard in detail."
},
{
"code": null,
"e": 848,
"s": 506,
"text": "In this Part 2, I will discuss how we can create an independent experiment script to encapsulate the core implementation of an ML model on the cloud, i.e. by training and tracking through repetitive experiment run. Also, I will demonstrate how to set up a prerequisite environment and configurations required to execute an experiment script."
},
{
"code": null,
"e": 971,
"s": 848,
"text": "This particular post is extracted from the Kaggle notebook hosted — here. Use the link to setup and execute the experiment"
},
{
"code": null,
"e": 1329,
"s": 971,
"text": "Once connected to the Azure Machine Learning workspace, the next step is to define a model experiment script, this is a very general python script which is loaded and executed form the experiment’s ‘workspace’ compute context. This also requires that the data files’ root (folder) has to be at the same location where this script is loaded, as shown below —"
},
{
"code": null,
"e": 1500,
"s": 1329,
"text": "Experiment Output Folder — Mostly, Run of an experiment generates some output files, e.g. a saved model, that are saved in the workspace’s outputs folder as shown below —"
},
{
"code": null,
"e": 1636,
"s": 1500,
"text": "os.makedirs(\"outputs\", exist_ok=True)joblib.dump(value=model, filename='outputs/iris_simple_model.pkl')# Complete the runrun.complete()"
},
{
"code": null,
"e": 1900,
"s": 1636,
"text": "One can also use the Run object’s upload_file method in the experiment file code as shown below, this enables that any files written to the outputs folder in the compute context are automatically uploaded to the run’s outputs folder when the run completed, e.g. —"
},
{
"code": null,
"e": 1992,
"s": 1900,
"text": "run.upload_file(name='outputs/IRIS.csv', path_or_stream='./sample.csv') # upload from local"
},
{
"code": null,
"e": 2434,
"s": 1992,
"text": "After the script for implementing the ML model is ready, the next step is to define RunConfiguration object — which defines the Python environment in which the script will run, and ScriptRunConfig object— which associates the run environment with the script. The below code snippet instantiates the Python environment by calling the RunConfiguration() method and ScriptRunConfig() encapsulate the same environment for the script’s execution:"
},
{
"code": null,
"e": 2845,
"s": 2434,
"text": "from azureml.core import Experiment, RunConfiguration, ScriptRunConfig# create a new RunConfig objectexperiment_run_config = RunConfiguration()experiment_run_config.environment.python.user_managed_dependencies = True# Create a script configsrc = ScriptRunConfig(source_directory=experiment_folder, script='iris_simple_experiment.py', run_config=experiment_run_config)"
},
{
"code": null,
"e": 2964,
"s": 2845,
"text": "The RunConfig object also allows to additionally include the Python packages which are necessary for script execution."
},
{
"code": null,
"e": 3324,
"s": 2964,
"text": "Access the Azure Machine Learning Studio to navigate for the sample experiment run and verify the results in results on the dashboard. Here, the entire details of the experiment’s run history is displayed, as shown below — the details of run stats, history, results, metrics, logs, outputs, errors, diagnostics, etc.. are readily available from the dashboard:"
},
{
"code": null,
"e": 3720,
"s": 3324,
"text": "In this part of the series, I tried to cover the most fundamental concept of Azure Machine Learning Service, i.e., to prepare and execute a machine learning experiment and generate a model binary. In the next article, I will cover a slightly more advanced way to set up and control the script’s execution environment, install or update the required dependencies & packages. So please stay tuned!"
},
{
"code": null,
"e": 3873,
"s": 3720,
"text": "This is a series of blog posts encompassing a detailed overview of various Azure Machine Learning capabilities, the URLs for other posts are as follows:"
},
{
"code": null,
"e": 3938,
"s": 3873,
"text": "Post 1: Azure Machine Learning Service: Part 1 — An Introduction"
},
{
"code": null,
"e": 4010,
"s": 3938,
"text": "Post 2 (this): Azure Machine Learning Service — Run a Simple Experiment"
},
{
"code": null,
"e": 4065,
"s": 4010,
"text": "Post 3: Azure Machine Learning Service — Train a model"
},
{
"code": null,
"e": 4124,
"s": 4065,
"text": "Post 4: Azure Machine Learning Service — Where is My Data?"
},
{
"code": null,
"e": 4197,
"s": 4124,
"text": "Post 5: Azure Machine Learning Service — What is the Target Environment?"
},
{
"code": null,
"e": 4244,
"s": 4197,
"text": "Connect with me on LinkedIn to discuss further"
}
] |
Implementing circular queue ring buffer in JavaScript
|
The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer".
One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.
We are required to design our implementation of the circular queue in JavaScript that can support the following operations −
MyCircularQueue(k) − Constructor, set the size of the queue to be k.
MyCircularQueue(k) − Constructor, set the size of the queue to be k.
Front() − Get the front item from the queue. If the queue is empty, return -1.
Front() − Get the front item from the queue. If the queue is empty, return -1.
Rear() − Get the last item from the queue. If the queue is empty, return -1.
Rear() − Get the last item from the queue. If the queue is empty, return -1.
enQueue(value) − Insert an element into the circular queue. Return true if the operation is successful.
enQueue(value) − Insert an element into the circular queue. Return true if the operation is successful.
deQueue() − Delete an element from the circular queue. Return true if the operation is successful.
deQueue() − Delete an element from the circular queue. Return true if the operation is successful.
isEmpty() − Checks whether the circular queue is empty or not.
isEmpty() − Checks whether the circular queue is empty or not.
isFull() − Checks whether the circular queue is full or not.
isFull() − Checks whether the circular queue is full or not.
Following is the code −
Live Demo
const CircularQueue = function(k) {
this.size = k
this.queue = []
this.start1 = 0
this.end1 = 0
this.start2 = 0
this.end2 = 0
}
CircularQueue.prototype.enQueue = function(value) {
if(this.isFull()) {
return false
}
if(this.end2 <= this.size - 1) {
this.queue[this.end2++] = value
} else {
this.queue[this.end1++] = value
}
return true
}
CircularQueue.prototype.deQueue = function() {
if(this.isEmpty()) {
return false
}
if(this.queue[this.start2] !== undefined) {
this.queue[this.start2++] = undefined
} else {
this.queue[this.start1++] = undefined
}
return true
}
CircularQueue.prototype.Front = function() {
if(this.isEmpty()) {
return -1
}
return this.queue[this.start2] === undefined ? this.queue[this.start1] : this.queue[this.start2]
}
CircularQueue.prototype.Rear = function() {
if(this.isEmpty()) {
return -1
}
return this.queue[this.end1 - 1] === undefined ? this.queue[this.end2 - 1] : this.queue[this.end1 - 1]
}
CircularQueue.prototype.isEmpty = function() {
if(this.end2 - this.start2 + this.end1 - this.start1 <= 0) {
return true
}
return false
}
CircularQueue.prototype.isFull = function() {
if(this.end2 - this.start2 + this.end1 - this.start1 >= this.size) {
return true
}
return false
}
const queue = new CircularQueue(2);
console.log(queue.enQueue(1));
console.log(queue.enQueue(2));
console.log(queue.enQueue(3));
console.log(queue.Rear());
console.log(queue.isFull());
console.log(queue.deQueue());
console.log(queue.enQueue(3));
console.log(queue.Rear());
true
true
false
2
true
true
true
3
|
[
{
"code": null,
"e": 1304,
"s": 1062,
"text": "The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called \"Ring Buffer\"."
},
{
"code": null,
"e": 1609,
"s": 1304,
"text": "One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values."
},
{
"code": null,
"e": 1734,
"s": 1609,
"text": "We are required to design our implementation of the circular queue in JavaScript that can support the following operations −"
},
{
"code": null,
"e": 1803,
"s": 1734,
"text": "MyCircularQueue(k) − Constructor, set the size of the queue to be k."
},
{
"code": null,
"e": 1872,
"s": 1803,
"text": "MyCircularQueue(k) − Constructor, set the size of the queue to be k."
},
{
"code": null,
"e": 1951,
"s": 1872,
"text": "Front() − Get the front item from the queue. If the queue is empty, return -1."
},
{
"code": null,
"e": 2030,
"s": 1951,
"text": "Front() − Get the front item from the queue. If the queue is empty, return -1."
},
{
"code": null,
"e": 2107,
"s": 2030,
"text": "Rear() − Get the last item from the queue. If the queue is empty, return -1."
},
{
"code": null,
"e": 2184,
"s": 2107,
"text": "Rear() − Get the last item from the queue. If the queue is empty, return -1."
},
{
"code": null,
"e": 2288,
"s": 2184,
"text": "enQueue(value) − Insert an element into the circular queue. Return true if the operation is successful."
},
{
"code": null,
"e": 2392,
"s": 2288,
"text": "enQueue(value) − Insert an element into the circular queue. Return true if the operation is successful."
},
{
"code": null,
"e": 2491,
"s": 2392,
"text": "deQueue() − Delete an element from the circular queue. Return true if the operation is successful."
},
{
"code": null,
"e": 2590,
"s": 2491,
"text": "deQueue() − Delete an element from the circular queue. Return true if the operation is successful."
},
{
"code": null,
"e": 2653,
"s": 2590,
"text": "isEmpty() − Checks whether the circular queue is empty or not."
},
{
"code": null,
"e": 2716,
"s": 2653,
"text": "isEmpty() − Checks whether the circular queue is empty or not."
},
{
"code": null,
"e": 2777,
"s": 2716,
"text": "isFull() − Checks whether the circular queue is full or not."
},
{
"code": null,
"e": 2838,
"s": 2777,
"text": "isFull() − Checks whether the circular queue is full or not."
},
{
"code": null,
"e": 2862,
"s": 2838,
"text": "Following is the code −"
},
{
"code": null,
"e": 2873,
"s": 2862,
"text": " Live Demo"
},
{
"code": null,
"e": 4507,
"s": 2873,
"text": "const CircularQueue = function(k) {\n this.size = k\n this.queue = []\n this.start1 = 0\n this.end1 = 0\n this.start2 = 0\n this.end2 = 0\n}\nCircularQueue.prototype.enQueue = function(value) {\n if(this.isFull()) {\n return false\n }\n if(this.end2 <= this.size - 1) {\n this.queue[this.end2++] = value\n } else {\n this.queue[this.end1++] = value\n }\n return true\n}\nCircularQueue.prototype.deQueue = function() {\n if(this.isEmpty()) {\n return false\n }\n if(this.queue[this.start2] !== undefined) {\n this.queue[this.start2++] = undefined\n } else {\n this.queue[this.start1++] = undefined\n }\n return true\n}\nCircularQueue.prototype.Front = function() {\n if(this.isEmpty()) {\n return -1\n }\n return this.queue[this.start2] === undefined ? this.queue[this.start1] : this.queue[this.start2]\n}\nCircularQueue.prototype.Rear = function() {\n if(this.isEmpty()) {\n return -1\n }\n return this.queue[this.end1 - 1] === undefined ? this.queue[this.end2 - 1] : this.queue[this.end1 - 1]\n}\nCircularQueue.prototype.isEmpty = function() {\n if(this.end2 - this.start2 + this.end1 - this.start1 <= 0) {\n return true\n }\n return false\n}\nCircularQueue.prototype.isFull = function() {\n if(this.end2 - this.start2 + this.end1 - this.start1 >= this.size) {\n return true\n }\n return false\n}\nconst queue = new CircularQueue(2);\nconsole.log(queue.enQueue(1));\nconsole.log(queue.enQueue(2));\nconsole.log(queue.enQueue(3));\nconsole.log(queue.Rear());\nconsole.log(queue.isFull());\nconsole.log(queue.deQueue());\nconsole.log(queue.enQueue(3));\nconsole.log(queue.Rear());"
},
{
"code": null,
"e": 4542,
"s": 4507,
"text": "true\ntrue\nfalse\n2\ntrue\ntrue\ntrue\n3"
}
] |
Matplotlib.axes.Axes.set_xlabel() in Python
|
19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_xlabel() function in axes module of matplotlib library is used to set the label for the x-axis.
Syntax: Axes.set_xlabel(self, xlabel, fontdict=None, labelpad=None, **kwargs)
Parameters: This method accepts the following parameters.
xlabel : This parameter is the label text.
labelpad : This parameter is the spacing in points from the axes bounding box including ticks and tick labels.
Returns:This method does not returns any value.
Below examples illustrate the matplotlib.axes.Axes.set_xlabel() function in matplotlib.axes:
Example 1:
import matplotlib.pyplot as pltimport numpy as np t = np.arange(0.01, 5.0, 0.01)s = np.exp(-t) fig, ax = plt.subplots() ax.plot(t, s)ax.set_xlim(5, 0)ax.set_xlabel('Display X-axis Label', fontweight ='bold')ax.grid(True) ax.set_title('matplotlib.axes.Axes.set_xlabel()\ Examples\n', fontsize = 14, fontweight ='bold')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.cbook as cbook with cbook.get_sample_data('goog.npz') as datafile: price_data = np.load(datafile)['price_data'].view(np.recarray) # get the most recent 250# trading daysprice_data = price_data[-250:] delta1 = np.diff(price_data.adj_close)/price_data.adj_close[:-1] volume = (25 * price_data.volume[:-2] / price_data.volume[0])**3close = (0.03 * price_data.close[:-2] / 0.03 * price_data.open[:-2])**2 fig, ax = plt.subplots()ax.scatter(delta1[:-1], delta1[1:], c = close, s = volume, alpha = 0.5) ax.set_xlabel(r'X-axis contains $\Delta_i$ values', fontweight ='bold')ax.grid(True)fig.suptitle('matplotlib.axes.Axes.set_xlabel() Examples\n', fontsize = 14, fontweight ='bold') plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 437,
"s": 328,
"text": "The Axes.set_xlabel() function in axes module of matplotlib library is used to set the label for the x-axis."
},
{
"code": null,
"e": 515,
"s": 437,
"text": "Syntax: Axes.set_xlabel(self, xlabel, fontdict=None, labelpad=None, **kwargs)"
},
{
"code": null,
"e": 573,
"s": 515,
"text": "Parameters: This method accepts the following parameters."
},
{
"code": null,
"e": 616,
"s": 573,
"text": "xlabel : This parameter is the label text."
},
{
"code": null,
"e": 727,
"s": 616,
"text": "labelpad : This parameter is the spacing in points from the axes bounding box including ticks and tick labels."
},
{
"code": null,
"e": 775,
"s": 727,
"text": "Returns:This method does not returns any value."
},
{
"code": null,
"e": 868,
"s": 775,
"text": "Below examples illustrate the matplotlib.axes.Axes.set_xlabel() function in matplotlib.axes:"
},
{
"code": null,
"e": 879,
"s": 868,
"text": "Example 1:"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np t = np.arange(0.01, 5.0, 0.01)s = np.exp(-t) fig, ax = plt.subplots() ax.plot(t, s)ax.set_xlim(5, 0)ax.set_xlabel('Display X-axis Label', fontweight ='bold')ax.grid(True) ax.set_title('matplotlib.axes.Axes.set_xlabel()\\ Examples\\n', fontsize = 14, fontweight ='bold')plt.show()",
"e": 1226,
"s": 879,
"text": null
},
{
"code": null,
"e": 1234,
"s": 1226,
"text": "Output:"
},
{
"code": null,
"e": 1245,
"s": 1234,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.cbook as cbook with cbook.get_sample_data('goog.npz') as datafile: price_data = np.load(datafile)['price_data'].view(np.recarray) # get the most recent 250# trading daysprice_data = price_data[-250:] delta1 = np.diff(price_data.adj_close)/price_data.adj_close[:-1] volume = (25 * price_data.volume[:-2] / price_data.volume[0])**3close = (0.03 * price_data.close[:-2] / 0.03 * price_data.open[:-2])**2 fig, ax = plt.subplots()ax.scatter(delta1[:-1], delta1[1:], c = close, s = volume, alpha = 0.5) ax.set_xlabel(r'X-axis contains $\\Delta_i$ values', fontweight ='bold')ax.grid(True)fig.suptitle('matplotlib.axes.Axes.set_xlabel() Examples\\n', fontsize = 14, fontweight ='bold') plt.show()",
"e": 2100,
"s": 1245,
"text": null
},
{
"code": null,
"e": 2108,
"s": 2100,
"text": "Output:"
},
{
"code": null,
"e": 2126,
"s": 2108,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2133,
"s": 2126,
"text": "Python"
},
{
"code": null,
"e": 2231,
"s": 2133,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2249,
"s": 2231,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2291,
"s": 2249,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2313,
"s": 2291,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2348,
"s": 2313,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2374,
"s": 2348,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2406,
"s": 2374,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2435,
"s": 2406,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2462,
"s": 2435,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2483,
"s": 2462,
"text": "Python OOPs Concepts"
}
] |
How to set the Background Color of the ComboBox in C#?
|
27 Jun, 2019
In windows forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. You are allowed to set the background color of the ComboBox by using the BackColor Property. It gives a more attractive look to your ComboBox control. You can set this property using two different methods:
1. Design-Time: It is the easiest method to set the background color of the ComboBox control using the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the ComboBox control to set the background color of the ComboBox.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the background color of the ComboBox programmatically with the help of given syntax:
public override System.Drawing.Color BackColor { get; set; }
Here, Color indicates the background color of the ComboBox. Following steps are used to set the background color of the ComboBox:
Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.// Creating ComboBox using ComboBox class
ComboBox mybox = new ComboBox();
// Creating ComboBox using ComboBox class
ComboBox mybox = new ComboBox();
Step 2: After creating ComboBox, set the background color of the ComboBox.// Set the background color of the ComboBox
mybox.BackColor = Color.LightBlue;
// Set the background color of the ComboBox
mybox.BackColor = Color.LightBlue;
Step 3: And last add this combobox control to form using Add() method.// Add this ComboBox to form
this.Controls.Add(mybox);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = "Select city name"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Sorted = true; mybox.BackColor = Color.LightBlue; mybox.Name = "My_Cobo_Box"; mybox.Items.Add("Mumbai"); mybox.Items.Add("Delhi"); mybox.Items.Add("Jaipur"); mybox.Items.Add("Kolkata"); mybox.Items.Add("Bengaluru"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}Output:
// Add this ComboBox to form
this.Controls.Add(mybox);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = "Select city name"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Sorted = true; mybox.BackColor = Color.LightBlue; mybox.Name = "My_Cobo_Box"; mybox.Items.Add("Mumbai"); mybox.Items.Add("Delhi"); mybox.Items.Add("Jaipur"); mybox.Items.Add("Kolkata"); mybox.Items.Add("Bengaluru"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}
Output:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
Differences Between .NET Core and .NET Framework
C# | Delegates
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object
C# | Replace() Method
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jun, 2019"
},
{
"code": null,
"e": 478,
"s": 28,
"text": "In windows forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. You are allowed to set the background color of the ComboBox by using the BackColor Property. It gives a more attractive look to your ComboBox control. You can set this property using two different methods:"
},
{
"code": null,
"e": 598,
"s": 478,
"text": "1. Design-Time: It is the easiest method to set the background color of the ComboBox control using the following steps:"
},
{
"code": null,
"e": 714,
"s": 598,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 895,
"s": 714,
"text": "Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need."
},
{
"code": null,
"e": 1029,
"s": 895,
"text": "Step 3: After drag and drop you will go to the properties of the ComboBox control to set the background color of the ComboBox.Output:"
},
{
"code": null,
"e": 1037,
"s": 1029,
"text": "Output:"
},
{
"code": null,
"e": 1214,
"s": 1037,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the background color of the ComboBox programmatically with the help of given syntax:"
},
{
"code": null,
"e": 1275,
"s": 1214,
"text": "public override System.Drawing.Color BackColor { get; set; }"
},
{
"code": null,
"e": 1405,
"s": 1275,
"text": "Here, Color indicates the background color of the ComboBox. Following steps are used to set the background color of the ComboBox:"
},
{
"code": null,
"e": 1574,
"s": 1405,
"text": "Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.// Creating ComboBox using ComboBox class\nComboBox mybox = new ComboBox();\n"
},
{
"code": null,
"e": 1650,
"s": 1574,
"text": "// Creating ComboBox using ComboBox class\nComboBox mybox = new ComboBox();\n"
},
{
"code": null,
"e": 1805,
"s": 1650,
"text": "Step 2: After creating ComboBox, set the background color of the ComboBox.// Set the background color of the ComboBox \nmybox.BackColor = Color.LightBlue;\n"
},
{
"code": null,
"e": 1886,
"s": 1805,
"text": "// Set the background color of the ComboBox \nmybox.BackColor = Color.LightBlue;\n"
},
{
"code": null,
"e": 3234,
"s": 1886,
"text": "Step 3: And last add this combobox control to form using Add() method.// Add this ComboBox to form\nthis.Controls.Add(mybox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = \"Select city name\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Sorted = true; mybox.BackColor = Color.LightBlue; mybox.Name = \"My_Cobo_Box\"; mybox.Items.Add(\"Mumbai\"); mybox.Items.Add(\"Delhi\"); mybox.Items.Add(\"Jaipur\"); mybox.Items.Add(\"Kolkata\"); mybox.Items.Add(\"Bengaluru\"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}Output:"
},
{
"code": null,
"e": 3290,
"s": 3234,
"text": "// Add this ComboBox to form\nthis.Controls.Add(mybox);\n"
},
{
"code": null,
"e": 3299,
"s": 3290,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = \"Select city name\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Sorted = true; mybox.BackColor = Color.LightBlue; mybox.Name = \"My_Cobo_Box\"; mybox.Items.Add(\"Mumbai\"); mybox.Items.Add(\"Delhi\"); mybox.Items.Add(\"Jaipur\"); mybox.Items.Add(\"Kolkata\"); mybox.Items.Add(\"Bengaluru\"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}",
"e": 4507,
"s": 3299,
"text": null
},
{
"code": null,
"e": 4515,
"s": 4507,
"text": "Output:"
},
{
"code": null,
"e": 4518,
"s": 4515,
"text": "C#"
},
{
"code": null,
"e": 4616,
"s": 4518,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4644,
"s": 4616,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 4687,
"s": 4644,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 4718,
"s": 4687,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 4767,
"s": 4718,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 4782,
"s": 4767,
"text": "C# | Delegates"
},
{
"code": null,
"e": 4805,
"s": 4782,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 4845,
"s": 4805,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 4863,
"s": 4845,
"text": "C# | Constructors"
},
{
"code": null,
"e": 4885,
"s": 4863,
"text": "C# | Class and Object"
}
] |
Minimax Algorithm in Game Theory | Set 5 (Zobrist Hashing)
|
18 Apr, 2022
Previous posts on this topic : Minimax Algorithm in Game Theory, Evaluation Function in Game Theory, Tic-Tac-Toe AI – Finding optimal move, Alpha-Beta Pruning.Zobrist Hashing is a hashing function that is widely used in 2 player board games. It is the most common hashing function used in transposition table. Transposition tables basically store the evaluated values of previous board states, so that if they are encountered again we simply retrieve the stored value from the transposition table. We will be covering transposition tables in a later article. In this article we shall take the example of chess board and implement a hashing function for that.
// A matrix with random numbers initialized once
Table[#ofBoardCells][#ofPieces]
// Returns Zobrist hash function for current conf-
// iguration of board.
function findhash(board):
hash = 0
for each cell on the board :
if cell is not empty :
piece = board[cell]
hash ^= table[cell][piece]
return hash
The idea behind Zobrist Hashing is that for a given board state, if there is a piece on a given cell, we use the random number of that piece from the corresponding cell in the table. If more bits are there in the random number the lesser chance of a hash collision. Therefore 64 bit numbers are commonly used as the standard and it is highly unlikely for a hash collision to occur with such large numbers. The table has to be initialized only once during the programs execution. Also the reason why Zobrist Hashing is widely used in board games is because when a player makes a move, it is not necessary to recalculate the hash value from scratch. Due to the nature of XOR operation we can simply use few XOR operations to recalculate the hash value.
We shall try to find a hash value for the given board configuration.
CPP
// A program to illustrate Zobrist Hashing Algorithm#include <bits/stdc++.h>using namespace std; unsigned long long int ZobristTable[8][8][12];mt19937 mt(01234567); // Generates a Random number from 0 to 2^64-1unsigned long long int randomInt(){ uniform_int_distribution<unsigned long long int> dist(0, UINT64_MAX); return dist(mt);} // This function associates each piece with// a numberint indexOf(char piece){ if (piece=='P') return 0; if (piece=='N') return 1; if (piece=='B') return 2; if (piece=='R') return 3; if (piece=='Q') return 4; if (piece=='K') return 5; if (piece=='p') return 6; if (piece=='n') return 7; if (piece=='b') return 8; if (piece=='r') return 9; if (piece=='q') return 10; if (piece=='k') return 11; else return -1;} // Initializes the tablevoid initTable(){ for (int i = 0; i<8; i++) for (int j = 0; j<8; j++) for (int k = 0; k<12; k++) ZobristTable[i][j][k] = randomInt();} // Computes the hash value of a given boardunsigned long long int computeHash(char board[8][9]){ unsigned long long int h = 0; for (int i = 0; i<8; i++) { for (int j = 0; j<8; j++) { if (board[i][j]!='-') { int piece = indexOf(board[i][j]); h ^= ZobristTable[i][j][piece]; } } } return h;} // Main Functionint main(){ // Uppercase letters are white pieces // Lowercase letters are black pieces char board[8][9] = { "---K----", "-R----Q-", "--------", "-P----p-", "-----p--", "--------", "p---b--q", "----n--k" }; initTable(); unsigned long long int hashValue = computeHash(board); printf("The hash value is : %llu\n", hashValue); //Move the white king to the left char piece = board[0][3]; board[0][3] = '-'; hashValue ^= ZobristTable[0][3][indexOf(piece)]; board[0][2] = piece; hashValue ^= ZobristTable[0][2][indexOf(piece)]; printf("The new hash value is : %llu\n", hashValue); // Undo the white king move piece = board[0][2]; board[0][2] = '-'; hashValue ^= ZobristTable[0][2][indexOf(piece)]; board[0][3] = piece; hashValue ^= ZobristTable[0][3][indexOf(piece)]; printf("The old hash value is : %llu\n", hashValue); return 0;}
The hash value is : 14226429382419125366
The new hash value is : 15124945578233295113
The old hash value is : 14226429382419125366
This article is contributed by Akshay L Aradhya. 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.
nidhi_biet
surinderdawra388
simmytarika5
Bitwise-XOR
Game Theory
Game Theory
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chessboard Pawn-Pawn game
Find the winner of a game of removing any number of stones from the least indexed non-empty pile from given N piles
Josephus Problem | (Iterative Solution)
Find the player who will win by choosing a number in range [1, K] with sum total N
Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy)
Minesweeper Solver
Two player game in which a player can remove all occurrences of a number
Game of Nim with removal of one stone allowed
Maximum cells attacked by Rook or Bishop in given Chessboard
Classification of Algorithms with Examples
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 714,
"s": 54,
"text": "Previous posts on this topic : Minimax Algorithm in Game Theory, Evaluation Function in Game Theory, Tic-Tac-Toe AI – Finding optimal move, Alpha-Beta Pruning.Zobrist Hashing is a hashing function that is widely used in 2 player board games. It is the most common hashing function used in transposition table. Transposition tables basically store the evaluated values of previous board states, so that if they are encountered again we simply retrieve the stored value from the transposition table. We will be covering transposition tables in a later article. In this article we shall take the example of chess board and implement a hashing function for that. "
},
{
"code": null,
"e": 1063,
"s": 716,
"text": "// A matrix with random numbers initialized once\nTable[#ofBoardCells][#ofPieces] \n\n// Returns Zobrist hash function for current conf-\n// iguration of board.\nfunction findhash(board):\n hash = 0\n for each cell on the board :\n if cell is not empty :\n piece = board[cell]\n hash ^= table[cell][piece]\n return hash"
},
{
"code": null,
"e": 1817,
"s": 1065,
"text": "The idea behind Zobrist Hashing is that for a given board state, if there is a piece on a given cell, we use the random number of that piece from the corresponding cell in the table. If more bits are there in the random number the lesser chance of a hash collision. Therefore 64 bit numbers are commonly used as the standard and it is highly unlikely for a hash collision to occur with such large numbers. The table has to be initialized only once during the programs execution. Also the reason why Zobrist Hashing is widely used in board games is because when a player makes a move, it is not necessary to recalculate the hash value from scratch. Due to the nature of XOR operation we can simply use few XOR operations to recalculate the hash value. "
},
{
"code": null,
"e": 1887,
"s": 1817,
"text": "We shall try to find a hash value for the given board configuration. "
},
{
"code": null,
"e": 1891,
"s": 1887,
"text": "CPP"
},
{
"code": "// A program to illustrate Zobrist Hashing Algorithm#include <bits/stdc++.h>using namespace std; unsigned long long int ZobristTable[8][8][12];mt19937 mt(01234567); // Generates a Random number from 0 to 2^64-1unsigned long long int randomInt(){ uniform_int_distribution<unsigned long long int> dist(0, UINT64_MAX); return dist(mt);} // This function associates each piece with// a numberint indexOf(char piece){ if (piece=='P') return 0; if (piece=='N') return 1; if (piece=='B') return 2; if (piece=='R') return 3; if (piece=='Q') return 4; if (piece=='K') return 5; if (piece=='p') return 6; if (piece=='n') return 7; if (piece=='b') return 8; if (piece=='r') return 9; if (piece=='q') return 10; if (piece=='k') return 11; else return -1;} // Initializes the tablevoid initTable(){ for (int i = 0; i<8; i++) for (int j = 0; j<8; j++) for (int k = 0; k<12; k++) ZobristTable[i][j][k] = randomInt();} // Computes the hash value of a given boardunsigned long long int computeHash(char board[8][9]){ unsigned long long int h = 0; for (int i = 0; i<8; i++) { for (int j = 0; j<8; j++) { if (board[i][j]!='-') { int piece = indexOf(board[i][j]); h ^= ZobristTable[i][j][piece]; } } } return h;} // Main Functionint main(){ // Uppercase letters are white pieces // Lowercase letters are black pieces char board[8][9] = { \"---K----\", \"-R----Q-\", \"--------\", \"-P----p-\", \"-----p--\", \"--------\", \"p---b--q\", \"----n--k\" }; initTable(); unsigned long long int hashValue = computeHash(board); printf(\"The hash value is : %llu\\n\", hashValue); //Move the white king to the left char piece = board[0][3]; board[0][3] = '-'; hashValue ^= ZobristTable[0][3][indexOf(piece)]; board[0][2] = piece; hashValue ^= ZobristTable[0][2][indexOf(piece)]; printf(\"The new hash value is : %llu\\n\", hashValue); // Undo the white king move piece = board[0][2]; board[0][2] = '-'; hashValue ^= ZobristTable[0][2][indexOf(piece)]; board[0][3] = piece; hashValue ^= ZobristTable[0][3][indexOf(piece)]; printf(\"The old hash value is : %llu\\n\", hashValue); return 0;}",
"e": 4358,
"s": 1891,
"text": null
},
{
"code": null,
"e": 4493,
"s": 4358,
"text": "The hash value is : 14226429382419125366\nThe new hash value is : 15124945578233295113\nThe old hash value is : 14226429382419125366"
},
{
"code": null,
"e": 4918,
"s": 4493,
"text": "This article is contributed by Akshay L Aradhya. 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": 4929,
"s": 4918,
"text": "nidhi_biet"
},
{
"code": null,
"e": 4946,
"s": 4929,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4959,
"s": 4946,
"text": "simmytarika5"
},
{
"code": null,
"e": 4971,
"s": 4959,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 4983,
"s": 4971,
"text": "Game Theory"
},
{
"code": null,
"e": 4995,
"s": 4983,
"text": "Game Theory"
},
{
"code": null,
"e": 5093,
"s": 4995,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5119,
"s": 5093,
"text": "Chessboard Pawn-Pawn game"
},
{
"code": null,
"e": 5235,
"s": 5119,
"text": "Find the winner of a game of removing any number of stones from the least indexed non-empty pile from given N piles"
},
{
"code": null,
"e": 5275,
"s": 5235,
"text": "Josephus Problem | (Iterative Solution)"
},
{
"code": null,
"e": 5358,
"s": 5275,
"text": "Find the player who will win by choosing a number in range [1, K] with sum total N"
},
{
"code": null,
"e": 5432,
"s": 5358,
"text": "Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy)"
},
{
"code": null,
"e": 5451,
"s": 5432,
"text": "Minesweeper Solver"
},
{
"code": null,
"e": 5524,
"s": 5451,
"text": "Two player game in which a player can remove all occurrences of a number"
},
{
"code": null,
"e": 5570,
"s": 5524,
"text": "Game of Nim with removal of one stone allowed"
},
{
"code": null,
"e": 5631,
"s": 5570,
"text": "Maximum cells attacked by Rook or Bishop in given Chessboard"
}
] |
Python lambda
|
23 Jun, 2022
In Python, an anonymous function means that a function is without a name. As we already know that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions.
Syntax:
lambda arguments : expression
This function can have any number of arguments but only one expression, which is evaluated and returned.
One is free to use lambda functions wherever function objects are required.
You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.
It has various uses in particular fields of programming besides other types of expressions in functions.
Example #1:
Python3
# Python program to demonstrate# lambda functions string = 'GeeksforGeeks' # lambda returns a function objectprint(lambda string: string)
<function <lambda> at 0x7fd7517ade18>
In this above example, the lambda is not being called by the print function but simply returning the function object and the memory location where it is stored. So, to make the print to print the string first we need to call the lambda so that the string will get pass the print.
Example #2:
Python3
# Python program to demonstrate# lambda functions x = "GeeksforGeeks" # lambda gets pass to print(lambda x: print(x))(x)
GeeksforGeeks
Example #3: Difference between lambda and normal function call
Python3
# Python program to illustrate cube of a number# showing difference between def() and lambda(). def cube(y): return y*y*y def g(x): return x*x*x print(g(7)) print(cube(5))
343
125
Example #4: The lambda function gets more helpful when used inside a function.
Python3
# Python program to demonstrate# lambda functions def power(n): return lambda a: a ** n # base = lambda a : a**2 get# returned to basebase = power(2) print("Now power is set to 2") # when calling base it gets# executed with already set with 2print("8 powerof 2 = ", base(8)) # base = lambda a : a**5 get# returned to basebase = power(5)print("Now power is set to 5") # when calling base it gets executed# with already set with newly 2print("8 powerof 5 = ", base(8))
Now power is set to 2
8 powerof 2 = 64
Now power is set to 5
8 powerof 5 = 32768
We can also replace list comprehension with Lambda by using a map() method, not only it is a fast but efficient too, and let’s also see how to use lambda in the filter().
Example #5: filter() and map()
Python3
# Python program to demonstrate# lambda functions inside map()# and filter() a = [100, 2, 8, 60, 5, 4, 3, 31, 10, 11] # in filter either we use assignment or# conditional operator, the pass actual# parameter will get returnfiltered = filter (lambda x: x % 2 == 0, a)print(list(filtered)) # in map either we use assignment or# conditional operator, the result of# the value will get returnedmapped = map (lambda x: x % 2 == 0, a)print(list(mapped))
[100, 2, 8, 60, 4, 10]
[True, True, True, True, False, True, False, False, True, False]
simmytarika5
as5853535
adnanirshad158
rmohanraj91
python-lambda
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 263,
"s": 52,
"text": "In Python, an anonymous function means that a function is without a name. As we already know that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions."
},
{
"code": null,
"e": 271,
"s": 263,
"text": "Syntax:"
},
{
"code": null,
"e": 302,
"s": 271,
"text": "lambda arguments : expression "
},
{
"code": null,
"e": 407,
"s": 302,
"text": "This function can have any number of arguments but only one expression, which is evaluated and returned."
},
{
"code": null,
"e": 483,
"s": 407,
"text": "One is free to use lambda functions wherever function objects are required."
},
{
"code": null,
"e": 593,
"s": 483,
"text": "You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression."
},
{
"code": null,
"e": 698,
"s": 593,
"text": "It has various uses in particular fields of programming besides other types of expressions in functions."
},
{
"code": null,
"e": 710,
"s": 698,
"text": "Example #1:"
},
{
"code": null,
"e": 718,
"s": 710,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# lambda functions string = 'GeeksforGeeks' # lambda returns a function objectprint(lambda string: string)",
"e": 857,
"s": 718,
"text": null
},
{
"code": null,
"e": 896,
"s": 857,
"text": "<function <lambda> at 0x7fd7517ade18>\n"
},
{
"code": null,
"e": 1176,
"s": 896,
"text": "In this above example, the lambda is not being called by the print function but simply returning the function object and the memory location where it is stored. So, to make the print to print the string first we need to call the lambda so that the string will get pass the print."
},
{
"code": null,
"e": 1189,
"s": 1176,
"text": "Example #2: "
},
{
"code": null,
"e": 1197,
"s": 1189,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# lambda functions x = \"GeeksforGeeks\" # lambda gets pass to print(lambda x: print(x))(x)",
"e": 1319,
"s": 1197,
"text": null
},
{
"code": null,
"e": 1334,
"s": 1319,
"text": "GeeksforGeeks\n"
},
{
"code": null,
"e": 1398,
"s": 1334,
"text": "Example #3: Difference between lambda and normal function call "
},
{
"code": null,
"e": 1406,
"s": 1398,
"text": "Python3"
},
{
"code": "# Python program to illustrate cube of a number# showing difference between def() and lambda(). def cube(y): return y*y*y def g(x): return x*x*x print(g(7)) print(cube(5))",
"e": 1584,
"s": 1406,
"text": null
},
{
"code": null,
"e": 1593,
"s": 1584,
"text": "343\n125\n"
},
{
"code": null,
"e": 1672,
"s": 1593,
"text": "Example #4: The lambda function gets more helpful when used inside a function."
},
{
"code": null,
"e": 1680,
"s": 1672,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# lambda functions def power(n): return lambda a: a ** n # base = lambda a : a**2 get# returned to basebase = power(2) print(\"Now power is set to 2\") # when calling base it gets# executed with already set with 2print(\"8 powerof 2 = \", base(8)) # base = lambda a : a**5 get# returned to basebase = power(5)print(\"Now power is set to 5\") # when calling base it gets executed# with already set with newly 2print(\"8 powerof 5 = \", base(8))",
"e": 2152,
"s": 1680,
"text": null
},
{
"code": null,
"e": 2236,
"s": 2152,
"text": "Now power is set to 2\n8 powerof 2 = 64\nNow power is set to 5\n8 powerof 5 = 32768\n"
},
{
"code": null,
"e": 2407,
"s": 2236,
"text": "We can also replace list comprehension with Lambda by using a map() method, not only it is a fast but efficient too, and let’s also see how to use lambda in the filter()."
},
{
"code": null,
"e": 2438,
"s": 2407,
"text": "Example #5: filter() and map()"
},
{
"code": null,
"e": 2446,
"s": 2438,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# lambda functions inside map()# and filter() a = [100, 2, 8, 60, 5, 4, 3, 31, 10, 11] # in filter either we use assignment or# conditional operator, the pass actual# parameter will get returnfiltered = filter (lambda x: x % 2 == 0, a)print(list(filtered)) # in map either we use assignment or# conditional operator, the result of# the value will get returnedmapped = map (lambda x: x % 2 == 0, a)print(list(mapped))",
"e": 2895,
"s": 2446,
"text": null
},
{
"code": null,
"e": 2984,
"s": 2895,
"text": "[100, 2, 8, 60, 4, 10]\n[True, True, True, True, False, True, False, False, True, False]\n"
},
{
"code": null,
"e": 2997,
"s": 2984,
"text": "simmytarika5"
},
{
"code": null,
"e": 3007,
"s": 2997,
"text": "as5853535"
},
{
"code": null,
"e": 3022,
"s": 3007,
"text": "adnanirshad158"
},
{
"code": null,
"e": 3034,
"s": 3022,
"text": "rmohanraj91"
},
{
"code": null,
"e": 3048,
"s": 3034,
"text": "python-lambda"
},
{
"code": null,
"e": 3055,
"s": 3048,
"text": "Python"
},
{
"code": null,
"e": 3074,
"s": 3055,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3172,
"s": 3074,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3200,
"s": 3172,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3250,
"s": 3200,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3272,
"s": 3250,
"text": "Python map() function"
},
{
"code": null,
"e": 3316,
"s": 3272,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 3358,
"s": 3316,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3380,
"s": 3358,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3415,
"s": 3380,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3441,
"s": 3415,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3473,
"s": 3441,
"text": "How to Install PIP on Windows ?"
}
] |
Python Program To Reverse Words In A Given String
|
15 Dec, 2021
Example: Let the input string be “i like this program very much”. The function should change the string to “much very program this like i”
Examples:
Input: s = “geeks quiz practice code” Output: s = “code practice quiz geeks”
Input: s = “getting good at coding needs a lot of practice” Output: s = “practice of lot a needs coding at good getting”
Algorithm:
Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”.
Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example.
Below is the implementation of the above approach:
Python3
# Python3 program to reverse a string # Function to reverse each word in # the stringdef reverse_word(s, start, end): while start < end: s[start], s[end] = s[end], s[start] start = start + 1 end -= 1 s = "i like this program very much" # Convert string to list to use it as # a char arrays = list(s)start = 0while True: # We use a try catch block because for # the last word the list.index() function # returns a ValueError as it cannot find # a space in the list try: # Find the next space end = s.index(' ', start) # Call reverse_word function # to reverse each word reverse_word(s, start, end - 1) #Update start variable start = end + 1 except ValueError: # Reverse the last word reverse_word(s, start, len(s) - 1) break # Reverse the entire lists.reverse() # Convert the list back to# string using string.join() functions = "".join(s) print(s) # This code is contributed by Prem Nagdeo
Output:
much very program this like i
Another Approach:
we can do the above task by splitting and saving the string in a reverse manner.
Below is the implementation of the above approach:
Python3
# Python3 program to reverse a string# s = input()s = "i like this program very much"words = s.split(' ')string =[]for word in words: string.insert(0, word) print("Reversed String:")print(" ".join(string)) # Solution proposed bu Uttam
Output:
Reversed String:
much very program this like i
Time Complexity: O(n)
Without using any extra space:The above task can also be accomplished by splitting and directly swapping the string starting from the middle. As direct swapping is involved, less space is consumed too.
Below is the implementation of the above approach:
Python3
# Python3 code to reverse a string # Reverse the stringdef RevString(s,l): # Check if number of words is even if l%2 == 0: # Find the middle word j = int(l/2) # Starting from the middle # start swapping words # at jth position and l-1-j position while(j <= l - 1): s[j], s[l - j - 1] = s[l - j - 1], s[j] j += 1 # Check if number of words is odd else: # Find the middle word j = int(l/2 + 1) # Starting from the middle # start swapping the words # at jth position and l-1-j position while(j <= l - 1): s[j], s[l - 1 - j] = s[l - j - 1], s[j] j += 1 # return the reversed sentence return s; # Driver Codes = 'getting good at coding needs a lot of practice'string = s.split(' ')string = RevString(string,len(string))print(" ".join(string))
Output:
practice of lot a needs coding at good getting
Please refer complete article on Reverse words in a given string for more details!
Accolite
Adobe
Amazon
CBSE - Class 11
Cisco
Goldman Sachs
MakeMyTrip
MAQ Software
Microsoft
Morgan Stanley
Paytm
Payu
Reverse
SAP Labs
school-programming
Wipro
Zoho
Python Programs
Strings
Paytm
Zoho
Morgan Stanley
Accolite
Amazon
Microsoft
MakeMyTrip
Payu
Goldman Sachs
MAQ Software
Adobe
Wipro
SAP Labs
Cisco
Strings
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to interchange first and last elements in a list
Appending to list in Python dictionary
Differences and Applications of List, Tuple, Set and Dictionary in Python
Appending a dictionary to a list in Python
Python Program to check Armstrong Number
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
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "Example: Let the input string be “i like this program very much”. The function should change the string to “much very program this like i”"
},
{
"code": null,
"e": 178,
"s": 167,
"text": "Examples: "
},
{
"code": null,
"e": 255,
"s": 178,
"text": "Input: s = “geeks quiz practice code” Output: s = “code practice quiz geeks”"
},
{
"code": null,
"e": 376,
"s": 255,
"text": "Input: s = “getting good at coding needs a lot of practice” Output: s = “practice of lot a needs coding at good getting”"
},
{
"code": null,
"e": 389,
"s": 376,
"text": "Algorithm: "
},
{
"code": null,
"e": 571,
"s": 389,
"text": "Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”."
},
{
"code": null,
"e": 694,
"s": 571,
"text": "Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example."
},
{
"code": null,
"e": 746,
"s": 694,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 754,
"s": 746,
"text": "Python3"
},
{
"code": "# Python3 program to reverse a string # Function to reverse each word in # the stringdef reverse_word(s, start, end): while start < end: s[start], s[end] = s[end], s[start] start = start + 1 end -= 1 s = \"i like this program very much\" # Convert string to list to use it as # a char arrays = list(s)start = 0while True: # We use a try catch block because for # the last word the list.index() function # returns a ValueError as it cannot find # a space in the list try: # Find the next space end = s.index(' ', start) # Call reverse_word function # to reverse each word reverse_word(s, start, end - 1) #Update start variable start = end + 1 except ValueError: # Reverse the last word reverse_word(s, start, len(s) - 1) break # Reverse the entire lists.reverse() # Convert the list back to# string using string.join() functions = \"\".join(s) print(s) # This code is contributed by Prem Nagdeo",
"e": 1778,
"s": 754,
"text": null
},
{
"code": null,
"e": 1786,
"s": 1778,
"text": "Output:"
},
{
"code": null,
"e": 1816,
"s": 1786,
"text": "much very program this like i"
},
{
"code": null,
"e": 1834,
"s": 1816,
"text": "Another Approach:"
},
{
"code": null,
"e": 1916,
"s": 1834,
"text": "we can do the above task by splitting and saving the string in a reverse manner. "
},
{
"code": null,
"e": 1967,
"s": 1916,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1975,
"s": 1967,
"text": "Python3"
},
{
"code": "# Python3 program to reverse a string# s = input()s = \"i like this program very much\"words = s.split(' ')string =[]for word in words: string.insert(0, word) print(\"Reversed String:\")print(\" \".join(string)) # Solution proposed bu Uttam",
"e": 2215,
"s": 1975,
"text": null
},
{
"code": null,
"e": 2224,
"s": 2215,
"text": "Output: "
},
{
"code": null,
"e": 2271,
"s": 2224,
"text": "Reversed String:\nmuch very program this like i"
},
{
"code": null,
"e": 2294,
"s": 2271,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 2496,
"s": 2294,
"text": "Without using any extra space:The above task can also be accomplished by splitting and directly swapping the string starting from the middle. As direct swapping is involved, less space is consumed too."
},
{
"code": null,
"e": 2547,
"s": 2496,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2555,
"s": 2547,
"text": "Python3"
},
{
"code": "# Python3 code to reverse a string # Reverse the stringdef RevString(s,l): # Check if number of words is even if l%2 == 0: # Find the middle word j = int(l/2) # Starting from the middle # start swapping words # at jth position and l-1-j position while(j <= l - 1): s[j], s[l - j - 1] = s[l - j - 1], s[j] j += 1 # Check if number of words is odd else: # Find the middle word j = int(l/2 + 1) # Starting from the middle # start swapping the words # at jth position and l-1-j position while(j <= l - 1): s[j], s[l - 1 - j] = s[l - j - 1], s[j] j += 1 # return the reversed sentence return s; # Driver Codes = 'getting good at coding needs a lot of practice'string = s.split(' ')string = RevString(string,len(string))print(\" \".join(string))",
"e": 3411,
"s": 2555,
"text": null
},
{
"code": null,
"e": 3419,
"s": 3411,
"text": "Output:"
},
{
"code": null,
"e": 3466,
"s": 3419,
"text": "practice of lot a needs coding at good getting"
},
{
"code": null,
"e": 3549,
"s": 3466,
"text": "Please refer complete article on Reverse words in a given string for more details!"
},
{
"code": null,
"e": 3558,
"s": 3549,
"text": "Accolite"
},
{
"code": null,
"e": 3564,
"s": 3558,
"text": "Adobe"
},
{
"code": null,
"e": 3571,
"s": 3564,
"text": "Amazon"
},
{
"code": null,
"e": 3587,
"s": 3571,
"text": "CBSE - Class 11"
},
{
"code": null,
"e": 3593,
"s": 3587,
"text": "Cisco"
},
{
"code": null,
"e": 3607,
"s": 3593,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 3618,
"s": 3607,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 3631,
"s": 3618,
"text": "MAQ Software"
},
{
"code": null,
"e": 3641,
"s": 3631,
"text": "Microsoft"
},
{
"code": null,
"e": 3656,
"s": 3641,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 3662,
"s": 3656,
"text": "Paytm"
},
{
"code": null,
"e": 3667,
"s": 3662,
"text": "Payu"
},
{
"code": null,
"e": 3675,
"s": 3667,
"text": "Reverse"
},
{
"code": null,
"e": 3684,
"s": 3675,
"text": "SAP Labs"
},
{
"code": null,
"e": 3703,
"s": 3684,
"text": "school-programming"
},
{
"code": null,
"e": 3709,
"s": 3703,
"text": "Wipro"
},
{
"code": null,
"e": 3714,
"s": 3709,
"text": "Zoho"
},
{
"code": null,
"e": 3730,
"s": 3714,
"text": "Python Programs"
},
{
"code": null,
"e": 3738,
"s": 3730,
"text": "Strings"
},
{
"code": null,
"e": 3744,
"s": 3738,
"text": "Paytm"
},
{
"code": null,
"e": 3749,
"s": 3744,
"text": "Zoho"
},
{
"code": null,
"e": 3764,
"s": 3749,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 3773,
"s": 3764,
"text": "Accolite"
},
{
"code": null,
"e": 3780,
"s": 3773,
"text": "Amazon"
},
{
"code": null,
"e": 3790,
"s": 3780,
"text": "Microsoft"
},
{
"code": null,
"e": 3801,
"s": 3790,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 3806,
"s": 3801,
"text": "Payu"
},
{
"code": null,
"e": 3820,
"s": 3806,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 3833,
"s": 3820,
"text": "MAQ Software"
},
{
"code": null,
"e": 3839,
"s": 3833,
"text": "Adobe"
},
{
"code": null,
"e": 3845,
"s": 3839,
"text": "Wipro"
},
{
"code": null,
"e": 3854,
"s": 3845,
"text": "SAP Labs"
},
{
"code": null,
"e": 3860,
"s": 3854,
"text": "Cisco"
},
{
"code": null,
"e": 3868,
"s": 3860,
"text": "Strings"
},
{
"code": null,
"e": 3876,
"s": 3868,
"text": "Reverse"
},
{
"code": null,
"e": 3974,
"s": 3876,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4038,
"s": 3974,
"text": "Python program to interchange first and last elements in a list"
},
{
"code": null,
"e": 4077,
"s": 4038,
"text": "Appending to list in Python dictionary"
},
{
"code": null,
"e": 4151,
"s": 4077,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 4194,
"s": 4151,
"text": "Appending a dictionary to a list in Python"
},
{
"code": null,
"e": 4235,
"s": 4194,
"text": "Python Program to check Armstrong Number"
},
{
"code": null,
"e": 4281,
"s": 4235,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 4306,
"s": 4281,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4366,
"s": 4306,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 4381,
"s": 4366,
"text": "C++ Data Types"
}
] |
Golomb sequence
|
18 Feb, 2022
In mathematics, the Golomb sequence is a non-decreasing integer sequence where n-th term is equal to number of times n appears in the sequence.The first few values are 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, ......
Explanation of few terms: Third term is 2, note that three appears 2 times. Second term is 2, note that two appears 2 times. Fourth term is 3, note that four appears 3 times.Given a positive integer n. The task is to find the first n terms of Golomb sequence.
Examples :
Input : n = 4
Output : 1 2 2 3
Input : n = 6
Output : 1 2 2 3 3 4
The recurrence relation to find the nth term of Golomb sequence: a(1) = 1 a(n + 1) = 1 + a(n + 1 – a(a(n)))
Below is the implementation using Recursion:
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find first// n terms of Golomb sequence.#include <bits/stdc++.h>using namespace std; // Return the nth element// of Golomb sequenceint findGolomb(int n){ // base case if (n == 1) return 1; // Recursive Step return 1 + findGolomb(n - findGolomb(findGolomb(n - 1)));} // Print the first n// term of Golomb Sequencevoid printGolomb(int n){ // Finding first n // terms of Golomb Sequence. for (int i = 1; i <= n; i++) cout << findGolomb(i) << " ";} // Driver Codeint main(){ int n = 9; printGolomb(n); return 0;}
// Java Program to find first // n terms of Golomb sequence.import java.util.*; class GFG{ public static int findGolomb(int n) { // base case if (n == 1) return 1; // Recursive Step return 1 + findGolomb(n - findGolomb(findGolomb(n - 1))); } // Print the first n term of // Golomb Sequence public static void printGolomb(int n) { // Finding first n terms of // Golomb Sequence. for (int i = 1; i <= n; i++) System.out.print(findGolomb(i) + " "); } // Driver Code public static void main (String[] args) { int n = 9; printGolomb(n); }} // This code is contributed by Akash Singh
# Python 3 Program to find first# n terms of Golomb sequence. # Return the nth element of# Golomb sequencedef findGolomb(n): # base case if (n == 1): return 1 # Recursive Step return 1 + findGolomb(n - findGolomb(findGolomb(n - 1))) # Print the first n term# of Golomb Sequencedef printGolomb(n): # Finding first n terms of # Golomb Sequence. for i in range(1, n + 1): print(findGolomb(i), end=" ") # Driver Coden = 9 printGolomb(n) # This code is contributed by# Smitha Dinesh Semwal
// C# Program to find first n // terms of Golomb sequence.using System; class GFG{ // Return the nth element // of Golomb sequence static int findGolomb(int n) { // base case if (n == 1) return 1; // Recursive Step return 1 + findGolomb(n - findGolomb(findGolomb(n - 1))); } // Print the first n term // of Golomb Sequence static void printGolomb(int n) { // Finding first n terms of // Golomb Sequence. for (int i = 1; i <= n; i++) Console .Write(findGolomb(i) + " "); } // Driver Code public static void Main () { int n = 9; printGolomb(n); }} // This code is contributed by vt_m
<?php// PHP Program to find first// n terms of Golomb sequence. // Return the nth element// of Golomb sequencefunction findGolomb($n){ // base case if ($n == 1) return 1; // Recursive Step return 1 + findGolomb($n - findGolomb(findGolomb($n - 1)));} // Print the first n// term of Golomb Sequencefunction printGolomb($n){ // Finding first n terms // of Golomb Sequence. for ($i = 1; $i <= $n; $i++) echo findGolomb($i) , " ";} // Driver Code$n = 9;printGolomb($n); // This code is contributed by anuj_67.?>
<script>// javascript Program to find first // n terms of Golomb sequence. function findGolomb(n) { // base case if (n == 1) return 1; // Recursive Step return 1 + findGolomb(n - findGolomb(findGolomb(n - 1))); } // Print the first n term of // Golomb Sequence function printGolomb(n) { // Finding first n terms of // Golomb Sequence. for (let i = 1; i <= n; i++) document.write(findGolomb(i) + " "); } // Driver Code var n = 9; printGolomb(n); // This code is contributed by Amit Katiyar</script>
1 2 2 3 3 4 4 4 5
Below is the implementation using Dynamic Programming:
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find first// n terms of Golomb sequence.#include <bits/stdc++.h>using namespace std; // Print the first n term// of Golomb Sequencevoid printGolomb(int n){ int dp[n + 1]; // base cases dp[1] = 1; cout << dp[1] << " "; // Finding and printing first // n terms of Golomb Sequence. for (int i = 2; i <= n; i++) { dp[i] = 1 + dp[i - dp[dp[i - 1]]]; cout << dp[i] << " "; }}// Driver Codeint main(){ int n = 9; printGolomb(n); return 0;}
// Java Program to find first// n terms of Golomb sequence.import java.util.*; class GFG{ public static void printGolomb(int n) { int dp[] = new int[n + 1]; // base cases dp[1] = 1; System.out.print(dp[1] + " "); // Finding and printing first n // terms of Golomb Sequence. for (int i = 2; i <= n; i++) { dp[i] = 1 + dp[i - dp[dp[i - 1]]]; System.out.print(dp[i] + " "); } } // Driver code public static void main (String[] args) { int n = 9; printGolomb(n); }} // This code is contributed by Akash Singh
# Python3 Program to find first# n terms of Golomb sequence. # Print the first n term# of Golomb Sequencedef Golomb( n): dp = [0] * (n + 1) # base cases dp[1] = 1 print(dp[1], end = " " ) # Finding and print first # n terms of Golomb Sequence. for i in range(2, n + 1): dp[i] = 1 + dp[i - dp[dp[i - 1]]] print(dp[i], end = " ") # Driver Coden = 9 Golomb(n) # This code is contributed by ash264
// C# Program to find first n// terms of Golomb sequence.using System; class GFG{ // Print the first n term of // Golomb Sequence static void printGolomb(int n) { int []dp = new int[n + 1]; // base cases dp[1] = 1; Console.Write(dp[1] + " "); // Finding and printing first n // terms of Golomb Sequence. for (int i = 2; i <= n; i++) { dp[i] = 1 + dp[i - dp[dp[i - 1]]]; Console.Write( dp[i] + " "); } } // Driver Code public static void Main () { int n = 9; printGolomb(n); }} // This code is contributed by vt_m
<?php// PHP Program to find first// n terms of Golomb sequence. // Print the first n term// of Golomb Sequencefunction printGolomb($n){ // base cases $dp[1] = 1; echo $dp[1], " "; // Finding and printing first // n terms of Golomb Sequence. for ($i = 2; $i <= $n; $i++) { $dp[$i] = 1 + $dp[$i - $dp[$dp[$i - 1]]]; echo $dp[$i], " "; }}// Driver Code$n = 9; printGolomb($n); // This code is contributed by ajit.?>
<script>// Javascript Program to find first// n terms of Golomb sequence. // Print the first n term// of Golomb Sequence function printGolomb( n) { let dp = Array(n + 1).fill(0); // base cases dp[1] = 1; document.write(dp[1] + " "); // Finding and printing first n // terms of Golomb Sequence. for ( i = 2; i <= n; i++) { dp[i] = 1 + dp[i - dp[dp[i - 1]]]; document.write(dp[i] + " "); } } // Driver code let n = 9; printGolomb(n); // This code is contributed by shikhasingrajput </script>
1 2 2 3 3 4 4 4 5
Smitha Dinesh Semwal
vt_m
jit_t
ash264
shikhasingrajput
amit143katiyar
surinderdawra388
simranarora5sos
varshagumber28
series
Dynamic Programming
Dynamic Programming
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 262,
"s": 54,
"text": "In mathematics, the Golomb sequence is a non-decreasing integer sequence where n-th term is equal to number of times n appears in the sequence.The first few values are 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, ......"
},
{
"code": null,
"e": 523,
"s": 262,
"text": "Explanation of few terms: Third term is 2, note that three appears 2 times. Second term is 2, note that two appears 2 times. Fourth term is 3, note that four appears 3 times.Given a positive integer n. The task is to find the first n terms of Golomb sequence. "
},
{
"code": null,
"e": 535,
"s": 523,
"text": "Examples : "
},
{
"code": null,
"e": 602,
"s": 535,
"text": "Input : n = 4\nOutput : 1 2 2 3\n\nInput : n = 6\nOutput : 1 2 2 3 3 4"
},
{
"code": null,
"e": 710,
"s": 602,
"text": "The recurrence relation to find the nth term of Golomb sequence: a(1) = 1 a(n + 1) = 1 + a(n + 1 – a(a(n)))"
},
{
"code": null,
"e": 756,
"s": 710,
"text": "Below is the implementation using Recursion: "
},
{
"code": null,
"e": 760,
"s": 756,
"text": "C++"
},
{
"code": null,
"e": 765,
"s": 760,
"text": "Java"
},
{
"code": null,
"e": 773,
"s": 765,
"text": "Python3"
},
{
"code": null,
"e": 776,
"s": 773,
"text": "C#"
},
{
"code": null,
"e": 780,
"s": 776,
"text": "PHP"
},
{
"code": null,
"e": 791,
"s": 780,
"text": "Javascript"
},
{
"code": "// C++ Program to find first// n terms of Golomb sequence.#include <bits/stdc++.h>using namespace std; // Return the nth element// of Golomb sequenceint findGolomb(int n){ // base case if (n == 1) return 1; // Recursive Step return 1 + findGolomb(n - findGolomb(findGolomb(n - 1)));} // Print the first n// term of Golomb Sequencevoid printGolomb(int n){ // Finding first n // terms of Golomb Sequence. for (int i = 1; i <= n; i++) cout << findGolomb(i) << \" \";} // Driver Codeint main(){ int n = 9; printGolomb(n); return 0;}",
"e": 1377,
"s": 791,
"text": null
},
{
"code": "// Java Program to find first // n terms of Golomb sequence.import java.util.*; class GFG{ public static int findGolomb(int n) { // base case if (n == 1) return 1; // Recursive Step return 1 + findGolomb(n - findGolomb(findGolomb(n - 1))); } // Print the first n term of // Golomb Sequence public static void printGolomb(int n) { // Finding first n terms of // Golomb Sequence. for (int i = 1; i <= n; i++) System.out.print(findGolomb(i) + \" \"); } // Driver Code public static void main (String[] args) { int n = 9; printGolomb(n); }} // This code is contributed by Akash Singh",
"e": 2168,
"s": 1377,
"text": null
},
{
"code": "# Python 3 Program to find first# n terms of Golomb sequence. # Return the nth element of# Golomb sequencedef findGolomb(n): # base case if (n == 1): return 1 # Recursive Step return 1 + findGolomb(n - findGolomb(findGolomb(n - 1))) # Print the first n term# of Golomb Sequencedef printGolomb(n): # Finding first n terms of # Golomb Sequence. for i in range(1, n + 1): print(findGolomb(i), end=\" \") # Driver Coden = 9 printGolomb(n) # This code is contributed by# Smitha Dinesh Semwal",
"e": 2695,
"s": 2168,
"text": null
},
{
"code": "// C# Program to find first n // terms of Golomb sequence.using System; class GFG{ // Return the nth element // of Golomb sequence static int findGolomb(int n) { // base case if (n == 1) return 1; // Recursive Step return 1 + findGolomb(n - findGolomb(findGolomb(n - 1))); } // Print the first n term // of Golomb Sequence static void printGolomb(int n) { // Finding first n terms of // Golomb Sequence. for (int i = 1; i <= n; i++) Console .Write(findGolomb(i) + \" \"); } // Driver Code public static void Main () { int n = 9; printGolomb(n); }} // This code is contributed by vt_m",
"e": 3504,
"s": 2695,
"text": null
},
{
"code": "<?php// PHP Program to find first// n terms of Golomb sequence. // Return the nth element// of Golomb sequencefunction findGolomb($n){ // base case if ($n == 1) return 1; // Recursive Step return 1 + findGolomb($n - findGolomb(findGolomb($n - 1)));} // Print the first n// term of Golomb Sequencefunction printGolomb($n){ // Finding first n terms // of Golomb Sequence. for ($i = 1; $i <= $n; $i++) echo findGolomb($i) , \" \";} // Driver Code$n = 9;printGolomb($n); // This code is contributed by anuj_67.?>",
"e": 4064,
"s": 3504,
"text": null
},
{
"code": "<script>// javascript Program to find first // n terms of Golomb sequence. function findGolomb(n) { // base case if (n == 1) return 1; // Recursive Step return 1 + findGolomb(n - findGolomb(findGolomb(n - 1))); } // Print the first n term of // Golomb Sequence function printGolomb(n) { // Finding first n terms of // Golomb Sequence. for (let i = 1; i <= n; i++) document.write(findGolomb(i) + \" \"); } // Driver Code var n = 9; printGolomb(n); // This code is contributed by Amit Katiyar</script>",
"e": 4675,
"s": 4064,
"text": null
},
{
"code": null,
"e": 4693,
"s": 4675,
"text": "1 2 2 3 3 4 4 4 5"
},
{
"code": null,
"e": 4751,
"s": 4695,
"text": "Below is the implementation using Dynamic Programming: "
},
{
"code": null,
"e": 4755,
"s": 4751,
"text": "C++"
},
{
"code": null,
"e": 4760,
"s": 4755,
"text": "Java"
},
{
"code": null,
"e": 4768,
"s": 4760,
"text": "Python3"
},
{
"code": null,
"e": 4771,
"s": 4768,
"text": "C#"
},
{
"code": null,
"e": 4775,
"s": 4771,
"text": "PHP"
},
{
"code": null,
"e": 4786,
"s": 4775,
"text": "Javascript"
},
{
"code": "// C++ Program to find first// n terms of Golomb sequence.#include <bits/stdc++.h>using namespace std; // Print the first n term// of Golomb Sequencevoid printGolomb(int n){ int dp[n + 1]; // base cases dp[1] = 1; cout << dp[1] << \" \"; // Finding and printing first // n terms of Golomb Sequence. for (int i = 2; i <= n; i++) { dp[i] = 1 + dp[i - dp[dp[i - 1]]]; cout << dp[i] << \" \"; }}// Driver Codeint main(){ int n = 9; printGolomb(n); return 0;}",
"e": 5290,
"s": 4786,
"text": null
},
{
"code": "// Java Program to find first// n terms of Golomb sequence.import java.util.*; class GFG{ public static void printGolomb(int n) { int dp[] = new int[n + 1]; // base cases dp[1] = 1; System.out.print(dp[1] + \" \"); // Finding and printing first n // terms of Golomb Sequence. for (int i = 2; i <= n; i++) { dp[i] = 1 + dp[i - dp[dp[i - 1]]]; System.out.print(dp[i] + \" \"); } } // Driver code public static void main (String[] args) { int n = 9; printGolomb(n); }} // This code is contributed by Akash Singh",
"e": 5957,
"s": 5290,
"text": null
},
{
"code": "# Python3 Program to find first# n terms of Golomb sequence. # Print the first n term# of Golomb Sequencedef Golomb( n): dp = [0] * (n + 1) # base cases dp[1] = 1 print(dp[1], end = \" \" ) # Finding and print first # n terms of Golomb Sequence. for i in range(2, n + 1): dp[i] = 1 + dp[i - dp[dp[i - 1]]] print(dp[i], end = \" \") # Driver Coden = 9 Golomb(n) # This code is contributed by ash264",
"e": 6398,
"s": 5957,
"text": null
},
{
"code": "// C# Program to find first n// terms of Golomb sequence.using System; class GFG{ // Print the first n term of // Golomb Sequence static void printGolomb(int n) { int []dp = new int[n + 1]; // base cases dp[1] = 1; Console.Write(dp[1] + \" \"); // Finding and printing first n // terms of Golomb Sequence. for (int i = 2; i <= n; i++) { dp[i] = 1 + dp[i - dp[dp[i - 1]]]; Console.Write( dp[i] + \" \"); } } // Driver Code public static void Main () { int n = 9; printGolomb(n); }} // This code is contributed by vt_m",
"e": 7075,
"s": 6398,
"text": null
},
{
"code": "<?php// PHP Program to find first// n terms of Golomb sequence. // Print the first n term// of Golomb Sequencefunction printGolomb($n){ // base cases $dp[1] = 1; echo $dp[1], \" \"; // Finding and printing first // n terms of Golomb Sequence. for ($i = 2; $i <= $n; $i++) { $dp[$i] = 1 + $dp[$i - $dp[$dp[$i - 1]]]; echo $dp[$i], \" \"; }}// Driver Code$n = 9; printGolomb($n); // This code is contributed by ajit.?>",
"e": 7552,
"s": 7075,
"text": null
},
{
"code": "<script>// Javascript Program to find first// n terms of Golomb sequence. // Print the first n term// of Golomb Sequence function printGolomb( n) { let dp = Array(n + 1).fill(0); // base cases dp[1] = 1; document.write(dp[1] + \" \"); // Finding and printing first n // terms of Golomb Sequence. for ( i = 2; i <= n; i++) { dp[i] = 1 + dp[i - dp[dp[i - 1]]]; document.write(dp[i] + \" \"); } } // Driver code let n = 9; printGolomb(n); // This code is contributed by shikhasingrajput </script>",
"e": 8165,
"s": 7552,
"text": null
},
{
"code": null,
"e": 8183,
"s": 8165,
"text": "1 2 2 3 3 4 4 4 5"
},
{
"code": null,
"e": 8206,
"s": 8185,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 8211,
"s": 8206,
"text": "vt_m"
},
{
"code": null,
"e": 8217,
"s": 8211,
"text": "jit_t"
},
{
"code": null,
"e": 8224,
"s": 8217,
"text": "ash264"
},
{
"code": null,
"e": 8241,
"s": 8224,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 8256,
"s": 8241,
"text": "amit143katiyar"
},
{
"code": null,
"e": 8273,
"s": 8256,
"text": "surinderdawra388"
},
{
"code": null,
"e": 8289,
"s": 8273,
"text": "simranarora5sos"
},
{
"code": null,
"e": 8304,
"s": 8289,
"text": "varshagumber28"
},
{
"code": null,
"e": 8311,
"s": 8304,
"text": "series"
},
{
"code": null,
"e": 8331,
"s": 8311,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 8351,
"s": 8331,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 8358,
"s": 8351,
"text": "series"
}
] |
Insert Python Dictionary in PostgreSQL using Psycopg2
|
21 Oct, 2021
In this article, we are going to see how to insert a Python dictionary in PostgreSQL using Psycopg2.
We can insert a python dictionary by taking the dictionary keys as column names and values as dictionary values. We import the Psycopg2 package and form a connection to the PostgreSQL database using psycopg2.connect() method. First, let’s create a table and then insert the python dictionary values into it. We create the table by executing the SQL statement using the cursor.execute() method.
'''CREATE TABLE DETAILS(employee_id int NOT NULL, employee_name char(20),
employee_email varchar(30), employee_salary float);'''
After creating an empty table, values in the table are taken from the dictionary by using the .values() method.
empty table
We loop through the dictionary values and insert them into the table. The below SQL statement is executed for each insertion.
'''insert into DETAILS(employee_id , employee_name ,
employee_email , employee_salary) VALUES{};'''
Below is the implementation:
Python3
import psycopg2 # connection establishmentconn = psycopg2.connect( database="geeks", user='postgres', password='root', host='localhost', port= '5432') conn.autocommit = Truecursor = conn.cursor() sql = '''CREATE TABLE DETAILS(employee_id int NOT NULL,\ employee_name char(20), employee_email varchar(30), employee_salary float);''' cursor.execute(sql)dictionary ={ 'empl1' : (187643,'sarah', '[email protected]',65000), 'empl2' : (187644,'rahul', '[email protected]',75000), 'empl3' : (187645,'arjun', '[email protected]',70000)}columns= dictionary.keys()for i in dictionary.values(): sql2='''insert into DETAILS(employee_id , employee_name , employee_email , employee_salary) VALUES{};'''.format(i) cursor.execute(sql2) sql3='''select * from DETAILS;'''cursor.execute(sql3)for i in cursor.fetchall(): print(i) conn.commit()conn.close()
Output:
(187643, 'sarah ', '[email protected]', 65000.0)
(187644, 'rahul ', '[email protected]', 75000.0)
(187645, 'arjun ', '[email protected]', 70000.0)
final table after insertion
isitapol2002
Picked
Python PostgreSQL
Python Pyscopg2
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 129,
"s": 28,
"text": "In this article, we are going to see how to insert a Python dictionary in PostgreSQL using Psycopg2."
},
{
"code": null,
"e": 524,
"s": 129,
"text": "We can insert a python dictionary by taking the dictionary keys as column names and values as dictionary values. We import the Psycopg2 package and form a connection to the PostgreSQL database using psycopg2.connect() method. First, let’s create a table and then insert the python dictionary values into it. We create the table by executing the SQL statement using the cursor.execute() method. "
},
{
"code": null,
"e": 662,
"s": 524,
"text": "'''CREATE TABLE DETAILS(employee_id int NOT NULL, employee_name char(20),\n employee_email varchar(30), employee_salary float);'''"
},
{
"code": null,
"e": 774,
"s": 662,
"text": "After creating an empty table, values in the table are taken from the dictionary by using the .values() method."
},
{
"code": null,
"e": 786,
"s": 774,
"text": "empty table"
},
{
"code": null,
"e": 912,
"s": 786,
"text": "We loop through the dictionary values and insert them into the table. The below SQL statement is executed for each insertion."
},
{
"code": null,
"e": 1021,
"s": 912,
"text": "'''insert into DETAILS(employee_id , employee_name ,\n employee_email , employee_salary) VALUES{};'''"
},
{
"code": null,
"e": 1050,
"s": 1021,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 1058,
"s": 1050,
"text": "Python3"
},
{
"code": "import psycopg2 # connection establishmentconn = psycopg2.connect( database=\"geeks\", user='postgres', password='root', host='localhost', port= '5432') conn.autocommit = Truecursor = conn.cursor() sql = '''CREATE TABLE DETAILS(employee_id int NOT NULL,\\ employee_name char(20), employee_email varchar(30), employee_salary float);''' cursor.execute(sql)dictionary ={ 'empl1' : (187643,'sarah', '[email protected]',65000), 'empl2' : (187644,'rahul', '[email protected]',75000), 'empl3' : (187645,'arjun', '[email protected]',70000)}columns= dictionary.keys()for i in dictionary.values(): sql2='''insert into DETAILS(employee_id , employee_name , employee_email , employee_salary) VALUES{};'''.format(i) cursor.execute(sql2) sql3='''select * from DETAILS;'''cursor.execute(sql3)for i in cursor.fetchall(): print(i) conn.commit()conn.close()",
"e": 2046,
"s": 1058,
"text": null
},
{
"code": null,
"e": 2054,
"s": 2046,
"text": "Output:"
},
{
"code": null,
"e": 2247,
"s": 2054,
"text": "(187643, 'sarah ', '[email protected]', 65000.0)\n(187644, 'rahul ', '[email protected]', 75000.0)\n(187645, 'arjun ', '[email protected]', 70000.0)"
},
{
"code": null,
"e": 2275,
"s": 2247,
"text": "final table after insertion"
},
{
"code": null,
"e": 2288,
"s": 2275,
"text": "isitapol2002"
},
{
"code": null,
"e": 2295,
"s": 2288,
"text": "Picked"
},
{
"code": null,
"e": 2313,
"s": 2295,
"text": "Python PostgreSQL"
},
{
"code": null,
"e": 2329,
"s": 2313,
"text": "Python Pyscopg2"
},
{
"code": null,
"e": 2336,
"s": 2329,
"text": "Python"
}
] |
Python | Data Augmentation
|
09 Sep, 2019
Data augmentation is the process of increasing the amount and diversity of data. We do not collect new data, rather we transform the already present data. I will be talking specifically about image data augmentation in this article.So we will look at various ways to transform and augment the image data.This article covers the following articles –
Need for data augmentationOperations in data augmentationData augmentation in KerasData augmentation using Augmentor
Need for data augmentation
Operations in data augmentation
Data augmentation in Keras
Data augmentation using Augmentor
1. Need for data augmentationData augmentation is an integral process in deep learning, as in deep learning we need large amounts of data and in some cases it is not feasible to collect thousands or millions of images, so data augmentation comes to the rescue.
It helps us to increase the size of the dataset and introduce variability in the dataset.
2. Operations in data augmentationThe most commonly used operations are-
RotationShearingZoomingCroppingFlippingChanging the brightness level
Rotation
Shearing
Zooming
Cropping
Flipping
Changing the brightness level
Now we will look at all these operations in detail. I will also provide the code for data augmentation later in the article.
The original image that I will use for illustration
RotationRotation operation as the name suggests, just rotates the image by a certain specified degree.In the example below, I specified the rotation degree as 40.
ShearingShearing is also used to transform the orientation of the image.The result of shearing operation looks like this –
ZoomingZooming operation allows us to either zoom in or zoom out.The result looks like this –
CroppingCropping allows us to crop the image or select a particular area from an image.
FlippingFlipping allows us to flip the orientation of the image. We can use horizontal or vertical flip.You should use this feature carefully as there will be scenarios where this operation might not make much sense e.g. suppose you are designing a facial recognition system, then it is highly unlikely that a person will stand upside down in front of a camera, so you can avoid using the vertical flip operation.
Changing the brightness levelThis feature helps us to combat illumination changes.You can encounter a scenario where most of your dataset comprises of images having a similar brightness level e.g. collecting the images of employees entering the office, by augmenting the images we make sure that our model is robust and is able to detect the person even in different surroundings.
3. Data augmentation in KerasKeras is a high-level machine learning framework build on top of TensorFlow. I won’t go into the details of the working of Keras, rather I just want to introduce the concept of data augmentation in Keras.We can perform data augmentation by using the ImageDataGenerator class.It takes in various arguments like – rotation_range, brightness_range, shear_range, zoom_range etc.
Code : Python code implementing Data augmentation
# Importing necessary functionsfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img # Initialising the ImageDataGenerator class.# We will pass in the augmentation parameters in the constructor.datagen = ImageDataGenerator( rotation_range = 40, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True, brightness_range = (0.5, 1.5)) # Loading a sample image img = load_img('image.jpg') # Converting the input sample image to an arrayx = img_to_array(img)# Reshaping the input imagex = x.reshape((1, ) + x.shape) # Generating and saving 5 augmented samples # using the above defined parameters. i = 0for batch in datagen.flow(x, batch_size = 1, save_to_dir ='preview', save_prefix ='image', save_format ='jpeg'): i += 1 if i > 5: break
The above code snippet allows you to generate 5 augmented images having different zoom, rotation, brightness etc.
Augmented Images
4. Data augmentation using Augmentor
# Importing necessary libraryimport Augmentor# Passing the path of the image directoryp = Augmentor.Pipeline("image_folder") # Defining augmentation parameters and generating 5 samplesp.flip_left_right(0.5)p.black_and_white(0.1)p.rotate(0.3, 10, 10)p.skew(0.4, 0.5)p.zoom(probability = 0.2, min_factor = 1.1, max_factor = 1.5)p.sample(5)
The above code snippet allows you to generate 5 augmented images based on the features defined above.
Augmented Images
You can checkout the Augmentor github repository for more information.
References –
https://keras.io/preprocessing/image/
https://github.com/mdbloice/Augmentor
Image-Processing
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Sep, 2019"
},
{
"code": null,
"e": 377,
"s": 28,
"text": "Data augmentation is the process of increasing the amount and diversity of data. We do not collect new data, rather we transform the already present data. I will be talking specifically about image data augmentation in this article.So we will look at various ways to transform and augment the image data.This article covers the following articles –"
},
{
"code": null,
"e": 494,
"s": 377,
"text": "Need for data augmentationOperations in data augmentationData augmentation in KerasData augmentation using Augmentor"
},
{
"code": null,
"e": 521,
"s": 494,
"text": "Need for data augmentation"
},
{
"code": null,
"e": 553,
"s": 521,
"text": "Operations in data augmentation"
},
{
"code": null,
"e": 580,
"s": 553,
"text": "Data augmentation in Keras"
},
{
"code": null,
"e": 614,
"s": 580,
"text": "Data augmentation using Augmentor"
},
{
"code": null,
"e": 875,
"s": 614,
"text": "1. Need for data augmentationData augmentation is an integral process in deep learning, as in deep learning we need large amounts of data and in some cases it is not feasible to collect thousands or millions of images, so data augmentation comes to the rescue."
},
{
"code": null,
"e": 965,
"s": 875,
"text": "It helps us to increase the size of the dataset and introduce variability in the dataset."
},
{
"code": null,
"e": 1038,
"s": 965,
"text": "2. Operations in data augmentationThe most commonly used operations are-"
},
{
"code": null,
"e": 1107,
"s": 1038,
"text": "RotationShearingZoomingCroppingFlippingChanging the brightness level"
},
{
"code": null,
"e": 1116,
"s": 1107,
"text": "Rotation"
},
{
"code": null,
"e": 1125,
"s": 1116,
"text": "Shearing"
},
{
"code": null,
"e": 1133,
"s": 1125,
"text": "Zooming"
},
{
"code": null,
"e": 1142,
"s": 1133,
"text": "Cropping"
},
{
"code": null,
"e": 1151,
"s": 1142,
"text": "Flipping"
},
{
"code": null,
"e": 1181,
"s": 1151,
"text": "Changing the brightness level"
},
{
"code": null,
"e": 1306,
"s": 1181,
"text": "Now we will look at all these operations in detail. I will also provide the code for data augmentation later in the article."
},
{
"code": null,
"e": 1358,
"s": 1306,
"text": "The original image that I will use for illustration"
},
{
"code": null,
"e": 1521,
"s": 1358,
"text": "RotationRotation operation as the name suggests, just rotates the image by a certain specified degree.In the example below, I specified the rotation degree as 40."
},
{
"code": null,
"e": 1644,
"s": 1521,
"text": "ShearingShearing is also used to transform the orientation of the image.The result of shearing operation looks like this –"
},
{
"code": null,
"e": 1738,
"s": 1644,
"text": "ZoomingZooming operation allows us to either zoom in or zoom out.The result looks like this –"
},
{
"code": null,
"e": 1826,
"s": 1738,
"text": "CroppingCropping allows us to crop the image or select a particular area from an image."
},
{
"code": null,
"e": 2240,
"s": 1826,
"text": "FlippingFlipping allows us to flip the orientation of the image. We can use horizontal or vertical flip.You should use this feature carefully as there will be scenarios where this operation might not make much sense e.g. suppose you are designing a facial recognition system, then it is highly unlikely that a person will stand upside down in front of a camera, so you can avoid using the vertical flip operation."
},
{
"code": null,
"e": 2621,
"s": 2240,
"text": "Changing the brightness levelThis feature helps us to combat illumination changes.You can encounter a scenario where most of your dataset comprises of images having a similar brightness level e.g. collecting the images of employees entering the office, by augmenting the images we make sure that our model is robust and is able to detect the person even in different surroundings."
},
{
"code": null,
"e": 3025,
"s": 2621,
"text": "3. Data augmentation in KerasKeras is a high-level machine learning framework build on top of TensorFlow. I won’t go into the details of the working of Keras, rather I just want to introduce the concept of data augmentation in Keras.We can perform data augmentation by using the ImageDataGenerator class.It takes in various arguments like – rotation_range, brightness_range, shear_range, zoom_range etc."
},
{
"code": null,
"e": 3075,
"s": 3025,
"text": "Code : Python code implementing Data augmentation"
},
{
"code": "# Importing necessary functionsfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img # Initialising the ImageDataGenerator class.# We will pass in the augmentation parameters in the constructor.datagen = ImageDataGenerator( rotation_range = 40, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True, brightness_range = (0.5, 1.5)) # Loading a sample image img = load_img('image.jpg') # Converting the input sample image to an arrayx = img_to_array(img)# Reshaping the input imagex = x.reshape((1, ) + x.shape) # Generating and saving 5 augmented samples # using the above defined parameters. i = 0for batch in datagen.flow(x, batch_size = 1, save_to_dir ='preview', save_prefix ='image', save_format ='jpeg'): i += 1 if i > 5: break",
"e": 3962,
"s": 3075,
"text": null
},
{
"code": null,
"e": 4076,
"s": 3962,
"text": "The above code snippet allows you to generate 5 augmented images having different zoom, rotation, brightness etc."
},
{
"code": null,
"e": 4093,
"s": 4076,
"text": "Augmented Images"
},
{
"code": null,
"e": 4130,
"s": 4093,
"text": "4. Data augmentation using Augmentor"
},
{
"code": "# Importing necessary libraryimport Augmentor# Passing the path of the image directoryp = Augmentor.Pipeline(\"image_folder\") # Defining augmentation parameters and generating 5 samplesp.flip_left_right(0.5)p.black_and_white(0.1)p.rotate(0.3, 10, 10)p.skew(0.4, 0.5)p.zoom(probability = 0.2, min_factor = 1.1, max_factor = 1.5)p.sample(5)",
"e": 4469,
"s": 4130,
"text": null
},
{
"code": null,
"e": 4571,
"s": 4469,
"text": "The above code snippet allows you to generate 5 augmented images based on the features defined above."
},
{
"code": null,
"e": 4588,
"s": 4571,
"text": "Augmented Images"
},
{
"code": null,
"e": 4659,
"s": 4588,
"text": "You can checkout the Augmentor github repository for more information."
},
{
"code": null,
"e": 4672,
"s": 4659,
"text": "References –"
},
{
"code": null,
"e": 4710,
"s": 4672,
"text": "https://keras.io/preprocessing/image/"
},
{
"code": null,
"e": 4748,
"s": 4710,
"text": "https://github.com/mdbloice/Augmentor"
},
{
"code": null,
"e": 4765,
"s": 4748,
"text": "Image-Processing"
},
{
"code": null,
"e": 4782,
"s": 4765,
"text": "Machine Learning"
},
{
"code": null,
"e": 4789,
"s": 4782,
"text": "Python"
},
{
"code": null,
"e": 4806,
"s": 4789,
"text": "Machine Learning"
}
] |
scipy stats.erlang() | Python
|
20 Mar, 2019
scipy.stats.erlang() : is an Erlang continuous random variable that is defined with a standard format and some shape parameters to complete its specification. it is a special case of the Gamma distribution.
Parameters :q : lower and upper tail probabilityx : quantilesloc : [optional] location parameter. Default = 0scale : [optional] scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : erlang continuous random variable
Code #1 : Creating erlang continuous random variable
from scipy.stats import erlang numargs = erlang.numargs[a] = [0.6, ] * numargsrv = erlang(a) print ("RV : \n", rv)
Output :
RV :
<scipy.stats._distn_infrastructure.rv_frozen object at 0x0000018D544FBC88>
Code #2 : erlang random variates and probability distribution.
import numpy as npquantile = np.arange (0.01, 1, 0.1) # Random VariatesR = erlang.rvs(a, scale = 2, size = 10)print ("Random Variates : \n", R) # PDFR = erlang.pdf(a, quantile, loc = 0, scale = 1)print ("\nProbability Distribution : \n", R)
Output :
Random Variates :
[5.65708510e+00 5.16045580e+00 1.02056956e-01 3.64349340e-01
5.65593073e+00 2.27100280e+00 9.77623414e-04 2.01994399e-01
8.84331471e-01 2.20817630e+00]
Probability Distribution :
[0.01, 0.11, 0.21, 0.31, 0.41, 0.51, 0.61, 0.71, 0.81, 0.91]
Code #3 : Graphical Representation.
import numpy as npimport matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 5))print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution))
Output :
Distribution :
Distribution :
[0. 0.10204082 0.20408163 0.30612245 0.40816327 0.51020408
0.6122449 0.71428571 0.81632653 0.91836735 1.02040816 1.12244898
1.2244898 1.32653061 1.42857143 1.53061224 1.63265306 1.73469388
1.83673469 1.93877551 2.04081633 2.14285714 2.24489796 2.34693878
2.44897959 2.55102041 2.65306122 2.75510204 2.85714286 2.95918367
3.06122449 3.16326531 3.26530612 3.36734694 3.46938776 3.57142857
3.67346939 3.7755102 3.87755102 3.97959184 4.08163265 4.18367347
4.28571429 4.3877551 4.48979592 4.59183673 4.69387755 4.79591837
4.89795918 5. ]
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as pltimport numpy as np x = np.linspace(0, 5, 100) # Varying positional argumentsy1 = erlang.pdf(x, 2, 6)y2 = erlang.pdf(x, 1, 4)plt.plot(x, y1, "*", x, y2, "r--")
Output :
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Mar, 2019"
},
{
"code": null,
"e": 235,
"s": 28,
"text": "scipy.stats.erlang() : is an Erlang continuous random variable that is defined with a standard format and some shape parameters to complete its specification. it is a special case of the Gamma distribution."
},
{
"code": null,
"e": 595,
"s": 235,
"text": "Parameters :q : lower and upper tail probabilityx : quantilesloc : [optional] location parameter. Default = 0scale : [optional] scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’)."
},
{
"code": null,
"e": 639,
"s": 595,
"text": "Results : erlang continuous random variable"
},
{
"code": null,
"e": 692,
"s": 639,
"text": "Code #1 : Creating erlang continuous random variable"
},
{
"code": "from scipy.stats import erlang numargs = erlang.numargs[a] = [0.6, ] * numargsrv = erlang(a) print (\"RV : \\n\", rv) ",
"e": 811,
"s": 692,
"text": null
},
{
"code": null,
"e": 820,
"s": 811,
"text": "Output :"
},
{
"code": null,
"e": 903,
"s": 820,
"text": "RV : \n <scipy.stats._distn_infrastructure.rv_frozen object at 0x0000018D544FBC88>\n"
},
{
"code": null,
"e": 966,
"s": 903,
"text": "Code #2 : erlang random variates and probability distribution."
},
{
"code": "import numpy as npquantile = np.arange (0.01, 1, 0.1) # Random VariatesR = erlang.rvs(a, scale = 2, size = 10)print (\"Random Variates : \\n\", R) # PDFR = erlang.pdf(a, quantile, loc = 0, scale = 1)print (\"\\nProbability Distribution : \\n\", R)",
"e": 1211,
"s": 966,
"text": null
},
{
"code": null,
"e": 1220,
"s": 1211,
"text": "Output :"
},
{
"code": null,
"e": 1485,
"s": 1220,
"text": "Random Variates : \n [5.65708510e+00 5.16045580e+00 1.02056956e-01 3.64349340e-01\n 5.65593073e+00 2.27100280e+00 9.77623414e-04 2.01994399e-01\n 8.84331471e-01 2.20817630e+00]\n\nProbability Distribution :\n[0.01, 0.11, 0.21, 0.31, 0.41, 0.51, 0.61, 0.71, 0.81, 0.91]\n "
},
{
"code": null,
"e": 1521,
"s": 1485,
"text": "Code #3 : Graphical Representation."
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 5))print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution))",
"e": 1721,
"s": 1521,
"text": null
},
{
"code": null,
"e": 1730,
"s": 1721,
"text": "Output :"
},
{
"code": null,
"e": 2323,
"s": 1730,
"text": "Distribution : \nDistribution : \n [0. 0.10204082 0.20408163 0.30612245 0.40816327 0.51020408\n 0.6122449 0.71428571 0.81632653 0.91836735 1.02040816 1.12244898\n 1.2244898 1.32653061 1.42857143 1.53061224 1.63265306 1.73469388\n 1.83673469 1.93877551 2.04081633 2.14285714 2.24489796 2.34693878\n 2.44897959 2.55102041 2.65306122 2.75510204 2.85714286 2.95918367\n 3.06122449 3.16326531 3.26530612 3.36734694 3.46938776 3.57142857\n 3.67346939 3.7755102 3.87755102 3.97959184 4.08163265 4.18367347\n 4.28571429 4.3877551 4.48979592 4.59183673 4.69387755 4.79591837\n 4.89795918 5. ]"
},
{
"code": null,
"e": 2362,
"s": 2323,
"text": "Code #4 : Varying Positional Arguments"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np x = np.linspace(0, 5, 100) # Varying positional argumentsy1 = erlang.pdf(x, 2, 6)y2 = erlang.pdf(x, 1, 4)plt.plot(x, y1, \"*\", x, y2, \"r--\")",
"e": 2554,
"s": 2362,
"text": null
},
{
"code": null,
"e": 2563,
"s": 2554,
"text": "Output :"
},
{
"code": null,
"e": 2592,
"s": 2563,
"text": "Python scipy-stats-functions"
},
{
"code": null,
"e": 2605,
"s": 2592,
"text": "Python-scipy"
},
{
"code": null,
"e": 2612,
"s": 2605,
"text": "Python"
}
] |
Matplotlib.axes.Axes.set_facecolor() in Python
|
19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_facecolor() function in axes module of matplotlib library is used to set the facecolor of the Axes..
Syntax: Axes.set_facecolor(self, color)
Parameters: This method accept only one parameters.color: This parameter accepts the color for the facecolor of the axes.
Returns:This method does not returns any value.
Below examples illustrate the matplotlib.axes.Axes.set_facecolor() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.arange(-5, 5, 0.01)y1 = -3 * x*x + 10 * x + 10y2 = 3 * x*x + x fig, ax = plt.subplots()ax.plot(x, y1, x, y2, color ='black')ax.fill_between(x, y1, y2, where = y2 >y1, facecolor ='green', alpha = 0.8)ax.fill_between(x, y1, y2, where = y2 <= y1, facecolor ='black', alpha = 0.8) ax.set_facecolor('# eafff5')ax.set_title('matplotlib.axes.Axes.get_facecolor() \Example\n', fontsize = 12, fontweight ='bold')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt t = np.linspace(0.0, 2.0, 201)s = np.sin(2 * np.pi * t) fig, ax = plt.subplots()ax.set_facecolor('# E56B51')ax.set_xlabel('x-axis')ax.set_ylabel('y-axis')ax.plot(t, s, )ax.set_title('matplotlib.axes.Axes.get_facecolor()\ Example\n', fontsize = 12, fontweight ='bold')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 442,
"s": 328,
"text": "The Axes.set_facecolor() function in axes module of matplotlib library is used to set the facecolor of the Axes.."
},
{
"code": null,
"e": 482,
"s": 442,
"text": "Syntax: Axes.set_facecolor(self, color)"
},
{
"code": null,
"e": 604,
"s": 482,
"text": "Parameters: This method accept only one parameters.color: This parameter accepts the color for the facecolor of the axes."
},
{
"code": null,
"e": 652,
"s": 604,
"text": "Returns:This method does not returns any value."
},
{
"code": null,
"e": 748,
"s": 652,
"text": "Below examples illustrate the matplotlib.axes.Axes.set_facecolor() function in matplotlib.axes:"
},
{
"code": null,
"e": 759,
"s": 748,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.arange(-5, 5, 0.01)y1 = -3 * x*x + 10 * x + 10y2 = 3 * x*x + x fig, ax = plt.subplots()ax.plot(x, y1, x, y2, color ='black')ax.fill_between(x, y1, y2, where = y2 >y1, facecolor ='green', alpha = 0.8)ax.fill_between(x, y1, y2, where = y2 <= y1, facecolor ='black', alpha = 0.8) ax.set_facecolor('# eafff5')ax.set_title('matplotlib.axes.Axes.get_facecolor() \\Example\\n', fontsize = 12, fontweight ='bold')plt.show()",
"e": 1308,
"s": 759,
"text": null
},
{
"code": null,
"e": 1316,
"s": 1308,
"text": "Output:"
},
{
"code": null,
"e": 1327,
"s": 1316,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt t = np.linspace(0.0, 2.0, 201)s = np.sin(2 * np.pi * t) fig, ax = plt.subplots()ax.set_facecolor('# E56B51')ax.set_xlabel('x-axis')ax.set_ylabel('y-axis')ax.plot(t, s, )ax.set_title('matplotlib.axes.Axes.get_facecolor()\\ Example\\n', fontsize = 12, fontweight ='bold')plt.show()",
"e": 1699,
"s": 1327,
"text": null
},
{
"code": null,
"e": 1707,
"s": 1699,
"text": "Output:"
},
{
"code": null,
"e": 1725,
"s": 1707,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1732,
"s": 1725,
"text": "Python"
}
] |
Communication between Parent and Child process using pipe in Python
|
16 Apr, 2019
Prerequisite – Creating child process in PythonAs there are many processes running simultaneously on the computer so it is very necessary to have proper communication between them as one process may be dependent on other processes.There are various methods to communicate between processes. Here is a simple Python program to demonstrate communication between the parent process and child process using the pipe method.
Library Used –OS Module in Python : The OS module in Python provides a way of using operating system dependent functionality. The functions that the OS module provides allows you to interface with the underlying operating system that Python is running on; be that Windows, Mac or Linux. It can be imported as –
import os
System Call Used –pipe() System call : The method pipe() creates a pipe and returns a pair of file descriptors (r, w) usable for reading and writing, respectively. This method returns a pair of file descriptor.
Syntax – Following is the syntax for pipe() method –
os.pipe()
Note – Pipe is one-way communication only i.e we can use a pipe such that One process write to the pipe, and the other process reads from the pipe.
# Python code to demonstrate communication# between parent and child process using # python. import os def communication(child_writes): # file descriptors r, w for reading and writing r, w = os.pipe() #Creating child process using fork processid = os.fork() if processid: # This is the parent process # Closes file descriptor w os.close(w) r = os.fdopen(r) print ("Parent reading") str = r.read() print( "Parent reads =", str) else: # This is the child process os.close(r) w = os.fdopen(w, 'w') print ("Child writing") w.write(child_writes) print("Child writes = ",child_writes) w.close() # Driver code child_writes = "Hello geeks"communication(child_writes) # Contributed by "Sharad_Bhardwaj".
Output :
Child writing
Child writes = Hello geeks
Parent reading
Parent reads = Hello geeks
Akanksha_Rai
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Apr, 2019"
},
{
"code": null,
"e": 472,
"s": 52,
"text": "Prerequisite – Creating child process in PythonAs there are many processes running simultaneously on the computer so it is very necessary to have proper communication between them as one process may be dependent on other processes.There are various methods to communicate between processes. Here is a simple Python program to demonstrate communication between the parent process and child process using the pipe method."
},
{
"code": null,
"e": 783,
"s": 472,
"text": "Library Used –OS Module in Python : The OS module in Python provides a way of using operating system dependent functionality. The functions that the OS module provides allows you to interface with the underlying operating system that Python is running on; be that Windows, Mac or Linux. It can be imported as –"
},
{
"code": null,
"e": 794,
"s": 783,
"text": "import os\n"
},
{
"code": null,
"e": 1005,
"s": 794,
"text": "System Call Used –pipe() System call : The method pipe() creates a pipe and returns a pair of file descriptors (r, w) usable for reading and writing, respectively. This method returns a pair of file descriptor."
},
{
"code": null,
"e": 1058,
"s": 1005,
"text": "Syntax – Following is the syntax for pipe() method –"
},
{
"code": null,
"e": 1069,
"s": 1058,
"text": "os.pipe()\n"
},
{
"code": null,
"e": 1217,
"s": 1069,
"text": "Note – Pipe is one-way communication only i.e we can use a pipe such that One process write to the pipe, and the other process reads from the pipe."
},
{
"code": "# Python code to demonstrate communication# between parent and child process using # python. import os def communication(child_writes): # file descriptors r, w for reading and writing r, w = os.pipe() #Creating child process using fork processid = os.fork() if processid: # This is the parent process # Closes file descriptor w os.close(w) r = os.fdopen(r) print (\"Parent reading\") str = r.read() print( \"Parent reads =\", str) else: # This is the child process os.close(r) w = os.fdopen(w, 'w') print (\"Child writing\") w.write(child_writes) print(\"Child writes = \",child_writes) w.close() # Driver code child_writes = \"Hello geeks\"communication(child_writes) # Contributed by \"Sharad_Bhardwaj\".",
"e": 2053,
"s": 1217,
"text": null
},
{
"code": null,
"e": 2062,
"s": 2053,
"text": "Output :"
},
{
"code": null,
"e": 2147,
"s": 2062,
"text": "Child writing\nChild writes = Hello geeks\nParent reading\nParent reads = Hello geeks\n"
},
{
"code": null,
"e": 2160,
"s": 2147,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2167,
"s": 2160,
"text": "Python"
},
{
"code": null,
"e": 2183,
"s": 2167,
"text": "Python Programs"
}
] |
Python string | capwords() method
|
11 Aug, 2021
In Python, string capwords() method is used to capitalize all the words in the string using split() method.
Syntax: string.capwords(string, sep=None) Return Value: Returns a formatted string after above operations.
Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.Code #1: If sep parameter is left None.
Python3
# imports string moduleimport string sentence = 'Python is one of the best programming languages.' # sep parameter is left Noneformatted = string.capwords(sentence, sep = None) print(formatted)
Python Is One Of The Best Programming Languages.
Code #2: When sep is not None.
Python3
# imports string moduleimport string sentence = 'Python is one of the best programming languages.' # sep parameter is 'g'formatted = string.capwords(sentence, sep = 'g')print('When sep = "g"', formatted) # sep parameter is 'o'formatted = string.capwords(sentence, sep = 'o')print('When sep = "o"', formatted)
When sep = "g" Python is one of the best progRamming langUagEs.
When sep = "o" PythoN is oNe oF the best proGramming languages.
akshaysingh98088
python-string
Python-string-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 138,
"s": 28,
"text": "In Python, string capwords() method is used to capitalize all the words in the string using split() method. "
},
{
"code": null,
"e": 245,
"s": 138,
"text": "Syntax: string.capwords(string, sep=None) Return Value: Returns a formatted string after above operations."
},
{
"code": null,
"e": 627,
"s": 245,
"text": "Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.Code #1: If sep parameter is left None. "
},
{
"code": null,
"e": 635,
"s": 627,
"text": "Python3"
},
{
"code": "# imports string moduleimport string sentence = 'Python is one of the best programming languages.' # sep parameter is left Noneformatted = string.capwords(sentence, sep = None) print(formatted)",
"e": 829,
"s": 635,
"text": null
},
{
"code": null,
"e": 878,
"s": 829,
"text": "Python Is One Of The Best Programming Languages."
},
{
"code": null,
"e": 915,
"s": 880,
"text": " Code #2: When sep is not None. "
},
{
"code": null,
"e": 923,
"s": 915,
"text": "Python3"
},
{
"code": "# imports string moduleimport string sentence = 'Python is one of the best programming languages.' # sep parameter is 'g'formatted = string.capwords(sentence, sep = 'g')print('When sep = \"g\"', formatted) # sep parameter is 'o'formatted = string.capwords(sentence, sep = 'o')print('When sep = \"o\"', formatted)",
"e": 1232,
"s": 923,
"text": null
},
{
"code": null,
"e": 1360,
"s": 1232,
"text": "When sep = \"g\" Python is one of the best progRamming langUagEs.\nWhen sep = \"o\" PythoN is oNe oF the best proGramming languages."
},
{
"code": null,
"e": 1379,
"s": 1362,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 1393,
"s": 1379,
"text": "python-string"
},
{
"code": null,
"e": 1417,
"s": 1393,
"text": "Python-string-functions"
},
{
"code": null,
"e": 1424,
"s": 1417,
"text": "Python"
}
] |
Kali Linux – Default Passwords
|
30 Jun, 2020
Kali Linux is a great OS for hacking and penetration testing, but as it could be used to hack others it could even get you hacked easily. So it is recommended to use Kali Linux in live mode but during the time of installation we are asked for credentials so we enter them manually. But when we use Kali Live, it uses some default credentials. Here is the list of these credentials:
Kali Linux user policy has changes after the version 2020.1. So, Kali Linux has 2 credentials depending on the version of kali Linux you are using.
For Versions before 2020.1
Root username : root
Root password : toor
For versions after 2020.1 including it
Root username : kali
Root password : kali
For vagrant images(based on their policy)
Root username : vagrant
Root password : vagrant
BeEf-XSS
username : beef
password : beef
MySQL
username : root
password : (blank)
Note: Here (blank) means you have to leave the password space empty.
OpenVAS
username : admin
password : <Generated during Setup>
Metasploit
username : postgres
password : postgres
Kali-Linux
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2020"
},
{
"code": null,
"e": 410,
"s": 28,
"text": "Kali Linux is a great OS for hacking and penetration testing, but as it could be used to hack others it could even get you hacked easily. So it is recommended to use Kali Linux in live mode but during the time of installation we are asked for credentials so we enter them manually. But when we use Kali Live, it uses some default credentials. Here is the list of these credentials:"
},
{
"code": null,
"e": 558,
"s": 410,
"text": "Kali Linux user policy has changes after the version 2020.1. So, Kali Linux has 2 credentials depending on the version of kali Linux you are using."
},
{
"code": null,
"e": 585,
"s": 558,
"text": "For Versions before 2020.1"
},
{
"code": null,
"e": 628,
"s": 585,
"text": "Root username : root\nRoot password : toor\n"
},
{
"code": null,
"e": 667,
"s": 628,
"text": "For versions after 2020.1 including it"
},
{
"code": null,
"e": 710,
"s": 667,
"text": "Root username : kali\nRoot password : kali\n"
},
{
"code": null,
"e": 752,
"s": 710,
"text": "For vagrant images(based on their policy)"
},
{
"code": null,
"e": 801,
"s": 752,
"text": "Root username : vagrant\nRoot password : vagrant\n"
},
{
"code": null,
"e": 810,
"s": 801,
"text": "BeEf-XSS"
},
{
"code": null,
"e": 843,
"s": 810,
"text": "username : beef\npassword : beef\n"
},
{
"code": null,
"e": 849,
"s": 843,
"text": "MySQL"
},
{
"code": null,
"e": 885,
"s": 849,
"text": "username : root\npassword : (blank)\n"
},
{
"code": null,
"e": 954,
"s": 885,
"text": "Note: Here (blank) means you have to leave the password space empty."
},
{
"code": null,
"e": 962,
"s": 954,
"text": "OpenVAS"
},
{
"code": null,
"e": 1016,
"s": 962,
"text": "username : admin\npassword : <Generated during Setup>\n"
},
{
"code": null,
"e": 1027,
"s": 1016,
"text": "Metasploit"
},
{
"code": null,
"e": 1068,
"s": 1027,
"text": "username : postgres\npassword : postgres\n"
},
{
"code": null,
"e": 1079,
"s": 1068,
"text": "Kali-Linux"
},
{
"code": null,
"e": 1090,
"s": 1079,
"text": "Linux-Unix"
}
] |
Difference between include() and include_once() in PHP
|
29 Oct, 2021
The include() function in PHP is mostly used to include the code/data of one PHP file to another file. During this process if there are any kind of errors then this require() function will display/give a warning but unlike the require() function in which the execution comes to a halt, the include() function will not stop the execution of the script rather the script will continue its process.
In order to use the include() function, we will first need to create two PHP files. Then using the include() function put one PHP file into another one. After that, you will see two PHP files combined into one HTML file. This include() will not see whether the code is already included in the specified file, rather it will include the code number of times the include() is been used.
Example: Assume we have a file called includegfg.php.
includegfg.php
<?php echo "<p>Visit Again; " . date("Y") . " Geeks for geeks.com</p>";?>
We have created a file demo.php. Using the include() method we will include the includegfg.php file into the demo.php file.
demo.php
<html><body> <h1>Welcome to geeks for geeks!</h1> <p>Myself, Gaurav Gandal</p> <p>Thank you</p> <?php include 'includegfg.php'; ?></body></html>
Output:
include_once():
The include_once() function in PHP is mainly used to include one PHP file into another PHP file. It provides us with a feature that if a code from a PHP file is already included in a specified file then it will not include that code again. It means that this function will add a file into another only once. In case this function locates an error then it will produce a warning but will not stop the execution.
If ABC.php file calls XYZ.php file using include_once() and any error occurs then it will produce a warning but will not stop the script execution.
Example: Below we have created a sample PHP file called demo.php, which displays the message “Hello from Geeks for Geeks.”
demo.php
<?php echo "Hello from Geeks for Geeks";?>
In the following PHP file require_once_demo.php, we have called the demo.php file twice using the require_once(), but it will not execute the second call.
require_once_demo.php
<?php include_once('demo.php'); include_once('demo.php');?>
Output:
Difference between include() and include_once():
PHP-Questions
Difference Between
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 424,
"s": 28,
"text": "The include() function in PHP is mostly used to include the code/data of one PHP file to another file. During this process if there are any kind of errors then this require() function will display/give a warning but unlike the require() function in which the execution comes to a halt, the include() function will not stop the execution of the script rather the script will continue its process."
},
{
"code": null,
"e": 809,
"s": 424,
"text": "In order to use the include() function, we will first need to create two PHP files. Then using the include() function put one PHP file into another one. After that, you will see two PHP files combined into one HTML file. This include() will not see whether the code is already included in the specified file, rather it will include the code number of times the include() is been used."
},
{
"code": null,
"e": 863,
"s": 809,
"text": "Example: Assume we have a file called includegfg.php."
},
{
"code": null,
"e": 878,
"s": 863,
"text": "includegfg.php"
},
{
"code": "<?php echo \"<p>Visit Again; \" . date(\"Y\") . \" Geeks for geeks.com</p>\";?>",
"e": 954,
"s": 878,
"text": null
},
{
"code": null,
"e": 1078,
"s": 954,
"text": "We have created a file demo.php. Using the include() method we will include the includegfg.php file into the demo.php file."
},
{
"code": null,
"e": 1087,
"s": 1078,
"text": "demo.php"
},
{
"code": "<html><body> <h1>Welcome to geeks for geeks!</h1> <p>Myself, Gaurav Gandal</p> <p>Thank you</p> <?php include 'includegfg.php'; ?></body></html>",
"e": 1243,
"s": 1087,
"text": null
},
{
"code": null,
"e": 1251,
"s": 1243,
"text": "Output:"
},
{
"code": null,
"e": 1267,
"s": 1251,
"text": "include_once():"
},
{
"code": null,
"e": 1678,
"s": 1267,
"text": "The include_once() function in PHP is mainly used to include one PHP file into another PHP file. It provides us with a feature that if a code from a PHP file is already included in a specified file then it will not include that code again. It means that this function will add a file into another only once. In case this function locates an error then it will produce a warning but will not stop the execution."
},
{
"code": null,
"e": 1826,
"s": 1678,
"text": "If ABC.php file calls XYZ.php file using include_once() and any error occurs then it will produce a warning but will not stop the script execution."
},
{
"code": null,
"e": 1949,
"s": 1826,
"text": "Example: Below we have created a sample PHP file called demo.php, which displays the message “Hello from Geeks for Geeks.”"
},
{
"code": null,
"e": 1958,
"s": 1949,
"text": "demo.php"
},
{
"code": "<?php echo \"Hello from Geeks for Geeks\";?>",
"e": 2003,
"s": 1958,
"text": null
},
{
"code": null,
"e": 2158,
"s": 2003,
"text": "In the following PHP file require_once_demo.php, we have called the demo.php file twice using the require_once(), but it will not execute the second call."
},
{
"code": null,
"e": 2180,
"s": 2158,
"text": "require_once_demo.php"
},
{
"code": "<?php include_once('demo.php'); include_once('demo.php');?>",
"e": 2244,
"s": 2180,
"text": null
},
{
"code": null,
"e": 2252,
"s": 2244,
"text": "Output:"
},
{
"code": null,
"e": 2301,
"s": 2252,
"text": "Difference between include() and include_once():"
},
{
"code": null,
"e": 2315,
"s": 2301,
"text": "PHP-Questions"
},
{
"code": null,
"e": 2334,
"s": 2315,
"text": "Difference Between"
},
{
"code": null,
"e": 2338,
"s": 2334,
"text": "PHP"
},
{
"code": null,
"e": 2355,
"s": 2338,
"text": "Web Technologies"
},
{
"code": null,
"e": 2359,
"s": 2355,
"text": "PHP"
}
] |
ReactJS UI Ant Design Tabs Component
|
01 Jun, 2021
Ant Design Library has this component pre-built, and it is very easy to integrate as well. Tabs Component to used as Tabs make it easy to switch between different views. We can use the following approach in ReactJS to use the Ant Design Tabs Component.
Tabs Props:
activeKey: It is used to denote the current TabPane’s key.
addIcon: It is used for the customize add icon.
animated: It is used to indicate whether to change tabs with animation.
centered: It is used to centers the tabs.
defaultActiveKey: It is used to denote the initial active TabPane’s key.
hideAdd: It is used to indicate whether to hide plus icon or not.
moreIcon: It is used for the custom icon of ellipsis.
renderTabBar: It is used to replace the TabBar.
size: It is used to denote the tab bar size.
tabBarExtraContent: It is used to denote the extra content in the tab bar.
tabBarGutter: It is used to denote the gap between tabs.
tabBarStyle: It is used for the Tab bar-style object.
tabPosition: It is used to position the tabs.
type: It is used to denote the basic style of tabs.
onChange: It is a callback function that is triggered when the active tab is changed.
onEdit: It is a callback function that is triggered when the tab is added or removed.
onTabClick: It is a callback function that is triggered when the tab is clicked.
onTabScroll: It is a callback function that is triggered when the tab scrolls.
Tabs.TabPane Props:
closeIcon: It is used for customize close icon in TabPane’s head.
forceRender: It is used for the forced render of content in tabs.
key: It is used to denote the TabPane’s key.
tab: It is used to show text in TabPane’s head.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install antd
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react'import "antd/dist/antd.css";import { Tabs } from 'antd'; const { TabPane } = Tabs; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design ConfigProvider Component</h4> <Tabs> <TabPane tab="Tab 1" key="1"> 1st TAB PANE Content </TabPane> <TabPane tab="Tab 2" key="2"> 2nd TAB PANE Content </TabPane> <TabPane tab="Tab 3" key="3"> 3rd TAB PANE Content </TabPane> </Tabs> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://ant.design/components/tabs/
ReactJS-Ant Design
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from an API in ReactJS ?
Axios in React: A Guide for Beginners
How to redirect to another page in ReactJS ?
ReactJS Functional Components
ReactJS setState()
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": "\n01 Jun, 2021"
},
{
"code": null,
"e": 281,
"s": 28,
"text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. Tabs Component to used as Tabs make it easy to switch between different views. We can use the following approach in ReactJS to use the Ant Design Tabs Component."
},
{
"code": null,
"e": 293,
"s": 281,
"text": "Tabs Props:"
},
{
"code": null,
"e": 352,
"s": 293,
"text": "activeKey: It is used to denote the current TabPane’s key."
},
{
"code": null,
"e": 400,
"s": 352,
"text": "addIcon: It is used for the customize add icon."
},
{
"code": null,
"e": 472,
"s": 400,
"text": "animated: It is used to indicate whether to change tabs with animation."
},
{
"code": null,
"e": 514,
"s": 472,
"text": "centered: It is used to centers the tabs."
},
{
"code": null,
"e": 587,
"s": 514,
"text": "defaultActiveKey: It is used to denote the initial active TabPane’s key."
},
{
"code": null,
"e": 653,
"s": 587,
"text": "hideAdd: It is used to indicate whether to hide plus icon or not."
},
{
"code": null,
"e": 707,
"s": 653,
"text": "moreIcon: It is used for the custom icon of ellipsis."
},
{
"code": null,
"e": 755,
"s": 707,
"text": "renderTabBar: It is used to replace the TabBar."
},
{
"code": null,
"e": 800,
"s": 755,
"text": "size: It is used to denote the tab bar size."
},
{
"code": null,
"e": 875,
"s": 800,
"text": "tabBarExtraContent: It is used to denote the extra content in the tab bar."
},
{
"code": null,
"e": 932,
"s": 875,
"text": "tabBarGutter: It is used to denote the gap between tabs."
},
{
"code": null,
"e": 986,
"s": 932,
"text": "tabBarStyle: It is used for the Tab bar-style object."
},
{
"code": null,
"e": 1032,
"s": 986,
"text": "tabPosition: It is used to position the tabs."
},
{
"code": null,
"e": 1084,
"s": 1032,
"text": "type: It is used to denote the basic style of tabs."
},
{
"code": null,
"e": 1170,
"s": 1084,
"text": "onChange: It is a callback function that is triggered when the active tab is changed."
},
{
"code": null,
"e": 1256,
"s": 1170,
"text": "onEdit: It is a callback function that is triggered when the tab is added or removed."
},
{
"code": null,
"e": 1337,
"s": 1256,
"text": "onTabClick: It is a callback function that is triggered when the tab is clicked."
},
{
"code": null,
"e": 1416,
"s": 1337,
"text": "onTabScroll: It is a callback function that is triggered when the tab scrolls."
},
{
"code": null,
"e": 1436,
"s": 1416,
"text": "Tabs.TabPane Props:"
},
{
"code": null,
"e": 1502,
"s": 1436,
"text": "closeIcon: It is used for customize close icon in TabPane’s head."
},
{
"code": null,
"e": 1568,
"s": 1502,
"text": "forceRender: It is used for the forced render of content in tabs."
},
{
"code": null,
"e": 1613,
"s": 1568,
"text": "key: It is used to denote the TabPane’s key."
},
{
"code": null,
"e": 1661,
"s": 1613,
"text": "tab: It is used to show text in TabPane’s head."
},
{
"code": null,
"e": 1711,
"s": 1661,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 1806,
"s": 1711,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 1870,
"s": 1806,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 1902,
"s": 1870,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 2015,
"s": 1902,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 2115,
"s": 2015,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 2129,
"s": 2115,
"text": "cd foldername"
},
{
"code": null,
"e": 2250,
"s": 2129,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd"
},
{
"code": null,
"e": 2355,
"s": 2250,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 2372,
"s": 2355,
"text": "npm install antd"
},
{
"code": null,
"e": 2424,
"s": 2372,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 2442,
"s": 2424,
"text": "Project Structure"
},
{
"code": null,
"e": 2572,
"s": 2442,
"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": 2579,
"s": 2572,
"text": "App.js"
},
{
"code": "import React from 'react'import \"antd/dist/antd.css\";import { Tabs } from 'antd'; const { TabPane } = Tabs; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design ConfigProvider Component</h4> <Tabs> <TabPane tab=\"Tab 1\" key=\"1\"> 1st TAB PANE Content </TabPane> <TabPane tab=\"Tab 2\" key=\"2\"> 2nd TAB PANE Content </TabPane> <TabPane tab=\"Tab 3\" key=\"3\"> 3rd TAB PANE Content </TabPane> </Tabs> </div> );}",
"e": 3155,
"s": 2579,
"text": null
},
{
"code": null,
"e": 3268,
"s": 3155,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 3278,
"s": 3268,
"text": "npm start"
},
{
"code": null,
"e": 3377,
"s": 3278,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 3424,
"s": 3377,
"text": "Reference: https://ant.design/components/tabs/"
},
{
"code": null,
"e": 3443,
"s": 3424,
"text": "ReactJS-Ant Design"
},
{
"code": null,
"e": 3451,
"s": 3443,
"text": "ReactJS"
},
{
"code": null,
"e": 3468,
"s": 3451,
"text": "Web Technologies"
},
{
"code": null,
"e": 3566,
"s": 3468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3609,
"s": 3566,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 3647,
"s": 3609,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 3692,
"s": 3647,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 3722,
"s": 3692,
"text": "ReactJS Functional Components"
},
{
"code": null,
"e": 3741,
"s": 3722,
"text": "ReactJS setState()"
},
{
"code": null,
"e": 3774,
"s": 3741,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3836,
"s": 3774,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3897,
"s": 3836,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3947,
"s": 3897,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to convert Python’s .isoformat() string back into datetime object
|
28 Jul, 2021
In this article, we will learn how to convert Pythons .isoFormat() string back into a datetime object. Here we are using the current time and for that, we will store the current time in the current_time variable.
The function now() of this module, does the job perfectly.
Example: Getting current time
Python3
from datetime import datetime current_time = datetime.now() print(current_time)
Output:
2021-07-22 15:17:19.735037
In this step, we are going to get the string format of the iso time. For this, isoformat() function is used.
Example: getting string format of time
Python3
from datetime import datetime current_time = datetime.now().isoformat()print(current_time)
2021-07-26T11:36:17.090181
So here we are going to get the DateTime object from the iso string. For that fromisoformat() function is used.
Example: Get the DateTime object from the iso format
Python3
from datetime import datetime current_time = datetime.now().isoformat() print(datetime.fromisoformat(current_time))
Output:
2021-07-26 17:06:51.149731
Picked
Python datetime-program
Python-datetime
Python
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": 241,
"s": 28,
"text": "In this article, we will learn how to convert Pythons .isoFormat() string back into a datetime object. Here we are using the current time and for that, we will store the current time in the current_time variable."
},
{
"code": null,
"e": 300,
"s": 241,
"text": "The function now() of this module, does the job perfectly."
},
{
"code": null,
"e": 330,
"s": 300,
"text": "Example: Getting current time"
},
{
"code": null,
"e": 338,
"s": 330,
"text": "Python3"
},
{
"code": "from datetime import datetime current_time = datetime.now() print(current_time)",
"e": 420,
"s": 338,
"text": null
},
{
"code": null,
"e": 428,
"s": 420,
"text": "Output:"
},
{
"code": null,
"e": 455,
"s": 428,
"text": "2021-07-22 15:17:19.735037"
},
{
"code": null,
"e": 564,
"s": 455,
"text": "In this step, we are going to get the string format of the iso time. For this, isoformat() function is used."
},
{
"code": null,
"e": 603,
"s": 564,
"text": "Example: getting string format of time"
},
{
"code": null,
"e": 611,
"s": 603,
"text": "Python3"
},
{
"code": "from datetime import datetime current_time = datetime.now().isoformat()print(current_time)",
"e": 703,
"s": 611,
"text": null
},
{
"code": null,
"e": 731,
"s": 703,
"text": "2021-07-26T11:36:17.090181\n"
},
{
"code": null,
"e": 843,
"s": 731,
"text": "So here we are going to get the DateTime object from the iso string. For that fromisoformat() function is used."
},
{
"code": null,
"e": 896,
"s": 843,
"text": "Example: Get the DateTime object from the iso format"
},
{
"code": null,
"e": 904,
"s": 896,
"text": "Python3"
},
{
"code": "from datetime import datetime current_time = datetime.now().isoformat() print(datetime.fromisoformat(current_time))",
"e": 1022,
"s": 904,
"text": null
},
{
"code": null,
"e": 1030,
"s": 1022,
"text": "Output:"
},
{
"code": null,
"e": 1057,
"s": 1030,
"text": "2021-07-26 17:06:51.149731"
},
{
"code": null,
"e": 1064,
"s": 1057,
"text": "Picked"
},
{
"code": null,
"e": 1088,
"s": 1064,
"text": "Python datetime-program"
},
{
"code": null,
"e": 1104,
"s": 1088,
"text": "Python-datetime"
},
{
"code": null,
"e": 1111,
"s": 1104,
"text": "Python"
}
] |
How to connect Node.js application to MySQL ?
|
19 Oct, 2021
Node.js is an open-source and cross-platform runtime environment built on Chrome’s V8 engine that enables us to use JavaScript outside the browser. Node.js helps us to use build server-side applications using JavaScript. In this article, we will discuss how to connect the Node.js application to MySQL. For connecting the node.js with MySQL database we need a third-party mysql module.
Approach:
First, initialize the node.js project in the particular folder in your machine.
Download the mysql module in the project folder.
After this create connection to the database with the createconnection() method of the mysql module.
The above approach is discussed below:
Step 1: Create a NodeJS Project and initialize it using the following command:
npm init
Step 2: Install the mysql modules using the following command:
npm install mysql
File Structure: Our file structure will look like the following:
Mysql database Structure:
index.js
// Importing modulevar mysql = require('mysql') var connection = mysql.createConnection({ host:"localhost", user:"root", password:"Aayush", database : "aayush"}) // Connecting to databaseconnection.connect(function(err) { if(err){ console.log("Error in the connection") console.log(err) } else{ console.log(`Database Connected`) connection.query(`SHOW DATABASES`, function (err, result) { if(err) console.log(`Error executing the query - ${err}`) else console.log("Result: ",result) }) }})
Run index.js file using below command:
node index.js
Console Output:
NodeJS-MySQL
NodeJS-Questions
Picked
TrueGeek-2021
Node.js
TrueGeek
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": 414,
"s": 28,
"text": "Node.js is an open-source and cross-platform runtime environment built on Chrome’s V8 engine that enables us to use JavaScript outside the browser. Node.js helps us to use build server-side applications using JavaScript. In this article, we will discuss how to connect the Node.js application to MySQL. For connecting the node.js with MySQL database we need a third-party mysql module."
},
{
"code": null,
"e": 424,
"s": 414,
"text": "Approach:"
},
{
"code": null,
"e": 504,
"s": 424,
"text": "First, initialize the node.js project in the particular folder in your machine."
},
{
"code": null,
"e": 553,
"s": 504,
"text": "Download the mysql module in the project folder."
},
{
"code": null,
"e": 654,
"s": 553,
"text": "After this create connection to the database with the createconnection() method of the mysql module."
},
{
"code": null,
"e": 693,
"s": 654,
"text": "The above approach is discussed below:"
},
{
"code": null,
"e": 772,
"s": 693,
"text": "Step 1: Create a NodeJS Project and initialize it using the following command:"
},
{
"code": null,
"e": 781,
"s": 772,
"text": "npm init"
},
{
"code": null,
"e": 844,
"s": 781,
"text": "Step 2: Install the mysql modules using the following command:"
},
{
"code": null,
"e": 862,
"s": 844,
"text": "npm install mysql"
},
{
"code": null,
"e": 927,
"s": 862,
"text": "File Structure: Our file structure will look like the following:"
},
{
"code": null,
"e": 953,
"s": 927,
"text": "Mysql database Structure:"
},
{
"code": null,
"e": 962,
"s": 953,
"text": "index.js"
},
{
"code": "// Importing modulevar mysql = require('mysql') var connection = mysql.createConnection({ host:\"localhost\", user:\"root\", password:\"Aayush\", database : \"aayush\"}) // Connecting to databaseconnection.connect(function(err) { if(err){ console.log(\"Error in the connection\") console.log(err) } else{ console.log(`Database Connected`) connection.query(`SHOW DATABASES`, function (err, result) { if(err) console.log(`Error executing the query - ${err}`) else console.log(\"Result: \",result) }) }})",
"e": 1542,
"s": 962,
"text": null
},
{
"code": null,
"e": 1581,
"s": 1542,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 1595,
"s": 1581,
"text": "node index.js"
},
{
"code": null,
"e": 1611,
"s": 1595,
"text": "Console Output:"
},
{
"code": null,
"e": 1624,
"s": 1611,
"text": "NodeJS-MySQL"
},
{
"code": null,
"e": 1641,
"s": 1624,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 1648,
"s": 1641,
"text": "Picked"
},
{
"code": null,
"e": 1662,
"s": 1648,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 1670,
"s": 1662,
"text": "Node.js"
},
{
"code": null,
"e": 1679,
"s": 1670,
"text": "TrueGeek"
},
{
"code": null,
"e": 1696,
"s": 1679,
"text": "Web Technologies"
}
] |
Seaborn - Color Palette
|
Color plays an important role than any other aspect in the visualizations. When used effectively, color adds more value to the plot. A palette means a flat surface on which a painter arranges and mixes paints.
Seaborn provides a function called color_palette(), which can be used to give colors to plots and adding more aesthetic value to it.
seaborn.color_palette(palette = None, n_colors = None, desat = None)
The following table lists down the parameters for building color palette −
n_colors
Number of colors in the palette. If None, the default will depend on how palette is specified. By default the value of n_colors is 6 colors.
desat
Proportion to desaturate each color.
Return refers to the list of RGB tuples. Following are the readily available Seaborn palettes −
Deep
Muted
Bright
Pastel
Dark
Colorblind
Besides these, one can also generate new palette
It is hard to decide which palette should be used for a given data set without knowing the characteristics of data. Being aware of it, we will classify the different ways for using color_palette() types −
qualitative
sequential
diverging
We have another function seaborn.palplot() which deals with color palettes. This function plots the color palette as horizontal array. We will know more regarding seaborn.palplot() in the coming examples.
Qualitative or categorical palettes are best suitable to plot the categorical data.
from matplotlib import pyplot as plt
import seaborn as sb
current_palette = sb.color_palette()
sb.palplot(current_palette)
plt.show()
We haven’t passed any parameters in color_palette(); by default, we are seeing 6 colors. You can see the desired number of colors by passing a value to the n_colors parameter. Here, the palplot() is used to plot the array of colors horizontally.
Sequential plots are suitable to express the distribution of data ranging from relative lower values to higher values within a range.
Appending an additional character ‘s’ to the color passed to the color parameter will plot the Sequential plot.
from matplotlib import pyplot as plt
import seaborn as sb
current_palette = sb.color_palette()
sb.palplot(sb.color_palette("Greens"))
plt.show()
Note −We need to append ‘s’ to the parameter like ‘Greens’ in the above example.
Diverging palettes use two different colors. Each color represents variation in the value ranging from a common point in either direction.
Assume plotting the data ranging from -1 to 1. The values from -1 to 0 takes one color and 0 to +1 takes another color.
By default, the values are centered from zero. You can control it with parameter center by passing a value.
from matplotlib import pyplot as plt
import seaborn as sb
current_palette = sb.color_palette()
sb.palplot(sb.color_palette("BrBG", 7))
plt.show()
The functions color_palette() has a companion called set_palette() The relationship between them is similar to the pairs covered in the aesthetics chapter. The arguments are same for both set_palette() and color_palette(), but the default Matplotlib parameters are changed so that the palette is used for all plots.
import numpy as np
from matplotlib import pyplot as plt
def sinplot(flip = 1):
x = np.linspace(0, 14, 100)
for i in range(1, 5):
plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)
import seaborn as sb
sb.set_style("white")
sb.set_palette("husl")
sinplot()
plt.show()
Distribution of data is the foremost thing that we need to understand while analysing the data. Here, we will see how seaborn helps us in understanding the univariate distribution of the data.
Function distplot() provides the most convenient way to take a quick look at univariate distribution. This function will plot a histogram that fits the kernel density estimation of the data.
seaborn.distplot()
The following table lists down the parameters and their description −
data
Series, 1d array or a list
bins
Specification of hist bins
hist
bool
kde
bool
These are basic and important parameters to look into.
11 Lectures
4 hours
DATAhill Solutions Srinivas Reddy
11 Lectures
2.5 hours
DATAhill Solutions Srinivas Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2250,
"s": 2039,
"text": "Color plays an important role than any other aspect in the visualizations. When used effectively, color adds more value to the plot. A palette means a flat surface on which a painter arranges and mixes paints.\n"
},
{
"code": null,
"e": 2383,
"s": 2250,
"text": "Seaborn provides a function called color_palette(), which can be used to give colors to plots and adding more aesthetic value to it."
},
{
"code": null,
"e": 2453,
"s": 2383,
"text": "seaborn.color_palette(palette = None, n_colors = None, desat = None)\n"
},
{
"code": null,
"e": 2528,
"s": 2453,
"text": "The following table lists down the parameters for building color palette −"
},
{
"code": null,
"e": 2537,
"s": 2528,
"text": "n_colors"
},
{
"code": null,
"e": 2678,
"s": 2537,
"text": "Number of colors in the palette. If None, the default will depend on how palette is specified. By default the value of n_colors is 6 colors."
},
{
"code": null,
"e": 2684,
"s": 2678,
"text": "desat"
},
{
"code": null,
"e": 2721,
"s": 2684,
"text": "Proportion to desaturate each color."
},
{
"code": null,
"e": 2817,
"s": 2721,
"text": "Return refers to the list of RGB tuples. Following are the readily available Seaborn palettes −"
},
{
"code": null,
"e": 2822,
"s": 2817,
"text": "Deep"
},
{
"code": null,
"e": 2828,
"s": 2822,
"text": "Muted"
},
{
"code": null,
"e": 2835,
"s": 2828,
"text": "Bright"
},
{
"code": null,
"e": 2842,
"s": 2835,
"text": "Pastel"
},
{
"code": null,
"e": 2847,
"s": 2842,
"text": "Dark"
},
{
"code": null,
"e": 2858,
"s": 2847,
"text": "Colorblind"
},
{
"code": null,
"e": 2907,
"s": 2858,
"text": "Besides these, one can also generate new palette"
},
{
"code": null,
"e": 3112,
"s": 2907,
"text": "It is hard to decide which palette should be used for a given data set without knowing the characteristics of data. Being aware of it, we will classify the different ways for using color_palette() types −"
},
{
"code": null,
"e": 3124,
"s": 3112,
"text": "qualitative"
},
{
"code": null,
"e": 3135,
"s": 3124,
"text": "sequential"
},
{
"code": null,
"e": 3145,
"s": 3135,
"text": "diverging"
},
{
"code": null,
"e": 3350,
"s": 3145,
"text": "We have another function seaborn.palplot() which deals with color palettes. This function plots the color palette as horizontal array. We will know more regarding seaborn.palplot() in the coming examples."
},
{
"code": null,
"e": 3434,
"s": 3350,
"text": "Qualitative or categorical palettes are best suitable to plot the categorical data."
},
{
"code": null,
"e": 3569,
"s": 3434,
"text": "from matplotlib import pyplot as plt\nimport seaborn as sb\ncurrent_palette = sb.color_palette()\nsb.palplot(current_palette)\nplt.show()\n"
},
{
"code": null,
"e": 3815,
"s": 3569,
"text": "We haven’t passed any parameters in color_palette(); by default, we are seeing 6 colors. You can see the desired number of colors by passing a value to the n_colors parameter. Here, the palplot() is used to plot the array of colors horizontally."
},
{
"code": null,
"e": 3949,
"s": 3815,
"text": "Sequential plots are suitable to express the distribution of data ranging from relative lower values to higher values within a range."
},
{
"code": null,
"e": 4061,
"s": 3949,
"text": "Appending an additional character ‘s’ to the color passed to the color parameter will plot the Sequential plot."
},
{
"code": null,
"e": 4207,
"s": 4061,
"text": "from matplotlib import pyplot as plt\nimport seaborn as sb\ncurrent_palette = sb.color_palette()\nsb.palplot(sb.color_palette(\"Greens\"))\nplt.show()\n"
},
{
"code": null,
"e": 4288,
"s": 4207,
"text": "Note −We need to append ‘s’ to the parameter like ‘Greens’ in the above example."
},
{
"code": null,
"e": 4427,
"s": 4288,
"text": "Diverging palettes use two different colors. Each color represents variation in the value ranging from a common point in either direction."
},
{
"code": null,
"e": 4547,
"s": 4427,
"text": "Assume plotting the data ranging from -1 to 1. The values from -1 to 0 takes one color and 0 to +1 takes another color."
},
{
"code": null,
"e": 4655,
"s": 4547,
"text": "By default, the values are centered from zero. You can control it with parameter center by passing a value."
},
{
"code": null,
"e": 4802,
"s": 4655,
"text": "from matplotlib import pyplot as plt\nimport seaborn as sb\ncurrent_palette = sb.color_palette()\nsb.palplot(sb.color_palette(\"BrBG\", 7))\nplt.show()\n"
},
{
"code": null,
"e": 5118,
"s": 4802,
"text": "The functions color_palette() has a companion called set_palette() The relationship between them is similar to the pairs covered in the aesthetics chapter. The arguments are same for both set_palette() and color_palette(), but the default Matplotlib parameters are changed so that the palette is used for all plots."
},
{
"code": null,
"e": 5397,
"s": 5118,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\ndef sinplot(flip = 1):\n x = np.linspace(0, 14, 100)\n for i in range(1, 5):\n plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)\n\nimport seaborn as sb\nsb.set_style(\"white\")\nsb.set_palette(\"husl\")\nsinplot()\nplt.show()\n"
},
{
"code": null,
"e": 5590,
"s": 5397,
"text": "Distribution of data is the foremost thing that we need to understand while analysing the data. Here, we will see how seaborn helps us in understanding the univariate distribution of the data."
},
{
"code": null,
"e": 5781,
"s": 5590,
"text": "Function distplot() provides the most convenient way to take a quick look at univariate distribution. This function will plot a histogram that fits the kernel density estimation of the data."
},
{
"code": null,
"e": 5801,
"s": 5781,
"text": "seaborn.distplot()\n"
},
{
"code": null,
"e": 5871,
"s": 5801,
"text": "The following table lists down the parameters and their description −"
},
{
"code": null,
"e": 5876,
"s": 5871,
"text": "data"
},
{
"code": null,
"e": 5903,
"s": 5876,
"text": "Series, 1d array or a list"
},
{
"code": null,
"e": 5908,
"s": 5903,
"text": "bins"
},
{
"code": null,
"e": 5935,
"s": 5908,
"text": "Specification of hist bins"
},
{
"code": null,
"e": 5940,
"s": 5935,
"text": "hist"
},
{
"code": null,
"e": 5945,
"s": 5940,
"text": "bool"
},
{
"code": null,
"e": 5949,
"s": 5945,
"text": "kde"
},
{
"code": null,
"e": 5954,
"s": 5949,
"text": "bool"
},
{
"code": null,
"e": 6009,
"s": 5954,
"text": "These are basic and important parameters to look into."
},
{
"code": null,
"e": 6042,
"s": 6009,
"text": "\n 11 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6077,
"s": 6042,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 6112,
"s": 6077,
"text": "\n 11 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6147,
"s": 6112,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 6154,
"s": 6147,
"text": " Print"
},
{
"code": null,
"e": 6165,
"s": 6154,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.