title stringlengths 3 221 | text stringlengths 17 477k | parsed listlengths 0 3.17k |
|---|---|---|
Array element with minimum sum of absolute differences? | Here we will see one interesting problem. We are taking one array ‘a’ with N elements. We have to find an element x such that |a[0] - x| + |a[1] - x|+ ... + |a[n-1] - x| is minimized. Then we have to find the minimized sum.
Let the array is: {1, 3, 9, 6, 3} now the x is 3. So the sum is |1 - 3| + |3 - 3| + |9 - 3| + |6 - 3| + |3 - 3| = 11.
To solve this problem, we have to choose the median of the array as x. If the array size is even, then two median values will be there. Both of them will be an optimal choice of x.
begin
sort array arr
sum := 0
med := median of arr
for each element e in arr, do
sum := sum + |e - med|
done
return sum
end
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int minSum(int arr[], int n){
sort(arr, arr + n);
int sum = 0;
int med = arr[n/2];
for(int i = 0; i<n; i++){
sum += abs(arr[i] - med);
}
return sum;
}
int main() {
int arr[5] = {1, 3, 9, 6, 3};
int n = 5;
cout << "Sum : " << minSum(arr, n);
}
Sum : 11 | [
{
"code": null,
"e": 1286,
"s": 1062,
"text": "Here we will see one interesting problem. We are taking one array ‘a’ with N elements. We have to find an element x such that |a[0] - x| + |a[1] - x|+ ... + |a[n-1] - x| is minimized. Then we have to find the minimized sum."
},
{
"code": null,
... |
How to call a function that return another function in JavaScript ? - GeeksforGeeks | 24 Jul, 2019
The task is to call a function which returns another function with the help of JavaScript. we’re going to discuss few techniques.
Approach:
First call the first function-1.
Define a function-2 inside the function-1.
Return the call to the function-2 from the function-1.
Example 1: In this example, “from function 2” is returned from the fun2 which is finally returned by fun1.
<!DOCTYPE HTML><html> <head> <title> JavaScript | Function that return a function. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to call a function, "+ "which returns the call to another function."; function fun1() { function fun2() { return "From function fun2"; } return fun2(); } function GFG_Fun() { el_down.innerHTML = fun1(); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: In this example, “Alert from fun2” is returned from the fun2 alongwith an alert, Returned value finally returned by fun1.
<!DOCTYPE HTML><html> <head> <title> JavaScript | Function that return a function. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to call a function, "+ "which returns the call to another function."; function fun1() { function fun2() { alert("From function fun2"); return "Alert from fun2 "; } return fun2(); } function GFG_Fun() { el_down.innerHTML = fun1(); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24049,
"s": 24021,
"text": "\n24 Jul, 2019"
},
{
"code": null,
"e": 24179,
"s": 24049,
"text": "The task is to call a function which returns another function with the help of JavaScript. we’re going to discuss few techniques."
},
{
"code": null,
"... |
How to change the color of bars in base R barplot? | To change the color of bars in base R barplot, we can use col argument inside the barplot function.
For example, if we have a vector called V for which we want to create the barplot then we can use the command given below to get the bars in blue color −
barplot(V,col="blue")
Check out the below example to understand how it can be done.
To change the color of bars in base R barplot, use the code given below −
x<-rpois(10,5)
x
If you execute the above given code, it generates the following output −
[1] 4 3 2 8 2 8 4 2 3 5
To change the color of bars in base R barplot, add the following code to the above code −
x<-rpois(10,5)
barplot(x)
If you execute all the above given snippets as a single program, it generates the following output −
To change the color of bars in base R barplot, add the following code to the above code −
x<-rpois(10,5)
barplot(x,col="red")
If you execute all the above given snippets as a single program, it generates the following output −
To change the color of bars in base R barplot, add the following code to the above code −
x<-rpois(10,5)
barplot(x,col="blue")
If you execute all the above given snippets as a single program, it generates the following output − | [
{
"code": null,
"e": 1162,
"s": 1062,
"text": "To change the color of bars in base R barplot, we can use col argument inside the barplot function."
},
{
"code": null,
"e": 1316,
"s": 1162,
"text": "For example, if we have a vector called V for which we want to create the barplot ... |
MongoDB - Advanced Indexing | we have inserted the following document in the collection named users as shown below −
db.users.insert(
{
"address": {
"city": "Los Angeles",
"state": "California",
"pincode": "123"
},
"tags": [
"music",
"cricket",
"blogs"
],
"name": "Tom Benzamin"
}
)
The above document contains an address sub-document and a tags array.
Suppose we want to search user documents based on the user’s tags. For this, we will create an index on tags array in the collection.
Creating an index on array in turn creates separate index entries for each of its fields. So in our case when we create an index on tags array, separate indexes will be created for its values music, cricket and blogs.
To create an index on tags array, use the following code −
>db.users.createIndex({"tags":1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
>
After creating the index, we can search on the tags field of the collection like this −
> db.users.find({tags:"cricket"}).pretty()
{
"_id" : ObjectId("5dd7c927f1dd4583e7103fdf"),
"address" : {
"city" : "Los Angeles",
"state" : "California",
"pincode" : "123"
},
"tags" : [
"music",
"cricket",
"blogs"
],
"name" : "Tom Benzamin"
}
>
To verify that proper indexing is used, use the following explain command −
>db.users.find({tags:"cricket"}).explain()
This gives you the following result −
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "mydb.users",
"indexFilterSet" : false,
"parsedQuery" : {
"tags" : {
"$eq" : "cricket"
}
},
"queryHash" : "9D3B61A7",
"planCacheKey" : "04C9997B",
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"tags" : 1
},
"indexName" : "tags_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"tags" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"tags" : [
"[\"cricket\", \"cricket\"]"
]
}
}
},
"rejectedPlans" : [ ]
},
"serverInfo" : {
"host" : "Krishna",
"port" : 27017,
"version" : "4.2.1",
"gitVersion" : "edf6d45851c0b9ee15548f0f847df141764a317e"
},
"ok" : 1
}
>
The above command resulted in "cursor" : "BtreeCursor tags_1" which confirms that proper indexing is used.
Suppose that we want to search documents based on city, state and pincode fields. Since all these fields are part of address sub-document field, we will create an index on all the fields of the sub-document.
For creating an index on all the three fields of the sub-document, use the following code −
>db.users.createIndex({"address.city":1,"address.state":1,"address.pincode":1})
{
"numIndexesBefore" : 4,
"numIndexesAfter" : 4,
"note" : "all indexes already exist",
"ok" : 1
}
>
Once the index is created, we can search for any of the sub-document fields utilizing this index as follows −
> db.users.find({"address.city":"Los Angeles"}).pretty()
{
"_id" : ObjectId("5dd7c927f1dd4583e7103fdf"),
"address" : {
"city" : "Los Angeles",
"state" : "California",
"pincode" : "123"
},
"tags" : [
"music",
"cricket",
"blogs"
],
"name" : "Tom Benzamin"
}
Remember that the query expression has to follow the order of the index specified. So the index created above would support the following queries −
>db.users.find({"address.city":"Los Angeles","address.state":"California"}).pretty()
{
"_id" : ObjectId("5dd7c927f1dd4583e7103fdf"),
"address" : {
"city" : "Los Angeles",
"state" : "California",
"pincode" : "123"
},
"tags" : [
"music",
"cricket",
"blogs"
],
"name" : "Tom Benzamin"
}
>
44 Lectures
3 hours
Arnab Chakraborty
54 Lectures
5.5 hours
Eduonix Learning Solutions
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
40 Lectures
2.5 hours
University Code
26 Lectures
8 hours
Bassir Jafarzadeh
70 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2640,
"s": 2553,
"text": "we have inserted the following document in the collection named users as shown below −"
},
{
"code": null,
"e": 2836,
"s": 2640,
"text": "db.users.insert(\n\t{\n\t\t\"address\": {\n\t\t\t\"city\": \"Los Angeles\",\n\t\t\t\"state\": \... |
C# | PadRight() Method - GeeksforGeeks | 31 Jan, 2019
In C#, PadRight() is a string method. This method is used to left-aligns the characters in String by padding them with spaces or specified character on the right, for a specified total length. This method can be overloaded by passing different parameters to it.
String.PadRight Method(Int32)
String.PadRight Method(Int32, Char)
String.PadRight Method(Int32)
This method is used to left-aligns the characters in this string by padding them with spaces on the right. The parameter “totalWidth” will specify the number of padding characters in the string and this method will return a new string.
Syntax:
public string PadRight(int totalWidth)
Parameter: This method will accept one parameter “totalWidth” which specify the number of padding characters in string. The type of this parameter is System.Int32.
Return Value: This method will return the string which pads the left portion of the string. The return value type is System.String.
Exception: If totalWidth is less than zero then it will arise ArgumentOutOfRangeException.
Example:
Input : str = "GeeksForGeeks"
str.PadRight(2);
Output: 'GeeksForGeeks'
// String is same because totalWidth
// is less than length of String.
Input : str = "GeeksForGeeks"
str.PadRight(13);
Output: 'GeeksForGeeks'
// String is same because of totalWidth
// is equal to the length of String.
Input : str = "GeeksForGeeks"
str.PadRight(20);
Output: 'GeeksForGeeks '
// String is changed because of totalWidth
// is greater than the length of String.
So Right Padding will show only if the
totalWidth is greater than string length.
Below program illustrate the above-discussed method:
// C# program to illustrate the// String.PadRight(totalWidth) methodusing System;class Geeks { // Main Method public static void Main() { string s1 = "GeeksForGeeks"; Console.WriteLine("String : " + s1); // totalwidth is less than string length Console.WriteLine("Pad 2 :'{0}'", s1.PadRight(2)); // totalwidth is equal to string length Console.WriteLine("Pad 13 :'{0}'", s1.PadRight(13)); // totalwidth is greater then string length Console.WriteLine("Pad 20 :'{0}'", s1.PadRight(20)); }}
String : GeeksForGeeks
Pad 2 :'GeeksForGeeks'
Pad 13 :'GeeksForGeeks'
Pad 20 :'GeeksForGeeks '
String.PadRight Method (Int32, Char)
This method is used to left-aligns the characters in this string by padding them with specified character on the right. The parameter “totalWidth” will specify the number of padding characters in string and “paddingChar” is the specified Character.
Syntax:
public string PadRight(int totalWidth, char paddingChar)
Parameter: This method accept two parameter “totalWidth” and “paddingChar“. The parameter “totalWidth” will specify the number of padding characters in string and type of this parameter is System.Int32. The parameter “paddingChar” will specify the padding character and type of this parameter is System.Char.
Return Value: This method will return a new string which will be equivalent to current string, but left-aligned and padded on the right with the characters specified by “paddingChar” parameter. If totalWidth is less than the length of string, the method returns the same string. If totalWidth is equal to the length of the string, the method returns a new string that is identical to current String. The return value type is System.String.
Exception: If totalWidth is less than zero then it will arise ArgumentOutOfRangeException.
Example:
Input : str = "GeeksForGeeks"
str.PadRight(2, '*');
Output: 'GeeksForGeeks'
// String is same because totalWidth
// is less than the length of String.
Input : str = "GeeksForGeeks"
str.PadRight(13, '*');
Output: 'GeeksForGeeks'
// String is same because of totalWidth
// is equal to the length of String.
Input : str = "GeeksForGeeks"
str.PadRight(20, '*');
Output: 'GeeksForGeeks*******'
// String is changed because totalWidth
// is greater than the length of String.
Below program illustrate the above-discussed method:
// C# program to illustrate the// String.PadRight(int totalWidth, // char paddingChar) method using System;class Geeks { // Main Method public static void Main() { string s1 = "GeeksForGeeks"; char pad = '*'; Console.WriteLine("String : " + s1); // totalwidth is less than string length Console.WriteLine("Pad 2 :'{0}'", s1.PadRight(2, pad)); // totalwidth is equal to string length Console.WriteLine("Pad 13 :'{0}'", s1.PadRight(13, pad)); // totalwidth is greater then string length Console.WriteLine("Pad 20 :'{0}'", s1.PadRight(20, pad)); }}
String : GeeksForGeeks
Pad 2 :'GeeksForGeeks'
Pad 13 :'GeeksForGeeks'
Pad 20 :'GeeksForGeeks*******'
References:
https://msdn.microsoft.com/en-us/library/system.string.padright1
https://msdn.microsoft.com/en-us/library/system.string.padright2
CSharp-method
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
Partial Classes in C#
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C# | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n31 Jan, 2019"
},
{
"code": null,
"e": 24564,
"s": 24302,
"text": "In C#, PadRight() is a string method. This method is used to left-aligns the characters in String by padding them with spaces or specified character on the right, ... |
Mastering Summary Statistics with Pandas | by Sadrach Pierre, Ph.D. | Towards Data Science | Pandas is a python library used for data manipulation and statistical analysis. It is a fast and easy to use open-source library that enables several data manipulation tasks. These include merging, reshaping, wrangling, statistical analysis and much more. In this post, we will discuss how to calculate summary statistics using the Pandas library.
Let’s get started!
For our purposes we will be exploring the Movies on Netflix, Prime Video, Hulu and Disney Plus data set. The data can be found here.
Let’s get started!
First, let’s read the data into a Pandas data frame:
import pandas as pd pd.set_option('display.max_columns', None)pd.set_option('display.max_rows', None)df = pd.read_csv("MoviesOnStreamingPlatforms_updated.csv")
Next, we will print the columns available in this data:
print(df.columns)
We won’t need the ‘Unamed: 0’ column so we can delete it with the ‘del’ keyword:
del df['Unnamed: 0’]
Now, let’s print the first five rows of data using the ‘head()’ method:
print(df.head())
The first method we will look at is the Pandas’ ‘mean()’ method. Let’s display the mean IMDb rating:
print("Mean IMDb Rating: ", df['IMDb'].mean())
We can use the Numpy ‘round()’ method to round the mean to the nearest tenth:
import numpy as npprint("Mean IMDb: ", np.round(df['IMDb'].mean(), 1))
We can also display the standard deviation, median, max and min for the ‘IMDb’ column:
print("Standard Deviation in IMDb Rating: ", np.round(df['IMDb'].std()))print("Median IMDb Rating: ", np.round(df['IMDb'].median(), 1))print("Max IMDb Rating: ", df['IMDb'].max())print("Min IMDb Rating: ", df['IMDb'].min())
For convenience we can write a function that gives these summary statistics for any numerical column:
def get_statistics(column_name): df_copy = df.copy() print(f"Mean {column_name}: ", np.round(df_copy[column_name].mean(), 1)) print(f"Standard Deviation in {column_name}: ", np.round(df_copy[column_name].std())) print(f"Median {column_name}: ", np.round(df_copy[column_name].median(), 1)) print(f"Max {column_name}: ", df_copy[column_name].max()) print(f"Min {column_name}: ", df_copy[column_name].min())
If we call our function with ‘IMDb’ we get the following:
get_statistics('IMDb')
Let’s call our function on the ‘Runtime’ column:
get_statistics('Runtime')
Finally, let’s try the ‘Rotten Tomatoes’ column:
get_statistics('Rotten Tomatoes')
We get the following error:
It’s clear that we need to treat this case separately. If we print the first five rows of ‘Rotten Tomatoes’ values we see that the values are strings:
print(df[‘Rotten Tomatoes’].head())
In our function, we can check if the ‘column_name’ input is ‘Rotten Tomatoes’. If it is we remove the ‘%’ symbol and convert the string to a float before calculating the summary statistics:
def get_statistics(column_name): df_copy = df.copy() if column_name == 'Rotten Tomatoes': df_copy[column_name] = df[column_name].str.rstrip('%') df_copy[column_name] = df_copy[column_name].astype(float) ...
Now we can call our function with ‘Rotten Tomatoes’:
get_statistics('Rotten Tomatoes')
We can use the describe function to generate the statistics above and apply it to multiple columns simultaneously. It also provides the lower, median and upper percentiles. Let’s apply the ‘describe()’ method to ‘IMDb’ and ‘Runtime’:
print(df[['IMDb', 'Runtime']].describe())
If we wanted to include ‘Rotten Tomatoes’ in these statistics we’d need to convert it into a float like before:
df['Rotten Tomatoes'] = df['Rotten Tomatoes'].str.rstrip('%')df['Rotten Tomatoes'] = df['Rotten Tomatoes'].astype(float)print(df[['IMDb', 'Runtime', 'Rotten Tomatoes']].describe())
Suppose we wanted to know the average runtime for each genre. We can use the ‘groupby()’ method to calculate these statistics:
runtime_genre = df[["Genres", "Runtime"]].groupby("Genres").mean()print(runtime_genre.head())
We can also look at the average ‘Rotten Tomatoes’ by ‘Country’:
rottentomatoes_country = df[["Country", "Rotten Tomatoes"]].groupby("Country").mean().dropna()print(rottentomatoes_country.head())
Finally, we can write a function that allows us to reuse this logic for any categorical column and numerical column:
def get_group_statistics(categorical, numerical): group_df = df[[categorical, numerical]].groupby(categorical).mean().dropna() print(group_df.head())
Let’s call our function with ‘Genres’ and ‘Runtime’:
get_group_statistics('Genres', 'Runtime')
I’ll stop here but I encourage you to play around with the data and code yourself.
To summarize, in this post we discussed how to generate summary statistics using the Pandas library. First we discussed how to use pandas methods to generate mean, median, max, min and standard deviation. We also implemented a function that generates these statistics given a numerical column name. Next we discussed the ‘describe()’ method which allows us to generate percentiles, in addition to the mean, median, max, min and standard deviation, for any numerical column. Finally, we showed how to generate aggregate statistics for categorical columns. If you are interested in learning more about data manipulation with pandas, machine learning or even just some of the basics of python programming check out Python for Data Science and Machine Learning: Python Programming, Pandas and Scikit-learn Tutorials for Beginners. I hope you found this post useful/interesting. The code from this post is available on GitHub. Thank you for reading! | [
{
"code": null,
"e": 520,
"s": 172,
"text": "Pandas is a python library used for data manipulation and statistical analysis. It is a fast and easy to use open-source library that enables several data manipulation tasks. These include merging, reshaping, wrangling, statistical analysis and much more.... |
Linux Admin - head Command | head is a basic opposite of tail in relation to what part of the file operations are performed on. By default, head will read the first 10 lines of a file.
head offers similar options as tail −
Note − Head offers no -f option, since the files are appended from the bottom.
head is useful for reading descriptions of configuration files. When making such a file, it is a good idea to use the first 10 lines effectively.
[root@centosLocal centos]# head /etc/sudoers
## Sudoers allows particular users to run various commands as
## the root user, without needing the root password.
##
## Examples are provided at the bottom of the file for collections
## of related commands, which can then be delegated out to particular
## users or groups.
##
## This file must be edited with the 'visudo' command.
## Host Aliases
[root@centosLocal centos]#
57 Lectures
7.5 hours
Mamta Tripathi
25 Lectures
3 hours
Lets Kode It
14 Lectures
1.5 hours
Abhilash Nelson
58 Lectures
2.5 hours
Frahaan Hussain
129 Lectures
23 hours
Eduonix Learning Solutions
23 Lectures
5 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2413,
"s": 2257,
"text": "head is a basic opposite of tail in relation to what part of the file operations are performed on. By default, head will read the first 10 lines of a file."
},
{
"code": null,
"e": 2451,
"s": 2413,
"text": "head offers similar option... |
How to convert an OutputStream to a Writer in Java? | An OutputStream class is a byte-oriented whereas Writer class is a character-oriented. We can convert an OutputStream class to a Writer class using an OutputStreamWriter class and pass an argument of ByteArrayOutputStream object to OutputStreamWriter constructor. An OutputStreamWriter is a bridge from a character stream to a byte stream, the characters written to it are encoded into bytes using a specified charset.
public class OutputStreamWriter extends Writer
import java.io.*;
public class OutputStreamToWriterTest {
public static void main(String[] args) throws Exception {
String str = "TUTORIALSPOINT";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(baos);
for (int i=0; i < str.length(); i++) {
osw.write((int) str.charAt(i));
}
osw.close();
byte[] b = baos.toByteArray();
for (int j=0; j < b.length; j++) {
System.out.println(b[j]);
}
}
}
84
85
84
79
82
73
65
76
83
80
79
73
78
84 | [
{
"code": null,
"e": 1481,
"s": 1062,
"text": "An OutputStream class is a byte-oriented whereas Writer class is a character-oriented. We can convert an OutputStream class to a Writer class using an OutputStreamWriter class and pass an argument of ByteArrayOutputStream object to OutputStreamWriter co... |
Realistic Face Images from Sketches Using Deep Learning | by Frank Xu | Towards Data Science | Have you ever thought about the limit of what Deep Learning and AI could do? 8 years ago, AlexNet achieved a top-5 error of 15.3% in the ImageNet 2012 Challenge, which was incredible at the time thanks to CNN and GPU training. 3 years later in 2015, ResNet-152 shows only 3.57% error, which is better than human error for this task at 5%. Also in 2015, DCGAN shown the world that Deep Learning algorithms can not only classify objects, but also create new ones. In late 2017, transformer architecture introduced by Google not only brought faster training and better results than LSTMs in the NLP field, but also challenged the Computer Vision world by bringing the attention module.
Thanks to all of the people who contributed to the Deep Learning field, we have more and more applications that we could not have thought of before, which brings up today’s topic, generating realistic face images from hand sketches. Before anything, credit goes to the researchers, and thanks for the open-source code. I will briefly introduce the model architecture, then we’ll go hands-on where you can deploy this model locally!
As shown in the architecture above, the model is separated into three parts, which are the Component Embedding (CE) Module, Feature Mapping (FM) Module, and Image Synthesis (IS) Module. An input of hand sketch face image of size 512 by 512, is first decomposed into five components: “left-eye”, “right-eye”, “nose”, “mouth”, and “remainder”. The “eye”s, “nose” and “mouth” are separated by taking heat windows size of 128, 168 and 192, while the “remainder” is literally the remainder part of the sketch. The five components are then feature-encoded using 5 auto-encoders with latent descriptors of 512 dimensions. The feature vectors of components are considered as the point samples of the underlying component manifolds, and are used to refine the hand-drawn sketch by projecting its individual parts to the corresponding component manifolds using K nearest neighbors, as shown in the Manifold Projection part.
The individual feature vectors of components are projected to manifolds to increase their plausibility. In the FM module, instead of decoding each component vector back to image then synthesis on the component-level, the authors chose to fuse the vectors’ sketches into one complete face then generate the complete image, as it helps with a more consistent result in terms of both local details and global styles. Given the combined feature vector maps, the IS module converts them to a realistic face image using a conditional GAN architecture. They also applied a two-stage training method, wherein stage 1 only the five individual auto-encoders in the CE module were trained using different component sketches. Then in stage 2, the parameters in stage 1 are fixed, and the FM/IS modules work together to generate face images through training GAN.
Before anything, If you are just looking for a quick test-drawing with the application, make sure to check out the project homepage, where the original author created a web-based testing interface.
The motivation for starting this blog came from me trying to implement along with the original GitHub Repository. Since Jittor requires Ubuntu >= 16.04, while most of the people are using MacOS/Windows, one of the easiest ways is to use Docker to build a working environment from scratch.
System: MacOS/Windows/Linux (Any OS that supports docker)
RAM: 8 GB minimum, the running model will be taking up around 6 GB
Disk Space: 5 GB minimum
GPU: None is fine, except you want to do further training
Download and install Docker in your operating system.
Here we are going to construct our docker image for running the model. First create a Dockerfile with following contents.
vim Dockerfile
Then build the docker image and run it. In the same directory of Dockerfile,
# Build the docker image called ubuntu_for_deepfacedocker build -t ubuntu_for_deepface .# Start a container called ubuntu_env and memory limit of 8GBdocker run -it --name ubuntu_env --memory=8g ubuntu_for_deepface
Alternatively, you can pull the pre-compiled docker image that I created to avoid creating and compiling Dockerfile.
# Pull the docker image from Docker Hubdocker pull frank0124/drawing-to-face# Start a container called ubuntu_env based on the pulled imagedocker run -it --name ubuntu_env --memory=8g frank0124/drawing-to-face
You should be able to see the terminal/CMD prompt changed to
root@xxxxxxxxxxxx:/#
Which means you are in the up-and-running docker container. Docker can be frustrated to deal with in the beginning, but you can master it if you utilize the search engines and read through some documentation.
The original REPO is already available in the container. Here I also provide a simplified version of code by removing unnecessary features from my GitHub. In the container,
git clone https://github.com/franknb/Drawing-to-Face.gitcd /Drawing-to-Face/Params# If you are using the original code, simplycd /DeepFaceDrawing-Jittor/Params
Then download the pre-trained weights,
wget https://www.dropbox.com/s/5s5c4zuq6jy0cgc/Combine.zipunzip Combine.zip && rm Combine.zipwget https://www.dropbox.com/s/cs4895ci51h8xn3/AE_whole.zipunzip AE_whole.zip && rm AE_whole.zipcd ..
cd /Drawing-to-Facepython3.7 example.py
After it runs through, you should expect generated images in the /results directory in the running container. It would be tough to view the result .jpg files directly from docker, which requires you to set up X11 socket before running the docker. Here I recommend the simple “copy and paste” method.
Open up a new terminal/CMD on your own operating system,
# This line of code copies the results folder to your current directory in your OSdocker cp ubuntu_env:/Drawing-to-Face/results ./
Then you can simply go to that current directory where you run your terminal/CMD, and find the pasted images.
Alternatively, if you are running the original test_model.py, check this page for detailed instructions.
Now you know the model could run on your own environment, it’s time to draw and run more tests.
First, you want to create some 512 by 512 sized sketch jpg files. You can draw it wherever you want, on an iPad or even on paper then take a picture of it. Then make sure it has right format and size, I recommend Photoshop for this process for easy size/format control. If you are not ready to make face sketches all by yourself, please also refer to this testing interface. It has a shadow-based sketch board, which could give you some references for drawing. Put all the images you want to test in a directory/folder called test.
Now, inside the docker, you want to remove the existing test images to avoid running them again.
# In the running containerrm /Drawing-to-Face/test/*
Lastly, open up terminal/CMD again and find the test directory that you created, which contains images you want to test.
# In your own OSdocker cp test ubuntu_env:/Drawing-to-Face/
Next steps for you? Maybe read through the code for the model part to gain a better understanding of how it works, or build an App that utilizes the algorithm.
Let’s look at some model outputs above. All the cases are generated with all refinement parameters set at 0.5, which is the secret sauce of this model to enable better image generation. There are in total 6 parameters (for sex, eye1, eye2, nose, mouth and remainder) you can set for one picture generated. In example.py that I provided, I set all refinement parameters to 0.5 and sex to 0 (male), while in the original test_model.py, the author gave a matrix of 30 parameters for 5 testing images.
The first sketch on the left has a little bit of cartoon-ish touch on it, specifically in the bigger eyes, slightly higher eyebrows and weird looking nose. In the generated images, we can see the model struggled to put the eye and eyebrows on. For the hair, face, mouth and ears, the model did wonderful work in making the results as real as possible. The same goes with the second sketch from the left, with exaggerated eye/mouth shapes, and the model really strikes the balance between sketch and reality.
Sketches 3 to 5 from the left are more “realistic”, with the comparison with the first two. We also ended up with better (more realistic) generated images, closing to the quality of the teaser image in the front.
This model output above is based on the 5th sketch above, where sex is set at female. We did a full transformation of all refinement parameters set from 0 to 1. As stated in paper (Refinement parameter = 1- Confidence parameter),
wbc = 1 (confidence parameter) means a full use of an input sketch for image synthesis, while by setting wbc = 0 we fully trust the data for interpolation. This blending feature is particularly useful for creating faces that are very different from any existing samples or their blending.
We can see that the sketched hairstyle (with bangs) isn’t available from existing samples or their blending, but we can generate images with bangs by setting the parameter around 0.5, halfway between faithful and realistic, which enables us to get a sketch-like but realistic output.
You can check out all the source code at my GitHub. | [
{
"code": null,
"e": 855,
"s": 172,
"text": "Have you ever thought about the limit of what Deep Learning and AI could do? 8 years ago, AlexNet achieved a top-5 error of 15.3% in the ImageNet 2012 Challenge, which was incredible at the time thanks to CNN and GPU training. 3 years later in 2015, ResNe... |
How to extract the first digit from a character column in an R data frame? | If we have a character column in the data frame that contains string as well as numeric values and the first digit of the numeric values has some meaning that can help in data analysis then we can extract those first digits. For this purpose, we can use stri_extract_first function from stringi package.
Consider the below data frame −
Live Demo
> x1<-1:20
> y1<-sample(c("HT23L","HT14L","HT32L"),20,replace=TRUE)
> df1<-data.frame(x1,y1)
> df1
x1 y1
1 1 HT14L
2 2 HT14L
3 3 HT23L
4 4 HT14L
5 5 HT32L
6 6 HT32L
7 7 HT14L
8 8 HT32L
9 9 HT32L
10 10 HT32L
11 11 HT23L
12 12 HT32L
13 13 HT14L
14 14 HT23L
15 15 HT14L
16 16 HT23L
17 17 HT23L
18 18 HT23L
19 19 HT23L
20 20 HT23L
Loading stringi package and extracting first digit in column y1 −
> library(stringi)
> stri_extract_first(df1$y1,regex="\\d")
[1] "1" "1" "2" "1" "3" "3" "1" "3" "3" "3" "2" "3" "1" "2" "1" "2" "2" "2" "2"
[20] "2"
Live Demo
> x2<-sample(c("India1RT1","UK5RT1","Egypt2PT4"),20,replace=TRUE)
> y2<-rpois(20,5)
> df2<-data.frame(x2,y2)
> df2
x2 y2
1 India1RT1 2
2 India1RT1 8
3 India1RT1 7
4 India1RT1 6
5 UK5RT1 6
6 India1RT1 5
7 UK5RT1 6
8 India1RT1 6
9 India1RT1 7
10 UK5RT1 10
11 Egypt2PT4 8
12 Egypt2PT4 5
13 Egypt2PT4 7
14 India1RT1 2
15 UK5RT1 3
16 Egypt2PT4 5
17 UK5RT1 3
18 Egypt2PT4 6
19 Egypt2PT4 3
20 UK5RT1 5
Extracting first digit in column x2 −
> stri_extract_first(df2$x2,regex="\\d")
[1] "1" "1" "1" "1" "5" "1" "5" "1" "1" "5" "2" "2" "2" "1" "5" "2" "5" "2" "2"
[20] "5"
Live Demo
> x3<-sample(c("abc123","dfe456"),20,replace=TRUE)
> y3<-rnorm(20)
> df3<-data.frame(x3,y3)
> df3
x3 y3
1 abc123 0.1027005
2 dfe456 0.2297002
3 dfe456 -0.1441151
4 dfe456 1.0510760
5 abc123 0.8182656
6 dfe456 -0.5018968
7 dfe456 0.2957634
8 abc123 -0.4240910
9 dfe456 -1.0700713
10 dfe456 -0.3374661
11 dfe456 -0.4654241
12 dfe456 -0.4542710
13 abc123 0.6969808
14 dfe456 -0.6514574
15 abc123 0.2258769
16 dfe456 -0.5348958
17 abc123 0.6629195
18 dfe456 1.0998636
19 dfe456 -1.3147809
20 dfe456 -2.3015384
Extracting first digit in column x3 −
> stri_extract_first(df3$x3,regex="\\d")
[1] "1" "4" "4" "4" "1" "4" "4" "1" "4" "4" "4" "4" "1" "4" "1" "4" "1" "4" "4"
[20] "4" | [
{
"code": null,
"e": 1366,
"s": 1062,
"text": "If we have a character column in the data frame that contains string as well as numeric values and the first digit of the numeric values has some meaning that can help in data analysis then we can extract those first digits. For this purpose, we can use... |
Program to extract words from a given String | 11 Jun, 2021
The task is to extract words from a given string. There may be one or more space between words.
Examples:
Input : geeks for geeks
Output : geeks
for
geeks
Input : I love coding.
Output: I
love
coding
We have discussed a solution in the below post. How to split a string in C/C++, Python and Java?
In this post, a new solution using stringstream is discussed.
1. Make a string stream.
2. extract words from it till there are still words in the stream.
3. Print each word on new line.
This solution works even if we have multiple spaces between words.
C++
Java
Python3
C#
Javascript
// C++ program to extract words from// a string using stringstream#include<bits/stdc++.h>using namespace std; void printWords(string str){ // word variable to store word string word; // making a string stream stringstream iss(str); // Read and print each word. while (iss >> word) cout << word << endl;} // Driver codeint main(){ string s = "sky is blue"; printWords(s); return 0;}
// A Java program for splitting a string// using split()import java.io.*;class GFG{ // Method splits String into // all possible tokens public static void printWords(String s) { // Using split function. for (String val: s.split(" ")) // printing the final value. System.out.println(val); } // Driver Code public static void main(String args[]) { // Sample string to check the code String Str = "sky is blue"; // function calling printWords(Str); }} // This code is contributed// by Animesh_Gupta
# Python3 program to extract words from# a stringdef printWords(strr): word = strr.split(" ") print(*word, sep="\n") # Driver codes = "sky is blue"printWords(s) # This code is contributed by shubhamsingh10
// A C# program for splitting a string// using split()using System;class GFG{ // Method splits String into // all possible tokens public static void printWords(String s) { // Using split function. foreach(String val in s.Split(" ")) // printing the final value. Console.WriteLine(val); } // Driver Code static public void Main () { // Sample string to check the code String Str = "sky is blue"; // function calling printWords(Str); }} // This code is contributed// by shivanisingh
<script> // A Javascript program for splitting// a string using split() // Method splits String into// all possible tokensfunction printWords(s){ s = s.split(" "); for(let val = 0; val < s.length; val++) { document.write(s[val] + "</br>"); }} // Driver code // Sample string to check the codelet Str = "sky is blue"; // function callingprintWords(Str); // This code is contributed by divyeshrabadiya07 </script>
Output:
sky
is
blue
This article is contributed by Tanya Anand. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Animesh_Gupta
SHUBHAMSINGH10
shivanisinghss2110
akshaysingh98088
divyeshrabadiya07
cpp-string
cpp-stringstream
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
What is Data Structure: Types, Classifications and Applications
Print all the duplicates in the input string
Print all subsequences of a string
A Program to check if strings are rotations of each other or not
String class in Java | Set 1
Find if a string is interleaved of two other strings | DP-33
Remove first and last character of a string in Java
Find the smallest window in a string containing all characters of another string
Program to count occurrence of a given character in a string | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 148,
"s": 52,
"text": "The task is to extract words from a given string. There may be one or more space between words."
},
{
"code": null,
"e": 159,
"s": 148,
"text": "Examples:... |
Program to generate CAPTCHA and verify user | 13 Jun, 2022
A CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a test to determine whether the user is human or not.So, the task is to generate unique CAPTCHA every time and to tell whether the user is human or not by asking user to enter the same CAPTCHA as generated automatically and checking the user input with the generated CAPTCHA.Examples:
CAPTCHA: x9Pm72se
Input: x9Pm62es
Output: CAPTCHA Not Matched
CAPTCHA: cF3yl9T4
Input: cF3yl9T4
Output: CAPTCHA Matched
The set of characters to generate CAPTCHA are stored in a character array chrs[] which contains (a-z, A-Z, 0-9), therefore size of chrs[] is 62. To generate a unique CAPTCHA every time, a random number is generated using rand() function (rand()%62) which generates a random number between 0 to 61 and the generated random number is taken as index to the character array chrs[] thus generates a new character of captcha[] and this loop runs n (length of CAPTCHA) times to generate CAPTCHA of given length.
CPP
Java
Python3
// C++ program to automatically generate CAPTCHA and// verify user#include<bits/stdc++.h>using namespace std; // Returns true if given two strings are samebool checkCaptcha(string &captcha, string &user_captcha){ return captcha.compare(user_captcha) == 0;} // Generates a CAPTCHA of given lengthstring generateCaptcha(int n){ time_t t; srand((unsigned)time(&t)); // Characters to be included char *chrs = "abcdefghijklmnopqrstuvwxyzABCDEFGHI" "JKLMNOPQRSTUVWXYZ0123456789"; // Generate n characters from above set and // add these characters to captcha. string captcha = ""; while (n--) captcha.push_back(chrs[rand()%62]); return captcha;} // Driver codeint main(){ // Generate a random CAPTCHA string captcha = generateCaptcha(9); cout << captcha; // Ask user to enter a CAPTCHA string usr_captcha; cout << "\nEnter above CAPTCHA: "; cin >> usr_captcha; // Notify user about matching status if (checkCaptcha(captcha, usr_captcha)) printf("\nCAPTCHA Matched"); else printf("\nCAPTCHA Not Matched"); return 0;}
// Java pprogram to automatically generate CAPTCHA and// verify userimport java.util.*;import java.io.*; class GFG{ // Returns true if given two strings are same static boolean checkCaptcha(String captcha, String user_captcha) { return captcha.equals(user_captcha); } // Generates a CAPTCHA of given length static String generateCaptcha(int n) { //to generate random integers in the range [0-61] Random rand = new Random(62); // Characters to be included String chrs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // Generate n characters from above set and // add these characters to captcha. String captcha = ""; while (n-->0){ int index = (int)(Math.random()*62); captcha+=chrs.charAt(index); } return captcha; } // Driver code public static void main(String[] args)throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // Generate a random CAPTCHA String captcha = generateCaptcha(9); System.out.println(captcha); // Ask user to enter a CAPTCHA System.out.println("Enter above CAPTCHA: "); String usr_captcha = reader.readLine(); // Notify user about matching status if (checkCaptcha(captcha, usr_captcha)) System.out.println("CAPTCHA Matched"); else System.out.println("CAPTCHA Not Matched"); }} // This code is contributed by shruti456rawal
# Python program to automatically generate CAPTCHA and# verify userimport random # Returns true if given two strings are samedef checkCaptcha(captcha, user_captcha): if captcha == user_captcha: return True return False # Generates a CAPTCHA of given lengthdef generateCaptcha(n): # Characters to be included chrs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" # Generate n characters from above set and # add these characters to captcha. captcha = "" while (n): captcha += chrs[random.randint(1, 1000) % 62] n -= 1 return captcha # Driver code # Generate a random CAPTCHAcaptcha = generateCaptcha(9)print(captcha) # Ask user to enter a CAPTCHAprint("Enter above CAPTCHA:")usr_captcha = input() # Notify user about matching statusif (checkCaptcha(captcha, usr_captcha)): print("CAPTCHA Matched")else: print("CAPTCHA Not Matched") # This code is contributed by shubhamsingh10
Output:
CAPTCHA: cF3yl9T4
Enter CAPTCHA: cF3yl9T4
CAPTCHA Matched
This article is contributed by Himanshu Gupta(Bagri). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SHUBHAMSINGH10
shruti456rawal
Randomized
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Generating Random String Using PHP
Randomized Algorithms | Set 1 (Introduction and Analysis)
Primality Test | Set 2 (Fermat Method)
Operations on Sparse Matrices
Random Walk (Implementation in Python)
Randomized Algorithms | Set 2 (Classification and Applications)
Birthday Paradox
Expected Number of Trials until Success
Randomized Binary Search Algorithm | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 429,
"s": 52,
"text": "A CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a test to determine whether the user is human or not.So, the task is to generate uni... |
Count ways to express a number as sum of exactly two numbers | 19 May, 2021
Given a positive integer N. The task is to find the number of ways in which you can express N as a sum of exactly two numbers A and B (N = A + B) where A > 0, B > 0 and B > A.
Examples:
Input: N = 8
Output: 3
Explanation:
N = 8 can be expressed as (1, 7), (2, 6), (3, 5)
Input: N = 14
Output: 6
Approach:
An observation here is that for every number N, if we take a number A which is less than N/2, then there must be a number B which is greater than N/2 and A + B = N.
This leads to a simple solution of finding the count of numbers for either B or A. Hence, the floor value of (N-1)/2 will lead to the solution.
C++
Java
Python3
C#
Javascript
// C++ program to Count ways to// express a number as sum of// two numbers.#include <bits/stdc++.h>using namespace std; // Function returns the count// of ways express a number// as sum of two numbers.int CountWays(int n){ int ans = (n - 1) / 2; return ans;} // Driver codeint main(){ int N = 8; cout << CountWays(N);}
// Java program to count ways to// express a number as sum of// two numbers.class GFG{ // Function returns the count// of ways express a number// as sum of two numbers.static int CountWays(int n){ int ans = (n - 1) / 2; return ans;} // Driver codepublic static void main(String[] args){ int N = 8; System.out.print(CountWays(N));}} // This code is contributed by Rajput-Ji
# Python3 program to Count ways to# express a number as sum of# two numbers. # Function returns the count# of ways express a number# as sum of two numbers.def CountWays(n) : ans = (n - 1) // 2 return ans # Driver codeN = 8print(CountWays(N)) # This code is contributed by Sanjit_Prasad
// C# program to count ways to// express a number as sum of// two numbers.using System;class GFG{ // Function returns the count// of ways express a number// as sum of two numbers.static int CountWays(int n){ int ans = (n - 1) / 2; return ans;} // Driver codepublic static void Main(){ int N = 8; Console.Write(CountWays(N));}} // This code is contributed by Code_Mech
<script> // Javascript program to count ways to// express a number as sum of// two numbers. // Function returns the count// of ways express a number// as sum of two numbers.function CountWays(n){ let ans = Math.floor((n - 1) / 2); return ans;} // Driver Code let N = 8; document.write(CountWays(N)); </script>
3
Time complexity: O(N)
Sanjit_Prasad
Rajput-Ji
Code_Mech
souravghosh0416
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Find next greater number with same set of digits
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Count ways to reach the n'th stair
Fizz Buzz Implementation
Count all possible paths from top left to bottom right of a mXn matrix
Product of Array except itself | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 229,
"s": 53,
"text": "Given a positive integer N. The task is to find the number of ways in which you can express N as a sum of exactly two numbers A and B (N = A + B) where A > 0, B > 0 and B > A... |
Why Java is not a purely Object-Oriented Language? | 30 May, 2017
Pure Object Oriented Language or Complete Object Oriented Language are Fully Object Oriented Language which supports or have features which treats everything inside program as objects. It doesn’t support primitive datatype(like int, char, float, bool, etc.). There are seven qualities to be satisfied for a programming language to be pure Object Oriented. They are:
Encapsulation/Data HidingInheritancePolymorphismAbstractionAll predefined types are objectsAll user defined types are objectsAll operations performed on objects must be only through methods exposed at the objects.
Encapsulation/Data Hiding
Inheritance
Polymorphism
Abstraction
All predefined types are objects
All user defined types are objects
All operations performed on objects must be only through methods exposed at the objects.
Example: Smalltalk
Why Java is not a Pure Object Oriented Language?
Java supports property 1, 2, 3, 4 and 6 but fails to support property 5 and 7 given above. Java language is not a Pure Object Oriented Language as it contain these properties:
Primitive Data Type ex. int, long, bool, float, char, etc as Objects: Smalltalk is a “pure” object-oriented programming language unlike Java and C++ as there is no difference between values which are objects and values which are primitive types. In Smalltalk, primitive values such as integers, booleans and characters are also objects.In Java, we have predefined types as non-objects (primitive types).int a = 5;
System.out.print(a);
int a = 5;
System.out.print(a);
The static keyword: When we declares a class as static then it can be used without the use of an object in Java. If we are using static function or static variable then we can’t call that function or variable by using dot(.) or class object defying object oriented feature.
Wrapper Class: Wrapper class provides the mechanism to convert primitive into object and object into primitive. In Java, you can use Integer, Float etc. instead of int, float etc. We can communicate with objects without calling their methods. ex. using arithmetic operators.String s1 = "ABC" + "A" ;
Even using Wrapper classes does not make Java a pure OOP language, as internally it will use the operations like Unboxing and Autoboxing. So if you create instead of int Integer and do any mathematical operation on it, under the hoods Java is going to use primitive type int only.public class BoxingExample { public static void main(String[] args) { Integer i = new Integer(10); Integer j = new Integer(20); Integer k = new Integer(i.intValue() + j.intValue()); System.out.println("Output: "+ k); }}In the above code, there are 2 problems where Java fails to work as pure OOP:While creating Integer class you are using primitive type “int” i.e. numbers 10, 20.While doing addition Java is using primitive type “int”.
String s1 = "ABC" + "A" ;
Even using Wrapper classes does not make Java a pure OOP language, as internally it will use the operations like Unboxing and Autoboxing. So if you create instead of int Integer and do any mathematical operation on it, under the hoods Java is going to use primitive type int only.
public class BoxingExample { public static void main(String[] args) { Integer i = new Integer(10); Integer j = new Integer(20); Integer k = new Integer(i.intValue() + j.intValue()); System.out.println("Output: "+ k); }}
In the above code, there are 2 problems where Java fails to work as pure OOP:
While creating Integer class you are using primitive type “int” i.e. numbers 10, 20.While doing addition Java is using primitive type “int”.
While creating Integer class you are using primitive type “int” i.e. numbers 10, 20.
While doing addition Java is using primitive type “int”.
Related Article: Why C++ is partially Object Oriented Language?
This article is contributed by Sangeet Anand. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Collections in Java
Set in Java
Introduction to Java
Constructors in Java
Initializing a List in Java
Multithreading in Java
Exceptions in Java
LinkedList in Java
Queue Interface In Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 May, 2017"
},
{
"code": null,
"e": 418,
"s": 52,
"text": "Pure Object Oriented Language or Complete Object Oriented Language are Fully Object Oriented Language which supports or have features which treats everything inside program a... |
Insert a character after every n characters in JavaScript | 14 May, 2021
Here given a string and the task is to insert a character after every n characters in that string. Here are 2 examples discussed below.
Approach 1: In this approach, the string is broken into chunks by using substr() method and pushed to an array by push() method. The array of chunks is returned which then joined using join() method on any character.
Example:
html
<!DOCTYPE HTML> <html> <head> <title> Insert a character after every n characters in JavaScript </title> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script> </head> <body style = "text-align:center;"> <h1 style = "color: green"> GeeksForGeeks </h1> <p id = "GFG_UP"> </p> <button onclick = "gfg_Run()"> Click Here </button> <p id = "GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "A computer science portal for Geeks"; el_up.innerHTML = "Click on the button to perform the operation.<br>'" + str + "'"; function partition(str, n) { var return = []; var i, l; for(i = 0, l = str.length; i < l; i += n) { return.push(str.substr(i, n)); } return return; }; function gfg_Run() { el_down.innerHTML = partition(str, 5).join('@'); } </script> </body> </html>
Output:
Approach 2: In this approach, a RegExp is used which selects the parts of string and then joined on any character using join() method.
Example:
html
<!DOCTYPE HTML> <html> <head> <title> Insert a character after every n characters in JavaScript </title> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script> </head> <body style = "text-align:center;"> <h1 style = "color: green"> GeeksForGeeks </h1> <p id = "GFG_UP"> </p> <button onclick = "gfg_Run()"> Click Here </button> <p id = "GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "A computer science portal for Geeks"; el_up.innerHTML = "Click on the button to perform the operation.<br>'" + str + "'"; function gfg_Run() { el_down.innerHTML = str.match(/.{1, 5}/g).join('@'); } </script> </body> </html>
Output:
surinderdawra388
JavaScript-Misc
JavaScript
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": "\n14 May, 2021"
},
{
"code": null,
"e": 164,
"s": 28,
"text": "Here given a string and the task is to insert a character after every n characters in that string. Here are 2 examples discussed below."
},
{
"code": null,
"e": 38... |
Scatter Plot with Marginal Histograms in Python with Seaborn | 11 Dec, 2020
Prerequisites: Seaborn
Scatter Plot with Marginal Histograms is basically a joint distribution plot with the marginal distributions of the two variables. In data visualization, we often plot the joint behavior of two random variables (bi-variate distribution) or any number of random variables. But if data is too large, overlapping can be an issue. Hence, to distinguish between variables it is useful to have the probability distribution of each variable on the side along with the joint plot. This individual probability distribution of a random variable is referred to as its marginal probability distribution.
In seaborn, this is facilitated with jointplot(). It represents the bi-variate distribution using scatterplot() and the marginal distributions using histplot().
Import seaborn library
Load dataset of your choice
Use jointplot() on variables of your dataset
Example 1:
Python3
# importing and creating alias for seabornimport seaborn as sns # loading tips datasettips = sns.load_dataset("tips") # plotting scatterplot with histograms for features total bill and tip.sns.jointplot(data=tips, x="total_bill", y="tip")
Output :
<seaborn.axisgrid.JointGrid at 0x26203152688>
jointplot_with_histograms
Example 2: Using kind=”reg” attribute you can add a linear regression fit and univariate KDE curves.
Python3
import seaborn as sns tips = sns.load_dataset("tips") # here "*" is used as a marker for scatterplotsns.jointplot(data=tips, x="total_bill", y="tip", kind="reg", marker="*")
Output :
scatterplot with a linear regression fit
Example3: To add conditional colors to the scatterplot you can use hue attribute but it draws separate density curves (using kdeplot()) on the marginal axes.
Python3
import seaborn as sns tips = sns.load_dataset("tips") sns.jointplot(data=tips, x="total_bill", y="tip", hue="time")
Output :
scatterplot3
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace() | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 76,
"s": 52,
"text": "Prerequisites: Seaborn "
},
{
"code": null,
"e": 669,
"s": 76,
"text": "Scatter Plot with Marginal Histograms is basically a joint distribution plot with t... |
Python | Pandas Series.str.rfind() | 23 Jun, 2021
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas str.rfind() method is used to search a substring in each string present in a series from the Right side. If the string is found, it returns the highest index of its occurrence. If string is not found, it will return -1. Start and end points can also be passed to search a specific part of string for the passed character or substring.
Syntax: Series.str.rfind(sub, start=0, end=None)Parameters: sub: String or character to be searched in the text value in series start: int value, start point of searching. Default is 0 which means from the beginning of string end: int value, end point where the search needs to be stopped. Default is None.Return type: Series with Highest index position of substring occurrence
To download the CSV used in code, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example #1: Finding single characterIn this example, a single character ‘r’ is searched from the Right side in each string of Name column using str.rfind() method. Start and end parameters are kept default. The returned series is stored in a new column so that the indexes can be compared by looking directly. Before applying this method, null rows are dropped using .dropna() to avoid errors.
Python3
# importing pandas moduleimport pandas as pd # reading csv file from urldata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # substring to be searchedsub ='r' # creating and passing series to new columndata["Indexes"]= data["Name"].str.rfind(sub) # displaydata
Output: As shown in the output image, the occurrence of index in the Indexes column is equal to the position of Last occurrence of character in the string. If the substring doesn’t exist in the text, -1 is returned.
Example #2: Searching substring (More than one character)In this example, ‘ey’ substring will be searched in the Name column of data frame. The start parameter is kept 2 to start search from 3rd(index position 2) element.
Python3
# importing pandas moduleimport pandas as pd # reading csv file from urldata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/upload/nba.csv") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # substring to be searchedsub ='ey' # start varstart = 2 # creating and passing series to new columndata["Indexes"]= data["Name"].str.rfind(sub, start) # displaydata
Output: As shown in the output image, the highest or Last index of occurrence of substring is returned.
ruhelaa48
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 584,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes imp... |
VBScript | Introduction | 07 Jun, 2022
The VBScript stands for Visual Basics Script language. Basically it is the combination of Visual Basic programming language and JavaScript language. VBScript was invented and maintained by Microsoft. It is used to develop dynamic web pages. It is much lighter compared to Visual Basic programming language but works as a scripting language like JavaScript. To run VBScript on the client-side, the client must have to use Internet Explorer because other browsers are still not supported by the VBScript.
VBScript currently runs on below mentioned environments:
Internet Information Server (IIS) – It is a Microsoft web server.
Windows Script Host(WSH) – It is a native hosting environment of Windows operating system.
Internet Explorer (IE) – It is the simplest hosting environment where we can run VBScript code.
Prerequisite: To run VBScript script locally we need only two things:
Text Editor (Any VBScript editors like Notepad++, Text Hawk, EditPlus, etc.)
Microsoft Edge
Note: All the VBScript editors are actually HTML editors that supports VBScript. Setup for VBScript:
Step 1: Open your text editor and create a basic HTML file (for example: index.html) and paste the below code inside that file.
html
<!DOCTYPE html><html> <head> <title>VBScript Introduction</title> </head> <body> <!-- Paste VBScript Here --> </body></html>
Step 2: Paste the below code inside the body tag of your HTML code, or you can paste it inside the head tag. Exactly the same as you have done with JavaScript.
javascript
<script type="text/vbscript"> document.write("Hello geeks, greeting from GeeksforGeeks")</script>
Step 3: Combine both the code and run it on Microsoft Edge and you will get the below output in the console.
html
<!DOCTYPE html><html><head> <title>VBScript Introduction</title></head> <body> <script type="text/vbscript"> document.write("Welcome to GeeksforGeeks") </script></body></html>
Output:
Welcome to GeeksforGeeks
Note: To use in client-side, client have to use Microsoft Edge.
Troubleshoot: If your VBScript code is not working then use the following steps:
Press F12 key or use Right click to open Inspect Element.
Click on “Emulation” to open Emulation setting.
Change the Document mode from Default to 10.
Disadvantages:
The VBScript code will be processed by Microsoft Edge only. Other browsers except Microsoft Edge (like Chrome, Firefox, Safari, Opera etc) will not process the VBScript code.
The VBScript code will run only Windows Operating System platform. Other operating systems (like Linux, Mac, etc) will not run.
The VBScript code is used as a default scripting language of ASP.
satyamm09
VBScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jun, 2022"
},
{
"code": null,
"e": 558,
"s": 54,
"text": "The VBScript stands for Visual Basics Script language. Basically it is the combination of Visual Basic programming language and JavaScript language. VBScript was invented and... |
SortedSet Interface in Java with Examples | 26 Jun, 2020
The SortedSet interface present in java.util package extends the Set interface present in the collection framework. It is an interface that implements the mathematical set. This interface contains the methods inherited from the Set interface and adds a feature that stores all the elements in this interface to be stored in a sorted manner.
In the above image, the navigable set extends the sorted set interface. Since a set doesn’t retain the insertion order, the navigable set interface provides the implementation to navigate through the Set. The class which implements the navigable set is a TreeSet which is an implementation of a self-balancing tree. Therefore, this interface provides us with a way to navigate through this tree.
Declaration: The SortedSet interface is declared as:
public interface SortedSet extends Set
Example of a Sorted Set:
// Java program to demonstrate the// Sorted Setimport java.util.*; class SortedSetExample{ public static void main(String[] args) { SortedSet<String> ts = new TreeSet<String>(); // Adding elements into the TreeSet // using add() ts.add("India"); ts.add("Australia"); ts.add("South Africa"); // Adding the duplicate // element ts.add("India"); // Displaying the TreeSet System.out.println(ts); // Removing items from TreeSet // using remove() ts.remove("Australia"); System.out.println("Set after removing " + "Australia:" + ts); // Iterating over Tree set items System.out.println("Iterating over set:"); Iterator<String> i = ts.iterator(); while (i.hasNext()) System.out.println(i.next()); }}
[Australia, India, South Africa]
Set after removing Australia:[India, South Africa]
Iterating over set:
India
South Africa
Note: All the elements of a SortedSet must implement the Comparable interface (or be accepted by the specified Comparator) and all such elements must be mutually comparable. Mutually Comparable simply means that two objects accept each other as the argument to their compareTo method.
Creating SortedSet Objects
Since SortedSet is an interface, objects cannot be created of the type SortedSet. We always need a class which extends this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the SortedSet. This type-safe set can be defined as:
// Obj is the type of the object to be stored in SortedSetSortedSet<Obj> set = new TreeSet<Obj> ();
Since SortedSet is an interface, it can be used only with a class which implements this interface. TreeSet is the class which implements the SortedSet interface. Now, let’s see how to perform a few frequently used operations on the TreeSet.
1. Adding Elements: In order to add an element to the SortedSet, we can use the add() method. However, the insertion order is not retained in the TreeSet. Internally, for every element, the values are compared and sorted in the ascending order. We need to keep a note that duplicate elements are not allowed and all the duplicate elements are ignored. And also, Null values are not accepted by the SortedSet.
// Java code to demonstrate// the working of SortedSetimport java.util.*; class GFG { public static void main(String[] args) { SortedSet<String> ts = new TreeSet<String>(); // Elements are added using add() method ts.add("A"); ts.add("B"); ts.add("C"); ts.add("A"); System.out.println(ts); }}
[A, B, C]
2. Accessing the Elements: After adding the elements, if we wish to access the elements, we can use inbuilt methods like contains(), first(), last(), etc.
// Java code to demonstrate// the working of SortedSet import java.util.*;class GFG { public static void main(String[] args) { SortedSet<String> ts = new TreeSet<String>(); // Elements are added using add() method ts.add("A"); ts.add("B"); ts.add("C"); ts.add("A"); System.out.println("Sorted Set is " + ts); String check = "D"; // Check if the above string exists in // the SortedSet or not System.out.println("Contains " + check + " " + ts.contains(check)); // Print the first element in // the SortedSet System.out.println("First Value " + ts.first()); // Print the last element in // the SortedSet System.out.println("Last Value " + ts.last()); }}
Sorted Set is [A, B, C]
Contains D false
First Value A
Last Value C
3. Removing the Values: The values can be removed from the SortedSet using the remove() method.
// Java code to demonstrate// the working of SortedSet import java.util.*;class GFG{ public static void main(String[] args) { SortedSet<String> ts = new TreeSet<String>(); // Elements are added using add() method ts.add("A"); ts.add("B"); ts.add("C"); ts.add("B"); ts.add("D"); ts.add("E"); System.out.println("Initial TreeSet " + ts); // Removing the element b ts.remove("B"); System.out.println("After removing element " + ts); }}
Initial TreeSet [A, B, C, D, E]
After removing element [A, C, D, E]
4. Iterating through the SortedSet: There are various ways to iterate through the SortedSet. The most famous one is to use the enhanced for loop.
// Java code to demonstrate// the working of SortedSet import java.util.*;class GFG { public static void main(String[] args) { SortedSet<String> ts = new TreeSet<String>(); // Elements are added using add() method ts.add("C"); ts.add("D"); ts.add("E"); ts.add("A"); ts.add("B"); ts.add("Z"); // Iterating though the SortedSet for (String value : ts) System.out.print(value + ", "); System.out.println(); }}
A, B, C, D, E, Z,
The class which implements the SortedSet interface is TreeSet.
TreeSet: TreeSet class which is implemented in the collections framework is an implementation of the SortedSet Interface and SortedSet extends Set Interface. It behaves like a simple set with the exception that it stores elements in a sorted format. TreeSet uses a tree data structure for storage. Objects are stored in sorted, ascending order. But we can iterate in descending order using method TreeSet.descendingIterator(). Let’s see how to create a sortedset object using this class.
// Java program to demonstrate the// creation of SortedSet object using// the TreeSet class import java.util.*; class GFG { public static void main(String[] args) { SortedSet<String> ts = new TreeSet<String>(); // Adding elements into the TreeSet // using add() ts.add("India"); ts.add("Australia"); ts.add("South Africa"); // Adding the duplicate // element ts.add("India"); // Displaying the TreeSet System.out.println(ts); // Removing items from TreeSet // using remove() ts.remove("Australia"); System.out.println("Set after removing " + "Australia:" + ts); // Iterating over Tree set items System.out.println("Iterating over set:"); Iterator<String> i = ts.iterator(); while (i.hasNext()) System.out.println(i.next()); }}
[Australia, India, South Africa]
Set after removing Australia:[India, South Africa]
Iterating over set:
India
South Africa
The following are the methods present in the SortedSet interface. Here, the “*” represents that the methods are part of the Set interface.
yifan
KaashyapMSK
Java-Collections
Java-SortedSet
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
How to iterate any Map in Java
Stream In Java
Singleton Class in Java
Initializing a List in Java
Initialize an ArrayList in Java
Generics in Java
Java Programming Examples | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Jun, 2020"
},
{
"code": null,
"e": 393,
"s": 52,
"text": "The SortedSet interface present in java.util package extends the Set interface present in the collection framework. It is an interface that implements the mathematical set. T... |
Month length() method in Java | 22 Mar, 2019
The length() method is a built-in method of the Month ENUM which is used to get the number of days in this month instance. The number of days in a month can be 28, 30 or 31. Number of days in February in a leap year is 29.
This method accepts a boolean flag variable which indicates whether this Year is a leap year or not.
Syntax:
public int length(boolean leapYear)
Parameters: This method accepts a single parameter leapYear, which indicates whether this year is a leapYear or not.
Return Value: This method returns the length of this month in number of days present in it.
Below programs illustrate the above method:
Program 1:
import java.time.*;import java.time.Month;import java.time.temporal.ChronoField; class monthEnum { public static void main(String[] args) { // Create a month instance Month month = Month.MAY; // Print the length of this Month System.out.println(month.length(false)); }}
31
Program 2:
import java.time.*;import java.time.Month;import java.time.temporal.ChronoField; class monthEnum { public static void main(String[] args) { // Create a month instance Month month = Month.FEBRUARY; // Print the length of this Month System.out.println(month.length(true)); }}
29
Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Month.html#length-boolean-
Java-Functions
Java-Month
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Mar, 2019"
},
{
"code": null,
"e": 251,
"s": 28,
"text": "The length() method is a built-in method of the Month ENUM which is used to get the number of days in this month instance. The number of days in a month can be 28, 30 or 31. N... |
p5.js | lerpColor() Function - GeeksforGeeks | 26 Feb, 2020
The lerpColor() function is used to interpolate two colors to find a third color between them. The amount of interpolation between the two colors can be set using the amt parameters. The color interpolation depends on the current color mode.
Syntax:
lerpColor(c1, c2, amt)
Parameters: This function accepts three parameters as mentioned above and described below:
c1: It is a p5.Color which represents the first color from which the final color will be interpolated.
c2: It is a p5.Color which represents the second color to which the final color will be interpolated.
amt: It is a number between 0 and 1 which determines which color will be used more for the interpolation. A value near 0.1 would prefer the first color more and a value near 0.9 would prefer the second color for interpolation.
Return Value: It returns a p5.Color element with the interpolated color.
The example below illustrate the lerpColor() function in p5.js:
Example:
function setup() { createCanvas(500, 350); textSize(18); text("From Color", 20, 20); fromColor = color("red"); text("Lerped Color", 150, 20); text("To Color", 300, 20); toColor = color("blue"); text("Adjust this slider to change the"+ " amount of lerping", 20, 200) alphaSlider = createSlider(0, 100, 50); alphaSlider.position(20, 220); alphaSlider.style('width', '250px');} function draw() { lerpedColor = lerpColor(fromColor, toColor, alphaSlider.value() / 100); fill(fromColor); rect(30, 30, 50, 100); fill(lerpedColor); rect(170, 30, 50, 100); fill(toColor); rect(310, 30, 50, 100);}
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/lerpColor
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 43612,
"s": 43584,
"text": "\n26 Feb, 2020"
},
{
"code": null,
"e": 43854,
"s": 43612,
"text": "The lerpColor() function is used to interpolate two colors to find a third color between them. The amount of interpolation between the two colors can be set using ... |
Check if the String contains only unicode letters or digits in Java | To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements.
The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit. It returns a boolean value, either true or false.
Declaration −The java.lang.Character.isLetter() method is declared as follows −
public static boolean isLetter(char ch)
The charAt() method returns a character value at a given index. It belongs to the String class in Java. The index must be between 0 to length()-1.
Declaration −The java.lang.String.charAt() method is declared as follows −
public char charAt(int index)
Let us see a program in Java to check whether a String contains only Unicode letters or digits.
public class Example {
boolean check(String s) {
if (s == null) // checks if the String is null {
return false;
}
int len = s.length();
for (int i = 0; i < len; i++) {
// checks whether the character is neither a letter nor a digit
// if it is neither a letter nor a digit then it will return false
if ((Character.isLetterOrDigit(s.charAt(i)) == false)) {
return false;
}
}
return true;
}
public static void main(String [] args) {
Example e = new Example();
String s = "10@4"; // returns false due to special character presence
String s1 = "13y4"; // returns true
String s2 = "1000"; // returns true
String s3= "abcd"; // returns true
System.out.println("String "+s+" has only unicode letters or digits : "+e.check(s));
System.out.println("String "+s1+" has only unicode letters or digits : "+e.check(s1));
System.out.println("String "+s2+" has only unicode letters or digits : "+e.check(s2));
System.out.println("String "+s3+" has only unicode letters or digits : "+e.check(s3));
}
}
String 10@4 has only unicode letters or digits : false
String 13y4 has only unicode letters or digits : true
String 1000 has only unicode letters or digits : true
String abcd has only unicode letters or digits : true | [
{
"code": null,
"e": 1226,
"s": 1062,
"text": "To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements."
},
{
"code": null,
"e": 1398,
"s": 1226,
"text": "The isLetterOrDigi... |
Building QR Code Generator Application using PyQt5 - GeeksforGeeks | 31 Jan, 2022
In this article we will see how we can make a QR code generator application using PyQt5. A QR code is a type of matrix barcode first designed in 1994 for the automotive industry in Japan. A barcode is a machine-readable optical label that contains information about the item to which it is attached. Below is how the application will look like
In order to make this we will use the libraries given belowPyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. Below is the command to install the PyQt5
pip install PyQt5
qrcode :For generating a Quick Response code is a two-dimensional pictographic code used for its fast readability and comparatively large storage capacity. The code consists of black modules arranged in a square pattern on a white background. The information encoded can be made up of any kind of data (e.g., binary, alphanumeric, or Kanji symbols). Below is the command to install the qrcode module
pip install qrcode
Implementation Steps : 1. Create a Image class which inherits qrcode base image 2. Inside the Image class, get the size from the border and width and override the painter event and create a initial image and fill it with white color 3. Create a main window class 4. Inside the window class create a label which will show the QR code image 5. Create a line edit to receive the text from the user 6. Add label and line edit to the vertical layout and set layout to the window 7. Add action to the line edit when entered is pressed 8. Inside the line edit action get the text of the line edit 9. Create a pixmap image of the line edit text and use Image class as image_factory 10. Set the pixmap i.e QR code image to the label
Below is the implementation
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import qrcodeimport sys # Image class for QR codeclass Image(qrcode.image.base.BaseImage): # constructor def __init__(self, border, width, box_size): # assigning border self.border = border # assigning width self.width = width # assigning box size self.box_size = box_size # creating size size = (width + border * 2) * box_size # image self._image = QImage(size, size, QImage.Format_RGB16) # initial image as white self._image.fill(Qt.white) # pixmap method def pixmap(self): # returns image return QPixmap.fromImage(self._image) # drawrect method for drawing rectangle def drawrect(self, row, col): # creating painter object painter = QPainter(self._image) # drawing rectangle painter.fillRect( (col + self.border) * self.box_size, (row + self.border) * self.box_size, self.box_size, self.box_size, QtCore.Qt.black) # Main Window classclass Window(QMainWindow): # constructor def __init__(self): QMainWindow.__init__(self) # setting window title self.setWindowTitle("QR Code") # setting geometry self.setGeometry(100, 100, 300, 300) # creating a label to show the qr code self.label = QLabel(self) # creating a line edit to receive text self.edit = QLineEdit(self) # adding action when entered is pressed self.edit.returnPressed.connect(self.handleTextEntered) # setting font to the line edit self.edit.setFont(QFont('Times', 9)) # setting alignment self.edit.setAlignment(Qt.AlignCenter) # creating a vertical layout layout = QVBoxLayout(self) # adding label to the layout layout.addWidget(self.label) # adding line edit to the layout layout.addWidget(self.edit) # creating a QWidget object widget = QWidget() # setting layout to the widget widget.setLayout(layout) # setting widget as central widget to the main window self.setCentralWidget(widget) # method called by the line edit def handleTextEntered(self): # get the text text = self.edit.text() # creating a pix map of qr code qr_image = qrcode.make(text, image_factory = Image).pixmap() # set image to the label self.label.setPixmap(qr_image) # create pyqt5 appapp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # showing windowwindow.show() # start the appsys.exit(app.exec_())
Output :
When user entered the the text in the line edit and press enter key, QR code will be displayed and window size will get adjusted according to the size of QR code
sumitgumber28
PyQt-exercise
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n31 Jan, 2022"
},
{
"code": null,
"e": 24637,
"s": 24292,
"text": "In this article we will see how we can make a QR code generator application using PyQt5. A QR code is a type of matrix barcode first designed in 1994 for the autom... |
Python | Decimal as_tuple() method - GeeksforGeeks | 05 Sep, 2019
Decimal#as_tuple() : as_tuple() is a Decimal class method which returns named tuple representation of the Decimal value.
Syntax: Decimal.as_tuple()
Parameter: Decimal values
Return: tuple with values– sign– digits– exponent
Code #1 : Example for as_tuple() method
# Python Program explaining # as_tuple() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(-1) b = Decimal('0.142857') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.as_tuple() methodprint ("\n\nDecimal a with as_tuple() method : ", a.as_tuple()) print ("Decimal b with as_tuple() method : ", b.as_tuple())
Output :
Decimal value a : -1
Decimal value b : 0.142857
Decimal a with as_tuple() method : DecimalTuple(sign=1, digits=(1, ), exponent=0)
Decimal b with as_tuple() method : DecimalTuple(sign=0, digits=(1, 4, 2, 8, 5, 7), exponent=-6)
Code #2 : Example for as_tuple() method
# Python Program explaining # as_tuple() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal('-3.14') b = Decimal('321e + 5') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.as_tuple() methodprint ("\n\nDecimal a with as_tuple() method : ", a.as_tuple()) print ("Decimal b with as_tuple() method : ", b.as_tuple())
Output :
Decimal value a : -3.14
Decimal value b : 3.21E+7
Decimal a with as_tuple() method : DecimalTuple(sign=1, digits=(3, 1, 4), exponent=-2)
Decimal b with as_tuple() method : DecimalTuple(sign=0, digits=(3, 2, 1), exponent=5)
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": "\n05 Sep, 2019"
},
{
"code": null,
"e": 25676,
"s": 25555,
"text": "Decimal#as_tuple() : as_tuple() is a Decimal class method which returns named tuple representation of the Decimal value."
},
{
"code": null,
"e": 25703... |
Hibernate 4 Example with Annotations Mysql - onlinetutorialspoint | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorials, we are going to implement a complete CRUD application using Hibernate annotations and MySQL. The same example using xml configuration, we have developed in the previous tutorial – Hibernate CRUD using XML Configuration.
The present tutorial is for Hibernate 4 Example with annotation-based configuration using maven.
Technologies :
Hibernate-core 4.0
Mysql 5.5.43
NetBeans 8.0
mysql> create database onlinetutorialspoint;
mysql> use onlinetutorialspoint;
Then create a student table in onlinetutorialspoint database.
CREATE TABLE `student` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NULL DEFAULT NULL,
`rollnumber` INT(10) NULL DEFAULT NULL,
`gender` TINYINT(4) NULL DEFAULT NULL,
`class` VARCHAR(50) NULL DEFAULT NULL,
`lastupdated` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.onlinetutorialspoint</groupId>
<artifactId>HibernateMaven</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<repositories>
<repository>
<id>JBoss repository</id>
<url>http://repository.jboss.com/maven2/</url>
</repository>
<repository>
<id>unknown-jars-temp-repo</id>
<name>A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository.</name>
<url>file:${project.basedir}/lib</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.1.Final</version>
<classifier>tests</classifier>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.8.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.0.CR2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.10</version>
</dependency>
<dependency>
<groupId>mysql-connector</groupId>
<artifactId>mysql-connector-java-5.1.23-bin</artifactId>
<version>SNAPSHOT</version>
</dependency>
</dependencies>
</project>
Above is the pom.xml, where we can define all required maven dependencies.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/onlinetutorialspoint?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">XYZ-ABC</property>
<!--Here we are mapping Pojo class not hbm-->
<mapping class="com.onlinetutorialspoint.pojo.Student" />
</session-factory>
</hibernate-configuration>
Create HibernateConnector.java, responsible to create singleton session factory object and to connect with the database.
package com.onlinetutorialspoint.config;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateConnector {
private static HibernateConnector me;
private Configuration cfg;
private SessionFactory sessionFactory;
private HibernateConnector() throws HibernateException {
// build the config
cfg = new Configuration().configure();
sessionFactory = cfg.buildSessionFactory();
}
public static synchronized HibernateConnector getInstance() throws HibernateException {
if (me == null) {
me = new HibernateConnector();
}
return me;
}
public Session getSession() throws HibernateException {
Session session = sessionFactory.openSession();
if (!session.isConnected()) {
this.reconnect();
}
return session;
}
private void reconnect() throws HibernateException {
this.sessionFactory = cfg.buildSessionFactory();
}
}
package com.onlinetutorialspoint.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "student", catalog = "onlinetutorialspoint"
)
public class Student implements java.io.Serializable {
private Integer id;
private String name;
private Integer rollnumber;
private Byte gender;
private String class_;
public Student() {
}
public Student(String name, Integer rollnumber, Byte gender, String class_) {
this.name = name;
this.rollnumber = rollnumber;
this.gender = gender;
this.class_ = class_;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "name", length = 50)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "rollnumber")
public Integer getRollnumber() {
return this.rollnumber;
}
public void setRollnumber(Integer rollnumber) {
this.rollnumber = rollnumber;
}
@Column(name = "gender")
public Byte getGender() {
return this.gender;
}
public void setGender(Byte gender) {
this.gender = gender;
}
@Column(name = "class", length = 50)
public String getClass_() {
return this.class_;
}
public void setClass_(String class_) {
this.class_ = class_;
}
}
Points to Note :
@Entity: Is an EJB 3 standard annotation, used to specify the class is an entity. By using this annotation we are going to tell the hibernate, treat this class as an Entity.
@Table: @Table annotation comes from javax.persistence, used to specify the primary table to the annotated Entity. We do configure the secondary tables too, by using the @SecondaryTable annotation.
@Id and @GeneratedValue: In hibernate, each entity will have the primary key or keys (composite). We can configure the primary keys by using the @id annotation. The type of the particular primary key will be defined as @GeneratedValue.
@Column: annotation is used to specify the mapped column with persistent property. It represents the table column with entity class field.
Note: No need to create “hbm.xml”, as this is an annotation based example.
Create StudentDAO.java to access the Student details.
package com.onlinetutorialspoint.dao;
import com.onlinetutorialspoint.config.HibernateConnector;
import com.onlinetutorialspoint.pojo.Student;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class StudentDAO {
public List<Student> listStudent() {
Session session = null;
try {
session = HibernateConnector.getInstance().getSession();
Query query = session.createQuery("from Student s");
List queryList = query.list();
if (queryList != null && queryList.isEmpty()) {
return null;
} else {
System.out.println("list " + queryList);
return (List<Student>) queryList;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.close();
}
}
public Student findStudentById(int id) {
Session session = null;
try {
session = HibernateConnector.getInstance().getSession();
Query query = session.createQuery("from Student s where s.id = :id");
query.setParameter("id", id);
List queryList = query.list();
if (queryList != null && queryList.isEmpty()) {
return null;
} else {
return (Student) queryList.get(0);
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.close();
}
}
public void updateStudent(Student student) {
Session session = null;
try {
session = HibernateConnector.getInstance().getSession();
session.saveOrUpdate(student);
session.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
public Student addStudent(Student student) {
Session session = null;
Transaction transaction = null;
try {
session = HibernateConnector.getInstance().getSession();
System.out.println("session : "+session);
transaction = session.beginTransaction();
session.save(student);
transaction.commit();
return student;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void deleteStudent(int id) {
Session session = null;
try {
session = HibernateConnector.getInstance().getSession();
Transaction beginTransaction = session.beginTransaction();
Query createQuery = session.createQuery("delete from Student s where s.id =:id");
createQuery.setParameter("id", id);
createQuery.executeUpdate();
beginTransaction.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
}
Create a client class, from which we can access the StudentDAO.java to make CRUD operations.
package com.onlinetutorialspoint.service;
import com.onlinetutorialspoint.dao.StudentDAO;
import com.onlinetutorialspoint.pojo.Student;
import java.util.List;
public class DbOperations {
StudentDAO studentDAO = new StudentDAO();
public static void main(String[] args) {
DbOperations dbOperations = new DbOperations();
Student createStudent = dbOperations.createStudent();
List<Student> studentList = dbOperations.getStudentList();
if (studentList != null) {
for (Student student : studentList) {
System.out.println("Student Name : " + student.getName());
}
}
dbOperations.updateStudent(createStudent.getId());
Student student = dbOperations.getStudent(createStudent.getId());
if (student != null) {
System.out.println("Student Details After Updation : " + student.getName());
}
dbOperations.deleteStudent(createStudent.getId());
}
public Student createStudent() {
Student s = new Student();
s.setGender(new Byte("1"));
s.setName("smith");
s.setClass_("12");
s.setRollnumber(007);
studentDAO.addStudent(s);
return s;
}
public void updateStudent(Integer id) {
Student student = studentDAO.findStudentById(id);
student.setName("online tutorials point");
studentDAO.updateStudent(student);
System.out.println("Student Updated Success");
}
public void deleteStudent(Integer id) {
studentDAO.deleteStudent(id);
System.out.println("Student Deleted Success");
}
public List<Student> getStudentList() {
return studentDAO.listStudent();
}
public Student getStudent(Integer id) {
return studentDAO.findStudentById(id);
}
}
Output :
Student Name : smith Student Updated Success Student Details After Updation : online tutorials point Student Deleted Success
Happy Learning 🙂
Hibernate 4 with Annotations
File size: 795 KB
Downloads: 2876
Basic Hibernate Example with XML Configuration
Hibernate One To Many Using Annotations
Hibernate Table per Class strategy Annotations Example
Hibernate Composite Key Mapping Example
Calling Stored Procedures in Hibernate
hibernate update query example
Hibernate Filter Example Xml Configuration
hbm2ddl.auto Example in Hibernate XML Config
Hibernate Filters Example Annotation
Hibernate Left Join Example
@Formula Annotation in Hibernate Example
One to One Mapping in Hibernate using foreign key (XML)
Hibernate One to One Mapping using primary key (XML)
Difference between update vs merge in Hibernate example
Hibernate Native SQL Query Example
Basic Hibernate Example with XML Configuration
Hibernate One To Many Using Annotations
Hibernate Table per Class strategy Annotations Example
Hibernate Composite Key Mapping Example
Calling Stored Procedures in Hibernate
hibernate update query example
Hibernate Filter Example Xml Configuration
hbm2ddl.auto Example in Hibernate XML Config
Hibernate Filters Example Annotation
Hibernate Left Join Example
@Formula Annotation in Hibernate Example
One to One Mapping in Hibernate using foreign key (XML)
Hibernate One to One Mapping using primary key (XML)
Difference between update vs merge in Hibernate example
Hibernate Native SQL Query Example
Kiran
May 1, 2017 at 12:15 pm - Reply
Nice article
Kiran
May 1, 2017 at 12:15 pm - Reply
Nice article
Nice article
Δ
Hibernate – Introduction
Hibernate – Advantages
Hibernate – Download and Setup
Hibernate – Sql Dialect list
Hibernate – Helloworld – XML
Hibernate – Install Tools in Eclipse
Hibernate – Object States
Hibernate – Helloworld – Annotations
Hibernate – One to One Mapping – XML
Hibernate – One to One Mapping foreign key – XML
Hibernate – One To Many -XML
Hibernate – One To Many – Annotations
Hibernate – Many to Many Mapping – XML
Hibernate – Many to One – XML
Hibernate – Composite Key Mapping
Hibernate – Named Query
Hibernate – Native SQL Query
Hibernate – load() vs get()
Hibernate Criteria API with Example
Hibernate – Restrictions
Hibernate – Projection
Hibernate – Query Language (HQL)
Hibernate – Groupby Criteria HQL
Hibernate – Orderby Criteria
Hibernate – HQLSelect Operation
Hibernate – HQL Update, Delete
Hibernate – Update Query
Hibernate – Update vs Merge
Hibernate – Right Join
Hibernate – Left Join
Hibernate – Pagination
Hibernate – Generator Classes
Hibernate – Custom Generator
Hibernate – Inheritance Mappings
Hibernate – Table per Class
Hibernate – Table per Sub Class
Hibernate – Table per Concrete Class
Hibernate – Table per Class Annotations
Hibernate – Stored Procedures
Hibernate – @Formula Annotation
Hibernate – Singleton SessionFactory
Hibernate – Interceptor
hbm2ddl.auto Example in Hibernate XML Config
Hibernate – First Level Cache | [
{
"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,
... |
Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif) - GeeksforGeeks | 07 Sep, 2021
Decision Making in programming is similar to decision making in real life. In programming, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.
If
If – else
Nested – If
if – elsif ladder
Unless
Unless – else
Unless – elsif
if statement
The if statement is same as in other programming languages. It is used to perform basic condition based task. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.Syntax :
if(condition)
{
# code to be executed
}
Note : If the curly brackets { } are not used with if statements than there will be compile time error. So it is must to use the brackets { } with if statement.Flowchart :
Example :
Perl
# Perl program to illustrate if statement $a = 10; # if condition to check# for even numberif($a % 2 == 0 ){ printf "Even Number";}
Output :
Even Number
if – else Statement
The if statement evaluates the code if the condition is true but what if the condition is not true, here comes the else statement. It tells the code what to do when the if condition is false.Syntax :
if(condition)
{
# code if condition is true
}
else
{
# code if condition is false
}
Flowchart :
Example :
Perl
# Perl program to illustrate# if - else statement $a = 21; # if condition to check# for even numberif($a % 2 == 0 ){ printf "Even Number";}else{ printf "Odd Number\n";}
Output :
Odd Number
Nested – if Statement
if statement inside an if statement is known as nested if. if statement in this case is the target of another if or else statement. When more then one condition needs to be true and one of the condition is the sub-condition of parent condition, nested if can be used.Syntax :
if (condition1)
{
# Executes when condition1 is true
if (condition2)
{
# Executes when condition2 is true
}
}
Flowchart :
Example :
Perl
# Perl program to illustrate# Nested if statement $a = 10; if($a % 2 ==0){ # Nested - if statement # Will only be executed # if above if statement # is true if($a % 5 == 0) { printf "Number is divisible by 2 and 5\n"; }}
Output :
Number is divisible by 2 and 5
If – elsif – else ladder Statement
Here, a user can decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that get executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.Syntax :
if(condition1)
{
# code to be executed if condition1 is true
}
elsif(condition2)
{
# code to be executed if condition2 is true
}
elsif(condition3)
{
# code to be executed if condition3 is true
}
...
else
{
# code to be executed if all the conditions are false
}
Flowchart :
if-else-if
Example :
Perl
# Perl program to illustrate# if - elseif ladder statement $i = 20; if($i == 10){ printf "i is 10\n"; } elsif($i == 15){ printf "i is 15\n";} elsif($i == 20){ printf "i is 20\n";} else{ printf "i is not present\n";}
Output :
i is 20
unless Statement
In this case if the condition is false then the statements will execute. The number 0, the empty string “”, character ‘0’, the empty list (), and undef are all false in a boolean context and all other values are true.Syntax :
unless(boolean_expression)
{
# will execute if the given condition is false
}
Flowchart :
Example :
Perl
# Perl program to illustrate# unless statement $a = 10; unless($a != 10){ # if condition is false then # print the following printf "a is not equal to 10\n";}
Output :
a is not equal to 10
Unless-else Statement
Unless statement can be followed by an optional else statement, which executes when the boolean expression is true.Syntax :
unless(boolean_expression)
{
# execute if the given condition is false
}
else
{
# execute if the given condition is true
}
Flowchart :
Example :
Perl
# Perl program to illustrate# unless - else statement $a = 10; unless($a == 10){ # if condition is false then # print the following printf "a is not equal to 10\n";} else{ # if condition is true then # print the following printf "a is equal to 10\n";}
Output :
a is equal to 10
Unless – elsif Statement
Unless statement can be followed by an optional elsif...else statement, which is very useful to test the various conditions using single unless...elsif statement.Points to Remember :
Unless statement can have zero to many elsif’s and all that must come before the else.
Unless statement can have zero or one else’s and that must come after any elsif’s.
Once an elsif succeeds, then none of remaining elsif’s or else’s will be tested.
Syntax :
unless(boolean_expression 1)
{
# Executes when the boolean expression 1 is false
}
elsif( boolean_expression 2)
{
# Executes when the boolean expression 2 is true
}
else
{
# Executes when the none of the above condition is met
}
Flowchart :
Example :
Perl
# Perl program to illustrate# unless - elsif statement$a = 50; unless($a == 60){ # if condition is false printf "a is not equal to 60\n";}elsif($a == 60){ # if condition is true printf "a is equal to 60\n";}else{ # if none of the condition matches printf "The value of a is $a\n";}
a is not equal to 60
Output :
a is not equal to 60
ManasChhabra2
varshagumber28
akshaysingh98088
perl-basics
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl | split() Function
Perl | push() Function
Perl | exists() Function
Perl | chomp() Function
Perl | length() Function
Perl | grep() Function
Perl | sleep() Function
Perl | Regex Cheat Sheet
Perl | Removing leading and trailing white spaces (trim)
Perl Tutorial - Learn Perl With Examples | [
{
"code": null,
"e": 25226,
"s": 25198,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 25633,
"s": 25226,
"text": "Decision Making in programming is similar to decision making in real life. In programming, a certain block of code needs to be executed when some condition is fulf... |
Write a C program demonstrating examples on pointers | A pointer is a variable that stores the address of another variable.
Pointer saves the memory space.
Pointer saves the memory space.
The execution time of a pointer is faster because of direct access to memory location.
The execution time of a pointer is faster because of direct access to memory location.
With the help of pointers, the memory is accessed efficiently, i.e., memory is allocated and deallocated dynamically.
With the help of pointers, the memory is accessed efficiently, i.e., memory is allocated and deallocated dynamically.
Pointers are used with data structures.
Pointers are used with data structures.
int *p;
It means ‘p’ is a pointer variable that holds the address of another integer variable.
Address operator (&) is used to initialize a pointer variable.
For example,
int qty = 175;
int *p;
p= &qty;
To access the value of the variable, the indirection operator (*) is used.
Live Demo
#include<stdio.h>
void main(){
//Declaring variables and pointer//
int a=2;
int *p;
//Declaring relation between variable and pointer//
p=&a;
//Printing required example statements//
printf("Size of the integer is %d\n",sizeof (int));//4//
printf("Address of %d is %d\n",a,p);//Address value//
printf("Value of %d is %d\n",a,*p);//2//
printf("Value of next address location of %d is %d\n",a,*(p+1));//Garbage value from (p+1) address//
printf("Address of next address location of %d is %d\n",a,(p+1));//Address value +4//
//Typecasting the pointer//
//Initializing and declaring character data type//
//a=2 = 00000000 00000000 00000000 00000010//
char *p0;
p0=(char*)p;
//Printing required statements//
printf("Size of the character is %d\n",sizeof(char));//1//
printf("Address of %d is %d\n",a,p0);//Address Value(p)//
printf("Value of %d is %d\n",a,*p0);//First byte of value a - 2//
printf("Value of next address location of %d is %d\n",a,*(p0+1));//Second byte of value a - 0//
printf("Address of next address location of %d is %d\n",a,(p0+1));//Address value(p)+1//
}
Size of the integer is 4
Address of 2 is 6422028
Value of 2 is 2
Value of next address location of 2 is 10818512
Address of next address location of 2 is 6422032
Size of the character is 1
Address of 2 is 6422028
Value of 2 is 2
Value of next address location of 2 is 0
Address of next address location of 2 is 6422029 | [
{
"code": null,
"e": 1131,
"s": 1062,
"text": "A pointer is a variable that stores the address of another variable."
},
{
"code": null,
"e": 1163,
"s": 1131,
"text": "Pointer saves the memory space."
},
{
"code": null,
"e": 1195,
"s": 1163,
"text": "Pointer sa... |
When to use the ofNullable() method of Stream in Java 9?
| The ofNullable() method is a static method of Stream class that returns a sequential Stream containing a single element if non-null, otherwise returns an empty. Java 9 has introduced this method to avoid NullPointerExceptions and also avoid null checks of streams. The main objective of using the ofNullable() method is to return an empty option if the value is null.
static <T> Stream<T> ofNullable(T t)
import java.util.stream.Stream;
public class OfNullableMethodTest1 {
public static void main(String args[]) {
System.out.println("TutorialsPoint");
int count = (int) Stream.ofNullable(5000).count();
System.out.println(count);
System.out.println("Tutorix");
count = (int) Stream.ofNullable(null).count();
System.out.println(count);
}
}
TutorialsPoint
1
Tutorix
0
import java.util.stream.Stream;
public class OfNullableMethodTest2 {
public static void main(String args[]) {
String str = null;
Stream.ofNullable(str).forEach(System.out::println); // prints nothing in the console
str = "TutorialsPoint";
Stream.ofNullable(str).forEach(System.out::println); // prints TutorialsPoint
}
}
TutorialsPoint | [
{
"code": null,
"e": 1430,
"s": 1062,
"text": "The ofNullable() method is a static method of Stream class that returns a sequential Stream containing a single element if non-null, otherwise returns an empty. Java 9 has introduced this method to avoid NullPointerExceptions and also avoid null checks ... |
Ditch p-values. Use Bootstrap confidence intervals instead | by Florent Buisson | Towards Data Science | A few years ago, I was hired by one of the largest insurance companies in the US to start and lead their behavioral science team. I had a PhD in behavioral economics from one of the top 10 economics departments in the world and half a decade of experience as a strategy consultant, so I was confident my team would be able to drive business decisions through well-crafted experiments and data analyses.
And indeed, I worked with highly-skilled data scientists who had a very sharp understanding of statistics. But after years of designing and analyzing experiments, I grew dissatisfied with the way we communicated results to decision-makers. I felt that the over-reliance on p-values led to sub-optimal decisions. After talking to colleagues in other companies, I realized that this was a broader problem, and I set up to write a guide to better data analysis1. In this article, I’ll present one of the biggest recommendations of the book, which is to ditch p-values and use Bootstrap confidence intervals instead.
There are many reasons why you should abandon p-values, and I’ll examine three of the main ones here:
They don’t mean what people think they meanThey rely on hidden assumptions that are unlikely to be fulfilledThey detract from the real questions
They don’t mean what people think they mean
They rely on hidden assumptions that are unlikely to be fulfilled
They detract from the real questions
When you’re running applied data analyses, whether in the private, non-profit or public sectors, your goal is to inform decisions. A big part of the problem we need to solve is uncertainty: the data tells us that the number is 10, but could it be 5 instead? Maybe 100? Can we rely on the number that the data analysis spouted? After years, sometimes decades, of educating business partners on the matter, they generally understand the risks of uncertainty. Unfortunately, they often jump from there to assuming that the p-value represents the probability that a result is due to chance: a p-value of 0.03 would mean that there’s a 3% chance a number we thought were positive is indeed null or negative. It does not. In fact, it represents the probability of seeing the result we saw assuming that the real value is indeed zero.
In scientific jargon, the real value being zero or negative is called the null hypothesis (abbreviated H0), and the real value being strictly above zero is called the alternative hypothesis (abbreviated H1). People mistakenly believe that the p-value is the probability of H0 given the data, P(H0|data), when in reality it is the probability of the data given H0, P(data|H0). You may be thinking: potato po-tah-to, that’s hair splitting and a very small p-value is indeed a good sign that a result is not due to chance. In many circumstances, you’ll be approximately correct, but in some cases, you’ll be utterly wrong.
Let’s take a simplified but revealing example: we want to determine Robert’s citizenship. Null hypothesis: H0, Robert is a US citizen. Alternative hypothesis: H1, he is not. Our data: we know that Robert is a US senator. There are 100 senators out of 330 million US citizens, so under the null hypothesis, the probability of our data (i.e., the p-value) is 100 / 300,000,000 ≈ 0.000000303. Per the rules of statistical significance, we can safely conclude that our null hypothesis is rejected and Robert is not a US citizen. That’s obviously false, so what went wrong? The probability that Robert is a US senator is indeed very low if he is a US citizen, but it’s even lower if he is not (namely zero!). P-values cannot help us here, even with a stricter 0.01 or even 0.001 threshold (for an alternative illustration of this problem, see xkcd).
P-values were invented at a time when all calculations had to be done by hand, and so they rely on simplifying statistical assumption. Broadly speaking, they assume that the phenomenon you’re observing obeys some regular statistical distribution, often the normal distribution (or a distribution from the same family). Unfortunately, that’s rarely true2:
Unless you’re measuring some low-level psycho-physiological variable, your population of interest is generally made up of heterogeneous groups. Let’s say you’re a marketing manager for Impossible Burgers looking at the demand for meat substitutes. You would have to account for two groups: on the one hand, vegetarians, for whom the relevant alternative is a different vegetarian product; on the other hand, meat eaters, who can be enticed but will care much more about taste and price compared to meat itself.
A normal distribution is symmetrical and extends to infinity in both directions. In real life, there are asymmetries, threshold and limits. People never buy negative quantities, nor infinite ones. They don’t vote at all before they’re 18 and the market of 120-year-old is much narrower than the market for 90-year-old and 60-year-old would suggest.
Conversely, we see “fat-tailed” distributions, where extreme values are much more frequent than expected from a normal distribution. There are more multi-billionaires than you would expect from looking at the number of millionaires and billionaires.
This implies that the p-values coming from a standard model are often wrong. Even if you correctly treat them as P(data|H0) and not P(H0|data), they’ll often be significantly off.
Let’s say that you have taken to heart the two previous issues and built a complete Bayesian model that finally allows you to properly calculate P(H0|data), the probability that the real value is zero or negative given the observed data. Should you bring it to your decision-maker? I would argue that you shouldn’t, because it doesn’t reflect economic outcomes.
Let’s say that a business decision-maker is pondering two possible actions, A and B. Based on observed data, the probability of zero or negative benefits is:
0.08 for action A
0.001 for action B
Should the decision-maker pick action B based on these numbers? What if I told you that the corresponding 90% confidence intervals are:
[-$0.5m; $99.5m] for action A
[$0.1m; $0.2m] for action B
Action B may have a lower probability of leading to a zero or negative outcome, but its expected value for the business is much lower, unless the business is incredibly risk-averse. In most situations, “economic significance” for a decision-maker hangs on two questions:
How much money are we likely to gain? (aka, the expected value)
In a “reasonably-likely worst-case scenario”, how much money do we stand to lose? (aka, the lower bound of the confidence interval)
Confidence intervals are a much better tool to answer these questions than a single probability number.
Let’s take a concrete example, adapted and simplified from my book1. A company has executed a time study of how long it takes its bakers to prepare made-to-order cakes depending on their level of experience. Having an industrial engineer measure how long it takes to make a cake in various stores across the country is expensive and time-consuming, so the data set has only 10 points, as you can see in the following figure.
In addition to the very small size of the sample, it contains an an outlier, in the upper left corner: a new employee spending most of a day working on a complex cake for a corporate retreat. How should the data be reported to business partners? One could discard the extreme observation. But that observation, while unusual, is not an aberration per se. There was no measurement error, and those circumstances probably occur from time to time. An other option would be to only report the overall mean duration, 56 minutes, but that would also be misleading because it would not convey the variability and uncertainty in the data.
Alternatively, one could calculate a normal confidence interval (CI) based on the traditional statistical assumptions. Normal confidence intervals are closely linked to the p-value: an estimate is statistically significant if and only if the corresponding confidence interval does not include zero. As you’ll learn in any stats class, the lower limit of a normal 95%-CI is equal to the mean minus 1.96 times the standard error, and the upper limit is equal to the mean plus 1.96 times the standard error. Unfortunately, in the present case the confidence interval is [-23;135] and we can imagine that business partners would not take too kindly to the possibility of negative baking duration...
This issue comes from the assumption that baking times are normally distributed, which they are obviously not. One could try to fit a better distribution, but using a Bootstrap confidence interval is much simpler.
To build Bootstrap confidence intervals, you simply need to build “a lot of similar samples” by drawing with replacement from your original sample. Drawing with replacement is very simple in both R and Python, we just set “replace” to true in each case:
## Rboot_dat <- slice_sample(dat, n=nrow(dat), replace = TRUE)## Pythonboot_df = data_df.sample(len(data_df), replace = True)
Why are we drawing with replacement? To really grasp what’s happening with the Bootstrap, it’s worth taking a step back and remembering the point of statistics: we have a population that we cannot fully examine, so we’re trying to make inferences about this population based on a limited sample. To do so, we create an “imaginary” population through either statistical assumptions or the Bootstrap. With statistical assumptions we say, “imagine that this sample is drawn from a population with a normal distribution,” and then make inferences based on that. With the Bootstrap we’re saying, “imagine that the population has exactly the same probability distribution as the sample,” or equivalently, “imagine that the sample is drawn from a population made of a large (or infinite) number of copies of that sample.” Then drawing with replacement from that sample is equivalent to drawing without replacement from that imaginary population. As statisticians will say, “the Bootstrap sample is to the sample what the sample is to the population.”
We repeat that process many times (let’s say 2,000 times):
## Rmean_lst <- list()B <- 2000N <- nrow(dat)for(i in 1:B){ boot_dat <- slice_sample(dat, n=N, replace = TRUE) M <- mean(boot_dat$times) mean_lst[[i]] <- M}mean_summ <- tibble(means = unlist(mean_lst))## Pythonres_boot_sim = []B = 2000N = len(data_df)for i in range(B): boot_df = data_df.sample(N, replace = True) M = np.mean(boot_df.times) res_boot_sim.append(M)
The result of the procedure is a list of Bootstrap sample means, which we can plot with an histogram:
As you can see, the histogram is very irregular: there is a peak close to the mean of our original data set along with smaller peaks corresponding to certain patterns. Given how extreme our outlier is, each of the seven peaks corresponds to its number of repetitions in the Bootstrap sample, from zero to six. In other words, it doesn’t appear at all in the samples whose means are in the first (leftmost) peak, it appears exactly once in the samples whose means are in the second peak, and so on.
From there, we can calculate the Bootstrap confidence interval (CI). The bounds of the CI are determined from the empirical distribution of the preceding means. Instead of trying to fit a statistical distribution (e.g., normal), we can simply order the values from smallest to largest and then look at the 2.5% quantile and the 97.5% quantile to find the two-tailed 95%-CI. With 2,000 samples, the 2.5% quantile is equal to the value of the 50th smallest mean (because 2,000 * 0.025 = 50), and the 97.5% quantile is equal to the value of the 1950th mean from smaller to larger, or the 50th largest mean (because both tails have the same number of values). Fortunately, we don’t have to calculate these by hand:
## R LL_b <- as.numeric(quantile(mean_summ$means, c(0.025)))UL_b <- as.numeric(quantile(mean_summ$means, c(0.975)))## Python LL_b = np.quantile(mean_lst, 0.025) UL_b = np.quantile(mean_lst, 0.975)
The following figure shows the same histogram as before but adds the mean of the means, the normal CI bounds and the Bootstrap CI bounds.
The Bootstrap 95%-CI is [7.50; 140.80] (plus or minus some sampling difference), which is much more realistic. No negative values as with the normal assumptions!
Once you start using the Bootstrap, you’ll be amazed at its flexibility. Small sample size, irregular distributions, business rules, expected values, A/B tests with clustered groups: the Bootstrap can do it all!
Let’s imagine, for example, that the company in our previous example is considering instituting a time promise — “your cake in three hours or 50% off” — and wants to know how often a cake currently takes more than three hours to be baked. Our estimate would be the sample percentage: it happens in 1 of the 10 observed cases, or 10%. But we can’t leave it at that, because there is significant uncertainty around that estimate, which we need to convey. Ten percent out of 10 observations is much more uncertain than 10% out of 100 or 1,000 observations. So how could we build a CI around that 10% value? With the Bootstrap, of course!
The histogram of Bootstrap estimates also offers a great visualization to show business partners: “This vertical line is the result of the actual measurement, but you can also see all the possible values it could have taken”. The 90% or 95% lower bound offers a “reasonable worst case scenario” based on available information.
Finally, if your boss or business partners are dead set on p-values, the Bootstrap offers a similar metric, the Achieved Significance Level (ASL). The ASL is simply the percentage of Bootstrap values that are zero or less. That interpretation is very close to the one people wrongly assign to the p-value, so there’s very limited education needed: “the ASL is 3% so there’s a 3% chance that the true value is zero or less; the ASL is less than 0.05 so we can treat this result as significant”.
To recap, even though p-values remain ubiquitous in applied data analysis, they have overstayed their welcome. They don’t mean what people generally think they mean; and even if they did, that’s not the answer that decision-makers are looking for. Even in academia, there’s currently a strong push towards reducing the blind reliance on p-values (see the ASA statement below4).
Using Bootstrap confidence intervals is both easier and more compelling. They don’t rely on hidden statistical assumptions, only on a straightforward one: the overall population looks the same as our sample. They provide information on possible outcomes that is richer and more relevant to business decisions.
Here comes the final shameless plug. If you want to learn more about the Bootstrap, my book will show you:
How to determine the number of Bootstrap samples to draw;
How to apply the Bootstrap to regression, A/B test and ad-hoc statistics;
How to write high-performance code that will not have your colleagues snickering at your FOR loops;
And a lot of other cool things about analyzing customer data in business.
[1] F. Buisson, Behavioral Data Analysis with R and Python (2021). My book, obviously! The code for the example is available on the book’s Github repo.
[2] R. Wilcox, Fundamentals of Modern Statistical Methods: Substantially Improving Power and Accuracy (2010). We routinely assume that our data is normally distributed “enough.” Wilcox shows that this is unwarranted and can severely bias analyses. A very readable book on an advanced topic.
[3] See my earlier post “Is Your Behavioral Data Truly Behavioral?”.
[4] R. L. Wasserstein & N. A. Lazar (2016) “The ASA Statement onp-Values: Context, Process, and Purpose”, The American Statistician, 70:2, 129–133, DOI:10.1080/00031305.2016.1154108. | [
{
"code": null,
"e": 574,
"s": 171,
"text": "A few years ago, I was hired by one of the largest insurance companies in the US to start and lead their behavioral science team. I had a PhD in behavioral economics from one of the top 10 economics departments in the world and half a decade of experience... |
Explain in detail about the memory life cycle of JavaScript? | Regardless of the programming language, the memory cycle is almost same for any programming language.
1) Allocation of memory .
2) use the allocated memory(reading or writing)
3) Release the allocated memory when it is unnecessary.
The first and last parts are directly connected in low-level languages but are indirectly connected in high-level languages such as JavaScript.
JavaScript is called garbage collected language, that is when variables are declared, it will automatically allocate memory to them.When there are no more references for the declared variables, allocated memory will be released.
In the following example javascript allocated memory for a number, a string and an object.
var n = 989; // allocates memory for a number
var s = 'qwerty'; // allocates memory for a string
var o = {
a: 1,
b: null
}; // allocates memory for an object and contained values
Using values basically means reading and writing in allocated memory.This can be done by reading or writing the value of a variable or an object property or even passing an argument to a function.
Most of the memory management issues will come in this stage.The herculean task here is to figure out when the allocated memory is not needed any longer.To sort out this issue most of the high level languages embed a piece of software called garbage collector.
The task of garbage collector is to track memory allocation and find when the allocated memory is of no longer required so as to release it.Unfortunately this process is just an estimation because the general problem of knowing whether some piece of memory is needed is undecidable.(algorithm can't trace out)
Javascript garbage collector uses some algorithms such as Reference-counting garbage collection to figure out the memory which is no longer in use. | [
{
"code": null,
"e": 1164,
"s": 1062,
"text": "Regardless of the programming language, the memory cycle is almost same for any programming language."
},
{
"code": null,
"e": 1190,
"s": 1164,
"text": "1) Allocation of memory ."
},
{
"code": null,
"e": 1238,
"s": 11... |
PHP - Installation on Windows with Apache | To install Apache with PHP 5 on Windows follow the following steps. If your PHP and Apache versions are different then please take care accordingly.
Download Apache server from www.apache.org/dist/httpd/binaries/win32. You want the current stable release version with the no_src.msi extension. Double-click the installer file to install; C:\Program Files is a common location. The installer will also ask you whether you want to run Apache as a service or from the command line or DOS prompt. We recommend you do not install as a service, as this may cause problems with startup.
Download Apache server from www.apache.org/dist/httpd/binaries/win32. You want the current stable release version with the no_src.msi extension. Double-click the installer file to install; C:\Program Files is a common location. The installer will also ask you whether you want to run Apache as a service or from the command line or DOS prompt. We recommend you do not install as a service, as this may cause problems with startup.
Extract the PHP binary archive using your unzip utility; C:\PHP is a common location.
Extract the PHP binary archive using your unzip utility; C:\PHP is a common location.
Copy some .dll files from your PHP directory to your system directory (usually C:\Windows). You need php5ts.dll for every case. You will also probably need to copy the file corresponding to your Web server module - C:\PHP\Sapi\php5apache.dll. to your Apache modules directory. It's possible that you will also need others from the dlls subfolder.but start with the two mentioned previously and add more if you need them.
Copy some .dll files from your PHP directory to your system directory (usually C:\Windows). You need php5ts.dll for every case. You will also probably need to copy the file corresponding to your Web server module - C:\PHP\Sapi\php5apache.dll. to your Apache modules directory. It's possible that you will also need others from the dlls subfolder.but start with the two mentioned previously and add more if you need them.
Copy either php.ini-dist or php.ini-recommended (preferably the latter) to your Windows directory, and rename it php.ini. Open this file in a text editor (for example, Notepad). Edit this file to get configuration directives; At this point, we highly recommend that new users set error reporting to E_ALL on their development machines.
Copy either php.ini-dist or php.ini-recommended (preferably the latter) to your Windows directory, and rename it php.ini. Open this file in a text editor (for example, Notepad). Edit this file to get configuration directives; At this point, we highly recommend that new users set error reporting to E_ALL on their development machines.
Tell your Apache server where you want to serve files from and what extension(s) you want to identify PHP files (.php is the standard, but you can use .html, .phtml, or whatever you want). Go to your HTTP configuration files (C:\Program Files\Apache Group\Apache\conf or whatever your path is), and open httpd.conf with a text editor. Search for the word DocumentRoot (which should appear twice) and change both paths to the directory you want to serve files out of. (The default is C:\Program Files\Apache Group\Apache\htdocs.). Add at least one PHP extension directive as shown in the first line of the following code −
Tell your Apache server where you want to serve files from and what extension(s) you want to identify PHP files (.php is the standard, but you can use .html, .phtml, or whatever you want). Go to your HTTP configuration files (C:\Program Files\Apache Group\Apache\conf or whatever your path is), and open httpd.conf with a text editor. Search for the word DocumentRoot (which should appear twice) and change both paths to the directory you want to serve files out of. (The default is C:\Program Files\Apache Group\Apache\htdocs.). Add at least one PHP extension directive as shown in the first line of the following code −
LoadModule php5_module modules/php5apache.dll
AddType application/x-httpd-php .php .phtml
You may also need to add the following line −
You may also need to add the following line −
AddModule mod_php5.c
Stop and restart the WWW service. Go to the Start menu → Settings → Control Panel → Services. Scroll down the list to IIS Admin Service. Select it and click Stop. After it stops, select World Wide Web Publishing Service and click Start. Stopping and restarting the service from within Internet Service Manager will not suffice. Since this is Windows, you may also wish to reboot.
Stop and restart the WWW service. Go to the Start menu → Settings → Control Panel → Services. Scroll down the list to IIS Admin Service. Select it and click Stop. After it stops, select World Wide Web Publishing Service and click Start. Stopping and restarting the service from within Internet Service Manager will not suffice. Since this is Windows, you may also wish to reboot.
Open a text editor. Type: <?php phpinfo(); ?>. Save this file in your Web server's document root as info.php.
Open a text editor. Type: <?php phpinfo(); ?>. Save this file in your Web server's document root as info.php.
Start any Web browser and browse the file.you must always use an HTTP request (http://www.testdomain.com/info.php or http://localhost/info.php or http://127.0.0.1/info.php) rather than a filename (/home/httpd/info.php) for the file to be parsed correctly
Start any Web browser and browse the file.you must always use an HTTP request (http://www.testdomain.com/info.php or http://localhost/info.php or http://127.0.0.1/info.php) rather than a filename (/home/httpd/info.php) for the file to be parsed correctly
You should see a long table of information about your new PHP installation message Congratulations!
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2906,
"s": 2757,
"text": "To install Apache with PHP 5 on Windows follow the following steps. If your PHP and Apache versions are different then please take care accordingly."
},
{
"code": null,
"e": 3337,
"s": 2906,
"text": "Download Apache server from www.a... |
Data Visualization in Python like in R’s ggplot2 | by Dr. Gregor Scheithauer | Towards Data Science | If you love plotting your data with R’s ggplot2 but you are bound to use Python, the plotnine package is worth to look into as an alternative to matplotlib. In this post I show you how to get started with plotnine for productive output.
If you want to follow along please find the whole script on GitHub:
github.com
ggplot2 is a system for declaratively creating graphics, based on The Grammar of Graphics. You provide the data, tell ggplot2 how to map variables to aesthetics, what graphical primitives to use, and it takes care of the details. Source: http://ggplot2.tidyverse.org/
In my experience the advantage of ggplot2 is the implementation of the grammar of graphics.
plotnine is a Grammar of Graphics for Python by Hassan Kibirige and brings the same advantages to python: Less coding and easy understanding (declarative paradigm).
# Using pip$ pip install plotnine # 1. should be sufficient for most$ pip install 'plotnine[all]' # 2. includes extra/optional packages# Or using conda$ conda install -c conda-forge plotnine
I used the craft-beers-dataset from Jean-Nicholas Hould. It contains information about 2,410 US craft beers. The information includes:
abv — The alcoholic content by volume with 0 being no alcohol and 1 being pure alcohol
ibu — International bittering units, which describe how bitter a drink is.
name — Name of the beer.
style — Beer style (lager, ale, IPA, etc.)
brewery_id — Unique identifier for brewery that produces this beer
ounces — Size of beer in ounces.
Install necessary libs
import pandas as pdimport numpy as npfrom plotnine import *
Define useful constants
c_remote_data ='https://raw.githubusercontent.com/nickhould/craft-beers-dataset/master/data/processed/beers.csv'c_col = ["#2f4858", "#f6ae2d", "#f26419", "#33658a", "#55dde0", "#2f4858", "#2f4858", "#f6ae2d", "#f26419", "#33658a", "#55dde0", "#2f4858"]
Useful functions
def labels(from_, to_, step_): return pd.Series(np.arange(from_, to_ + step_, step_)).apply(lambda x: '{:,}'.format(x)).tolist()def breaks(from_, to_, step_): return pd.Series(np.arange(from_, to_ + step_, step_)).tolist()
Read data and set index
data = pd.read_csv(c_remote_data)data = ( data.filter([ 'abv', 'ibu', 'id', 'name', 'style', 'brewery_id', 'ounces' ]). set_index('id'))
fig = ( ggplot(data.dropna(subset = ['abv'])) + geom_histogram(aes(x = 'abv')))
fig = ( ggplot(data.dropna(subset = ['abv'])) + geom_histogram( aes(x = 'abv'), fill = c_col[0], color = 'black' ))
fig = ( ggplot(data.dropna(subset = ['abv'])) + geom_histogram( aes(x = 'abv'), fill = c_col[0], color = 'black' ) + labs( title ='Distribution of The alcoholic content by volume (abv)', x = 'abv - The alcoholic content by volume', y = 'Count', ))
fig = ( ggplot(data.dropna(subset = ['abv'])) + geom_histogram( aes(x = 'abv'), fill = c_col[0], color = 'black' ) + labs( title ='Distribution of The alcoholic content by volume (abv)', x = 'abv - The alcoholic content by volume', y = 'Count', ) + scale_x_continuous( limits = (0, 0.14), labels = labels(0, 0.14, 0.02), breaks = breaks(0, 0.14, 0.02) ) + scale_y_continuous( limits = (0, 350), labels = labels(0, 350, 50), breaks = breaks(0, 350, 50) ))
theme_set( theme_538()) # one time call
theme_set( theme_538() + theme( figure_size = (8, 4), text = element_text( size = 8, color = 'black', family = 'Arial' ), plot_title = element_text( color = 'black', family = 'Arial', weight = 'bold', size = 12 ), axis_title = element_text( color = 'black', family = 'Arial', weight = 'bold', size = 6 ), ))
fig = ( ggplot(data.dropna(subset = ['abv'])) + geom_histogram( aes(x = 'abv'), fill = c_col[0], color = 'black' ) + labs( title ='Distribution of The alcoholic content by volume (abv)', x = 'abv - The alcoholic content by volume (median = dashed line; mean = solid line)', y = 'Count', ) + scale_x_continuous( limits = (0, 0.14), labels = labels(0, 0.14, 0.02), breaks = breaks(0, 0.14, 0.02) ) + scale_y_continuous( limits = (0, 350), labels = labels(0, 350, 50), breaks = breaks(0, 350, 50) ) + geom_vline(aes(xintercept = data.abv.mean()), color = 'gray') + geom_vline(aes(xintercept = data.abv.median()), linetype = 'dashed', color = 'gray'))
fig = ( ggplot(data.dropna(subset = ['abv', 'style'])[data['style'].dropna().str.contains('American')]) + geom_histogram( aes(x = 'abv'), fill = c_col[0], color = 'black' ) + labs( title ='Distribution of The alcoholic content by volume (abv)', x = 'abv - The alcoholic content by volume', y = 'Count', ) + scale_x_continuous( limits = (0, 0.14), labels = labels(0, 0.14, 0.07), breaks = breaks(0, 0.14, 0.07) ) + scale_y_continuous( limits = (0, 300), labels = labels(0, 300, 100), breaks = breaks(0, 300, 100) ) + theme(figure_size = (8, 12)) + facet_wrap('~style', ncol = 4))
fig = ( ggplot(data.dropna(subset = ['abv'])) + geom_point( aes(x = 'abv', y = 'ibu'), fill = c_col[0], color = 'black' ) + labs( title ='Relationship between alcoholic content (abv) and int. bittering untis (ibu)', x = 'abv - The alcoholic content by volume', y = 'ibu - International bittering units', ) + scale_x_continuous( limits = (0, 0.14), labels = labels(0, 0.14, 0.02), breaks = breaks(0, 0.14, 0.02) ) + scale_y_continuous( limits = (0, 150), labels = labels(0, 150, 30), breaks = breaks(0, 150, 30) ))
fig = ( ggplot(data.dropna(subset = ['abv'])) + geom_point( aes(x = 'abv', y = 'ibu', size = 'ounces'), fill = c_col[0], color = 'black' ) + labs( title ='Relationship between alcoholic content (abv) and int. bittering untis (ibu)', x = 'abv - The alcoholic content by volume', y = 'ibu - International bittering units', ) + scale_x_continuous( limits = (0, 0.14), labels = labels(0, 0.14, 0.02), breaks = breaks(0, 0.14, 0.02) ) + scale_y_continuous( limits = (0, 150), labels = labels(0, 150, 30), breaks = breaks(0, 150, 30) ))
data['ounces_str'] = data['ounces']data['ounces_str'] = data['ounces_str'].apply(str)fig = ( ggplot(data.dropna(subset = ['abv'])) + geom_point( aes(x = 'abv', y = 'ibu', fill = 'ounces_str'), alpha = 0.5, color = 'black' ) + labs( title ='Relationship between alcoholic content (abv) and int. bittering untis (ibu)', x = 'abv - The alcoholic content by volume', y = 'ibu - International bittering units', ) + scale_fill_manual( name = 'Ounces', values = c_col) + scale_x_continuous( limits = (0, 0.14), labels = labels(0, 0.14, 0.02), breaks = breaks(0, 0.14, 0.02) ) + scale_y_continuous( limits = (0, 150), labels = labels(0, 150, 30), breaks = breaks(0, 150, 30) ))
fig = ( ggplot(data.dropna(subset = ['abv'])) + geom_point( aes(x = 'abv', y = 'ibu', fill = 'ounces_str'), alpha = 0.5, color = 'black' ) + geom_smooth( aes(x = 'abv', y = 'ibu') ) + labs( title ='Relationship between alcoholic content (abv) and int. bittering untis (ibu)', x = 'abv - The alcoholic content by volume', y = 'ibu - International bittering units', ) + scale_fill_manual( name = 'Ounces', values = c_col) + scale_x_continuous( limits = (0, 0.14), labels = labels(0, 0.14, 0.02), breaks = breaks(0, 0.14, 0.02) ) + scale_y_continuous( limits = (0, 150), labels = labels(0, 150, 30), breaks = breaks(0, 150, 30) ))
fig = ( ggplot(data.dropna(subset = ['abv'])) + geom_jitter( aes(x = 'abv', y = 'ibu', fill = 'ounces_str'), width = 0.0051, height = 5, color = 'black' ) + labs( title ='Relationship between alcoholic content (abv) and int. bittering untis (ibu)', x = 'abv - The alcoholic content by volume', y = 'ibu - International bittering units', ) + scale_fill_manual( guide = False, name = 'Ounces', values = c_col) + scale_x_continuous( limits = (0, 0.14), labels = labels(0, 0.14, 0.02), breaks = breaks(0, 0.14, 0.02) ) + scale_y_continuous( limits = (0, 150), labels = labels(0, 150, 30), breaks = breaks(0, 150, 30) ) + facet_wrap('ounces_str'))
fig = ( ggplot(data.dropna(subset = ['abv'])) + geom_bin2d( aes(x = 'abv', y = 'ibu') ) + labs( title ='Relationship between alcoholic content (abv) and int. bittering untis (ibu)', x = 'abv - The alcoholic content by volume', y = 'ibu - International bittering units', ) + scale_x_continuous( limits = (0, 0.14), labels = labels(0, 0.14, 0.02), breaks = breaks(0, 0.14, 0.02) ) + scale_y_continuous( limits = (0, 150), labels = labels(0, 150, 30), breaks = breaks(0, 150, 30) ) + theme(figure_size = (8, 8)))
fig = ( ggplot(data.dropna(subset = ['abv'])) + geom_boxplot( aes(x = 'ounces_str', y = 'abv') ) + labs( title ='Distribution of alcoholic content (abv) by size', x = 'size in ounces', y = 'abv - The alcoholic content by volume', ) + scale_y_continuous( limits = (0, 0.14), labels = labels(0, 0.14, 0.02), breaks = breaks(0, 0.14, 0.02) ))
fig = ( ggplot(data.dropna(subset = ['abv'])) + geom_violin( aes(x = 'ounces_str', y = 'abv'), fill = c_col[0] ) + labs( title ='Distribution of alcoholic content (abv) by size', x = 'size in ounces', y = 'abv - The alcoholic content by volume', ) + scale_y_continuous( limits = (0, 0.14), labels = labels(0, 0.14, 0.02), breaks = breaks(0, 0.14, 0.02) ))
plotnine offers a wide range of different visualizations, which are easy to adapt for customized outputs. If you have experience with ggplot in R then a switch to plotnine is effortless.
Find more articles from me here:
Learn how I plan my articles for MediumLearn how to write clean code in Python using chaining (or pipes)Learn how to analyze your LinkedIn data using RLearn how to create charts in a descriptive way in Python using grammar of graphicsLearn how to set up logging in your python data science code in under 2 minutes
Learn how I plan my articles for Medium
Learn how to write clean code in Python using chaining (or pipes)
Learn how to analyze your LinkedIn data using R
Learn how to create charts in a descriptive way in Python using grammar of graphics
Learn how to set up logging in your python data science code in under 2 minutes
Gregor Scheithauer is a consultant, data scientist, and researcher. He is specialized in the topics of Process Mining, Business Process Management, and Analytics. You can connect with him on LinkedIn, Twitter, or here on Medium. Thank you! | [
{
"code": null,
"e": 409,
"s": 172,
"text": "If you love plotting your data with R’s ggplot2 but you are bound to use Python, the plotnine package is worth to look into as an alternative to matplotlib. In this post I show you how to get started with plotnine for productive output."
},
{
"cod... |
Using regression with correlated data | by Emily A. Halford | Towards Data Science | While regression models are easy to run given their short, simple syntax, this accessibility also makes it easy to use regression inappropriately. These models have several key assumptions that need to be met in order for their output to be valid, but your code will typically run whether or not these assumptions have been met.
For linear regression (used with a continuous outcome), these assumptions are as follows:
Independence: All observations are independent of each other, residuals are uncorrelatedLinearity: The relationship between X and Y is linearHomoscedasticity: Constant variance of residuals at different values of XNormality: Data should be normally distributed around the regression line
Independence: All observations are independent of each other, residuals are uncorrelated
Linearity: The relationship between X and Y is linear
Homoscedasticity: Constant variance of residuals at different values of X
Normality: Data should be normally distributed around the regression line
For logistic regression (used with a binary or ordinal categorical outcome), these assumptions are as follows:
Independence: All observations are independent of each other, residuals are uncorrelatedLinearity in the logit: The relationship between X and the logit of Y is linearModel is correctly specified, including lack of multicollinearity
Independence: All observations are independent of each other, residuals are uncorrelated
Linearity in the logit: The relationship between X and the logit of Y is linear
Model is correctly specified, including lack of multicollinearity
In both kinds of simple regression models, independent observations are absolutely necessary to fit a valid model. If your data points are correlated, this assumption of independence is violated. Fortunately, there are still ways to produce a valid regression model with correlated data.
Correlation in data occurs primarily through multiple measurements (e.g. two measurements are taken on each participant 1 week apart, and data points within individuals are not independent) or if there is clustering in the data (e.g. a survey is conducted among students attending different schools, and data points from students within a given school are not independent).
The result is that that the outcome has been measured on the level of an individual observation, but that there is a second level of either an individual (in the case of multiple time points) or clusters on which individual data points can be correlated. Ignoring this correlation means that standard error cannot be accurately computed, and in most cases will be artificially low.
The best way to know if your data is correlated is simply through familiarity with your data and the collection process that produced it. If you know that you have repeated measures from the same individuals or have data on participants who can be grouped into families or schools, you can assume that your data points are probably not independent. You can also investigate your data for possible correlation by calculating the ICC (intraclass correlation coefficient) to determine how correlated data points are within possible groups, or by looking for correlation in your residuals.
As previously mentioned, simple regression will produce inaccurate standard errors with correlated data and therefore should not be used.
Instead, you want to use models that can account for the correlation that is present in your data. If the correlation is due to some grouping variable (e.g. school) or repeated measures over time, then you can choose between Generalized Estimating Equations or Multilevel Models. These modeling techniques can handle either binary or continuous outcome variables, so can be used to replace either logistic or linear regression when the data are correlated.
Generalized estimating equations (GEE) will give you beta estimates that are the same or similar to those produced by simple regression, but with appropriate standard errors. Generalized estimating equations are particularly useful when you have repeated measures for the same individuals or units. This modeling technique tends to work well when you have many small clusters, which is often the result of having a few measurements on a large number of participants. GEE also allows the user to specify one of numerous correlation structures, which can be a useful feature depending on your data.
Multilevel modeling (MLM) also provides appropriate standard errors when data points are not independent. It is typically the best modeling approach when the user is interested in relationships both within and between clustered groups, and is not simply looking to account for the effect of correlation in standard error estimates. MLM has the additional advantage of being able to handle more than two levels in the response variable. The primary drawback of MLM models is that they require larger sample sizes within each cluster, so may not work well when clusters are small.
Both GEE and MLM are fairly easy to use in R. Below, I will walk through examples with the two most common kinds of correlated data: data with repeated measures from individuals and data collected from individuals with an important grouping variable (in this case, country). I will fit simple regression, GEE, and MLM models with each dataset, and will discuss which modeling technique is best for these different data types.
The data that I will be working with first comes from Years 9 and 15 of the Princeton University Fragile Families & Child Wellbeing Study, which follows the families of selected children born between 1998 and 2000 in major US cities. Data are publicly available, and can be accessed by submitting a brief request on the Fragile Families Data and Documentation page. Since this study follows up with the same families year after year, data points from the same family units at different time points are not independent.
This dataset contains dozens of variables representing the health of wellbeing of participating children and their parents. Being in psychiatric epidemiology, I am primarily interested in examining the children’s mental-wellbeing. Participating children are asked if they frequently feel sad, and I will be using answers to this “often feeling sad” question as my outcome. Since substance use is tied to poorer mental wellbeing among adolescents, I will be using variables representing alcohol and tobacco use as predictors*.
*Note: Models created in this article are for demonstration purposes only and should not be considered to be meaningful. I have not considered confounding, mediation, other model assumptions, or other possible data issues in the construction of these models.
First, let’s load the packages that we’ll be using. I’ve loaded “tidyverse” to clean our data, “haven” because the data we’ll be reading in comes in SAS format, “geepack” to run our GEE model, and “lme4” to run our multilevel model:
library(tidyverse)library(haven)library(geepack)library(lme4)
Now let’s do some data cleaning to get these data ready for modeling!
Data from Years 9 and 15 are housed in separate SAS files (identifiable by the .sas7bdat extension), so we have one code chunk to read in and clean each file. This cleaning has to be done separately because variable names and coding differ slightly between study years (see the Data and Documentation page for codebooks).
There are hundreds of variables included in the datasets, so we first select those that will be used in our model and assign meaningful variable names that are consistent across data frames. Next, we filter the data to only include individuals with complete data for our variables of interest (the code below excludes individuals with missing data for these variables as well as those who refused to answer).
We then recode our variables in the standard 1 = “yes”, 0 = “no” format. For the “feel_sad” variable, this also means dichotomizing a variable with 4 levels which represent varying degrees of sadness. We end up with a binary variable where 1 = “sad” and 0 = “not sad.” Some regression techniques can handle multiple levels in your response variable (MLM included), but I have binarized it here for simplicity. Finally, we create a “time_order” variable indicating if the observation comes from the first or second round of the study.
year_9 = read_sas("./data/FF_wave5_2020v2_SAS.sas7bdat") %>% select(idnum, k5g2g, k5f1l, k5f1j) %>% rename("feel_sad" = "k5g2g", "tobacco" = "k5f1l", "alcohol" = "k5f1j") %>% filter( tobacco == 1 | tobacco == 2, alcohol == 1 | alcohol == 2, feel_sad == 0 | feel_sad == 1 | feel_sad == 2 | feel_sad == 3 ) %>% mutate( tobacco = ifelse(tobacco == 1, 1, 0), alcohol = ifelse(alcohol == 1, 1, 0), feel_sad = ifelse(feel_sad == 0, 0, 1), time_order = 1 )year_15 = read_sas("./data/FF_wave6_2020v2_SAS.sas7bdat") %>% select(idnum, k6d2n, k6d40, k6d48) %>% rename("feel_sad" = "k6d2n", "tobacco" = "k6d40", "alcohol" = "k6d48") %>% filter( tobacco == 1 | tobacco == 2, alcohol == 1 | alcohol == 2, feel_sad == 1 | feel_sad == 2 | feel_sad == 3 | feel_sad == 4 ) %>% mutate( tobacco = ifelse(tobacco == 1, 1, 0), alcohol = ifelse(alcohol == 1, 1, 0), feel_sad = ifelse(feel_sad == 4, 0, 1), time_order = 2 )
We then combine data from Years 9 and 15 by stacking our two cleaned data frames using rbind(). The rbind() function works well here because both data frames now share all variable names. We next transform the “idnum” variable (which identifies unique family units) into a numeric variable so that it can be properly used to sort the data in the final code chunk. This step is necessary because the geeglm() function that we will be using to run the GEE model assumes that the data frame is sorted first by a unique identifier (in this case, “idnum”), and next by the order of observations (indicated here by the new “time_order” variable).
fragile_families = rbind(year_9, year_15) %>% mutate( idnum = as.numeric(idnum) )fragile_families = fragile_families[ with(fragile_families, order(idnum)),]
The above code produces the following cleaned data frame, which is now ready to be used for regression modeling:
Let’s fit our models:
Simple Logistic Regression
Simple Logistic Regression
First, we use the glm() function to fit a simple logistic regression model using the “fragile_families” data. Since we have a binary outcome variable, “family = binomial” is used to specify that logistic regression should be used. We also use tidy() from the “broom” package to clean up the model output. We are creating this model for comparison purposes only — as indicated before, the independence assumption has been violated and the standard errors associated with this model will not be valid!
glm(formula = feel_sad ~ tobacco + alcohol, family = binomial, data = fragile_families) %>% broom::tidy()
The above code produces the following output, which the subsequent modeling approaches will be compared to. Tobacco and alcohol use both appear to be significant predictors of sadness in participating children.
2. Generalized Estimating Equations
The syntax used to specify a GEE model using the geeglm() function from the “geepack” package is fairly similar to that used with the standard glm() function. The “formula”, “family”, and “data” are arguments are exactly the same for both functions. What’s new are the “id,” “waves,” and “corstr” arguments (see package documentation for all available arguments). The unique identifier that links observations from the same subject is specified in the “id” argument. In this case the ID is “idnum,” the unique identifier assigned to each family participating in the study. The “time_order” variable created during data cleaning comes into play in the “waves” argument, where it indicates the order in which observations were made. Finally, “corstr” can be used to specify the within-subject correlation structure. “Independence” is actually the default input for this argument, and it makes sense in this context because it is useful when clusters are small. However, “exchangeable” can be specified when all observations within a subject can be considered to be equally correlated, and “ar1” is best when the internal correlations change over time. Information on choosing the right correlation structure can be found here and here.
geeglm(formula = feel_sad ~ tobacco + alcohol, family = binomial, id = idnum, data = fragile_families, waves = time_order, corstr = "independence") %>% broom::tidy()
Our GEE model gives us the following output:
As you can see, our beta estimates are exactly the same as those produced using glm(), but standard error differs slightly now that the correlations in the data have been accounted for. While tobacco and alcohol are still significant predictors of sadness, the p-values are somewhat different**. If these p-values were closer to 0.05, having accurate standard error measurements could easily push a p-value over or under the level of significance.
**Note: The test statistics for GEE and logistic regression look drastically different, but this is only because the test statistic provided in the logistic regression output is a Z-statistic and the test statistic provided in the GEE output is a Wald statistic. The Z-statistic is calculated by dividing the estimate by the standard error, while the Wald statistic is calculated by squaring the result of dividing the estimate by the standard error. The two values are therefore mathematically related, and by taking the square root of the values in the GEE “statistic” column you will see a much more moderate change from the initial Z-statistics.
With the geeglm() function, it is also important to verify that your clusters have been properly recognized. You can do this by running the above code without the broom::tidy() step, so:
geeglm(formula = feel_sad ~ tobacco + alcohol, family = binomial, id = idnum, data = fragile_families, waves = time_order, corstr = "independence")
This code produces the output shown below. You want to look to the last line of the output, where “Number of clusters” and “Maximum cluster size” are described. We had 2 observations for several thousand individuals, so these values make sense in the context of our data and indicate that clusters were registered correctly by the function. If, however, the number of clusters is equal to the number of rows in your dataset, something is not working properly (most likely the sorting of your data is off).
3. Multilevel Modeling
Next, let’s fit a multilevel model using glmer() from the lme4 package. Again, the required code is almost identical to that used for logistic regression. The only required change is specifying random slopes and intercepts in the formula argument. This is done with the “(1 | idnum)” bit of code, which follows the following structure: (random slopes | random intercepts). The grouping variable, in this case “idnum,” is specified to the right of the | as “random intercepts,” and the “1” indicates that we don’t want the predictors’ effects to vary across groups. A useful blog post by Rense Nieuwenhuis provides various examples of this glmer() syntax.
The lme4 package is not compatible with the broom package, so instead we pull the model’s coefficients after creating a list with a summary of the model’s output.
mlm = summary(glmer(formula = feel_sad ~ tobacco + alcohol + (1 | idnum), data = fragile_families, family = binomial))mlm$coefficients
Again, the output is similar to that of the simple logistic regression model, and both tobacco and alcohol use are still significant predictors of sadness. Estimates vary slightly from those produced using the glm() and geeglm() functions because groupings in the data are no longer ignored or treated as an annoyance to be addressed by correcting standard error; instead, they are now incorporated as an important part of the model. Standard error estimates are higher for all estimates in comparison to those produced through logistic regression, and Z- and p-values remain similar but reflect these important changes in the estimate and standard error values.
The second dataset that we will walk through comes from the WHO’s Global School-Based Student Health Survey (GSHS). This survey is conducted among schoolchildren aged 13–17 with the goals of helping countries to determine health priorities, establishing the prevalences of health-related behaviors, and facilitating direct comparison of these prevalences across nations. We will be using data from two countries, Indonesia and Bangladesh, which can be downloaded directly from these countries’ respective descriptive pages.
The data are cross-sectional: an identical survey was conducted one time among schoolchildren in both nations. I am interested in using variables from this dataset to describe the relationship between whether or not a child has friends, whether or not the child is bullied (my predictors) and whether or not the child has seriously contemplated suicide (my outcome). It is likely that these relationships differ between the two countries and that children are more similar to other children from the same country. Therefore, knowing whether a child is from Indonesia or Bangladesh provides important information about that child’s responses and the assumption of independent observations is violated.
Let’s load packages again:
library(tidyverse)library(haven)library(lme4)library(gee)
Note that the “geepack” package has been replaced with the “gee” package. The “gee” package is easier to use (in my opinion) with data that is clustered by a grouping variable such as country rather than within an individual who has multiple observations.
Next, let’s load in the data (which is also in SAS format, so we use the “haven” package again) and conduct some basic cleaning. Data cleaning here follows a similar structure to the procedure used with the Fragile Families & Child Wellbeing Study data: important variables are selected and assigned meaningful, consistent names, and a new variable is created to indicate which cluster an observation belongs to (in this case the new “country” variable).
indonesia = read_sas("./data/IOH2007_public_use.sas7bdat") %>% select(q21, q25, q27) %>% rename( "bullied" = "q21", "suicidal_thoughts" = "q25", "friends" = "q27" ) %>% mutate( country = 1, )bangladesh = read_sas("./data/bdh2014_public_use.sas7bdat") %>% select(q20, q24, q27) %>% rename( "bullied" = "q20", "suicidal_thoughts" = "q24", "friends" = "q27" ) %>% mutate( country = 2 )
Again, the two data frames are stacked together. Since variables were coded consistently during collection in both countries, some cleaning can be conducted only once using this combined dataset. Missing data is eliminated, and all variables are converted from string format to numeric. Finally, variables are mutated into a consistent, binarized format.
survey = rbind(indonesia, bangladesh) %>% mutate( suicidal_thoughts = as.numeric(suicidal_thoughts), friends = as.numeric(friends), bullied = as.numeric(bullied), suicidal_thoughts = ifelse(suicidal_thoughts == 1, 1, 0), friends = ifelse(friends == 1, 0, 1), bullied = ifelse(bullied == 1, 0, 1) ) %>% drop_na()
Our cleaned data frame now looks like this:
Let’s fit our models:
Simple Logistic Regression
Simple Logistic Regression
With the exception of variable names and the data specified, the glm() code remains identical to that used with the Fragile Families study data.
glm(formula = suicidal_thoughts ~ bullied + friends, family = binomial, data = survey) %>% broom::tidy()
Unsurprisingly, whether or not a child has friends and whether or not a child is bullied are both significant predictors of the presence of suicidal thoughts in this sample.
2. Generalized Estimating Equations
The gee() function in the gee package allows us to easily use GEE with our survey data. This function is a better fit than the previously used geeglm() function as data are not correlated over time, but rather by a separate variable that can be indicated with the “id” argument (in this case, “country”). The formula and family arguments remain identical to those used with the glm() function, and the “corstr” argument used with the geeglm() function is the same here as well. However, unlike the geepack package, the gee package is not compatible with the broom::tidy() function so output is viewed using the summary() function instead.
gee = gee(suicidal_thoughts ~ bullied + friends, data = survey, id = country, family = binomial, corstr = "exchangeable")summary(gee)
One of the reasons that I particularly like the gee() function is that the naive standard error and Z-test statistics are actually included in the output (naive meaning that these values are produced by regression where clustering is not accounted for — you’ll see that these are exactly the same as those produced by the glm() function above). You’ll notice drastic changes in the standard errors and Z-test statistics produced using GEE (“Robust”), although both of our predictors remain significant. It appears that accounting for within-country correlation has allowed for much lower standard errors to be used.
3. Multilevel Modeling***
***Note: As noted above, models are for demonstration purposes only and are not necessarily valid. In this case, we would want more groups than two for our MLM model (meaning data from additional countries). If you are really only using two groups with MLM models, you should consider a small sample size correction.
Finally, we try MLM with the survey dataset. The code is exactly the same as that used with the Fragile Families study data, but with the new formula, grouping variable, and dataset specified.
mlm = summary(glmer(formula = suicidal_thoughts ~ bullied + friends + (1 | country), data = survey, family = binomial))mlm$coefficients
Again, beta estimates and standard error estimates are now adjusted slightly from those produced using glm(). Z- and p-values associated with the “bullied” and “friends” variables are slightly smaller, although bullying and having friends remain significant predictors of suicidal thoughts.
Data from Princeton University’s Fragile Families & Child Wellbeing Study would be best represented using GEE. This is due to the maximum cluster size of 2 observations, the fact that individual families have multiple data points over time, and the fact that we were more interested in accounting for grouping in the standard error estimates than actually assessing differences between families.
Multilevel modeling is most appropriate for data from the Global School-Based Student Health Survey (GSHS) because the data were collected cross-sectionally and can be divided into two large clusters. Additionally, the output could be further explored to determine both within- and between-group variances, and we might be interested in relationships both within and across countries.
How you account for violations of the independent observations assumption will depend on the structure of your data and your general knowledge of the data collection process, as well as whether or not you consider the correlation to be an annoyance to adjust for or something meaningful to explore.
In conclusion, regression is flexible and certain regression models can handle correlated data. However, it is always important to check the assumptions of a given technique and to make sure that your analytic strategy is appropriate for your data. | [
{
"code": null,
"e": 501,
"s": 172,
"text": "While regression models are easy to run given their short, simple syntax, this accessibility also makes it easy to use regression inappropriately. These models have several key assumptions that need to be met in order for their output to be valid, but you... |
How do I set the Selenium webdriver get timeout? | We can set the Selenium webdriver to get timeout. There are numerous methods to implement timeouts. They are listed below −
setScriptTimeout.
setScriptTimeout.
pageLoadTimeout.
pageLoadTimeout.
implicitlyWait.
implicitlyWait.
The setScriptTimeout is the method to set the time for the webdriver. This is usually applied for an asynchronous test to complete prior throwing an exception. The default value of timeout is 0.
This method is generally used for JavaScript commands in Selenium. If we omit setting time for the script, the executeAsyncScript method can encounter failure due to the more time consumed by the JavaScript to complete execution.
If the timeout time is set to negative, then the JavaScript can execute for an endless time.
driver.manage().timeouts().setScriptTimeout(5,TimeUnit.SECONDS);
The pageLoadTimeout is the method used to set the time for the entire page load prior to throwing an exception. If the timeout time is set to negative, then the time taken to load the page is endless.
This timeout is generally used with the navigate and manage methods.
driver.manage().timeouts().pageLoadTimeout(4, TimeUnit.SECONDS);
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class PageLoadWt{
public static void main(String[] args)
throws InterruptedException{
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//set time for page load
driver.manage().timeouts().pageLoadTimeout(4, TimeUnit.SECONDS);
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
driver.quit();
}
}
The implicitlyWait is the method applied to the webdriver to wait for elements to be available in the page. It is a global wait to every element. NoSuchElementException is thrown if an element is still not available after the wait time has elapsed.
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ImplicitWt{
public static void main(String[] args)
throws InterruptedException{
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//set implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
driver.quit();
}
} | [
{
"code": null,
"e": 1186,
"s": 1062,
"text": "We can set the Selenium webdriver to get timeout. There are numerous methods to implement timeouts. They are listed below −"
},
{
"code": null,
"e": 1204,
"s": 1186,
"text": "setScriptTimeout."
},
{
"code": null,
"e": 122... |
Comparison among Bubble Sort, Selection Sort and Insertion Sort - GeeksforGeeks | 31 Oct, 2021
Bubble sort repeatedly compares and swaps(if needed) adjacent elements in every pass. In i-th pass of Bubble Sort (ascending order), last (i-1) elements are already sorted, and i-th largest element is placed at (N-i)-th position, i.e. i-th last position.
Algorithm:
BubbleSort (Arr, N) // Arr is an array of size N.
{
For ( I:= 1 to (N-1) ) // N elements => (N-1) pass
{
// Swap adjacent elements of Arr[1:(N-I)]such that
// largest among { Arr[1], Arr[2], ..., Arr[N-I] } reaches to Arr[N-I]
For ( J:= 1 to (N-I) ) // Execute the pass
{
If ( Arr [J] > Arr[J+1] )
Swap( Arr[j], Arr[J+1] );
}
}
}
Optimization of Algorithm: Check if there happened any swapping operation in the inner loop (pass execution loop) or not. If there is no swapping in any pass, it means the array is now fully sorted, hence no need to continue, stop the sorting operation. So we can optimize the number of passes when the array gets sorted before the completion of all passes. And it can also detect if the given / input array is sorted or not, in the first pass.
BubbleSort (Arr, N) // Arr is an array of size N.
{
For ( I:= 1 to (N-1) ) // N elements => (N-1) pass
{
// Swap adjacent elements of Arr[1:(N-I)]such that
// largest among { Arr[1], Arr[2], ..., Arr[N-I] } reaches to Arr[N-I]
noSwap = true; // Check occurrence of swapping in inner loop
For ( J:= 1 to (N-I) ) // Execute the pass
{
If ( Arr [J] > Arr[J+1] )
{
Swap( Arr[j], Arr[J+1] );
noSwap = false;
}
}
If (noSwap) // exit the loop
break;
}
}
Time Complexity:
Best Case Sorted array as input. Or almost all elements are in proper place. [ O(N) ]. O(1) swaps.
Worst Case: Reversely sorted / Very few elements are in proper place. [ O(N2) ] . O(N2) swaps.
Average Case: [ O(N2) ] . O(N2) swaps.
Space Complexity: A temporary variable is used in swapping [ auxiliary, O(1) ]. Hence it is In-Place sort.
Advantage:
It is the simplest sorting approach.Best case complexity is of O(N) [for optimized approach] while the array is sorted.Using optimized approach, it can detect already sorted array in first pass with time complexity of O(N).Stable sort: does not change the relative order of elements with equal keys.In-Place sort.
It is the simplest sorting approach.
Best case complexity is of O(N) [for optimized approach] while the array is sorted.
Using optimized approach, it can detect already sorted array in first pass with time complexity of O(N).
Stable sort: does not change the relative order of elements with equal keys.
In-Place sort.
Disadvantage:
Bubble sort is comparatively slower algorithm.
Bubble sort is comparatively slower algorithm.
Selection sort selects i-th smallest element and places at i-th position. This algorithm divides the array into two parts: sorted (left) and unsorted (right) subarray. It selects the smallest element from unsorted subarray and places in the first position of that subarray (ascending order). It repeatedly selects the next smallest element.
Algorithm:
SelectionSort (Arr, N) // Arr is an array of size N.
{
For ( I:= 1 to (N-1) ) // N elements => (N-1) pass
{
// I=N is ignored, Arr[N] is already at proper place.
// Arr[1:(I-1)] is sorted subarray, Arr[I:N] is undorted subarray
// smallest among { Arr[I], Arr[I+1], Arr[I+2], ..., Arr[N] } is at place min_index
min_index = I;
For ( J:= I+1 to N ) // Search Unsorted Subarray (Right lalf)
{
If ( Arr [J] < Arr[min_index] )
min_index = J; // Current minimum
}
// Swap I-th smallest element with current I-th place element
If (min_Index != I)
Swap ( Arr[I], Arr[min_index] );
}
}
Time Complexity:
Best Case [ O(N2) ]. And O(1) swaps.
Worst Case: Reversely sorted, and when the inner loop makes a maximum comparison. [ O(N2) ] . Also, O(N) swaps.
Average Case: [ O(N2) ] . Also O(N) swaps.
Space Complexity: [ auxiliary, O(1) ]. In-Place sort.(When elements are shifted instead of being swapped (i.e. temp=a[min], then shifting elements from ar[i] to ar[min-1] one place up and then putting a[i]=temp). If swapping is opted for, the algorithm is not In-place.)
Advantage:
It can also be used on list structures that make add and remove efficient, such as a linked list. Just remove the smallest element of unsorted part and end at the end of sorted part.The number of swaps reduced. O(N) swaps in all cases.In-Place sort.
It can also be used on list structures that make add and remove efficient, such as a linked list. Just remove the smallest element of unsorted part and end at the end of sorted part.
The number of swaps reduced. O(N) swaps in all cases.
In-Place sort.
Disadvantage:
Time complexity in all cases is O(N2), no best case scenario.
Time complexity in all cases is O(N2), no best case scenario.
Insertion Sort is a simple comparison based sorting algorithm. It inserts every array element into its proper position. In i-th iteration, previous (i-1) elements (i.e. subarray Arr[1:(i-1)]) are already sorted, and the i-th element (Arr[i]) is inserted into its proper place in the previously sorted subarray. Find more details in this GFG Link.
Algorithm:
InsertionSort (Arr, N) // Arr is an array of size N.
{
For ( I:= 2 to N ) // N elements => (N-1) pass
{
// Pass 1 is trivially sorted, hence not considered
// Subarray { Arr[1], Arr[2], ..., Arr[I-I] } is already sorted
insert_at = I; // Find suitable position insert_at, for Arr[I]
// Move subarray Arr [ insert_at: I-1 ] to one position right
item = Arr[I]; J=I-1;
While ( J ? 1 && item < Arr[J] )
{
Arr[J+1] = Arr[J]; // Move to right
// insert_at = J;
J--;
}
insert_at = J+1; // Insert at proper position
Arr[insert_at] = item; // Arr[J+1] = item;
}
}
}
Time Complexity:
Best Case Sorted array as input, [ O(N) ]. And O(1) swaps.
Worst Case: Reversely sorted, and when inner loop makes maximum comparison, [ O(N2) ] . And O(N2) swaps.
Average Case: [ O(N2) ] . And O(N2) swaps.
Space Complexity: [ auxiliary, O(1) ]. In-Place sort.
Advantage:
It can be easily computed.Best case complexity is of O(N) while the array is already sorted.Number of swaps reduced than bubble sort.For smaller values of N, insertion sort performs efficiently like other quadratic sorting algorithms.Stable sort.Adaptive: total number of steps is reduced for partially sorted array.In-Place sort.
It can be easily computed.
Best case complexity is of O(N) while the array is already sorted.
Number of swaps reduced than bubble sort.
For smaller values of N, insertion sort performs efficiently like other quadratic sorting algorithms.
Stable sort.
Adaptive: total number of steps is reduced for partially sorted array.
In-Place sort.
Disadvantage:
It is generally used when the value of N is small. For larger values of N, it is inefficient.
It is generally used when the value of N is small. For larger values of N, it is inefficient.
Time and Space Complexity:
shivangigupta9820
sapcastic
mehulshukla141
Algorithms
Sorting
Sorting
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
Introduction to Algorithms
Quick Sort vs Merge Sort
Converting Roman Numerals to Decimal lying between 1 to 3999 | [
{
"code": null,
"e": 24278,
"s": 24250,
"text": "\n31 Oct, 2021"
},
{
"code": null,
"e": 24534,
"s": 24278,
"text": "Bubble sort repeatedly compares and swaps(if needed) adjacent elements in every pass. In i-th pass of Bubble Sort (ascending order), last (i-1) elements are alread... |
HTML - <address> Tag | The HTML <address> tag is used for indicating an address. The address usually renders in italic.
<!DOCTYPE html>
<html>
<head>
<title>HTML address Tag</title>
</head>
<body>
<address>
600 Wisdon Apartments<br />
Filmcity, Kondiura<br />
New Delhi - 50027
</address>
</body>
</html>
This will produce the following result −
This tag supports all the global attributes described in HTML Attribute Reference
This tag supports all the event attributes described in HTML Events Reference
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2471,
"s": 2374,
"text": "The HTML <address> tag is used for indicating an address. The address usually renders in italic."
},
{
"code": null,
"e": 2716,
"s": 2471,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML address Tag</title>\n </hea... |
Generate Anime Style Face Using DCGAN and Explore Its Latent Feature Representation | by Haryo Akbarianto Wibowo | Towards Data Science | Hello everyone , It’s been a while ! Today, I want to write about my result of learning and experimenting another Deep Learning technique , which is Generative Adversarial Network (GAN). I studied and learned about it recently . I think it would be nice if share my experiment to everyone.
GAN is mostly about generating something. In this article I want to share about the experiment on generating anime character faces. Not only generate, I’ve also experimented that the image can be manipulated by linear algebra operation of its latent variable (a vector that is used on generating the faces). I also see that the faces that are generated follow a statistic distribution, which is really awesome.
This article will be focused on the tutorial how to do GAN with each steps explained (with source code). It will be targeted for anyone who is interested in AI, especially who want to practice on using Deep Learning. It also targets everyone who want to learn how to do GAN for the first time. I will write this article as easy as possible to understand about it. I hope for the reader, by reading this article, they know how general GAN works.
If you want to grasp better understanding on reading this article, I suggest that you know at least neural network and Convolution Neural Network (CNN).
There is a GitHub link at the end of this article if you want to know about the complete source code. For now, I will give the python notebook and Colaboratory link in the repository.
Image 0 is one of the generated anime character faces that we will create by using the picture formed by the model. The first and second picture from the left is generated with GAN. The third is the addition of the first and second faces (You can call it a fusion of the first and second faces).
TechnologyIntroductionBrief Description About GANImplementationResultsLesson LearnedConclusionAfterwordsRepositorySources
Technology
Introduction
Brief Description About GAN
Implementation
Results
Lesson Learned
Conclusion
Afterwords
Repository
Sources
Python 3.7Colaboratory : Free Jupyter notebook environment that requires no setup and runs entirely in the cloud. Have GPU Tesla K80 or even TPU! Sadly Tensorflow v2.0 alpha still does not support TPU at the moment of this writing. Sadly, DCGAN cannot be trained via TPU.Keras : Python Library for doing Deep Learning.Data is taken from here
Python 3.7
Colaboratory : Free Jupyter notebook environment that requires no setup and runs entirely in the cloud. Have GPU Tesla K80 or even TPU! Sadly Tensorflow v2.0 alpha still does not support TPU at the moment of this writing. Sadly, DCGAN cannot be trained via TPU.
Keras : Python Library for doing Deep Learning.
Data is taken from here
One of the topic that is hot in the Deep Learning field is Generative Adversarial Network (GAN). Introduced by Ian Goodfellow et al., It can generate something from scratch unsupervised. In Computer Vision. There are many researchers out there researching and improving it. For example NVIDIA create realistic face generator by using GAN. There are also some research on the music domain on using GAN. My previous article that shows about generating music can also be done by using GAN.
There are many variant type of GAN developed by the researchers out there. One of the newest (by the time I write this article) is HoloGAN that can generate 3D representation from natural images. If you look at how it can do, it is actually amazing. Actually, these advanced GAN follow basic fundamental of how GAN works. Every GAN out there have two agents as its learner, discriminator and generator (We will dive into these terms later) . To know more about advanced GAN techniques, one must know how the basic GAN works.
This article will focus on implementing Deep Convolutional GAN (DCGAN), one of the variant of GAN proposed by A Radford et al,. Basically, it is a GAN with many Convolution Layers. It is one of the popular GAN neural network . We will build a different architecture from the proposed architecture in their paper. Although different, it still yield some good results.
One of the interesting things about GAN is that it will build its latent variables (a 1-D vector of any length) which can be linear algebra operated. The example on Image 0 is one of the example. The first face’s vector (from the left) is added to the second face’s vector. Then, it yield the third face.
It also yield some interesting data distribution. Every point in the distribution have different kind of faces. For example, the data who is centered at mean -0.7 will have face with yellow hair.
We will start from knowing a brief description about GAN.
To make it simpler, it is one of the Deep Learning technique used to generate some new data from scratch. It runs in unsupervised way meaning that it can run without labelled by human. It will make the data based on the pattern that it learns.
There are some characteristics aspects on GAN who is a generative model, which is:
Learns joint probability P(x,y) where x is the input and y the output. It will do inference based on P(x|y) , given output y, it will infer the x. You can say that y is the the real data in GAN.
When the model is given the training real data y, it will learn the characteristic of the real data. It will learn by identifying the real data latent feature representation variable. To make it simpler, it learns the base constructor feature of the images in the real data. For example, the model can learn that faces constructed by the color of the eyes and hair. These two will be one of the base which will be used on generating the faces. By tweaking its variable, it can also alter the generated faces. For example, by raising the variable of the eyes, the eyes will be blacker. Lowering it will make the opposite otherwise.
It can build a probability distribution such as normal distribution which can be used on avoiding the outlier. Since outlier usually very rare in the distribution, it will be very rare to generate it. So GAN functions well on real data that has outlier.
GAN composes into two neural networks, the Discriminator and Generator. GAN will make these two networks fight each others on a Zero-Sum game framework (Game Theory). This is a game between these agents (the networks). The adversarial name in GAN comes from this concept.
Generator will generate some fake data and the Discriminator will identify a couple of data which has the fake data generated by Generator and data sampled from real data. The objective of the Generator is mainly generating some fake data that is intended similar to the real data and fooling the Discriminator on identifying what data is real and fake. The objective of the Discriminator is to make it smarter on identifying the real and fake data. Each agents will move alternately. By dueling these agents, We hope that these agents will get stronger, especially the Generator.
You can say that they are rival destinied to each others. The main character is the Generator who strive better and better to make our purpose realized by learning from the fight from its rival.
Okay, in another word, the Generator will mimic the real data by sampling the distribution that is learned and intended to be the same distribution as the real data. It will train its neural network which can generate it. Whereas, The Discriminator will train its neural network in supervised technique on detecting the fake and real data. Each network will train its network alternately.
Here is the rough steps on how GAN works:
Generate random noise in a probability distribution such as normal distribution.Make it as an input of our Generator neural network. It will output generated fake data . These steps can also mean that we sample some data from the distribution that the generator learned. We will notate the noise as z_n and the generated data as G(z_n) . G(z_n) means the result of the noise processed by the generator G.We combine the generated fake data with the data that is sampled from the dataset (which is real data). Make them to be input of our Discriminator. We will notate it as D. Discriminator will try to learn by predicting whether the data is fake or not. Train the neural network by doing forward pass and followed by back propagation. Updates the D weights.Then, we need to train the Generator. We need to make the G(z_n) or the fake data generated from random noises as the input of the D. Note that this steps only input the fake data into the Discriminator. Forward pass the G(z_n) in D. By using the Discriminator neural network, on doing forward pass, predict whether the fake data is fake or not (D(G(z_n))). Then do back propagation where we will only update the G weights.Repeat these steps until we can see that the generator provide good fake data or maximum iteration has been reached.
Generate random noise in a probability distribution such as normal distribution.
Make it as an input of our Generator neural network. It will output generated fake data . These steps can also mean that we sample some data from the distribution that the generator learned. We will notate the noise as z_n and the generated data as G(z_n) . G(z_n) means the result of the noise processed by the generator G.
We combine the generated fake data with the data that is sampled from the dataset (which is real data). Make them to be input of our Discriminator. We will notate it as D. Discriminator will try to learn by predicting whether the data is fake or not. Train the neural network by doing forward pass and followed by back propagation. Updates the D weights.
Then, we need to train the Generator. We need to make the G(z_n) or the fake data generated from random noises as the input of the D. Note that this steps only input the fake data into the Discriminator. Forward pass the G(z_n) in D. By using the Discriminator neural network, on doing forward pass, predict whether the fake data is fake or not (D(G(z_n))). Then do back propagation where we will only update the G weights.
Repeat these steps until we can see that the generator provide good fake data or maximum iteration has been reached.
The illustration is as follow:
By updating the distribution of the Generator to match the Discriminator. It’s the same as minimizing the JS Divergence. For further information, you can read this article.
To make our agents learn, make sure to make the discriminator and generator dominate each other. Make them in a balance as possible and make discriminator and generator learn at the same time. When the discriminator is too strong (can differentiate between fake and real 100%), Generator become unable too learn anything. If at the process of training we reach this point, better to end it. The opposite also have effect where the Generator is stronger than Discriminator. It causes Mode Collapse where our model will always predict the same outcome for any random noises. This is one of the hard and difficult part of the GAN that can make someone frustrated.
If you want to understand more, I suggest to take a peek and read this awesome article.
This depends on the variant of the GAN that we will develop. Since we will be using DCGAN, we will use a sequential couple of CNNs layer.
We will use a custom architecture that is different from the original paper. I follow the architecture used in the François Chollet Deep Learning with Python book with some changes.
The configuration that we used for building the DCGAN is as follow:
latent_dim = 64height = 64width = 64channels = 3
This means that we will have a 64 dimension of latent variables. The height and width of our images are 64. Every images have 3 channels (R, G, B)
Here is the imported library and how the data is prepared:
Here is the architecture :
It consists of Convolution Layers where one of them is Convolution Transpose Layer. To upsample the size of the image (32 -> 62), we will use strides parameter in the Convolution Layer. This is done to avoid unstable training of the GAN.
Code
It also consists of Convolution Layers where we use strides to do downsampling.
Code
To make the backpropagation possible for the Generator, we create new network in Keras, which is Generator followed by Discriminator. In this network, we freeze all the weights so that its weight do not changes.
This is the network :
The config of the training is as follow:
iterations = 15000 batch_size = 32
The configuration means that we will do 15000 iterations. Every iteration we process 32 batches of real data and fake data (64 in total for training the discriminator).
Following the rough steps that I’ve explained above, here is how we train the DCGAN step by step:
Iterate until max iterations the following steps
Iterate until max iterations the following steps
for step in tqdm_notebook(range(iterations)):
2. Generate random noise in a probability distribution such as normal distribution.
random_latent_vectors = np.random.normal(size = (batch_size, latent_dim))generated_images = generator.predict(random_latent_vectors)
3. Combine the generated fake data with the data that is sampled from the dataset.
stop = start + batch_sizereal_images = x_train[start: stop]combined_images = np.concatenate([generated_images, real_images])labels = np.concatenate([np.ones((batch_size,1)), np.zeros((batch_size, 1))])
Note that we use sequential sampler where each data will be sampled sequentially until the end of the data. The number that will be sampled is equal to the batch size.
4. Add noise to the label of the input
labels += 0.05 * np.random.random(labels.shape)
This is an important trick on training GAN.
5. Train the Discriminator
d_loss = discriminator.train_on_batch(combined_images, labels)
6. Train the Generator
random_latent_vectors = np.random.normal(size=(batch_size, latent_dim))misleading_targets = np.zeros((batch_size, 1))a_loss = gan.train_on_batch(random_latent_vectors, misleading_targets)
Note that we create a new latent vectors . Don’t forget that we need to swap the label. Remember we want to minimize the loss resulted from the discriminator on failing predicting the fake . The label should be 1 for the misleading_targets.
7. Update the start index of the real dataset
start += batch_size if start > len(x_train) - batch_size: start = 0
That’s it, here is the complete code on training the DCGAN:
Okay, let the fun begins! We will begin on visualizing generated images on different mean point. Before we do that, let me tell you that this is the result of above model who is trained 20000 steps (iterations) and trained with 30000 steps. The model is trained around 7 hours ( ~4300 steps per hours) . I will give name to the fewer steps model as Model-A and the other as Model-B.
Here we go!
How to read
N ~ (x, y) : latent vectors randomly generated by following the normal distribution that has mean x and Standard Deviation y
Results on latent vectors on N ~ (0,0.4) on Model-A:
Not bad huh, although there are some images who has asymetric face.
Results on latent vectors on N ~ (0,1) on Model-A:
Look at it.. the model produced some abomination faces out there. This turns out that this model doesn’t really grasp the distribution of the real data. It can do better when the standard deviation is lower. The DCGAN that I trained has not yet grasped how to represent the data point which is not too close to the mean point. I think, it needs more training or more powerful architecture.
Let’s change the architecture to Model-B
Results on latent vectors on N ~ (0,0.4) on Model-B:
Its okay, but the faces become darker. I wonder what happened to the generator.
Results on latent vectors on N ~ (0,1) on Model-B:
Uhmm, well.. most of them still contains abomination faces. Some of them produced okay faces. The quality still almost the same as Model-A. Okay.. For the next batches of images, let’s change the standard deviation as close as the mean. 0.4 would be the best.
Let’s check if our latent vectors is generated with centered mean of -0.3 and 0.3 using the same standard deviation.
Results on latent vectors on N ~ (-0.3,0.4) on Model-A:
Results on latent vectors on N ~ (0.3,0.4) on Model-A:
Results on latent vectors on N ~ (-0.3,0.4) on Model-B:
Results on latent vectors on N ~ (0.3,0.4) on Model-B:
See the differences?
Yes, look at their hair. At mean 0.3 the hair is mostly black (some of them are brown). On the contrary, at mean -0.3 the hairs are mostly yellow. Yeah, our model can put the faces at its corresponding points. Also the Model-B generate faces that are darker than A.
From what we’ve done above, we can get the intuition on how the data distribution that our model has learnt.
Lets plot it:
From the result has shown above, I think the less the latent vector mean, it will make the face have brighter hair and the more the latent vector is, the faces will have purpler hair.
To make sure, let’s see the mean of face in each mean points:
We plot these latent vector whose mean is:
[-1, -0.8, -0.6, -0.4, -0.2, 0, 0.2 0.4, 0.6, 0.8 ]
The first row is MODEL-A and the second row is MODEL-B. By manipulating the mean of the latent vectors, we can see the face that it generate at that point. We can see that:
The lower the point of the vector is, the yellower the hair is.
It has darker face in the middle. It means that average faces in the dataset have these style.
The positive the point of the vector is , the bluer the hair is. The positive latent vector also has more open mouth on smiling.
Amazing isn’t it?
Not yet, We can do linear algebra operation to the latent vector. The result of the equation can also be generated and have interesting result. Take a result from our first faces before the introduction section:
G + D
GAN faces is the result of addition of G with D. You can see that the hair become a bit brown. and the hair follow the D style on the right and G on the left.
Below are the result of others operation:
G — D (Absolute)
Component-Wise multiplied (G, D)
We will see how is the generated images if we manipulate a dimension in the latent vector. As I said earlier, the model will learn latent feature representation. So, every element in the latent vector has a purpose on generating the image.
To do the visualization, we will freeze all elements in vectors and change tthe chosen dimension that want to be checked.
For example we want to examine the 1st elements in the latent vector, we change that dimension and keep the others the same.
We will generate some faces that has the mean in these points:
[-0.6, -0.3, 0.1, 0.3, 0.6]
For every mean points, we will generate faces whose a dimension in latent vector is changed with these values iteratively:
[-1.08031934, -0.69714143, -0.39691713, -0.12927146, 0.12927146, 0.39691713, 0.69714143, 1.08031934]
Let visualize on our chosen dimension: ( This section will only use MODEL-A)
28th dimension:
What are the 28th latent variable’s purposes?
I think, it make the hair become brighter, change the left eye shape, and also small changes on the right eye. Since it compresses the feature into 64 length latent vector, one dimension can have several purposes.
Let’s see another one!
5th dimension
What are this latent variable purposes?
I think it has something to do with the left eyes even though the treatment on how the left eyes is different for each mean points. It also make the hair a bit darker. What do you think?
11th dimension
I think, this dimension care about the mouth and the right eye.
Another example on faces that generated from a mean points by only tweaking a latent variable:
That’s it. We can plot any dimensions in the latent vectors and see what are its purposes. Although sometimes it’s hard to see what are a latent variable’s purposes.
Let’s sample 8 real faces from dataset:
And sample 8 from generator N ~ (0,1) for model A and B:
So, if we act as Discriminator, can we differentiate between the real and fake faces?
No doubt that we can still differentiate between what faces are fake and real. The model need more training or powerful architecture to make it happen. Even so, our model can still generate anime style faces shape, which is great.
Below is the lesson that I learnt after researched DCGAN:
Training GAN is hard. It’s hard on making a stable architecture without seeing tips and trick from the one who has experienced it. Especially on balancing the power of the Discriminator and Generator. Making the GAN not become collapse is also a challenge.
Actually, these model is still not good at generating the fake images. Nevertheless, it can build some good faces although not as good as the real one. We can still differentiate the fake images and real images. This is because the model hasn’t grasped the data distribution of the real data yet.
The model degrades its quality around 26000 steps. This is where in my experiment, the generator became weak. This is an instability in the GAN. I need to search a better architecture to do it. We can see the result on the Model B becomes darker.
And so, I’ve developed another architecture with the Batch Normalization and even Dropout Layer. Guess what? There are two result that I have in tweaking the architecture. Model collapse and Discriminator dominance. I guess developing the GAN architecture is not easy.
Yet, there are many tips and tricks on developing a good GAN that I haven’t implemented. Maybe the instability of the model can be reduced by following these tips.
There are many GAN variant that are more stable such as WGAN-DC and DRAGAN, and SAGAN. I need to use different architecture who might do better than DCGAN.
This article have tell us about what GAN is doing and tell us step by step on how to do it. After that, it tell us an interesting characteristic of its latent vector that show the data distribution learned by the generator. It shows us that It can form a data distribution.
The latent vector can be linear algebra operated. It can show us some interesting things such as addition of two latent vectors will combine the features each of these faces. It can also be manipulated to change the face based on the changed element in the latent vector.
Even so, our model still cannot make a face that can make us wondering whether that face is fake or not. It can still form an anime style faces though.
That’s it, my first experience on doing GAN. I got better on grasping what GAN is doing. I also want to explore my curiosity about what GAN has learned. There they are, It is really amazing what it actually do. The generator can map the random vector generated by normal random noise into a data distribution. It cluster the faces into designated data points.
On doing GAN, I actually run several model that I handcrafted. Well, they have failed miserably. One time I thought the model can success, but it go into mode collapse (the predicted face will be the same regardless of the latent vector). I found fchollet repository about DCGAN and follow its architecture.
Since this is my first time designing a GAN, I expect a lot feedback from everyone about this. Just point me the mistake that I’ve done since this is my first time doing it. Forgive me if the result is not that good. I just want to share my excitement on doing GAN. And share how to do it.
Even so, It is really fun and I want to experiment another variant of GAN such as WGAN-GP, DRAGAN, or SAGAN. I only skim a little what they are about and want to experiment it. Expect an article from doing these experiments 😃.
This meme actually picture this experiment 😆.
I welcome any feedback that can improve myself and this article. I’m in the process of learning on writing and learning about Deep Learning. I appreciate a feedback to make me become better. Make sure to give feedback in a proper manner 😄.
See ya in my next article!
See this GitHub repository:
github.com
Currently, I only provide IPython Notebook for training the GAN from scratch. Note if the model don’t output a face-shaped images on around 200 iterations, restart the training (run from ‘Create Model’ section).
Later, I will create a playground notebook to experiment on manipulating the latent variables.
medium.com
Thanks Renu Khandelwal for the awesome article.
https://www.cs.toronto.edu/~duvenaud/courses/csc2541/slides/gan-foundations.pdf
https://github.com/fchollet/deep-learning-with-python-notebooks
lilianweng.github.io
https://arxiv.org/pdf/1511.06434.pdf
medium.com
Thanks Jonathan Hui for the awesome article. | [
{
"code": null,
"e": 337,
"s": 47,
"text": "Hello everyone , It’s been a while ! Today, I want to write about my result of learning and experimenting another Deep Learning technique , which is Generative Adversarial Network (GAN). I studied and learned about it recently . I think it would be nice if... |
Python: Procedural or Object-Oriented Programming? | by Wie Kiang H. | Towards Data Science | Who does not know Python? Mostly used in Data Science and Machine Learning.Let us discuss more about it!
When you first learn a program, you are seemingly using a technique called procedural programming. A procedural program is typically a list of instructions that execute one after the other starting from the top of the line. On the other hand, object-oriented programs are built around well objects. You can think about objects as something that exists in the real world. For instance, if you were going to establish a shoe store, the store itself would be an object. The items in the store, for example, boots and sandals, would also be objects. The cash register would be an object, and even a salesperson would be an object.
Object-oriented programming has several advantages over procedural programming, which is the programming style you most likely first studied.
Object-oriented programming enables you to develop large, modular programs that can instantly expand over time.
Object-oriented programs hide the implementation from the end-user.
Object-oriented program would focus on the specific characteristics of each object and what each object can do.
An object has two fundamental parts, characteristics, and actions. For example, several characteristics of a salesperson would include the person’s name, address, phone number, and hourly payout, also what a salesperson can do. That might involve selling an item or taking items from a warehouse. As another example, shoes' characteristics could be the color, size, style, and price. What actions could a shoe take? A shoe is an inanimate object, but it could, for example, change its price.
In terms of English grammar:A characteristic would be a noun. An action would be a verb.Real-world example: a dog. Some of the characteristics could be:* weight* colour* breed* height -> These are all nouns.What actions would a dog take? * bark* run* bite* eat -> These are all verbs.
An object has characteristics and actions. Characteristics have a specific name. They are called attributes, and the actions are called methods. The color, size, style, and the price would be called attributes in the shoe example. The action of changing the price would be a method. There are two other terms, which are object and class.
An object would be a specific shoe, for instance, a brown shoe with a US size 7.5, and sneaker style with a price of $110 in the shoe example. This brown shoe could change its price. Another object would be something like, a white color shoe with a US size 4.5, and a flip-flop shoe that costs $80. This white shoe could change its price as well.
Do you notice anything special about the brown shoe and white shoe? They both have the same attributes. In other words, they both have a color, size, style, and price. They also have the same method. It is like they came from a blueprint, a generic shoe consisting of all the attributes and methods. This generic version of an object is called a class.
You only need to classify this blueprint known as class one time, and then you can create specific objects from the class over and over again. In other words, you can use the shoe blueprint, to make as many shoe objects as you want, in any size, shape, color, style, and price. These are fundamental terms in object-oriented programming.
Object-Oriented Programming (OOP) VocabularyClassa blueprint which is consisting of methods and attributes.Objectan instance of a class. It can help to think of objects as something in the real world like a yellow pencil, a small dog, a yellow shoe, etc. However, objects can be more abstract.Attributea descriptor or characteristic. Examples would be colour, length, size, etc. These attributes can take on specific values like blue, 3 inches, large, etc.Methodan action that a class or object could take.
If you have not worked with classes before, the syntax might be complicated.
In Figure 1, it is written a Shoe class. The class has color, size, style, and price attributes. It also has a method to change the price, as well as a method to output a discounted price. Inside the Shoe class, some codes come to shows examples of how to instantiate shoe objects so that you can see how to use a class in a program. Remember that a class represents a blueprint. Hence we are setting up the color, size, style, and price of a generic shoe.
Two things about this might seem a bit odd:* __init__ ---> Python built-in function* self -------> variable
Python use __init__ to create a specific shoe object. On the other hand, the self variable can be tricky to understand in the beginning. self saves attributes like color, size, and so on, making those attributes available throughout in the Shoe class. self is essentially a dictionary that holds all of your attributes and the attribute values — checkout the change price method to see how the self works.
We can pass in self as the first method input to have access to the price. The self has the price stored inside it, as well as the other attributes like color, size, and style. self will always be the first input to your methods if you want to access the attributes.
Note as well that the change price and the discount methods are like general Python functions. For instance, Python functions do not have to return anything, so like in the change price method, it does not return anything. It only changes the value of the price attribute. The discount method, however, does return something it returns the discounted price.
Additional: Function vs MethodA function and method seem very similar; both of them use the same keyword. They also have inputs and return outputs. The contrast is that a method is inside a class, whereas a function is outside of a class.
If you define two objects, how does Python differentiate between two objects? That is where self comes into play. If you call the change_price method on shoe_one, how does Python know to change the price of shoe_one and not of shoe_two?
def change_price(self, new_price): self.price = new_priceshoe_one = Shoe('brown', '7.5', 'sneaker', 110) shoe_two = Shoe('white', '4.5', 'flip-flop', 80)shoe_one.change_price(125)
self tells Python where to look in the computer's memory for the shoe_one object, and then Python changes the price of the shoe_one object. When you call the change_price method, shoe_one.change_price(125), self is implicitly passed in.
The word self is just a convention. You could actually use any other name as long as you are consistent; however, you should always use self rather than some other word, or else you might confuse people.
Now, we are going to write a separate Python script that uses the shoe class code. In the same folder, you need to create another file called project.py. Inside this file, we want to use the shoe class. First, you need to import the shoe class by typing from shoe import Shoe. The lowercase shoe refers to the shoe.py file, while the uppercase shoe refers to the class defined inside this file.
You could specify the file and class anything you wanted to. They do not have to be the same. We just did this for convenience. Now, in the project.py, you can use the shoe class. If you noticed, the code is now modularized. You will write some code that uses the shoe class.
The shoe class has a method to change the price of the shoe. In project.py file, you can see in line 9,shoe_two.change_price(90). In Python, you can also change the values of an attribute with the following syntax, shoe_one.color = ‘blue’ , shoe_one.size = 5.0 , and shoe_one.price = 78. There are some drawbacks to accessing attributes directly versus writing a method for accessing and displaying attributes.
In terms of object-oriented programming, Python’s rules are a bit looser than in other programming languages. In some languages like C++, you can explicitly state whether an object should be permitted to change or access an attribute value directly. Python does not have this option.
Why might it be better to change the value with a method instead of changing a value directly?
Changing values through a method gives you more flexibility in the long-term. But if the units of measurement replaced, for example, the store was initially meant to serve in US dollars and now has to work in euros. If you have changed an attribute directly like in line 14, if all of a sudden you have to use euros, you are going to have to modify this manually. You are going to have to do this wherever you access the price attribute directly.
If, on the other hand, you would use a method like the change price method, then all you have to do is go into the shoe class and change the original method one time. We are going to multiply by, for example, 0.81 to convert everything from dollars to euros. If you go back to project.py, a line like a number 9, you do not have to manually change the price from dollars to euros because the conversion will take care of that for you in the shoe class.
There is one more object-oriented topic to cover in this article, inheritance. We think inheritance is easier to understand using a real-world object like the shoe example from earlier. The shoe had four attributes, color, size, style, and price. The shoe also had two methods: a method to change the price, and a method for calculating a discounted price.
As the store expands, it might stock other types of shoes like heels, ankle boot, and mules. These footwears have a few attributes and methods in common with the shoe object. They probably all have a color, size, style, and price and, they could all use functions to change the price and calculate a discount.
Why code separate classes for each new footwears when they all have so much in common? Alternatively, you could code apparent shoe class, and then the heels, ankle boot, and mules class could inherit the attributes and methods of the shoe class.
This looks like a family tree where the shoe is the parent, and heels, ankle boot, and mules, are the children. One benefit is that, as you add more shoe types like ballerinas, you can easily add a new class inheriting from the shoe class. What if you wanted to add a new attribute like material to represent if the footwear is made of synthetic, rubber, or foam? Now, all you have to do is, add a material attribute to the shoe class, and all the children’s classes automatically inherit the new attribute. Your code becomes more efficient to write and maintain.
Python is considered as an object-oriented programming language rather than a procedural programming language.
It is identified by looking at Python packages like Scikit-learn1, pandas2, and NumPy3. These are all Python packages built with object-oriented programming. Scikit-learn, for example, is a relatively comprehensive and complicated package built with object-oriented programming. This package has grown over the years with the latest functionality and new algorithms.
When you train a machine learning algorithm with Scikit-learn, you do not have to know anything about how the algorithms work or how they were coded. You can straightly focus on the modeling.
Thus far, we have been exposed to the core of object-oriented programming languages in Python:
classes and objects
attributes and methods
inheritance
Knowing these topics is enough for you to start writing object-oriented software. However, these are only the fundamentals of object-oriented programming. You can learn more about this by accessing the advanced topics below. Additionally, the source code from this article is available on my GitHub4.
Other Interesting Articles#1 Function Arguments: Default, Keyword, and Arbitrary#2 Scope of Variable and LEGB Rule#3 Writing Your Own Functions#4 Data Science with Python: How to Use NumPy Library#5 Do you have the Software Engineer and Data Scientist skills?
Wie Kiang is a researcher who is responsible for collecting, organizing, and analyzing opinions and data to solve problems, explore issues, and predict trends.
He is working in almost every sector of Machine Learning and Deep Learning. He is carrying out experiments and investigations in a range of areas, including Convolutional Neural Networks, Natural Language Processing, and Recurrent Neural Networks.
Connect on LinkedIn
References#1 Scikit-learn#2 pandas#3 NumPy#4 Source code on GitHubAdvanced Python Object-Oriented Programming Topics* class methods, instance methods, and static methods* class attributes vs instance attributes* multiple inheritance, mixins* Python decorators | [
{
"code": null,
"e": 277,
"s": 172,
"text": "Who does not know Python? Mostly used in Data Science and Machine Learning.Let us discuss more about it!"
},
{
"code": null,
"e": 904,
"s": 277,
"text": "When you first learn a program, you are seemingly using a technique called proced... |
PHP - Function preg_match_all() | int preg_match_all (string pattern, string string, array pattern_array [, int order]);
The preg_match_all() function matches all occurrences of pattern in string.
It will place these matches in the array pattern_array in the order you specify using the optional input parameter order. There are two possible types of order −
PREG_PATTERN_ORDER − is the default if the optional order parameter is not included. PREG_PATTERN_ORDER specifies the order in the way that you might think most logical; $pattern_array[0] is an array of all complete pattern matches, $pattern_array[1] is an array of all strings matching the first parenthesized regexp, and so on.
PREG_PATTERN_ORDER − is the default if the optional order parameter is not included. PREG_PATTERN_ORDER specifies the order in the way that you might think most logical; $pattern_array[0] is an array of all complete pattern matches, $pattern_array[1] is an array of all strings matching the first parenthesized regexp, and so on.
PREG_SET_ORDER − will order the array a bit differently than the default setting. $pattern_array[0] will contain elements matched by the first parenthesized regexp, $pattern_array[1] will contain elements matched by the second parenthesized regexp, and so on.
PREG_SET_ORDER − will order the array a bit differently than the default setting. $pattern_array[0] will contain elements matched by the first parenthesized regexp, $pattern_array[1] will contain elements matched by the second parenthesized regexp, and so on.
Returns the number of matchings.
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$userinfo = "Name: <b>John Poul</b> <br> Title: <b>PHP Guru</b>";
preg_match_all ("/<b>(.*)<\/b>/U", $userinfo, $pat_array);
print $pat_array[0][0]." <br> ".$pat_array[0][1]."\n";
?>
This will produce the following result −
John Poul
PHP Guru
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2845,
"s": 2757,
"text": "int preg_match_all (string pattern, string string, array pattern_array [, int order]);\n"
},
{
"code": null,
"e": 2921,
"s": 2845,
"text": "The preg_match_all() function matches all occurrences of pattern in string."
},
{
"co... |
getopt - Unix, Linux Command | getopt [options] [--] optstring parameters
getopt [options] -o|--options optstring [options] [--] parameters
The parameters
getopt is called with can be divided into two parts: options
which modify the way getopt will parse
(options and
-o|--options optstring in the
SYNOPSIS), and the parameters which are to be
parsed
(parameters in the
SYNOPSIS). The second part will start at the first non-option parameter
that is not an option argument, or after the first occurrence of
‘--’. If no
‘-o’ or
‘--options’ option is found in the first part, the first
parameter of the second part is used as the short options string.
If the environment variable
GETOPT_COMPATIBLE is set, or if its first parameter
is not an option (does not start with a
‘-’, this is the first format in the
SYNOPSIS), getopt will generate output that is compatible with that of other versions of
getopt(1).
It will still do parameter shuffling and recognize optional
arguments (see section
COMPATIBILITY for more information).
Traditional implementations of
getopt(1)
are unable to cope with whitespace and other (shell-specific) special characters
in arguments and non-option parameters. To solve this problem, this
implementation can generate
quoted output which must once again be interpreted by the shell (usually
by using the
eval command). This has the effect of preserving those characters, but
you must call
getopt in a way that is no longer compatible with other versions (the second
or third format in the
SYNOPSIS). To determine whether this enhanced version of
getopt(1)
is installed, a special test option
(-T) can be used.
The parameters are parsed from left to right. Each parameter is classified as a
short option, a long option, an argument to an option,
or a non-option parameter.
A simple short option is a
‘-’ followed by a short option character. If
the option has a required argument, it may be written directly after the option
character or as the next parameter (ie. separated by whitespace on the
command line). If the
option has an optional argument, it must be written directly after the
option character if present.
It is possible to specify several short options after one
‘-’, as long as all (except possibly the last) do not have required or optional
arguments.
A long option normally begins with
‘--’ followed by the long option name.
If the option has a required argument, it may be written directly after
the long option name, separated by
‘=’, or as the next argument (ie. separated by whitespace on the command line).
If the option has an optional argument, it must
be written directly after the long option name, separated by
‘=’, if present (if you add the
‘=’ but nothing behind it, it is interpreted
as if no argument was present; this is a slight bug, see the
BUGS). Long options may be abbreviated, as long as the abbreviation is not
ambiguous.
Each parameter not starting with a
‘-’, and not a required argument of
a previous option, is a non-option parameter. Each parameter after
a
‘--’ parameter is always interpreted as a non-option parameter.
If the environment variable
POSIXLY_CORRECT is set, or if the short
option string started with a
‘+’, all remaining parameters are interpreted
as non-option parameters as soon as the first non-option parameter is
found.
If there are problems parsing the parameters, for example because a
required argument is not found or an option is not recognized, an error
will be reported on stderr, there will be no output for the offending
element, and a non-zero error status is returned.
For a short option, a single
‘-’ and the option character are generated
as one parameter. If the option has an argument, the next
parameter will be the argument. If the option takes an optional argument,
but none was found, the next parameter will be generated but be empty in
quoting mode,
but no second parameter will be generated in unquoted (compatible) mode.
Note that many other
getopt(1)
implemetations do not support optional arguments.
If several short options were specified after a single
‘-’, each will be present in the output as a separate parameter.
For a long option,
‘--’ and the full option name are generated as one
parameter. This is done regardless whether the option was abbreviated or
specified with a single
‘-’ in the input. Arguments are handled as with short options.
Normally, no non-option parameters output is generated until all options
and their arguments have been generated. Then
‘--’ is generated as a
single parameter, and after it the non-option parameters in the order
they were found, each as a separate parameter.
Only if the first character of the short options string was a
‘-’, non-option parameter output is generated at the place they are found in the
input (this is not supported if the first format of the
SYNOPSIS is used; in that case all preceding occurrences of
‘-’ and
‘+’ are ignored).
Quoting is not enabled if the environment variable
GETOPT_COMPATIBLE is set, if the first form of the
SYNOPSIS is used, or if the option
‘-u’ is found.
Different shells use different quoting conventions. You can use the
‘-s’ option to select the shell you are using. The following shells are
currently supported:
‘sh’, ‘bash’, ‘csh’ and
‘tcsh’. Actually, only two ‘flavors’ are distinguished: sh-like quoting conventions
and csh-like quoting conventions. Chances are that if you use another shell
script language, one of these flavors can still be used.
If the first character is
‘+’, or if the environment variable
POSIXLY_CORRECT is set, parsing stops as soon as the first non-option parameter
(ie. a parameter that does not start with a
‘-’) is found that
is not an option argument. The remaining parameters are all interpreted as
non-option parameters.
If the first character is a
‘-’, non-option parameters are outputed at the place where they are found; in normal
operation, they are all collected at the end of output after a
‘--’ parameter has been generated. Note that this
‘--’ parameter is still generated, but it will always be the last parameter in
this mode.
If the first character of the first parameter of getopt is not a
‘-’, getopt goes into compatibility mode. It will interpret its first parameter as
the string of short options, and all other arguments will be parsed. It
will still do parameter shuffling (ie. all non-option parameters are outputed
at the end), unless the environment variable
POSIXLY_CORRECT is set.
The environment variable
GETOPT_COMPATIBLE forces
getopt into compatibility mode. Setting both this environment variable and
POSIXLY_CORRECT offers 100% compatibility for ‘difficult’ programs. Usually, though,
neither is needed.
In compatibility mode, leading
‘-’ and
‘+’ characters in the short options string are ignored.
#!/bin/bash
# read the options
TEMP=`getopt -o f:s::d:a:: --long file-name:,source::,destination:,action:: -- "$@"`
eval set -- "$TEMP"
# extract options and their arguments into variables.
while true ; do
case "$1" in
-f|--file-name)
fileName=$2 ; shift 2 ;;
-s|--source)
case "$2" in
"") sourceDir='.' ; shift 2 ;;
*) sourceDir=$2 ; shift 2 ;;
esac ;;
-d|--destination)
destinationDir=$2 ; shift 2;;
-a|--action)
case "$2" in
"copy"|"move") action=$2 ; shift 2 ;;
*) action="copy" ; shift 2 ;;
esac ;;
--) shift ; break ;;
*) echo "Internal error!" ; exit 1 ;;
esac
done
# Now take action
echo "$action file $fileName from $sourceDir to $destinationDir"
-f or --file-name: Parameter is mandatory (indicated by :)
-s or --source: Parameter is options (indicated by ::), default current directory
-d or --destination: Parameter is mandatory
-a or --action (Copy): Parameter is options default is copy
$ ./getopt.sh -f MyFile.txt -s/home -d /home/test -aMove
Move file MyFile.txt from /home to /home/test
$ ./getopt.sh --file-name MyFile.txt --source=/home --dest /home/test --act=Move
Move file MyFile.txt from /home to /home/test
$ ./getopt.sh --file-name MyFile.txt --source=/home --dest /home/test --act
Copy file MyFile.txt from /home to /home/test
$ ./getopt.sh --file-name MyFile.txt --source=/home -a Move -d
getopt: option requires an argument -- d
Copy file MyFile.txt from /home to
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 10622,
"s": 10577,
"text": "\ngetopt [options] [--] optstring parameters "
},
{
"code": null,
"e": 10690,
"s": 10622,
"text": "\ngetopt [options] -o|--options optstring [options] [--] parameters "
},
{
"code": null,
"e": 11202,
"s": 10690,
... |
How to replace all occurrences of a string with another string in Python? | Pyhton has a method called replace in string class. It takes as input the string to be replaced and string to replace with. It is called on a string object. You can call this method in the following way to replace all 'no' with 'yes':
>>> 'no one knows how'.replace('no', 'yes')
'yes one kyesws how'
>>> "chihuahua".replace("hua", "hah")
'chihahhah'
The re module in python can also be used to get the same result using regexes. re.sub(regex_to_replace, regex_to_replace_with, string) can be used to replace the substring in string.
For example,
>>> import re
>>> re.sub('hua', 'hah', 'chihuahua')
'chihahhah'
re.sub is very powerful and can be used to make very subtle substitutions using regexes. | [
{
"code": null,
"e": 1297,
"s": 1062,
"text": "Pyhton has a method called replace in string class. It takes as input the string to be replaced and string to replace with. It is called on a string object. You can call this method in the following way to replace all 'no' with 'yes':"
},
{
"cod... |
Insert default into not null column if value is null in MySQL? | You can use IFNULL() property or simple IF() with IS NULL property. The syntax is as follows −
INSERT INTO yourTableName(yourColumnName1,yourColumnName2)
VALUES('yourValue’',IF(yourColumnName1 IS NULL,DEFAULT(yourColumnName2),'yourMessage'));
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table Post
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> UserName varchar(10),
-> UserPostMessage varchar(50) NOT NULL DEFAULT 'Hi Good Morning !!!'
-> );
Query OK, 0 rows affected (0.67 sec)
Now you can insert default into the not null column if the value is null. The query is as follows −
mysql> insert into Post(UserName,UserPostMessage)
-> values('John',if(UserName IS NULL,DEFAULT(UserPostMessage),'Hello'));
Query OK, 1 row affected (0.21 sec)
mysql> insert into Post(UserName,UserPostMessage)
-> values(NULL,if(UserName IS NULL,DEFAULT(UserPostMessage),'Hello'));
Query OK, 1 row affected (0.22 sec)
mysql> insert into Post(UserName,UserPostMessage)
-> values('Carol',if(UserName IS NULL,DEFAULT(UserPostMessage),'Hello'));
Query OK, 1 row affected (0.14 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from Post;
The following is the output −
+----+----------+---------------------+
| Id | UserName | UserPostMessage |
+----+----------+---------------------+
| 1 | John | Hello |
| 2 | NULL | Hi Good Morning !!! |
| 3 | Carol | Hello |
+----+----------+---------------------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1157,
"s": 1062,
"text": "You can use IFNULL() property or simple IF() with IS NULL property. The syntax is as follows −"
},
{
"code": null,
"e": 1305,
"s": 1157,
"text": "INSERT INTO yourTableName(yourColumnName1,yourColumnName2)\nVALUES('yourValue’',IF(your... |
C++ program to implement Simpson’s 3/8 rule | In this tutorial, we will be discussing a program to implement SImpson’s 3⁄8 rule.
Simpson’s 3⁄8 rule is used for doing numerical integrations. The most common use case of this method is in performing numerical approximations of definite integrals.
In this, the parabolas on the graph are used for performing the approximations.
#include<iostream>
using namespace std;
//function that is to be integrated
float func_inte( float x){
return (1 / ( 1 + x * x ));
}
//calculating the approximations
float func_calculate(float lower_limit, float upper_limit, int
interval_limit ){
float value;
float interval_size = (upper_limit - lower_limit) / interval_limit;
float sum = func_inte(lower_limit) + func_inte(upper_limit);
for (int i = 1 ; i < interval_limit ; i++) {
if (i % 3 == 0)
sum = sum + 2 * func_inte(lower_limit + i * interval_size);
else
sum = sum + 3 * func_inte(lower_limit + i * interval_size);
}
return ( 3 * interval_size / 8 ) * sum ;
}
int main(){
int interval_limit = 8;
float lower_limit = 1;
float upper_limit = 8;
float integral_res = func_calculate(lower_limit,
upper_limit, interval_limit);
cout << integral_res << endl;
return 0;
}
0.663129 | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to implement SImpson’s 3⁄8 rule."
},
{
"code": null,
"e": 1311,
"s": 1145,
"text": "Simpson’s 3⁄8 rule is used for doing numerical integrations. The most common use case of this metho... |
DirectX - Quaternion | The rotations of every graphic element are done with the help of xwing as per the rotations around the 3D axis, i.e., X, Y and Z axis. Xwing is something which is considered as a unique feature of rotating a particular object in quaternion. The only problem here is that it includes same dimensions with respect to matrices. For such a situation, a user or a developer will need a particular solution which would solve the problem.
Deriving a total rotation from the mentioned 3 separate values of each axis with reference to trigonometric formulae is something which should be discussed and it is included in further analysis.
Quaternion is matrix like structure which provides only one rotation. A quaternion is considered to be very easy to use from developer point of view. Consider for the following examples where where we declare vectors with mentioned below which describes the standard syntax −
Vector3 xwingPosition = new Vector3(18, 11, -3);
#Vector definition with three co-ordinates
Quaternion xwingRotation = Quaternion.Identity;
#Creation of identity with respect to rotation
Consider the CreateModel method where the user can change the world matrix for our xwing, with respect to correct location, and correct rotation −
Matrix worldMatrix = Matrix.CreateScale(0.07f, 0.0015f, 0.12 f)
* Matrix.CreateRotationY(MathHelper.Pi)
* Matrix.CreateTranslation(xwingPosition);
The mentioned code seems to be complex, but it is quite easy.
The mesh is translated to its correct position with the help of matrix.
The mesh is translated to its correct position with the help of matrix.
The xwing is rotated among the rotation stored in the xwingRotation quaternion.
The xwing is rotated among the rotation stored in the xwingRotation quaternion.
Once the above steps are achieved, it is rotated along 180 degrees to compensate the opposite direction stored inside the model. And finally, the model is scaled down so it fits nicely in our scene.
Once the above steps are achieved, it is rotated along 180 degrees to compensate the opposite direction stored inside the model. And finally, the model is scaled down so it fits nicely in our scene.
The code snippet for creating a dimension of camera is mentioned below −
private void UpdateCamera() {
Vector3 campos = new Vector3(0, 0.1f, 0.6f);
}
The sample code which is created is mentioned below −
D3DXQUATERNION qZ;
D3DXQUATERNION qY;
D3DXQUATERNION qX;
D3DXQUATERNION qOrient;
D3DXQUATERNION qTotal;
D3DXQuaternionIdentity(&qZ);
D3DXQuaternionIdentity(&qY);
D3DXQuaternionIdentity(&qX);
D3DXQuaternionIdentity(&qOrient);
D3DXVECTOR3 axisZ(0,0,1);
D3DXVECTOR3 axisY(0,1,0);
D3DXVECTOR3 axisX(1,0,0);
D3DXQuaternionRotationAxis(&qZ,&axisZ,ga->getRotation().z);
D3DXQuaternionRotationAxis(&qY,&axisY,ga->getRotation().y);
D3DXQuaternionRotationAxis(&qX,&axisX,ga->getRotation().x);
D3DXQuaternionNormalize(&qZ,&qZ);
D3DXQuaternionNormalize(&qY,&qY);
D3DXQuaternionNormalize(&qX,&qX);
qTotal=qY*qX*qZ;
D3DXMATRIX rotation;
D3DXMatrixRotationQuaternion(&rotation,&qTotal);
world=scale*rotation*move;
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2730,
"s": 2298,
"text": "The rotations of every graphic element are done with the help of xwing as per the rotations around the 3D axis, i.e., X, Y and Z axis. Xwing is something which is considered as a unique feature of rotating a particular object in quaternion. The only pro... |
Pruning Deep Neural Networks. TL; Different approaches of pruning... | by Ranjeet Singh | Towards Data Science | Deep Learning models these days require a significant amount of computing, memory, and power which becomes a bottleneck in the conditions where we need real-time inference or to run models on edge devices and browsers with limited computational resources. Energy efficiency is a major concern for current deep learning models. One of the methods for tackling this efficiency is enabling inference efficiency.
Larger Model => More Memory References => More Energy
Pruning is one of the methods for inference to efficiently produce models smaller in size, more memory-efficient, more power-efficient and faster at inference with minimal loss in accuracy, other such techniques being weight sharing and quantization. Out of several aspects that deep learning takes as an inspiration from the area of Neuroscience. Pruning in deep learning is also a biologically inspired concept that we will talk later in this post.
With the progress in Deep Learning, the state of the art models are getting more and more accurate but this progress comes with a cost. I will discuss a few of these here in this blog.
Hard to distribute large models through an over-the-air update
Such long training time limits ML researcher’s productivity.
AlphaGo: 1920 CPUs and 280 GPUs, $3000 electric bill per game
On Mobile devices: drains battery
On data-center: increases TCO
Pruning
Weight Sharing
Quantization
Low-Rank Approximation
Binary / Ternary Net
Winograd Transformation
Pruning in artificial neural networks has been taken as an idea from Synaptic Pruning in the human brain where axon and dendrite completely decay and die off resulting in synapse elimination that occurs between early childhood and the onset of puberty in many mammals. Pruning starts near the time of birth and continues into the mid-20s.
Networks generally look like the one on the left: every neuron in the layer below has a connection to the layer above, but this means that we have to multiply a lot of floats together. Ideally, we’d only connect each neuron to a few others and save on doing some of the multiplications; this is called a “sparse” network.
Sparse models are easier to compress, and we can skip the zeroes during inference for latency improvements.
If you could rank the neurons in the network according to how much they contribute, you could then remove the low ranking neurons from the network, resulting in a smaller and faster network.
Getting faster/smaller networks is important for running these deep learning networks on mobile devices.
The ranking, for example, can be done according to the L1/L2 norm of neuron weights. After the pruning, the accuracy will drop (hopefully not too much if the ranking is clever), and the network is usually trained-pruned-trained-pruned iteratively to recover. If we prune too much at once, the network might be damaged so much it won’t be able to recover. So in practice, this is an iterative process — often called ‘Iterative Pruning’: Prune / Train / Repeat.
See this code by the Tensorflow team to understand iterative pruning.
Set individual weights in the weight matrix to zero. This corresponds to deleting connections as in the figure above.
Here, to achieve sparsity of k% we rank the individual weights in weight matrix W according to their magnitude, and then set to zero the smallest k%.
f = h5py.File("model_weights.h5",'r+')for k in [.25, .50, .60, .70, .80, .90, .95, .97, .99]: ranks = {} for l in list(f[‘model_weights’])[:-1]: data = f[‘model_weights’][l][l][‘kernel:0’] w = np.array(data) ranks[l]=(rankdata(np.abs(w),method=’dense’) — 1).astype(int).reshape(w.shape) lower_bound_rank = np.ceil(np.max(ranks[l])*k).astype(int) ranks[l][ranks[l]<=lower_bound_rank] = 0 ranks[l][ranks[l]>lower_bound_rank] = 1 w = w*ranks[l] data[...] = w
Set entire columns to zero in the weight matrix to zero, in effect deleting the corresponding output neuron.
Here to achieve sparsity of k% we rank the columns of a weight matrix according to their L2-norm and delete the smallest k%.
f = h5py.File("model_weights.h5",'r+')for k in [.25, .50, .60, .70, .80, .90, .95, .97, .99]: ranks = {} for l in list(f[‘model_weights’])[:-1]: data = f[‘model_weights’][l][l][‘kernel:0’] w = np.array(data) norm = LA.norm(w,axis=0) norm = np.tile(norm,(w.shape[0],1)) ranks[l] = (rankdata(norm,method=’dense’) — 1).astype(int).reshape(norm.shape) lower_bound_rank = np.ceil(np.max(ranks[l])*k).astype(int) ranks[l][ranks[l]<=lower_bound_rank] = 0 ranks[l][ranks[l]>lower_bound_rank] = 1 w = w*ranks[l] data[...] = w
Naturally, as you increase the sparsity and delete more of the network, the task performance will progressively degrade. What do you anticipate the degradation curve of sparsity vs. performance to be?
Pruning results on image classification model on MNIST dataset using a simple neural network architecture given as -
Many researchers consider Pruning as an overlooked method that is going to get a lot more attention and use in practice. We showed how we can get nice results on a toy dataset using a very simple neural net architecture. I think many problems deep learning is used to solve in practice are similar to this one, using transfer learning on a limited dataset, so they can benefit from pruning too.
Code for this blog post
To prune, or not to prune: exploring the efficacy of pruning for model compression, Michael H. Zhu, Suyog Gupta, 2017
Learning to Prune Filters in Convolutional Neural Networks, Qiangui Huang et. al, 2018
Pruning deep neural networks to make them fast and small
Optimize machine learning models with Tensorflow Model Optimization Toolkit | [
{
"code": null,
"e": 581,
"s": 172,
"text": "Deep Learning models these days require a significant amount of computing, memory, and power which becomes a bottleneck in the conditions where we need real-time inference or to run models on edge devices and browsers with limited computational resources.... |
Using GANs to generate realistic images | by Victor Sim | Towards Data Science | GANs are one of the most promising new algorithms in the field of machine learning. With uses ranging from detecting glaucomatous images to reconstructing an image of a person’s face after listening to their voice. I wanted to try GANs out for myself so I constructed a GAN using Keras to generate realistic images.
The dataset that I will be using is the CIFAR10 Dataset. CIFAR is an acronym that stands for the Canadian Institute For Advanced Research and the CIFAR-10 dataset was developed along with the CIFAR-100 dataset (covered in the next section) by researchers at the CIFAR institute.
The dataset is comprised of 60,000 32×32 pixel color photographs of objects from 10 classes, such as frogs, birds, cats, ships, airplanes, etc.
These are very small images, much smaller than a typical photograph, and the dataset is intended for computer vision research.
General Adversarial Networks, or GANs for short, are a type of neural network for generative machine learning. They are able to accurately recreate similar, but not identical, content to what they are fed in.
A GAN consists of two parts: A generator and a discriminator.
The generator is a Neural Network that takes in random values and returns a long array of pixel values, that can be reconstructed to form images. The discriminator is another separate Neural Network that compares “real” and “fake” images, and tries to guess if they are real or fake.
The adversarial part of the GAN is how they work together and feed into each other: When training the GAN, the loss value for the generator is how accurate the discriminator is. The worse the discriminator performs, the better the generator is performing. On the other hand, the loss value of the discriminator is based on the accuracy of the predictions.
This means that the two Neural Networks are competing against each other: One is trying to trick the other, while the other tries to avoid being tricked.
Unsupervised Learning
Although the GAN itself is a form of Supervised Learning, the relationship between the generator and discriminator is unsupervised. This means that less data is required at every level of the network.
Highly applicable
Since the generator and discriminator of the data have convolutional layers as their input layers, the data for GANs usually come in the form of images. Since images can be expressed as a long array of numbers, most numerical data can be composed into images and are therefore compatible with GANs.
Long Computation Time
Because of the nested neural networks within the GAN, it can take a long time to train it. A good GPU is a necessity for training GANs.
Possible Collapse
The balance between the generator and the discriminator is very fragile. If there is a local minima for the generator, it might start creating unrecognizable generations that, by coincidence, perfectly fool the discriminator. This would happen more for images in which there is no clear pattern, as it would pick it up on false signals.
No True Way to Evaluate Model
On the premise that GANs would generate original image, there would be no objective, numerical way to check how accurate the recreations of the GAN is. One can only hope that the GAN will do its job.
Now that you have a basic understanding of how GANs should theoretically work, let’s look into the code.
from numpy import expand_dimsfrom numpy import zerosfrom numpy import onesfrom numpy import vstackfrom numpy.random import randnfrom numpy.random import randintfrom keras.datasets.cifar10 import load_datafrom keras.optimizers import Adamfrom keras.models import Sequentialfrom keras.layers import Densefrom keras.layers import Reshapefrom keras.layers import Flattenfrom keras.layers import Conv2Dfrom keras.layers import Conv2DTransposefrom keras.layers import LeakyReLUfrom keras.layers import Dropoutfrom matplotlib import pyplot
These are all the prerequisites necessary for the program to function. There is no need to download external files from the internet to get the CIFAR10 dataset. CIFAR10 is one of the few featured datasets on Keras, along with the MNIST dataset and the Boston Housing dataset. The first time the load_data function is called, it will be downloaded on your computer. After that, it just loads that file.
def define_discriminator(in_shape=(32,32,3)): model = Sequential() model.add(Conv2D(64, (3,3), padding='same', input_shape=in_shape)) model.add(LeakyReLU(alpha=0.2)) model.add(Conv2D(128, (3,3), strides=(2,2), padding='same')) model.add(LeakyReLU(alpha=0.2)) model.add(Conv2D(128, (3,3), strides=(2,2), padding='same')) model.add(LeakyReLU(alpha=0.2)) model.add(Conv2D(256, (3,3), strides=(2,2), padding='same')) model.add(LeakyReLU(alpha=0.2)) model.add(Flatten()) model.add(Dropout(0.4)) model.add(Dense(1, activation='sigmoid')) opt = Adam(lr=0.0002, beta_1=0.5) model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy']) return model
To give the discriminator the ability to evaluate if an image is fake or real, it must have a final layer with a sigmoid function. This is so that the predictions can be limited within 0 and 1. The in_shape represents the resolution of the image, the classic 3 channels, for an image of 32x32 pixels.
def define_generator(latent_dim): model = Sequential() n_nodes = 256 * 4 * 4 model.add(Dense(n_nodes, input_dim=latent_dim)) model.add(LeakyReLU(alpha=0.2)) model.add(Reshape((4, 4, 256))) model.add(Conv2DTranspose(128, (4,4), strides=(2,2), padding='same')) model.add(LeakyReLU(alpha=0.2)) model.add(Conv2DTranspose(128, (4,4), strides=(2,2), padding='same')) model.add(LeakyReLU(alpha=0.2)) model.add(Conv2DTranspose(128, (4,4), strides=(2,2), padding='same')) model.add(LeakyReLU(alpha=0.2)) model.add(Conv2D(3, (3,3), activation='tanh', padding='same')) return model
The generator is given a set of random points, that is upscaled with each Conv2DTRanspose, until it finally reaches the 32,32,3 resolution. The output can therefore be formed into an image using matplotlib.
def define_gan(g_model, d_model): d_model.trainable = False model = Sequential() model.add(g_model) model.add(d_model) opt = Adam(lr=0.0002, beta_1=0.5) model.compile(loss='binary_crossentropy', optimizer=opt) return model
The gan is simply stacking the generator on top of the discriminator, so that the output of the generator is fed directly into the discriminator. The loss is binary_crossentropy as there are only two possible outputs from the discriminator, fake or real.
def load_real_samples(): (trainX, _), (_, _) = load_data() X = trainX.astype('float32') X = (X - 127.5) / 127.5 return X def generate_real_samples(dataset, n_samples): ix = randint(0, dataset.shape[0], n_samples) X = dataset[ix] y = ones((n_samples, 1)) return X, y def generate_latent_points(latent_dim, n_samples): x_input = randn(latent_dim * n_samples) x_input = x_input.reshape(n_samples, latent_dim) return x_input def generate_fake_samples(g_model, latent_dim, n_samples): x_input = generate_latent_points(latent_dim, n_samples) X = g_model.predict(x_input) y = zeros((n_samples, 1)) return X, y
The first foresight one must have before training a network is whether one has configured enough information to perform a full propagation of the network. The necessary inputs for a full propagation are the set of latent points for the generator and the fake and real samples for the discriminator.
def train(g_model, d_model, gan_model, dataset, latent_dim, n_epochs=200, n_batch=128): bat_per_epo = int(dataset.shape[0] / n_batch) half_batch = int(n_batch / 2) for i in range(n_epochs): for j in range(bat_per_epo): X_real, y_real = generate_real_samples(dataset, half_batch) d_loss1, _ = d_model.train_on_batch(X_real, y_real) X_fake, y_fake = generate_fake_samples(g_model, latent_dim, half_batch) d_loss2, _ = d_model.train_on_batch(X_fake, y_fake) X_gan = generate_latent_points(latent_dim, n_batch) y_gan = ones((n_batch, 1)) g_loss = gan_model.train_on_batch(X_gan, y_gan) print('>%d, %d/%d, d1=%.3f, d2=%.3f g=%.3f' % (i+1, j+1, bat_per_epo, d_loss1, d_loss2, g_loss)) if (i+1) % 10 == 0: summarize_performance(i, g_model, d_model, dataset, latent_dim)
By training the GAN, the discriminator and the generator’s weights are presumed to be linked, and the gradients are propagated backwards. The batch size can be adjusted to control the fitting of the model or computation time and a basic report will be shown every epoch.
def summarize_performance(epoch, g_model, d_model, dataset, latent_dim, n_samples=150) X_real, y_real = generate_real_samples(dataset, n_samples) _, acc_real = d_model.evaluate(X_real, y_real, verbose=0) x_fake, y_fake = generate_fake_samples(g_model, latent_dim, n_samples) _, acc_fake = d_model.evaluate(x_fake, y_fake, verbose=0) print('>Accuracy real: %.0f%%, fake: %.0f%%' % (acc_real*100, acc_fake*100)) save_plot(x_fake, epoch) filename = 'generator_model_%03d.h5' % (epoch+1) g_model.save(filename)
Summarizing the performance will show the accuracy of the discriminator and save the best weights in a file of the same directory so that training can be spread out over time. I executed this program on a Google Colab notebook, as the data was on the Keras API, preventing the need for reading the documentation of loading local files into google colab notebooks.
latent_dim = 100d_model = define_discriminator()g_model = define_generator(latent_dim)gan_model = define_gan(g_model, d_model)dataset = load_real_samples()train(g_model, d_model, gan_model, dataset, latent_dim)
Now that all of the functions have been configured, we just have to call upon them with the relevant parameters.
The program is actually reasonably successful. Observe the results below!
I hope that I have piqued your interest with GANs and given you a sound argument on their place in machine learning in the future.
If you want to see more of my content, click this link. | [
{
"code": null,
"e": 488,
"s": 172,
"text": "GANs are one of the most promising new algorithms in the field of machine learning. With uses ranging from detecting glaucomatous images to reconstructing an image of a person’s face after listening to their voice. I wanted to try GANs out for myself so I... |
How to get the value of src attribute in jQuery? | To get the value of src attribute in jQuery is quite easy. We will get the src attribute of the img tag. This attribute has the URL of the image. Let’s first see how we can add jQuery −
You can try to run the following code to learn how to get the value of src attribute in jQuery −
Live Demo
<html>
<head>
<title> Selector Example</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
alert($('#myimg').attr('src'));
});
</script>
</head>
<body>
<p>Logo</p>
<img src="/green/images/logo.png" id="myimg">
</body>
</html> | [
{
"code": null,
"e": 1248,
"s": 1062,
"text": "To get the value of src attribute in jQuery is quite easy. We will get the src attribute of the img tag. This attribute has the URL of the image. Let’s first see how we can add jQuery −"
},
{
"code": null,
"e": 1345,
"s": 1248,
"text... |
How to display an image in HTML? | Use the <img> tag in HTML to display an image. The following are the attributes −
You can try to run the following code to add an image to a web document −
<!DOCTYPE html>
<html>
<head>
<title>HTML img Tag</title>
</head>
<body>
<img src = "https://www.tutorialspoint.com/html5/images/html5-mini-logo.jpg"
alt = "Learn HTML5" height = "250" width = "270" />
</body>
</html> | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "Use the <img> tag in HTML to display an image. The following are the attributes −"
},
{
"code": null,
"e": 1218,
"s": 1144,
"text": "You can try to run the following code to add an image to a web document −"
},
{
"code": null... |
Write a program in C++ to replace all the 0’s with 5 in a given number | Given an integer N, the task is to replace all the 0’s that appear in the number with ‘5’. However, the number with leading ‘0’ cannot be replaced with ‘5’ as it remains unchanged. For example,
Input-1 −
N= 1007
Output −
1557
Explanation − The given number has 2 zeros which when replaced by ‘5’ results in the output as 1557.
Input-2 −
N = 00105
Output −
155
Explanation − Since the given number starts with the leading ‘0’ which can be ignored and the output after replacing the 0 in the middle with ‘5’ results the output as 155.
To replace all the 0’s in the given number with ‘5’ we can find and extract the last digit of the number. If the last digit of that number is ‘0’ then change and replace the value with ‘5’ and extract another digit. However, any leading ‘0’s in the given number must be ignored.
The problem can be solved using a recursion approach where we will first extract the last digit and then again call the same function while extracting the other digit of that number.
Take Input a number N.
Take Input a number N.
An Integer function converToFive(int N) takes a number as input and returns the modified number by replacing all 0’s with ‘5’.
An Integer function converToFive(int N) takes a number as input and returns the modified number by replacing all 0’s with ‘5’.
In a base case, if the number is ‘0’, then return 0, otherwise extract the last digit of that number and check,
In a base case, if the number is ‘0’, then return 0, otherwise extract the last digit of that number and check,
If the last digit of the number is ‘0’ then replace the value with ‘5’.
If the last digit of the number is ‘0’ then replace the value with ‘5’.
Return the recursive function which takes another digit of the number by dividing ‘10’ and multiplying by ‘10’.
Return the recursive function which takes another digit of the number by dividing ‘10’ and multiplying by ‘10’.
Return the output which extracts the last digit by adding it into it.
Return the output which extracts the last digit by adding it into it.
Live Demo
#include <bits/stdc++.h>
using namespace std;
int convertToFive(int N) {
if(N==0){
return 0;
}
int last_digit= N%10;
if(last_digit==0)
last_digit=5;
return convertToFive(N/10)*10 +last_digit;
}
int main() {
int N= 14006;
cout << convertToFive(N) << endl;
}
If we will run the above code, then it will print the output as,
14556
Since there are two 0s in the given number, after replacing the number 14006, it will become 14556. | [
{
"code": null,
"e": 1256,
"s": 1062,
"text": "Given an integer N, the task is to replace all the 0’s that appear in the number with ‘5’. However, the number with leading ‘0’ cannot be replaced with ‘5’ as it remains unchanged. For example,"
},
{
"code": null,
"e": 1266,
"s": 1256,
... |
How to Adjust the Width of Input Field Automatically using JavaScript ? - GeeksforGeeks | 16 Apr, 2020
The HTML <input> element is used to create interactive controls for web-based forms in order to accept data from the user. The <input> element is one of the most powerful and complex in all of HTML due to the sheer number of combinations of input types and attributes. The HTML <input> width attribute is used to specify the width of the element.
To increase the width of <input> element dynamically.Approach 1:
The onkeypress event occurs when the user presses any key.
Select the width attribute of an element.
Make it equal to the length of the value of the input field by this.value.length
<input type="text" onkeypress="myFunction()">
Here, we select the <input> element and add a method to it which occurs when a key is pressed. This method selects and updates the value of the width property dynamically.
HTML Code:
<!DOCTYPE html> <html> <head> <title> How to adjust width of an input field to its input?</title> </head> <body> <form method="post" action=""> <label for="username">Input text</label> <input type="text" id="textbox" name="textbox" placeholder="Welcome" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';" id="input"/> </form></body> </html>
You can also write a JavaScript function to check the length of your string on input change, then adjust the width of the input based on the number of chars * character width.
Alternative JavaScript Code:
$('input').css('width', (( input.getAttribute('placeholder').length + 1) * 8) + 'px');$("input").focusout(function() { if (this.value.length > 0) { this.style.width = ((this.value.length + 1) * 8) + 'px'; } else { this.style.width = ((this.getAttribute('placeholder').length + 1) * 8) + 'px'; }});
Output:
Approach 2: Use jQuery keypress() event in combination with String.fromCharCode(e.which) to get the pressed character. Hence, we can calculate the width of the input element.
jQuery Code:
$('input[type="text"]').keypress(function(e) { if (e.which !== 0 && e.charCode !== 0) { // Only characters var c = String.fromCharCode(e.keyCode|e.charCode); $span = $(this).siblings('span').first(); // The hidden span takes $span.text($(this).val() + c) ; // The value of the input $inputSize = $span.width() ; // Apply width of the span to the input $(this).css("width", $inputSize) ; }}) ;
Output:
Browser Compatibility:
Chrome: Yes
Firefox: Yes (63.0)
Edge: Yes
Internet Explorer: Yes
Opera: Yes
Safari: Yes
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24986,
"s": 24958,
"text": "\n16 Apr, 2020"
},
{
"code": null,
"e": 25333,
"s": 24986,
"text": "The HTML <input> element is used to create interactive controls for web-based forms in order to accept data from the user. The <input> element is one of the most p... |
Aggregate method in C# | Use the Aggregate method in C# to perform mathematical operations such as Sum, Min, Max, Average, etc.
Let us see an example to multiply array elements using Aggregate method.
Here is our array −
int[] arr = { 10, 15, 20 };
Now, use Aggregate() method −
arr.Aggregate((x, y) => x * y);
Here is the complete code −
Live Demo
using System;
using System.Linq;
using System.IO;
public class Demo {
public static void Main() {
int[] arr = { 10, 15, 20 };
// Multiplication
int res = arr.Aggregate((x, y) => x * y);
Console.WriteLine(res);
}
}
3000 | [
{
"code": null,
"e": 1165,
"s": 1062,
"text": "Use the Aggregate method in C# to perform mathematical operations such as Sum, Min, Max, Average, etc."
},
{
"code": null,
"e": 1238,
"s": 1165,
"text": "Let us see an example to multiply array elements using Aggregate method."
},
... |
Why the main () method in Java is always static? | Java main() method is always static, so that compiler can call it without the creation of an object or before the creation of an object of the class.
In any Java program, the main() method is the starting point from where compiler starts program execution. So, the compiler needs to call the main() method.
If the main() is allowed to be non-static, then while calling the main() method JVM has to instantiate its class.
While instantiating it has to call the constructor of that class, There will be ambiguity if the constructor of that class takes an argument.
Static method of a class can be called by using the class name only without creating an object of a class.
The main() method in Java must be declared public, static and void. If any of these are missing, the Java program will compile but a runtime error will be thrown.
class Book {
public static void getBookInfo() { //static method
System.out.println("Welcome to TutorialsPoint Library");
}
}
public class Test {
public static void main(String[] args) {
//Call static method of Book class using class name only
Book.getBookInfo();
}
}
Welcome to TutorialsPoint Library | [
{
"code": null,
"e": 1212,
"s": 1062,
"text": "Java main() method is always static, so that compiler can call it without the creation of an object or before the creation of an object of the class."
},
{
"code": null,
"e": 1369,
"s": 1212,
"text": "In any Java program, the main() ... |
Scala - Bitwise Operators | Try the following example program to understand all the Bitwise operators available in Scala Programming Language.
object Demo {
def main(args: Array[String]) {
var a = 60; /* 60 = 0011 1100 */
var b = 13; /* 13 = 0000 1101 */
var c = 0;
c = a & b; /* 12 = 0000 1100 */
println("a & b = " + c );
c = a | b; /* 61 = 0011 1101 */
println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
println("a ^ b = " + c );
c = ~a; /* -61 = 1100 0011 */
println("~a = " + c );
c = a << 2; /* 240 = 1111 0000 */
println("a << 2 = " + c );
c = a >> 2; /* 215 = 1111 */
println("a >> 2 = " + c );
c = a >>> 2; /* 215 = 0000 1111 */
println("a >>> 2 = " + c );
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2 = 15
a >>> 2 = 15
82 Lectures
7 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
52 Lectures
1.5 hours
Bigdata Engineer
76 Lectures
5.5 hours
Bigdata Engineer
69 Lectures
7.5 hours
Bigdata Engineer
46 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2113,
"s": 1998,
"text": "Try the following example program to understand all the Bitwise operators available in Scala Programming Language."
},
{
"code": null,
"e": 2863,
"s": 2113,
"text": "object Demo {\n def main(args: Array[String]) {\n var a = 60... |
FastAPI + AWS = robust API (Part 1) | by Anna Geller | Towards Data Science | FastAPI revolutionized the way of developing modern Python-based REST APIs. Since its inception, the project has been adopted by large companies, such as Microsoft, Uber, and Netflix, and it’s increasingly gaining popularity, what we can observe by the number of Github stars growing every day.
Being able to build fast, robust, secure, and scalable APIs is a must-have skill for any backend (data) engineer. In this article, we’ll build a simple REST API that will show the market sentiment and current prices of selected cryptocurrencies in a currency of your choice (euro, dollar, etc.).
We’ll use the top-down approach: from packaging and deploying the API to diving into details on what it is about. In Part 1, we’ll deploy our FastAPI code to AWS by leveraging Amazon Lambda and API Gateway. In the future article (Part 2), we’ll make sure to secure our API by using API keys. We’ll also demonstrate how to enable distributed tracing and logging to track our application’s health. Let’s dive in!
Create a Pycharm project with a virtual environmentInstall the required librariesTest the API locallyPackage your code & prepare the deployment pipeline (incl. creation of Lambda function)Create the REST API in API GatewayConfigure your Lambda function as a proxy to forward requests from API Gateway to Amazon LambdaDeploy the API to dev stageTest the endpointDiving deeper into how it all works togetherDemo of the cryptocurrency API by using Swagger UIConclusion
Create a Pycharm project with a virtual environment
Install the required libraries
Test the API locally
Package your code & prepare the deployment pipeline (incl. creation of Lambda function)
Create the REST API in API Gateway
Configure your Lambda function as a proxy to forward requests from API Gateway to Amazon Lambda
Deploy the API to dev stage
Test the endpoint
Diving deeper into how it all works together
Demo of the cryptocurrency API by using Swagger UI
Conclusion
Let’s start by creating a Project with a virtual environment in Pycharm. You can either use a Virtualenv or Conda — whichever you prefer. I usually use Virtualenv on macOS and Conda on Windows.
If you want to follow along, this Github repository contains the code for this project.
Let’s change the current working directory to api folder and install the required packages:
cd api && pip install -r requirements.txt
After having installed all package dependencies, we can start the Uvicorn ASGI server in our terminal:
uvicorn main:app --reload
If you configured your virtual environment and downloaded (or cloned) the code from Github, you should be able to access the interactive Swagger UI from your browser:
http://localhost:8000/docs
In order to make our API accessible from API Gateway, we need to:
zip our API code with all site-packages dependencies into a zip file that will be used by our Lambda function
upload this zip file to S3 (we could, in theory, upload it directly to Lambda, but there is a 10MB zip file size limit → to prepare our application for growth, we will upload it directly to S3, and during the Amazon Lambda creation, we’ll make sure that Amazon Lambda uses this zip file from S3)
Note: this part requires that you installed and configured AWS CLI
create the Amazon Lambda function with Python 3.8 runtime, choose the option “Create a new role with basic Lambda permissions”, and configure the Lambda handler as main.handler, as shown in the GIF:
update the function to make sure that it uses the packaged code from S3 (we could have done it from the management console, as well):
aws lambda update-function-code --function-name medium-demo \--s3-bucket $bucket_name --s3-key lambda.zip
From the management console, make sure to choose the same region for your API in API Gateway as the one you selected for the Lambda function. Even though it’s possible to have API Gateway and Lambda function in different regions, it could potentially lead to some extra latency.
Then: Create API → Choose REST API (not the private one) → Build → enter the name for your API → Create API.
Now we need to configure the integration point for our request methods. To use a Lambda function as our integration point for ANY type of request (i.e., GET, POST, PATCH, DELETE, etc.), we will create a Method (to handle the root path) and a child Resource (to handle all child paths). We will configure them to handle any requests made to API Gateway by using the Lambda proxy integration [1].
From the dropdown menu Actions: 1. Create Method 2. Choose ANY 3. Select Lambda Function as your integration type and make sure to check the box “Use Lambda Proxy Integration”4. Add the name of your Lambda function (and its corresponding region) and keep the defaults for everything else → Save
When the pop-up window asks you whether you want to grant API Gateway permission to invoke your Lambda function, confirm. Without it, API Gateway will not be authorized to invoke your Lambda function.
Similarly to the “Method” configuration, go to Actions → Create Resource. Make sure to select the checkbox “Configure as proxy resource” and keep the defaults to enable Lambda proxy integration (as before), then select your Lambda function and Save.
Again, confirm that you allow API Gateway to invoke the Lambda function on behalf of your API requests:
Since our Lambda is now configured, we can deploy the API. We can name it dev stage. The deployment is crucial to make the Lambda function integration active.
Deploying your API to any deployment stage ensures that API Gateway creates a URL that serves as a front door to your API. You can click on this URL and test that the API has been properly configured.
In your browser, you should see a response corresponding to the root GET path of our FastAPI code:
{"Hello Medium Reader": "from FastAPI & API Gateway"}
We can continue testing further endpoints directly from our browser:
Side note: If the endpoint dev/v1/prices/ETH doesn’t work for you, and you get a message {"message": "Missing Authentication Token"}, you should retry the creation of the Resource proxy and redeploy the API.
Already at this point, we can see that our API is publicly accessible by anyone! In Part 2, we’ll change it by creating an API key directly from the API Gateway console.
By now, you may have many questions. I will try to guess and answer them in this Q&A form:
1. How did we make the local FastAPI code work with Amazon Lambda?
We used the Mangum library [5], which serves as a wrapper for ASGI APIs running inside of AWS Lambda and API Gateway. It provides an adapter, which:
routes requests made to the API Gateway to our Lambda function,
routes Lambda function responses back to the API Gateway.
We only had to add two lines (line 1 and 7) to turn our FastAPI code within main.py to an Amazon Lambda handler:
2. What is the difference between a Method and a Resource in API Gateway?
The ANY Method will route requests to the root path / to the Lambda function that executes our FastAPI code. In contrast, the child Resource will route all paths below the root path / in a greedy mode (greedy path parameter: {proxy+}) [7], i.e., it will route all other endpoints defined in your FastAPI code to Lambda, for example, the path /v1/prices/BTC/.
3. Why do we need {proxy+}?
Using the proxy, we don’t need to write any mapping templates that would route the specific paths to different Lambda functions - instead, we have a single Lambda function that serves all endpoints [6]. Then, API Gateway will route all types of requests (GET, POST, DELETE, PATCH, ...) from API Gateway to the paths defined within FastAPI code. And the FastAPI code gets executed inside of the Lambda function thanks to the Mangum adapter.
4. How does this architecture scale?
Each request made to API Gateway will invoke a Lambda function. This means that we can have thousands of parallel requests made to our API, as each will be served from a separate Lambda function invocation.
Note that there are soft concurrency limits of how many parallel Lambda executions we can have per account (at the time of writing, 1000). If you need more than that, you can use the Support Center console to request an increase to this limit [2].
5. Why is this architecture attractive?
It provides a completely serverless API infrastructure with many benefits:
all advantages of Python and the amazing FastAPI library combined with the benefits of a serverless architecture
scalability & no backend server to manage — API Gateway will spin up as many Lambda functions as needed to handle all requests made to our API
very cost-effective, especially for smaller APIs that may not yet get millions of requests
performant: due to Lambda’s context reuse, consecutive requests (within 15 minutes from a previous request) reuse the frozen execution context, allowing to mitigate the cold start of a serverless function
if enabled, API Gateway caching allows further latency improvements
easy management of API keys
API Gateway provides integration with Active Directories and third-party auth providers such as “Login with Google/Amazon account” via Cognito
out of the box centralized logging of all API requests and responses, as well as access logs via CloudWatch
distributed tracing capability by enabling X-Ray traces.
6. Why did we use site-packages from the virtual environment to install package dependencies?
We could have installed the libraries into some specific directory (ex. libs directory) by adding the flag -t, which stands for target:
pip install -r requirements.txt -t ../libs/
And then we could have added this directory to our lambda.zip.
However, this way, we would clutter our project with Python packages that would have been installed into the project directory, and it could make it harder for other developers later to distinguish between the actual API code and its dependencies. We would likely have to add the libs directory to .gitignore. Overall, it would add extra work, which we don’t need to do if we are working with a virtual environment and its site-packages.
7. Could we have used the Serverless Framework or AWS SAM to create a deployment pipeline?
Yes, this setup works well with Serverless Framework. Here is an example of how it could look like:
github.com
However, I prefer to minimize dependencies in my project and serverless requires additional components such as the Node package manager.
You can also use this setup with AWS SAM.
8. How much does it costs?
With the free tier, you get monthly (free) access to:
1 million API Gateway requests
1 million Lambda invocations with up to 3.2 million seconds of compute time per month
Apart from that, the prices may vary depending on your AWS region and your number of requests (bulk discount), but they are in ranges of 1–4.25 dollars per one million requests (at the time of writing). Lambda is priced based on the number of invocations and how long your code is running, measured in milliseconds. You can find out more here and here.
Finally, here is what the API is doing — all functionality is based on information coming from CryptoCompare [4]:
we are getting the trading signals to get the information about the market sentiment for a specific cryptocurrency, i.e., whether there is a current upward or downward tendency
we are getting real-time prices of selected cryptocurrencies and can display them in a specific currency of our choice.
In this article, we discussed the process of deploying a REST API to AWS by leveraging FastAPI, API Gateway, and Amazon Lambda. Along the way, we learned how to package the code and create a deployment pipeline, and we discussed how all those microservice components work together.
In Part 2 article, we’ll continue building this API by adding authentication via API Keys, distributed logging and tracing, as well as how to redeploy the API once we made changes to our FastAPI code.
towardsdatascience.com
If this article was useful, follow me to see my next articles.
References:
[1] Blog by Sean Baier
[2] Amazon Lambda docs
[3] API Gateway docs
[4] CryptoCompare API docs
[5] Mangum docs
[6] About the Lambda proxy integration
[7] How to use Amazon API Gateway {proxy+} | [
{
"code": null,
"e": 467,
"s": 172,
"text": "FastAPI revolutionized the way of developing modern Python-based REST APIs. Since its inception, the project has been adopted by large companies, such as Microsoft, Uber, and Netflix, and it’s increasingly gaining popularity, what we can observe by the nu... |
iText - Adding Image to a Table | In this chapter, we will see how to add an image to a table in a PDF document using the iText library.
You can create an empty PDF document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter, to its constructor. Then, to add a table to the document, you need to instantiate the Table class and add this object to the document using the add() method.
To add an image to this table, you need to instantiate the Cell class, create and an object of the image that is required to be added, add the image to the cell object using the add() method of the Cell class.
Following are the steps to insert an image into the cell of a table.
The PdfWriter class represents the Doc Writer for a PDF, this class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created.
Instantiate PdfWriter class by passing a string value representing the path where you need to create a PDF, to its constructor, as shown below.
// Creating a PdfWriter
String dest = "C:/itextExamples/addingImage.pdf";
PdfWriter writer = new PdfWriter(dest);
When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified.
The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor.
Instantiate the PdfDocument class by passing the above created PdfWriter object to its constructor, as shown below.
// Creating a PdfDocument
PdfDocument pdfDoc = new PdfDocument(writer);
Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class.
The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument.
Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below.
// Creating a Document
Document document = new Document(pdfDoc);
The Table class represents a two-dimensional grid filled with cells, ordered in rows and columns. It belongs to the package com.itextpdf.layout.element.
Instantiate the Table class as shown below.
// Creating a table
float [] pointColumnWidths = {200F, 200F};
Table table = new Table(pointColumnWidths);
Create a cell object by instantiating the Cell class of the package com.itextpdf.layout, as shown below.
// Adding cell to the table
Cell cell = new Cell(); // Creating a cell
To create the image object, first of all, create an ImageData object using the create() method of the ImageDataFactory class. As a parameter of this method, pass a string parameter representing the path of the image, as shown below.
// Creating an ImageData object
String imageFile = "C:/itextExamples/javafxLogo.jpg";
ImageData data = ImageDataFactory.create(imageFile);
Now, instantiate the Image class of the com.itextpdf.layout.element package. While instantiating, pass the ImageData object created above, as a parameter to its constructor, as shown below.
// Creating an Image object
Image img = new Image(data);
Add the image object to the cell using the add() method of the cell class, as shown below.
// Adding image to the cell
cell.add(img.setAutoScale(true));
Finally, to add this cell to the table, call the addCell() method of the Table class and pass the cell object as a parameter to this method, as shown below.
table.addCell(cell);
Add the table object created in the previous step using the add() method of the Document class, as shown below.
// Adding list to the document
document.add(table);
Close the document using the close() method of the Document class, as shown below.
// Closing the document
document.close();
The following Java program demonstrates how to add an image to a cell of a table in a PDF document using the iText library. It creates a PDF document with the name addingImage.pdf, adds a table to it, inserts an image (javafxLogo.jpg) to one of its cells, and saves it in the path C:/itextExamples/.
Save this code in a file with the name AddingImageToTable.java.
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Table;
public class a3AddingImageToTable {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter object
String dest = "C:/itextExamples/addingImage.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument object
PdfDocument pdfDoc = new PdfDocument(writer);
// Creating a Document object
Document doc = new Document(pdfDoc);
// Creating a table
float [] pointColumnWidths = {150f, 150f};
Table table = new Table(pointColumnWidths);
// Populating row 1 and adding it to the table
Cell cell1 = new Cell();
cell1.add("Tutorial ID");
table.addCell(cell1);
Cell cell2 = new Cell();
cell2.add("1");
table.addCell(cell2);
// Populating row 2 and adding it to the table
Cell cell3 = new Cell();
cell3.add("Tutorial Title");
table.addCell(cell3);
Cell cell4 = new Cell();
cell4.add("JavaFX");
table.addCell(cell4);
// Populating row 3 and adding it to the table
Cell cell5 = new Cell();
cell5.add("Tutorial Author");
table.addCell(cell5);
Cell cell6 = new Cell();
cell6.add("Krishna Kasyap");
table.addCell(cell6);
// Populating row 4 and adding it to the table
Cell cell7 = new Cell();
cell7.add("Submission date");
table.addCell(cell7);
Cell cell8 = new Cell();
cell8.add("2016-07-06");
table.addCell(cell8);
// Populating row 5 and adding it to the table
Cell cell9 = new Cell();
cell9.add("Tutorial Icon");
table.addCell(cell9);
// Creating the cell10
Cell cell10 = new Cell();
// Creating an ImageData object
String imageFile = "C:/itextExamples/javafxLogo.jpg";
ImageData data = ImageDataFactory.create(imageFile);
// Creating the image
Image img = new Image(data);
// Adding image to the cell10
cell10.add(img.setAutoScale(true));
// Adding cell110 to the table
table.addCell(cell10);
// Adding Table to document
doc.add(table);
// Closing the document
doc.close();
System.out.println("Image added to table successfully..");
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac AddingImageToTable.java
java AddingImageToTable
Upon execution, the above program creates a PDF document, displaying the following message.
Image added to table successfully..
If you verify the specified path, you can find the created PDF document, as shown below.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2471,
"s": 2368,
"text": "In this chapter, we will see how to add an image to a table in a PDF document using the iText library."
},
{
"code": null,
"e": 2789,
"s": 2471,
"text": "You can create an empty PDF document by instantiating the Document class. While... |
Python 3 - File write() Method | The method write() writes a string str to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.
Following is the syntax for write() method −
fileObject.write( str )
str − This is the String to be written in the file.
This method does not return any value.
The following example shows the usage of write() method.
Assuming that 'foo.txt' file contains following text:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
#!/usr/bin/python3
# Open a file in read/write mode
fo = open("abc.txt", "r+")
print ("Name of the file: ", fo.name)
str = "This is 6th line"
# Write a line at the end of the file.
fo.seek(0, 2)
line = fo.write( str )
# Now read complete file from beginning.
fo.seek(0,0)
for index in range(6):
line = next(fo)
print ("Line No %d - %s" % (index, line))
# Close opened file
fo.close()
When we run the above program, it produces the following result −
Name of the file: foo.txt
Line No 0 - This is 1st line
Line No 1 - This is 2nd line
Line No 2 - This is 3rd line
Line No 3 - This is 4th line
Line No 4 - This is 5th line
Line No 5 - This is 6th line
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2531,
"s": 2340,
"text": "The method write() writes a string str to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called."
},
{
"code": null,
"e": 2576,
"s": 2531,
... |
Spring Security - Taglib | Introduction and Overview
Spring Security Tags
The authorize Tag
The authentication tag
The csrfInput Tag
The csrfMetaTags Tag
Getting Started (Practical Guide)
In Spring MVC applications using JSP, we can use the Spring Security tags for applying security constraints as well as for accessing security information. Spring Security Tag library provides basic support for such operations. Using such tags, we can control the information displayed to the user based on his roles or permissions. Also, we can include CSRF protection features in our forms.
To use Spring security tags, we must have the security taglib declared in our JSP file.
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
Now, we can use Spring Security tags with the “sec” prefix. Let’s now see the usage of the tags.
The authorize Tag
The first tag we will be discussing is the authorize tag. Let’s check out some usage examples.
<sec:authorize access="!isAuthenticated()"> Login </sec:authorize>
<sec:authorize access="isAuthenticated()"> Logout </sec:authorize>
<sec:authorize access="hasRole('ADMIN')"> Hello Admin. </sec:authorize>
As we can see, we can use this tag to hide or show sections of information based on access or roles. To evaluate roles or access we also use the following Spring Security Expressions −
hasRole(“ADMIN”) − evaluates to true if the current user has the admin role.
hasRole(“ADMIN”) − evaluates to true if the current user has the admin role.
hasAnyRole(‘ADMIN’,’USER’) − evaluates to true if the current user has any of the listed roles
hasAnyRole(‘ADMIN’,’USER’) − evaluates to true if the current user has any of the listed roles
isAnonymous() − evaluates to true if the current user is an anonymous user
isAnonymous() − evaluates to true if the current user is an anonymous user
isRememberMe() − evaluates to true if the current user is a remember-me user
isRememberMe() − evaluates to true if the current user is a remember-me user
isFullyAuthenticated() − evaluates to true if the user is authenticated and is neither anonymous nor a remember-me user
isFullyAuthenticated() − evaluates to true if the user is authenticated and is neither anonymous nor a remember-me user
As we can see, the access attribute is where the web-security expression is specified. Then, Spring Security evaluates the expression The evaluation is generally delegated to SecurityExpressionHandler<FilterInvocation>, which is defined in the application context. If it returns true, then the user can get access to the information given in that section.
If we use the authorize tag with Spring Security ‘s Permission Evaluator, we can also check user permissions as given below −
<sec:authorize access="hasPermission(#domain,'read') or hasPermission(#domain,'write')">
This content is visible to users who have read or write permission.
</sec:authorize>
We can also allow or restrict the user from clicking on certain links within our content.
<sec:authorize url="/admin">
This content will only be visible to users who are authorized to send requests to the "/admin" URL.
</sec:authorize>
The authentication tag
When we want access to the current Authentication object stored in the Spring Security Context, we can use the authentication tag. Then we can use it to render properties of the object directly in our JSP page. For example, if we want to render the principal property of the Authentication object in our page, we can do it as follows −
<sec:authentication property="principal.username" />
The csrfInput Tag
We can use the csrfInput tag to insert a hidden form field with the correct values for the CSRF protection token when CSRF protection is enabled. If CSRF protection is not enabled, this tag outputs nothing.
We can place the tag within the HTML <form></form> block along with other input fields. However, we must not place the tag within the <form:form></form:form> block as Spring Security automatically inserts a CSRF form field within those tags and also takes care of Spring forms automatically.
<form method="post" action="/do/something">
<sec:csrfInput />
Username:<br />
<input type="text" username="username" />
...
</form>
The csrfMetaTags Tag
We can use this tag to insert meta tags which contain the CSRF protection token form field and header names and CSRF protection token value. These meta tags can be useful for employing CSRF protection within Javascript in our application. However, this tag only works when we have enabled CSRF protection in our application, otherwise, this tag outputs nothing.
<html>
<head>
<title>CSRF Protection in Javascript</title>
<sec:csrfMetaTags />
<script type="text/javascript" language="javascript">
var csrfParam = $("meta[name='_csrf_param']").attr("content");
var csrfToken = $("meta[name='_csrf']").attr("content");
</script>
</head>
<body>
...
</body>
</html>
Getting Started (Practical Guide)
Now that we have discussed the tags, let’s build an application to demonstrate the usage of the tags. We shall be using Spring Tool Suite 4 as our IDE. Additionally, we shall be using the Apache Tomcat server to serve our application. So, let’s get started.
Setting up the Application
Let’s create a simple Maven Project in STS. We can name our application as taglibsdemo, and package it as a .war file.
When we have finished setting up our application it should have a structure similar to this.
The pom.xml file
We shall add these following dependencies to our application −
Spring Web MVC
Spring-Security-Web
Spring-Security-Core
Spring-Security-Taglibs
Spring-Security-Config
Javax Servlet Api
JSTL
After adding these dependencies, our pom.xml should look similar to this −
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorial.spring.security</groupId>
<artifactId>taglibsdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency> <dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
Let’s create our base package for the application. We can name it com.taglibsdemo. Within the package, let’s create another package for our configuration files. Since, it will be holding the configuration files, we can name it config.
ApplicationConfig.java
Let’s create our first configuration class ApplicationConfig.java.
package com.taglibsdemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@Configuration @ComponentScan({ "com.taglibsdemo.controller"} )
public class ApplicationConfig {
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver
viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp"); return viewResolver;
}
}
Let’s break down the code here −
@EnableWebMvc − We use @EnableWebMvc to enable Spring MVC. So, we add this annotation to an @Configuration class to import the Spring MVC configuration from WebMvcConfigurationSupport. WebMvcConfigurationSupport is the main class that provides the configuration for the MVC Java config. Not using this annotation may result in things like content-type and accept header, generally content negotiation not working. @EnableWebMvc registers a RequestMappingHandlerMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver among others in support of processing requests with annotated controller methods using annotations such as @RequestMapping , @ExceptionHandler, and others.
@Configuration − This annotation indicates that the class declares one or more @Bean methods and may be processed by the Spring IoC container to generate bean definitions and service requests for those beans at runtime. A @Configuration class is typically bootstrapped using either AnnotationConfigApplicationContext or its web-capable variant, AnnotationConfigWebApplicationContext.
@ComponentScan − @ComponentScan annotation is used to tell Spring the packages to scan for annotated components. @ComponentScan also used to specify base packages and base package classes using thebasePackageClasses or basePackages attributes of @ComponentScan.
InternalResourceViewResolver − To resolve the provided URI to the actual URI in the format prefix + viewname + suffix.
setViewClass() − To set the view class that should be used to create views.
setPrefix() − To set the prefix that gets prepended to view names when building a URL.
setSuffix() − To set the suffix that gets appended to view names when building a URL.
WebSecurityConfig.java
Next we shall create our WebSecurityConfig class which will extend the familiar WebSecurityConfigurerAdapter class of Spring Security.
package com.taglibsdemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.User.UserBuilder;
@EnableWebSecurity @ComponentScan("com.taglibsdemo")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@SuppressWarnings("deprecation") @Bean
public UserDetailsService userdetailsService() {
UserBuilder users = User.withDefaultPasswordEncoder();
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(users.username("rony").password("rony123").roles("USER").build());
manager.createUser(users.username("admin").password("admin123").roles("ADMIN").build());
return manager;
}
@Override protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() .antMatchers("/index", "/").permitAll()
.antMatchers("/admin", "/user").authenticated() .and() .formLogin()
.and() .logout() .logoutRequestMatcher(
new AntPathRequestMatcher("/logout")
);
}
}
Let’s break the code down here −
WebSecurityConfigurerAdapter − The abstract class that implements WebSecurityConfigurer WebSecurityConfigurer and allows us to override methods for security configuration.
@EnableWebSecurity − It enables Spring to automatically find and apply the @Configuration class to the global WebSecurity.
We then create a UserDetailsService Bean using the method to create users using the InMemoryUserDetailsManager instance. We create two users – one with role “USER” and another with role “ADMIN” and add them to Spring Security.
After that, we override the configure method with HttpSecurity as a parameter. We make our home page or index page accessible to all and admin page to be accessible when the user is authenticated. Next, we add Spring Security form login and logout.
So, with those steps our security configuration is complete. Now, we are ready to move on to the next step.
SpringSecurityApplicationInitializer.java
Moving on, now we shall create the SpringSecurityApplicationInitializer.java class which extends the AbstractSecurityWebApplicationInitializer class of Spring Security.
package com.taglibsdemo.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SpringSecurityApplicationInitializer extends
AbstractSecurityWebApplicationInitializer { }
AbstractSecurityWebApplicationInitializer is an abstract class that implements Spring’s WebApplicationInitializer. So, SpringServletContainerInitializer will initialize the concrete implementations of this class if the classpath contains spring-web module.
MvcWebApplicationInitializer.java
package com.taglibsdemo.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MvcWebApplicationInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override protected Class</?>[] getRootConfigClasses() {
return new Class[] {WebSecurityConfig.class};
}
@Override protected Class</?>[] getServletConfigClasses() {
return null;
}
@Override protected String[] getServletMappings() {
return new String[] {"/"};
}
}
AbstractAnnotationConfigDispatcherServletInitializer − This class extends WebApplicationInitializer. We need this class as a base class for initializing a Spring application in Servlet container environment.As a result, the subclass of AbstractAnnotationConfigDispatcherServletInitializer will provide the classes annotated with @Configuration, Servlet config classes and DispatcherServlet mapping pattern.
getRootConfigClasses() − This method must be implemented by the class extending AbstractAnnotationConfigDispatcherServletInitializer. It provides “root” application context configuration.
getServletConfigClasses() − This method too, must be implemented to provide DispatcherServlet application context configuration.
getServletMappings() − This method is used specify the servlet mapping(s) for the DispatcherServlet.
We have set up the configuration classes. Now , we shall create our controller to serve the JSP pages.
HelloController.java
package com.taglibsdemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller public class HelloController {
@GetMapping("/")
public String index() { return "index"; }
@GetMapping("/user")
public String user() { return "admin"; }
@GetMapping("/admin")
public String admin() { return "admin"; }
}
Here, we have created three endpoints – “/”, “/user”, and “/admin”. As specified in our configuration previously, we will allow unauthorized access to the index page
“/”. On the other hand, the “/user” and “/admin” endpoints would be authorized only access.
Secure Content to serve
Moving on, we shall now create the JSP pages which are to be served on hitting the specific endpoints.
For this, inside our src/main folder we create a folder called webapp. Inside this folder, we create our WEB-INF folder and further as in ApplicationConfig.java class we add the views folder. Here, in this folder we shall be adding the views.
Let’s add our home page, i.e., index.jsp first.
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Home Page</title>
</head>
<body>
<a href="user">User</a>
<a href="admin">Admin</a>
<br>
<br> Welcome to the Application!
</body>
</html>
Then we shall create our admin.jsp file. Let’s add it.
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="security"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body> Welcome to Admin Page! <a href="logout"> Logout </a>
<br>
<br>
<security:authorize access="hasRole('ADMIN')"> Hello Admin!
</security:authorize>
</body>
</html>
here, we have added <%@ taglib uri="http://www.springframework.org/security/tags" prefix="security"%>. This is going to let us the Spring security tag libs as discussed before. As we can see, we have the added the “authorize” tag around the content. This content is will be only accessible by our admin. Any other user accessing this page will not be able to view this content.
Running the application
We now right click on the project and choose Run On Server. When the server starts and our application is running we can go to localhost:8080/taglibsdemo/ on our browser to view the page.
Login page
Now, if we click on the User link in our application, we shall be asked to log in.
Here, as we can see in our controller, we are serving the admin page for bothe the user and admin links. But our user, if he is not an admin cannot view the content which is protected by our “authorize”tag.
Let’s log in as the user first.
We can see that the “Hello Admin!” content is not visible to us. This is because the current user doesn’t have the admin role.
Let’s logout and log in as admin now.
We are now able to see the protected content “Hello Admin!” as the current user has the admin role.
Conclusion
We have learnt how we can use the Spring Security tag library to protect our content and get access to the current Authentication object in Our Spring Security Context.
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1861,
"s": 1835,
"text": "Introduction and Overview"
},
{
"code": null,
"e": 1882,
"s": 1861,
"text": "Spring Security Tags"
},
{
"code": null,
"e": 1900,
"s": 1882,
"text": "The authorize Tag"
},
{
"code": null,
"e": 1923,
... |
How to create an empty dictionary in Python? | You can create empty dictionary object by giving no elements in curly brackets in assignment statement. Empty dictionary object is also created by dict() built-in function without any arguments
>>> L1
[]
>>> d1 = {}
>>> d1
{}
>>> d1 = dict()
>>> d1
{} | [
{
"code": null,
"e": 1256,
"s": 1062,
"text": "You can create empty dictionary object by giving no elements in curly brackets in assignment statement. Empty dictionary object is also created by dict() built-in function without any arguments"
},
{
"code": null,
"e": 1314,
"s": 1256,
... |
How to Train Your Model (Dramatically Faster) | by Will Nowak | Towards Data Science | I work as a machine learning engineer at Unbox Research — Tyler Neylon’s new ML R+D studio. I just finished a project implementing a custom image classifier iOS app for a client — in instances like these, transfer learning is a powerful tool.
Transfer learning is a technique for efficiently, partially retraining a neural network. To do so, we reuse a previously constructed model architecture and most of the learned weights, and then use standard training methods to learn the remaining, non-reused parameters.
Transfer learning vs non-transfer learning
A fully trained neural net takes input values in an initial layer and then sequentially feeds this information forward (while simultaneously transforming it) until, crucially, some second-to-last layer has constructed a high level representation of the input that can more easily be transformed into a final output. The full training of the model involves the optimization of weight and bias terms used in each connection, labelled in green.
The second-to-last layer is referred to as a bottleneck layer. The bottleneck layer pushes values in a regression model, or softmax probabilities in a classification model, to our final network layer.
In transfer learning, we start with the pre-trained weights for the whole network. Then we fix the weights up to the last layer and let the weights in that layer change as we train on new data. As seen in the diagram, we keep the red connections fixed, and now only retrain the last layer of green connections.
Transfer efficiency
Transfer learning confers two major benefits:
Training on new data is faster than starting from scratch.We can often solve a problem with less training data than we’d need if we were starting from scratch.
Training on new data is faster than starting from scratch.
We can often solve a problem with less training data than we’d need if we were starting from scratch.
Here we consider exactly why transfer learning is so efficient.
By only retraining our final layer, we’re performing a far less computationally expensive optimization (learning hundreds or thousands of parameters, instead of millions) .
This contrasts with open source models like Inception v3 that contain 25 million parameters and were trained with best-in-class hardware. As a result, these nets have well-fit parameters and bottleneck layers with highly optimized representations of the input data. While you might find it difficult to train a high-performing model from scratch with your own limited computing and data resources, you can use transfer learning to leverage the work of others and force-multiply your performance.
Sample code
Let’s look at some Python code to get slightly more into the weeds (but not too far — don’t want to get lost down there!).
First, we need to start with a pretrained model. Keras has a bunch of pretrained models; we’ll use the InceptionV3 model.
# Keras and TensorFlow must be (pip) installed.from keras.applications import InceptionV3from keras.models import Model
InceptionV3 has been trained on the ImageNet data, which contains 1000 different objects, many of which I find to be pretty eccentric. For instance, class 924 is guacamole.
Indeed, the pretrained InceptionV3 recognizes it as such.
preds = InceptionV3().predict(guacamole_img)returns a 1000 dimension array (where guacamole_img is a 224x224x3 dimension np array).
preds.max() returns 0.99999, whereas preds.argmax(-1) returns index 924 — the Inception model is really sure that this guacamole is just that! (E.g. we are predicting that guacamole_imgis Imagenet image #924 with 99.999% confidence. Here’s a link to reproducible code.
Now that we know that InceptionV3 can at least confirm what I’m currently snacking on, let’s see if we can use the underlying data representation to retrain and learn a new classification scheme.
As noted above, we want to freeze the first n-1layers of the model, and just retrain a final layer.
Below, we load the pretrained model; we then grab the input and second to last (bottleneck) layer names from the original model using TensorFlow’s .get_layer() method and build a new model using those two layers as input and output.
original_model = InceptionV3()bottleneck_input = original_model.get_layer(index=0).inputbottleneck_output = original_model.get_layer(index=-2).outputbottleneck_model = Model(inputs=bottleneck_input, outputs=bottleneck_output)
Here, we get the input from the first layer (index = 0) of the Inception model. If we print(model.get_layer(index=0).input), we see Tensor("input_1:0", shape=(?,?,?,3), dtype=float32) — this indicates that our model is expecting some indeterminate amount of images as input, of an unspecified height and width, with 3 RBG channels. This, too, is what we want as the input for our bottleneck layer.
We see Tensor("avg_pool/Mean:0",shape=(?, 2048), dtype=float32) as the output of our bottleneck, which we accessed by referencing the second to last model layer. In this instance, the Inception model has learned a 2048 dimensional representation of any image input, where we can think of these 2048 dimensions as representing crucial components of an image that are essential to classification.
Lastly, we instantiate a new model with the original image input and the bottleneck layer as output: Model(inputs=bottleneck_input, outputs=bottleneck_output).
Next, we need to set each layer in the pretrained model to untrainable — essentially we are freezing the weights and biases of these layers and keeping the information that was already learned through Inception’s original, laborious training.
for layer in bottleneck_model.layers: layer.trainable = False
Now, we make a new Sequential() model, starting with our previous building block and then making a minor addition.
new_model = Sequential()new_model.add(bottleneck_model)new_model.add(Dense(2, activation=‘softmax’, input_dim=2048))
The above code serves to build a composite model which combines our Inception architecture with a final layer with 2 nodes. We use 2 because we are going to retrain a new model to learn to differentiate cats and dogs — so we only have 2 image classes. Replace this with however many classes you’re hoping to classify.
As noted before, the bottleneck output is of size 2048, so this is our input_dim to the Dense layer. Lastly, we insert a softmax activation to ensure our image class outputs can be interpreted as probabilities.
I’ve included a very tall network layout image of the full network at the very end of this article — be sure to check it out!.
To finish, we just need a few more standard TensorFlow steps:
# For a binary classification problemnew_model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])one_hot_labels = keras.utils.to_categorical(labels, num_classes=2)new_model.fit(processed_imgs_array, one_hot_labels, epochs=2, batch_size=32)
Here, processed_ims_array is an array of size (number_images_in_training_set, 224, 224, 3), and labels is a Python list of the ground truth image classes. These are scalars corresponding to the class of the image in the training data. num_classes=2, so labels is just a list of length number_of_images_in_training_setcontaining 0’s and 1’s.
In the end, when we run this model on our first cat training image (using Tensorflow’s very handy, built-in bilinear rescaling function):
The model predicts cat with 94% confidence. That’s pretty good, considering I only used 20 training images, and trained for a mere 2 epochs!
Take-aways
By leveraging a pre-built model architecture and pre-learned weights, transfer learning allows you to use the learned high-level representation of a given data structure and apply it to your own, new training data.
To recap, you need 3 ingredients to use transfer learning:
A pretrained modelSimilar training data — You need inputs to be “similar enough” to inputs of pre-trained model. Similar enough means that the inputs must be of the same format (e.g. shape of input tensors, data types...) and of similar interpretation. For example, if you are using a model pretrained for image classification, images will work as input! However, some clever folk have formatted audio to run through a pretrained image classifier, with some cool results. As ever, fortune favors the creative.Training labels
A pretrained model
Similar training data — You need inputs to be “similar enough” to inputs of pre-trained model. Similar enough means that the inputs must be of the same format (e.g. shape of input tensors, data types...) and of similar interpretation. For example, if you are using a model pretrained for image classification, images will work as input! However, some clever folk have formatted audio to run through a pretrained image classifier, with some cool results. As ever, fortune favors the creative.
Training labels
Check out a full working example here for a demonstration of transfer learning that uses local files.
Please leave comments and claps below if you have any questions / found this of value. Feel free to reach out to me if you have any machine learning projects that you’d like to discuss! will@unboxresearch.com.
For NYC readers — we’re hosting an entire workshop on TensorFlow in January 2019 — get tickets here.
Appendix:
A full graph representation of our network, created with Netron. Aren’t you glad we didn’t have to fully construct ourselves?! | [
{
"code": null,
"e": 415,
"s": 172,
"text": "I work as a machine learning engineer at Unbox Research — Tyler Neylon’s new ML R+D studio. I just finished a project implementing a custom image classifier iOS app for a client — in instances like these, transfer learning is a powerful tool."
},
{
... |
Hands on Tensorflow Data Validation | by Vincent Teyssier | Towards Data Science | Google just released their new piece for an end to end big data platform, TFDV! One of the big pain in data science is to handle data quality issue, ie data validation. Let’s see how google delivers on this first version and how useful this new library is.
Quite a standard installation process via pip, however make sure you have pre-installed a few dependencies to be sure it compiles without issues. In my case, on Ubuntu 16.04, I was missing python-dev and python-snappy for faster performance. Bazel is also good to have if you start to use TFX libraries.
sudo apt-get install python-dev python-snappypip install tensorflow-data-validation
This TFDV being a rather new library, the documentation is pretty.... inexistant, so I strongly advise you to clone the repository and look at what parameters each function you use are accepting.
No rocket science here, we first import the library, and the first step in your dataset analysis/validation is to generated_statistics on your dataset. I will load a csv here and specify a separator, but you can also load a TFRecords instead. For convenience here is both function definition headers:
import tensorflow_data_validation as tfdvdef generate_statistics_from_csv(data_location,column_names = None,delimiter = ‘,’,output_path = None,stats_options = stats_api.StatsOptions(),pipeline_options = None,):...def generate_statistics_from_tfrecord(data_location,output_path = None,stats_options = stats_api.StatsOptions(),pipeline_options = None,):
Let’s load and generate our stats:
BASE_DIR = os.getcwd()DATA_DIR = os.path.join(BASE_DIR, 'data')TRAIN_DATA = os.path.join(DATA_DIR, 'train.csv')train_stats = tfdv.generate_statistics_from_csv(TRAIN_DATA, delimiter=';')
First thing to notice is that the operation is quite memory intensive. My dataset was only a 86Mb csv file, but the RAM usage went up by nearly 1Gb, so make sure you have a lot of RAM available!
Once the stats are generated, you have 2 options to vizualize them. Either you use Facets Overview, which can be tricky to install depending on your platform, or you can use the built in TFDV visualization function which provides exactly the same information as facets:
tfdv.visualize_statistics(stats)
It is pretty useful to spot immediately if you have high amount of missing data, high standard deviation, etc.... however I really like Facets for the Dive module which let’s you explore in a very visual way how your dataset looks like.
So far nothing revolutionary.... but here comes the big deal...
The main feature of TFDV is the concept of “schema”. This is basically a description of how your data look like so you match this description against new coming data and validate them... or not.
It describes standard characteristics of your data such as column datatypes, presence/abscence of data, expected range of values.
You create your schema on a dataset that you consider as a reference dataset and can reuse it to validate other sets of the same structure.
One more interesting feature is that you can reuse this schema in TFTransform to automatically declare your dataset structure.
That’s where things become easy... to do that, only one line of code is sufficient:
schema = tfdv.infer_schema(train_stats)
However, as simply as it looks, the Tensorflow team comes with a warning:
In general, TFDV uses conservative heuristics to infer stable data properties from the statistics in order to avoid overfitting the schema to the specific dataset. It is strongly advised to review the inferred schema and refine it as needed, to capture any domain knowledge about the data that TFDV’s heuristics might have missed.
To store your schema, TFDV uses the protobuf library, which is becoming a unified method to manipulate your static data (datastructure, transformation scheme, frozen models...).
If there is one point on which we may all agree, it is that no dataset is perfect. Domain knowledge is essential when it comes to validate your data, hence why an automatic tool is a kind of unicorn! To take this into account, TFDV comes with helper functions so you manually hard code rules that your dataset shouldn’t derive from.Each feature is coming with a set of property that you can access and modify. For example let’s describe that we want feature f1 to be populated in at least 50% of the examples, this is achieved by this line:
tfdv.get_feature(schema, 'f1').presence.min_fraction = 0.5
Each feature is composed of the following components:Feature name, Type, Presence, Valency, Domain
And each component then gets its own subset of sub-components. I won’t list them here, but the best advice I can give you is to parse the schema protobuf and you will find something looking like that:
num_examples:1000000000000000weighted_num_examples: 1000000000000000features { name: “one_in_a_quadrillion” type:INT num_stats: { common_stats: { num_missing: 1 num_non_missing: 1000000000000000 min_num_values: 1 max_num_values: 1 weighted_common_stats { num_non_missing: 1000000000000000 num_missing: 1 } } min: 0.0 max: 10.0}
You can also simply display it in your notebook like this:
tfdv.display_schema(schema)
Your “perfect” training set is now described, but you keep getting fresh data everyday to ETL, and look for a way to validate the new coming set, here is the core of TFDV. Using the previously described schema/domain.... it will parse your new set and report outliers, missing or wrong data.
I think the picture included in the tutorial is a perfect illustration of what a nice pipeline data validation chain should look like:
When you try to productify a data ingestion pipeline for your models, this is basically what you try to achieve.
Let’s get a new CSV file, load it, generate stats, and parse it for validation using the previously generated schema:
NEW_DATA = os.path.join(DATA_DIR, 'test.csv')new_csv_stats = tfdv.generate_statistics_from_csv(NEW_DATA, delimiter=';') anomalies = tfdv.validate_statistics(statistics=new_csv_stats, schema=schema)
You can then display these anomalies the following way:
tfdv.display_anomalies(anomalies)
And you will get a list containing one or several of the following error messages describing which conditions the new dataset is not fullfilling knowing the expected conditions from the schema:
Integer larger than 1BYTES type when expected INT type BYTES type when expected STRING type FLOAT type when expected INT type FLOAT type when expected STRING type INT type when expected STRING type Integer smaller than 1 STRING type when expected INT type Expected a string, but not the string seen BYTES type when expected STRING type FLOAT type when expected STRING type INT type when expected STRING type Invalid UTF8 string observed Unexpected string values The number of values in a given example is too large The fraction of examples containing a feature is too small The number of examples containing a feature is too small The number of values in a given example is too small No examples contain the value The feature is present as an empty list The feature is repeated in an example, but was expected to be a singleton There is a float value that is too highThe type is not FLOAT There is a float value that is too low The feature is supposed to be floats encoded as strings, but there is a string that is not a float The feature is supposed to be floats encoded as strings, but it was some other type (INT, BYTES, FLOAT) The type is completely unknown There is an unexpectedly large integer The type was supposed to be INT, but it was not. The feature is supposed to be ints encoded as strings, but some string was not an int. The type was supposed to be STRING, but it was not. There is an unexpectedly small integerThe feature is supposed to be ints encoded as strings, but it was some other type (INT, BYTES, FLOAT) Unknown type in stats proto There are no stats for a column at all There is a new column that is not in the schema. Training serving skew issue Expected STRING type, but it was FLOAT. Expected STRING type, but it was INT. Control data is missing (either training data or previous day). Treatment data is missing (either scoring data or current day). L infinity between treatment and control is high. No examples in the span.
I have to say that I felt a bit disappointed by the result here.... I know we are only talking about data validation, but pointing at an error and not returning a subset containing these errors feels a bit like an unfinished work.I also know that this feature is a quite expensive one, if you take yearly license from packages like Talend or Alooma, pricing between 10k usd to 80k usd, you get a nice stream to handle your defects, but I believe TF will take this road sooner or later!
You still have a few more details in the column “Anomaly long description” so you should be fine with interpretability of what you have.
What is also nice is that if you believe the deviation from the schema is to be expected, you can amend the original schema easily:
tfdv.get_domain(schema, 'f2').value.append('new_unique_value')
You may want to validate your set using the schema definition, but depending on the context (in the tutorial example we take training and predicting, ie labels/no labels) you might have need to disregard some conditions. This is achievable the following way:
# All features are by default in both TRAINING and SERVING environments.schema.default_environment.append('TRAINING')schema.default_environment.append('SERVING')# Specify that labels column is not in SERVING environment.tfdv.get_feature(schema, 'labels').not_in_environment.append('SERVING')serving_anomalies_with_env = tfdv.validate_statistics( serving_stats, schema, environment='SERVING')
One picture says it all:
You get the benefit of all the above in one comparative visualization. You are however limited to 2 sets:
tfdv.visualize_statistics(lhs_statistics=train_stats, rhs_statistics=test_stats, lhs_name=’TRAIN’, rhs_name=’TEST’)
As previously explained the schema you generate will avoid you to manually describe your features types. It can be loaded in TFTransform the following way:
feature_spec = schema_utils.schema_as_feature_spec(schema).feature_specschema = dataset_schema.from_feature_spec(feature_spec)
I will skip the skew and drift comparator since they are an extension of the logic previously explained, and you may want to look deeper in the git for how you want to use these features in TFDV. Both are very useful!
To conclude, TFDV is exactly what it stands for, a data validation tool, nothing more, nothing less, that integrates perfectly with the Tensorflow ecosystem, providing more automation for TFTransform and completing the end-to-end framework that Google is trying to provide for machine learning practitioners. It still feels that defect handling is missing, but given the different libraries that have been offered to us to lighten our pain points, I believe this is coming soon! The next planned release by Google is Data Ingestion module, then the jobs management, orchestration, monitoring...as seen on top of the below picture.
You can find the full official TFDV tutorial there: | [
{
"code": null,
"e": 429,
"s": 172,
"text": "Google just released their new piece for an end to end big data platform, TFDV! One of the big pain in data science is to handle data quality issue, ie data validation. Let’s see how google delivers on this first version and how useful this new library is... |
From pandas to PySpark. Leveraging your pandas data... | by Zolzaya Luvsandorj | Towards Data Science | Being able to skillfully and efficiently manipulate big data is a useful skill to have for data analysts, data scientists and anyone working with data. If you are already comfortable with Python and pandas, and want to learn to wrangle big data, a good way to start is to get familiar with PySpark, a Python API for Apache Spark, a popular open source data processing engine for big data. In this post, we will look at side-by-side comparisons of pandas code snippets for basic data manipulation tasks and their counterparts in PySpark.
This post assumes that the reader is comfortable with manipulating data using pandas in Python.
Let’s start by importing necessary libraries. In PySpark, we will need to create a Spark session. Once the Spark session is created, Spark web user interface (Web UI) can be accessed from: http://localhost:4040/. The application name ‘tutorial’ defined below will be shown as the application name on the right top corner of Web UI. We won’t be using Web UI for the purpose of this post, however, if you are interested in learning more, check out the official documentation.
import pandas as pdfrom pyspark.sql import SparkSessionspark = SparkSession.builder.appName('tutorial').getOrCreate()
We will use the penguins dataset for this post. Using the script below, we will save penguins.csv, a modified version of the data, in the working directory.
from seaborn import load_dataset(load_dataset('penguins') .drop(columns=['culmen_length_mm', 'culmen_depth_mm']) .rename(columns={'flipper_length_mm': 'flipper', 'body_mass_g': 'mass'}) .to_csv('penguins.csv', index=False))
Now, let’s look at the syntax comparisons between the two libraries. Throughout this section, only PySpark outputs will be shown to keep the post less cluttered.
Both libraries’ data objects are called DataFrame: pandas DataFrame vs PySpark DataFrame. Let’s import the data and check its shape:
# 🐼 pandas df = pd.read_csv('penguins.csv')df.shape# 🎇 PySparkdf = spark.read.csv('penguins.csv', header=True, inferSchema=True)df.count(), len(df.columns)
When importing data with PySpark, the first row is used as a header because we specified header=True and data types are inferred to a more suitable type because we set inferSchema=True. If you are curious, try importing without these options and inspect the DataFrame and its data type (similar to pandas, you can check data types using df.dtypes for PySpark DataFrames).
Unlike pandas DataFrame, PySpark DataFrame has no attribute like .shape. So to get the data shape, we find the number of rows and columns separately.
Now, let’s check high level information about the data:
# 🐼 pandas df.info()# 🎇 PySparkdf.printSchema()
While this method doesn’t give identical output to df.info() , it’s one of the closest built-in methods. Time to look at the head of the data:
# 🐼 pandas df.head()# 🎇 PySparkdf.show(5)
By default, df.show() will show 20 rows if there are more than 20 rows. PySpark DataFrame actually has a method called .head(). Running df.head(5) provides output like this:
Output from .show() method is more succinct so we will be using .show() for the rest of the post when viewing top rows of the dataset. Now let’s look at how to select columns:
# 🐼 pandas df[['island', 'mass']].head(3)# 🎇 PySparkdf[['island', 'mass']].show(3)
While we can use almost pandas-like syntax here, the following version of snippets are probably more common for selecting columns in PySpark:
df.select('island', 'mass').show(3)df.select(['island', 'mass']).show(3)
Let’s look at how to filter the data based on a condition:
# 🐼 pandas df[df['species']=='Gentoo'].head()# 🎇 PySparkdf[df['species']=='Gentoo'].show(5)
The syntax is almost the same between the two libraries. To get the same output, we can also use:
df.filter(df['species']=='Gentoo').show(5) df.filter("species=='Gentoo'").show(5)
Below shows a few common filter comparisons:
# 🐼 pandas 2a df[df['species'].isin(['Chinstrap', 'Gentoo'])].head()3a df[df['species'].str.match('G.')].head()4a df[df['flipper'].between(225,229)].head()5a df[df['mass'].isnull()].head()1b df.loc[df['species']!='Gentoo'].head()2b df[~df['species'].isin(['Chinstrap', 'Gentoo'])].head()3b df[-df['species'].str.match('G.')].head()4b df[~df['flipper'].between(225,229)].head()5b df[df['mass'].notnull()].head()6 df[(df['mass']<3400) & (df['sex']=='Male')].head()7 df[(df['mass']<3400) | (df['sex']=='Male')].head()# 🎇 PySpark2a df[df['species'].isin(['Chinstrap', 'Gentoo'])].show(5)3a df[df['species'].rlike('G.')].show(5)4a df[df['flipper'].between(225,229)].show(5)5a df[df['mass'].isNull()].show(5)1b df[df['species']!='Gentoo'].show(5)2b df[~df['species'].isin(['Chinstrap', 'Gentoo'])].show(5)3b df[~df['species'].rlike('G.')].show(5)4b df[~df['flipper'].between(225,229)].show(5)5b df[df['mass'].isNotNull()].show(5)6 df[(df['mass']<3400) & (df['sex']=='Male')].show(5)7 df[(df['mass']<3400) |(df['sex']=='Male')].show(5)
While both ~ and - work as a negation in pandas, only ~ works as a valid negation in PySpark.
Let’s sort the data and inspect 5 rows with smallest mass:
# 🐼 pandas df.nsmallest(5, 'mass')# 🎇 PySparkdf[df['mass'].isNotNull()].orderBy('mass').show(5)
Pandas' .nsmallest() and .nlargest() methods sensibly excludes missing values. However, PySpark doesn’t have equivalent methods. To get the same output, we first filter out the rows with missing mass, then we sort the data and inspect the top 5 rows. If there was no missing data, syntax could be shortened to: df.orderBy(‘mass’).show(5).
Let’s look at another way of sorting using .sort() instead of .orderBy():
# 🐼 pandas df.nlargest(5, 'mass')# 🎇 PySparkdf.sort('mass', ascending=False).show(5)
These variations of the syntax also work:
df.sort(df['mass'].desc()).show(5)df.orderBy('mass', ascending=False).show(5)df.orderBy(df['mass'].desc()).show(5)
We can sort by multiple columns as follows:
# 🐼 pandas df.sort_values(['mass', 'flipper'], ascending=False).head()# 🎇 PySparkdf.orderBy(['mass', 'flipper'], ascending=False).show(5)
In PySpark, you can get away without the list like this: df.orderBy(‘mass’, ‘flipper’, ascending=False).show(5). To sort by multiple columns but in different directions:
# 🐼 pandas df.sort_values(['mass', 'flipper'], ascending=[True, False]).head()# 🎇 PySparkdf[df['mass'].isNotNull()]\ .sort('mass', 'flipper', ascending=[True, False]).show(5)
Here’s an alternative:
df[df['mass'].isNotNull()]\ .orderBy(df['mass'].asc(), df['flipper'].desc()).show(5)
Now, let’s look at a few examples to aggregate data. Simple aggregation can be done very similarly as follows:
# 🐼 pandas df.agg({‘flipper’: ‘mean’})# 🎇 PySparkdf.agg({'flipper': 'mean'}).show()
When looking at multiple aggregations, we will need to approach differently:
# 🐼 pandas df.agg({'flipper': ['min', 'max']})# 🎇 PySparkfrom pyspark.sql import functions as Fdf.agg(F.min('flipper'), F.max('flipper')).show()
To get distinct values in a column:
# 🐼 pandas df['species'].unique()# 🎇 PySparkdf.select('species').distinct().show()
To get a number of distinct values in a column:
# 🐼 pandas df['species'].nunique()# 🎇 PySparkdf.select('species').distinct().count()
By now, you may have noticed PySpark uses camelCase for the methods and functions. This is true for .groupBy() as well. Here’s a simple group by aggregation example:
# 🐼 pandas df.groupby('species')['mass'].mean()# 🎇 PySparkdf.groupBy('species').agg({'mass': 'mean'}).show()
Here’s an example aggregating multiple selected columns:
# 🐼 pandas df.groupby(‘species’).agg({‘flipper’: ‘sum’, ‘mass’: ‘mean’})# 🎇 PySparkdf.groupBy('species').agg({'flipper': 'sum', 'mass': 'mean'}).show()
If we don’t specify a column, it will show stats for all numerical columns:
# 🐼 pandas df.groupby('species').mean()# 🎇 PySparkdf.groupBy('species').mean().show()
We can also substitute .mean() with .avg() as well. In other words, we can use df.groupBy(‘species’).avg().show().
That was it for this post! Hope you find these comparisons useful and learned a bit about PySpark syntax. As you may have noticed, there are quite a bit of similarities between the two libraries when it comes to basic tasks. This makes it easier to get started on PySpark for those who have working knowledge in pandas.
Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me.
Thank you for reading my article. If you are interested, here are links to some of my other posts:◼️️ 5 tips for pandas users◼️️ 5 tips for data aggregation in pandas◼️️ Writing 5 common SQL queries in pandas◼️️ Writing advanced SQL queries in pandas◼️️ How to transform variables in a pandas DataFrame
Bye for now 🏃 💨 | [
{
"code": null,
"e": 708,
"s": 171,
"text": "Being able to skillfully and efficiently manipulate big data is a useful skill to have for data analysts, data scientists and anyone working with data. If you are already comfortable with Python and pandas, and want to learn to wrangle big data, a good wa... |
Matcher replaceFirst(String) Method in Java with Examples - GeeksforGeeks | 10 Nov, 2021
The replaceFirst() method of Matcher Class behaves as an append-and-replace method. This method reads the input string and replaces it with the first matched pattern in the matcher string.
Syntax:
public String replaceFirst(String stringToBeReplaced)
Parameters: The string to be replaced that is the String to be replaced in the matcher.
Return Type: A string with the target string constructed by replacing the string.
Example 1:
Java
// Java Program to Illustrate replaceFirst() Method// of Matcher class // Importing required classesimport java.util.regex.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Getting the regex to be checked String regex = "(Geeks)"; // Creating a pattern from regex Pattern pattern = Pattern.compile(regex); // Getting the String to be matched String stringToBeMatched = "GeeksForGeeks Geeks for For Geeks Geek"; // Creating a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Displaying the string to be matched // before replacing System.out.println("Before Replacement: " + stringToBeMatched); // Getting the string to be replaced String stringToBeReplaced = "GFG"; StringBuilder builder = new StringBuilder(); // Replacing every matched pattern with the target // string using replaceFirst() method System.out.println( "After Replacement: " + matcher.replaceFirst(stringToBeReplaced)); }}
Before Replacement: GeeksForGeeks Geeks for For Geeks Geek
After Replacement: GFGForGeeks Geeks for For Geeks Geek
Example 2:
Java
// Java Program to Illustrate replaceFirst() Method // Importing required classesimport java.util.regex.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Getting the regex to be checked String regex = "(FGF)"; // Creating a pattern from regex Pattern pattern = Pattern.compile(regex); // Getting the string to be matched String stringToBeMatched = "FGF FGF FGF FGF"; // Creating a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Printing string on console // before replacement System.out.println("Before Replacement: " + stringToBeMatched); // Getting the string to be replaced String stringToBeReplaced = "GFG"; StringBuilder builder = new StringBuilder(); // Replacing every matched pattern with target // string using replaceFirst() method and printing // the string to be replaced System.out.println( "After Replacement: " + matcher.replaceFirst(stringToBeReplaced)); }}
Before Replacement: FGF FGF FGF FGF
After Replacement: GFG FGF FGF FGF
Akanksha_Rai
solankimayank
Java - util package
Java-Functions
Java-Matcher
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Stream In Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Internal Working of HashMap in Java
Checked vs Unchecked Exceptions in Java
Strings in Java
StringBuilder Class in Java with Examples | [
{
"code": null,
"e": 23868,
"s": 23840,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 24058,
"s": 23868,
"text": "The replaceFirst() method of Matcher Class behaves as an append-and-replace method. This method reads the input string and replaces it with the first matched patte... |
Data Structures in R Programming - GeeksforGeeks | 05 Jul, 2021
A data structure is a particular way of organizing data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks. Data structures in R programming are tools for holding multiple values.
R’s base data structures are often organized by their dimensionality (1D, 2D, or nD) and whether they’re homogeneous (all elements must be of the identical type) or heterogeneous (the elements are often of various types). This gives rise to the six data types which are most frequently utilized in data analysis.
The most essential data structures used in R include:
Vectors
Lists
Dataframes
Matrices
Arrays
Factors
A vector is an ordered collection of basic data types of a given length. The only key thing here is all the elements of a vector must be of the identical data type e.g homogeneous data structures. Vectors are one-dimensional data structures.
Example:
Python3
# R program to illustrate Vector # Vectors(ordered collection of same data type)X = c(1, 3, 5, 7, 8) # Printing those elements in consoleprint(X)
Output:
[1] 1 3 5 7 8
A list is a generic object consisting of an ordered collection of objects. Lists are heterogeneous data structures. These are also one-dimensional data structures. A list can be a list of vectors, list of matrices, a list of characters and a list of functions and so on.
Example:
Python3
# R program to illustrate a List # The first attributes is a numeric vector# containing the employee IDs which is# created using the 'c' command hereempId = c(1, 2, 3, 4) # The second attribute is the employee name# which is created using this line of code here# which is the character vectorempName = c("Debi", "Sandeep", "Subham", "Shiba") # The third attribute is the number of employees# which is a single numeric variable.numberOfEmp = 4 # We can combine all these three different# data types into a list# containing the details of employees# which can be done using a list commandempList = list(empId, empName, numberOfEmp) print(empList)
Output:
[[1]]
[1] 1 2 3 4
[[2]]
[1] "Debi" "Sandeep" "Subham" "Shiba"
[[3]]
[1] 4
Dataframes are generic data objects of R which are used to store the tabular data. Dataframes are the foremost popular data objects in R programming because we are comfortable in seeing the data within the tabular form. They are two-dimensional, heterogeneous data structures. These are lists of vectors of equal lengths.
Data frames have the following constraints placed upon them:
A data-frame must have column names and every row should have a unique name.
Each column must have the identical number of items.
Each item in a single column must be of the same data type.
Different columns may have different data types.
To create a data frame we use the data.frame() function.
Example:
Python3
# R program to illustrate dataframe # A vector which is a character vectorName = c("Amiya", "Raj", "Asish") # A vector which is a character vectorLanguage = c("R", "Python", "Java") # A vector which is a numeric vectorAge = c(22, 25, 45) # To create dataframe use data.frame command# and then pass each of the vectors# we have created as arguments# to the function data.frame()df = data.frame(Name, Language, Age) print(df)
Output:
Name Language Age
1 Amiya R 22
2 Raj Python 25
3 Asish Java 45
A matrix is a rectangular arrangement of numbers in rows and columns. In a matrix, as we know rows are the ones that run horizontally and columns are the ones that run vertically. Matrices are two-dimensional, homogeneous data structures.Now, let’s see how to create a matrix in R. To create a matrix in R you need to use the function called matrix. The arguments to this matrix() are the set of elements in the vector. You have to pass how many numbers of rows and how many numbers of columns you want to have in your matrix and this is the important point you have to remember that by default, matrices are in column-wise order.
Example:
Python3
# R program to illustrate a matrix A = matrix( # Taking sequence of elements c(1, 2, 3, 4, 5, 6, 7, 8, 9), # No of rows and columns nrow = 3, ncol = 3, # By default matrices are # in column-wise order # So this parameter decides # how to arrange the matrix byrow = TRUE ) print(A)
Output:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
Arrays are the R data objects which store the data in more than two dimensions. Arrays are n-dimensional data structures. For example, if we create an array of dimensions (2, 3, 3) then it creates 3 rectangular matrices each with 2 rows and 3 columns. They are homogeneous data structures.
Now, let’s see how to create arrays in R. To create an array in R you need to use the function called array(). The arguments to this array() are the set of elements in vectors and you have to pass a vector containing the dimensions of the array.
Example:
Python3
# R program to illustrate an array A = array( # Taking sequence of elements c(1, 2, 3, 4, 5, 6, 7, 8), # Creating two rectangular matrices # each with two rows and two columns dim = c(2, 2, 2) ) print(A)
Output:
, , 1
[,1] [,2]
[1,] 1 3
[2,] 2 4
, , 2
[,1] [,2]
[1,] 5 7
[2,] 6 8
Factors are the data objects which are used to categorize the data and store it as levels. They are useful for storing categorical data. They can store both strings and integers. They are useful to categorize unique values in columns like “TRUE” or “FALSE”, or “MALE” or “FEMALE”, etc.. They are useful in data analysis for statistical modeling.
Now, let’s see how to create factors in R. To create a factor in R you need to use the function called factor(). The argument to this factor() is the vector.
Example:
Python3
# R program to illustrate factors # Creating factor using factor()fac = factor(c("Male", "Female", "Male", "Male", "Female", "Male", "Female")) print(fac)
Output:
[1] Male Female Male Male Female Male Female
Levels: Female Male
sooda367
Picked
R Data-types
R Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Adding elements in a vector in R programming - append() method
Loops in R (for, while, repeat)
Filter data by multiple conditions in R using Dplyr
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python | [
{
"code": null,
"e": 28989,
"s": 28961,
"text": "\n05 Jul, 2021"
},
{
"code": null,
"e": 29242,
"s": 28989,
"text": "A data structure is a particular way of organizing data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of ... |
HAVING with GROUP BY in MySQL | To use HAVING with GROUPBY in MySQL, the following is the syntax. Here, we have set a condition under HAVING to get check for maximum value condition −
SELECT yourColumnName FROM yourTableName GROUP BY yourColumnName HAVING MAX(yourColumnName) < yourValue;
Let us see an example by creating a table in MySQL −
mysql> create table WhereAfterGroupDemo
-> (
-> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> UserProcess int,
-> UserThreadId int
-> );
Query OK, 0 rows affected (5.74 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1211,3);
Query OK, 1 row affected (0.10 sec)
mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1412,3);
Query OK, 1 row affected (0.39 sec)
mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1510,4);
Query OK, 1 row affected (0.19 sec)
mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1511,4);
Query OK, 1 row affected (0.31 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from WhereAfterGroupDemo;
+--------+-------------+--------------+
| UserId | UserProcess | UserThreadId |
+--------+-------------+--------------+
| 1 | 1211 | 3 |
| 2 | 1412 | 3 |
| 3 | 1510 | 4 |
| 4 | 1511 | 4 |
+--------+-------------+--------------+
4 rows in set (0.00 sec)
The following is the query to use HAVING and GROUP BY and get the UserThreaId with process less than 1510 −
mysql> SELECT UserThreadId FROM WhereAfterGroupDemo GROUP BY UserThreadId HAVING MAX(UserProcess) < 1510;
+--------------+
| UserThreadId |
+--------------+
| 3 |
+--------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1214,
"s": 1062,
"text": "To use HAVING with GROUPBY in MySQL, the following is the syntax. Here, we have set a condition under HAVING to get check for maximum value condition −"
},
{
"code": null,
"e": 1319,
"s": 1214,
"text": "SELECT yourColumnName FROM you... |
MongoDB aggregate $slice to get the length of the array | For this, use projectandinthat,size to get the length. Let us first create a collection with documents −
> db.demo382.insertOne(
... {
...
... "Name" : "David",
... "details" : [
... {
... "SubjectName":"MySQL"
... },
... {
... "SubjectName":"MongoDB"
... },
... {
... "SubjectName":"Java"
... }
... ]
...
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5b5e1c22064be7ab44e7f0")
}
Display all documents from a collection with the help of find() method &Minus;
> db.demo382.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e5b5e1c22064be7ab44e7f0"),
"Name" : "David",
"details" : [
{
"SubjectName" : "MySQL"
},
{
"SubjectName" : "MongoDB"
},
{
"SubjectName" : "Java"
}
]
}
Following is the query to aggregate $slice and get the length −
> db.demo382.aggregate([
... { "$match": { "Name": "David" } },
... { "$project": { "count": { "$size": "$details" }}}
... ])
This will produce the following output −
{ "_id" : ObjectId("5e5b5e1c22064be7ab44e7f0"), "count" : 3 } | [
{
"code": null,
"e": 1167,
"s": 1062,
"text": "For this, use projectandinthat,size to get the length. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1580,
"s": 1167,
"text": "> db.demo382.insertOne(\n... {\n...\n... \"Name\" : \"David\",\n... ... |
Bokeh - Customising legends | Various glyphs in a plot can be identified by legend property appear as a label by default at top-right position of the plot area. This legend can be customised by following attributes −
Example code for legend customisation is as follows −
from bokeh.plotting import figure, output_file, show
import math
x2 = list(range(1,11))
y4 = [math.pow(i,2) for i in x2]
y2 = [math.log10(pow(10,i)) for i in x2]
fig = figure(y_axis_type = 'log')
fig.circle(x2, y2,size = 5, color = 'blue', legend = 'blue circle')
fig.line(x2,y4, line_width = 2, line_color = 'red', legend = 'red line')
fig.legend.location = 'top_left'
fig.legend.title = 'Legend Title'
fig.legend.title_text_font = 'Arial'
fig.legend.title_text_font_size = '20pt'
show(fig)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2457,
"s": 2270,
"text": "Various glyphs in a plot can be identified by legend property appear as a label by default at top-right position of the plot area. This legend can be customised by following attributes −"
},
{
"code": null,
"e": 2511,
"s": 2457,
"tex... |
Excel Sheet Column Title in C++ | Suppose we have a positive integer; we have to find its corresponding column title as appear in an Excel sheet. So [1 : A], [2 : B], [26 : Z], [27 : AA], [28 : AB] etc.
So, if the input is like 28, then the output will be AB.
To solve this, we will follow these steps −
while n is non-zero, do −n := n - 1res := res + n mod 26 + ASCII of 'A'n := n / 26
while n is non-zero, do −
n := n - 1
n := n - 1
res := res + n mod 26 + ASCII of 'A'
res := res + n mod 26 + ASCII of 'A'
n := n / 26
n := n / 26
reverse the array res
reverse the array res
return res
return res
Let us see the following implementation to get a better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string convertToTitle(int n) {
string res;
while(n){
res += (--n)%26 + 'A';
n /= 26;
}
reverse(res.begin(), res.end());
return res;
}
};
main(){
Solution ob;
cout << (ob.convertToTitle(30));
}
30
AD | [
{
"code": null,
"e": 1231,
"s": 1062,
"text": "Suppose we have a positive integer; we have to find its corresponding column title as appear in an Excel sheet. So [1 : A], [2 : B], [26 : Z], [27 : AA], [28 : AB] etc."
},
{
"code": null,
"e": 1288,
"s": 1231,
"text": "So, if the in... |
Yii - Logging | Yii provides a highly customizable and extensible framework. With the help of this framework, you can easily log various types of messages.
To log a message, you should call one of the following methods −
Yii::error() − Records a fatal error message.
Yii::error() − Records a fatal error message.
Yii::warning() − Records a warning message.
Yii::warning() − Records a warning message.
Yii::info() − Records a message with some useful information.
Yii::info() − Records a message with some useful information.
Yii::trace() − Records a message to trace how a piece of code runs.
Yii::trace() − Records a message to trace how a piece of code runs.
The above methods record log messages at various categories. They share the following function signature −
function ($message, $category = 'application')
where −
$message − The log message to be recorded
$message − The log message to be recorded
$category − The category of the log message
$category − The category of the log message
A simple and convenient way of naming scheme is using the PHP __METHOD__ magic constant. For example −
Yii::info('this is a log message', __METHOD__);
A log target is an instance of the yii\log\Target class. It filters all log messages by categories and exports them to file, database, and/or email.
Step 1 − You can register multiple log target as well, like.
return [
// the "log" component is loaded during bootstrapping time
'bootstrap' => ['log'],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\DbTarget',
'levels' => ['error', 'warning', 'trace', 'info'],
],
[
'class' => 'yii\log\EmailTarget',
'levels' => ['error', 'warning'],
'categories' => ['yii\db\*'],
'message' => [
'from' => ['log@mydomain.com'],
'to' => ['admin@mydomain.com', 'developer@mydomain.com'],
'subject' => 'Application errors at mydomain.com',
],
],
],
],
],
];
In the code above, two targets are registered. The first target selects all errors, warnings, traces, and info messages and saves them in a database. The second target sends all error and warning messages to the admin email.
Yii provides the following built-in log targets −
yii\log\DbTarget − Stores log messages in a database.
yii\log\DbTarget − Stores log messages in a database.
yii\log\FileTarget − Saves log messages in files.
yii\log\FileTarget − Saves log messages in files.
yii\log\EmailTarget − Sends log messages to predefined email addresses.
yii\log\EmailTarget − Sends log messages to predefined email addresses.
yii\log\SyslogTarget − Saves log messages to syslog by calling the PHP
function syslog().
yii\log\SyslogTarget − Saves log messages to syslog by calling the PHP
function syslog().
By default, log messages are formatted as follows −
Timestamp [IP address][User ID][Session ID][Severity Level][Category] Message Text
Step 2 − To customize this format, you should configure the yii\log\Target::$prefix property. For example.
[
'class' => 'yii\log\FileTarget',
'prefix' => function ($message) {
$user = Yii::$app->has('user', true) ? Yii::$app->get('user') :
'undefined user';
$userID = $user ? $user->getId(false) : 'anonym';
return "[$userID]";
}
]
The above code snippet configures a log target to prefix all log messages with the current userID.
By default, log messages include the values from these global PHP variables: $_GET, $_POST, $_SESSION, $_COOKIE, $_FILES, and $_SERVER. To modify this behavior, you should configure the yii\log\Target::$logVars property with the names of variables that you want to include.
All log messages are maintained in an array by the logger object. The logger object flushed the recorded messages to the log targets each time the array accumulates a certain number of messages(default is 1000).
Step 3 − To customize this number, you should call the flushInterval property.
return [
'bootstrap' => ['log'],
'components' => [
'log' => [
'flushInterval' => 50, // default is 1000
'targets' => [...],
],
],
];
Even when the logger object flushes log messages to log targets, they do not get exported immediately. The export occurs when a log target accumulates a certain number of messages(default is 1000).
Step 4 − To customize this number, you should configure the exportInterval property.
[
'class' => 'yii\log\FileTarget',
'exportInterval' => 50, // default is 1000
]
Step 5 − Now, modify the config/web.php file this way.
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this
//is required by cookie validation
'cookieValidationKey' => 'ymoaYrebZHa8gURuolioHGlK8fLXCKjO',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'flushInterval' => 1,
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'exportInterval' => 1,
'logVars' => []
],
],
],
'db' => require(__DIR__ . '/db.php'),
],
'modules' => [
'hello' => [
'class' => 'app\modules\hello\Hello',
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
?>
In the above code, we define the log application component, set the flushInterval and exportInteval properties to 1 so that all log messages appear in the log files immediately. We also omit the levels property of the log target. It means that log messages of all categories(error, warning, info, trace) will appear in the log files.
Step 6 − Then, create a function called actionLog() in the SiteController.
public function actionLog() {
Yii::trace('trace log message');
Yii::info('info log message');
Yii::warning('warning log message');
Yii::error('error log message');
}
In the above code, we just write four log messages of different categories to the log files.
Step 7 − Type the URL http://localhost:8080/index.php?r=site/log in the address bar of the web browser. Log messages should appear under the app/runtime/logs directory in the app.log file.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2973,
"s": 2833,
"text": "Yii provides a highly customizable and extensible framework. With the help of this framework, you can easily log various types of messages."
},
{
"code": null,
"e": 3038,
"s": 2973,
"text": "To log a message, you should call one of t... |
SIP - Forking | Sometime a proxy server forwards a single SIP call to multiple SIP endpoints. This process is known as forking. Here a single call can ring many endpoints at the same time.
With SIP forking, you can have your desk phone ring at the same time as your softphone or a SIP phone on your mobile, allowing you to take the call from either device easily.
Generally, in an office, suppose boss unable to pick the call or away, SIP forking allow the secretary to answer calls his extension.
Forking will be possible if there is a stateful proxy available as it needs to perform and response out of the many it receives.
We have two types of forking −
Parallel Forking
Sequential Forking
In this scenario, the proxy server will fork the INVITE to, say, two devices (UA2, UA3) at a time. Both the devices will generate 180 Ringing and whoever receives the call will generate a 200 OK. The response (suppose UA2) that reaches the Originator first will establish a session with UA2. For the other response, a CANCEL will be triggered.
If the originator receives both the responses simultaneously, then based on q-value, it will forward the response.
In this scenario, the proxy server will fork the INVITE to one device (UA2). If UA2 is unavailable or busy at that time, then the proxy will fork it to another device (UA3).
Branch IDs help proxies to match responses to forked requests. Without Branch IDs, a proxy server would not be able to understand the forked response. Branch-id will be available in Via header.
Tags are used by the UAC to distinguish multiple final responses from different UAS. A UAS cannot resolve whether the request has been forked or not. Therefore, it need to add a tag.
Proxies also can add tags if it generates a final response, they never insert tags into requests or responses they forward.
It may be possible that a single request can be forked by multiple proxy servers also. So the proxy which would fork shall add its own unique IDs to the branches it created.
A call leg refers to one to one signalling relationship between two user agents. The call ID is a unique identifier carried in SIP message that refers to the call. A call is a collection of call legs.
A UAC starts by sending an INVITE. Due to forking, it may receive multiple 200 OK from different UAs. Each corresponds to a different call leg within the same call.
A call is thus a group of call legs. A call leg refers to end-to-end connection between UAs.
The CSeq spaces in the two directions of a call leg are independent. Within a single direction, the sequence number is incremented for each transaction.
Voicemail is very common now-a-days for enterprise users. It’s a telephone application. It comes to picture when the called party is unavailable or unable to receive the call, the PBX will announce to calling party to leave a voice message.
User agent will either get a 3xx response or redirect to voicemail server if the called party’s number is unreachable. However, some kind of SIP extension is needed to indicate to the voicemail system which mailbox to use—that is, which greeting to play and where to store the recorded message. There are two ways to achieve this −
By using a SIP header field extension
By using a SIP header field extension
By using the Request-URI to signal this information
By using the Request-URI to signal this information
Suppose for the user sip:Tom@tutorialspoint.com has a voicemail system at sip:voicemail.tutorialspoint.com which is providing voicemail, the Request-URI of the INVITE when it is forwarded to the voicemail server could look like −
sip:voicemail.tutorialspoint.com;target = sip:Tom@tutorialspoint.com;cause = 486
The following illustration shows how the Request-URI carries the mailbox identifier and the reason (here 486).
27 Lectures
2.5 hours
Bernie Raffe
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2023,
"s": 1850,
"text": "Sometime a proxy server forwards a single SIP call to multiple SIP endpoints. This process is known as forking. Here a single call can ring many endpoints at the same time."
},
{
"code": null,
"e": 2198,
"s": 2023,
"text": "With SIP ... |
How to validate if input in input field has BIC or Swift code only using express-validator ? - GeeksforGeeks | 30 Jul, 2020
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. When working with a bank system, In a certain input field only a valid Bank identification code(BIC) is allowed. BIC is an 8 or 11 digit string. It represents a valid bank with its location uniquely. We can also validate these input fields to accept only valid BIC using express-validator middleware.
Condition to be a valid BIC:
Bank Code: 4 letter code and only upper case alphabets are allowed.
Country Code: 2 letter code and only upper case alphabets are allowed.
Location Code: 2 letter code, either digits (0 to 9) or upper case alphabets are allowed.
Branch Code: 3 letter optional code, either digits (0 to 9) or upper case alphabets are allowed.
Command to install express-validator:
npm install express-validator
Steps to use express-validator to implement the logic:
Install express-validator middleware.
Create a validator.js file to code all the validation logic.
Validate input by validateInputField: check(input field name) and chain on the validation isBIC() with ‘ . ‘
Use the validation name(validateInputField) in the routes as a middleware as an array of validations.
Destructure ‘validationResult’ function from express-validator to use it to find any errors.
If error occurs redirect to the same page passing the error information.
If error list is empty, give access to the user for the subsequent request.
Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql.
Example: This example illustrates how to validate a input field to accept only valid BIC.
Filename – index.js
const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateBic } = require('./validator')const formTemplet = require('./form')const showTemplet = require('./show') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic and app.post( '/account', [validateBic], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()){ return res.send(formTemplet({errors})) } const {aNumber, bic} = req.body const account = await repo.getOneBy({ 'accountNumber': aNumber, 'bic': bic }) if(account){ console.log(account) res.send(showTemplet(account)) }else{ res.send('<strong>Account Not Found</strong>') }}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})
Filename – repository.js: This file contains all the logic to create a local database and interact with it.
// Importing node.js file system module const fs = require('fs') class Repository { constructor(filename) { // The filename where datas are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Find record by property async getOneBy(filters){ const records = await this.getAll() for(let record of records){ let found = true for(let key in filters){ if(record[key] !== filters[key]){ found = false } } if(found) return record; } } } // The 'datastore.json' file created at runtime // and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')
Filename – form.js: This file contains logic to show the form to fetch bank Information.
const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' } } module.exports = ({errors}) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/account' method='POST'> <div> <div> <label class='label' id='aNumber'> Account Number </label> </div> <input class='input' type='text' name='aNumber' placeholder='Account Number' for='aNumber'> </div> <div> <div> <label class='label' id='bic'> Bank Identification Code </label> </div> <input class='input' type='text' name='bic' placeholder='BIC' for='bic'> <p class="help is-danger"> ${getError(errors, 'bic')} </p> </div> <div> <button class='button is-primary'> Submit </button> </div> </form> </div> </div> </div> </body> </html> `}
Filename – show.js: This file contains logic to show the fetched bank information.
module.exports = (account) => { return ` <div> <div> <strong>Account Name :</strong> ${account.accountName} </div> <div> <strong>Account Number :</strong> ${account.accountNumber} </div> <div> <strong>Account Type :</strong> ${account.accountType} </div> <div> <strong>BIC :</strong> ${account.bic} </div> <div> <strong>Bank Name :</strong> ${account.bankName} </div> <div> <strong>Bank Location :</strong> ${account.bankLocation} </div> <div> `}
Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to accept only valid BIC).
const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateBic : check('bic') // To delete leading and trialing space .trim() // Validate input field to accept only BIC .isBIC() .withMessage('Must be a valid Bank identification code')}
Filename – package.json
package.json file
Database:
Database
Output:
Invalid first two digit(Only Alphabets allowed)
Invalid 3rd and 4th digit(Only Alphabets allowed)
Invalid 5th and 6th digit(Only Alphabets allowed)
Response when submit invalid BIC(In first three cases)
valid BIC
Response when submit valid BIC
Note: We have used some Bulma classes(CSS framework) in the form.js file to design the content.
Express.js
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Difference between promise and async await in Node.js
How to read and write Excel file in Node.js ?
Express.js res.render() Function
How to use an ES6 import in Node.js?
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24694,
"s": 24666,
"text": "\n30 Jul, 2020"
},
{
"code": null,
"e": 25215,
"s": 24694,
"text": "In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow onl... |
Removing nth character from a string in Python program | In this article, we will learn about the solution to the problem statement given below −
We are given a string, we have to remove the ith indexed character from the given string and display it.
In any string in Python, indexing always starts from 0. Suppose we have a string “tutorialspoint” then its indexing will be done as shown below −
T u t o r i a l s p o i n t
0 1 2 3 4 5 6 7 8 9 10 11 12 13
Now let’s see the Python script gfor solving the statement −
Live Demo
def remove(string, i):
# slicing till ith character
a = string[ : i]
# slicing from i+1th index
b = string[i + 1: ]
return a + b
# Driver Code
if __name__ == '__main__':
string = "Tutorialspoint"
# Remove nth index element
i = 8
print(remove(string, i))
Tutorialpoint
From the given input string, i-th indexed element has to be popped. So, Split the string into two parts, before indexed character and after indexed character thereby leaving the ith character Return the merged string.
Here we have three variables declared in global scope as shown below −
In this article, we learnt about the removal of ith character from a given input string in Python 3.x or earlier | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "In this article, we will learn about the solution to the problem statement given below −"
},
{
"code": null,
"e": 1256,
"s": 1151,
"text": "We are given a string, we have to remove the ith indexed character from the given string and ... |
CSS | :not(:last-child):after Selector - GeeksforGeeks | 30 Jul, 2021
Often we encounter a situation in front-end web development where we have a number of elements in HTML and we need to give a specific style to just the last element or to every element except the last element or basically to that element which cannot be selected directly. There comes the use of pseudo selectors. This article explains the :not(:last-child):after selector. This selector does not select the element after the last child element. It is mostly used to add the content after every child element except the last.Example 1: This example creates a simple div element. It does not uses :not(:last-child):after selector.
html
<!DOCTYPE html><html> <head> <style> div { width: 100px; height: 100px; outline: 1px solid; margin: 10px; box-shadow: 0 0 5px black; background: green; font-family: 'Segoe UI', sans-serif; display: flex; flex-direction: column; justify-content: space-around; align-items: center; } .inner-div { width: 90%; height: 45%; background: white; margin: 0 auto; padding-left: 2px; } </style></head> <body> <div class="div"> <div class="inner-div"></div> <div class="inner-div"></div> </div> <div class="div"> <div class="inner-div"></div> <div class="inner-div"></div> </div> <div class="div"> <div class="inner-div"></div> <div class="inner-div"></div> </div></body> </html>
Output:
Example 2: After applying the pseudo selector :not(:last-child):after to the above example.
html
<!DOCTYPE html><html> <head> <style> div { width: 100px; height: 100px; outline: 1px solid; margin: 10px; box-shadow: 0 0 5px black; background: green; font-family: 'Segoe UI', sans-serif; display: flex; flex-direction: column; justify-content: space-around; align-items: center; } .inner-div { width: 90%; height: 45%; background: white; margin: 0 auto; padding-left: 2px; } .div .inner-div:not(:last-child):after { content: 'not in the bottom div'; } </style></head> <body> <div class="div"> <div class="inner-div"></div> <div class="inner-div"></div> </div> <div class="div"> <div class="inner-div"></div> <div class="inner-div"></div> </div> <div class="div"> <div class="inner-div"></div> <div class="inner-div"></div> </div></body> </html>
Output:
Explanation:
.div .inner-div: Selects all the elements with class ‘inner-div’ inside elements with ‘div’ class. Here, all three divs have class ‘div’ with two children divs with class ‘inner-div’. It selects all six div element with class name ‘inner-div’.
:not(:last-child) The :not() selector excludes the element passed to it from selection.The :last-child selector selects the last child.Combining these two above selector to excludes the last children (inner-div) of every parent div from the selection.
The :not() selector excludes the element passed to it from selection.
The :last-child selector selects the last child.
Combining these two above selector to excludes the last children (inner-div) of every parent div from the selection.
:after This is a great selector to add content (or sometimes, even block-level elements) after the selected elements (Here the first inner-div in every set of inner-divs). So, the content ‘not in the bottom div’ is indeed only added in the top div and not in the bottom div.
Example 3:
html
<!DOCTYPE html><html> <head> <style> li:not(:last-child):after { content: ' || '; color:green; font-weight:bold; } li { display: inline; } </style></head> <body style="text-align:center;"> <h1 style="color:green;">GeeksforGeeks</h1> <h3>CSS :not(:last-child):after Selector</h3> <div>GeeksforGeeks Subjects</div> <ul> <li>Data Structure</li> <li>Algorithm</li> <li>HTML</li> <li>CSS</li> <li>JavaScript</li> </ul></body>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
Akanksha_Rai
ysachin2314
Picked
CSS
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
How to set div width to fit content using CSS ?
Making a div vertically scrollable using CSS
How to set fixed width for <td> in a table ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 24664,
"s": 24636,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 25296,
"s": 24664,
"text": "Often we encounter a situation in front-end web development where we have a number of elements in HTML and we need to give a specific style to just the last elemen... |
How to update multiple rows and left pad values in MySQL? | Use the LPAD() function to left pad values. Let us first create a table −
mysql> create table DemoTable
-> (
-> Number int
-> );
Query OK, 0 rows affected (2.26 sec
Insert some records in the table using insert command −
mysql> insert into DemoTable values(857786);
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values(89696);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(89049443);
Query OK, 1 row affected (0.25 sec
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------+
| Number |
+----------+
| 857786 |
| 89696 |
| 89049443 |
+----------+
3 rows in set (0.00 sec)
Following is the query to update multiple rows and left pad values −
mysql> update DemoTable set Number=LPAD(Number, 7, "9") where length(Number) < 7;
Query OK, 2 rows affected (0.40 sec)
Rows matched: 2 Changed: 2 Warnings: 0
Let us check table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+----------+
| Number |
+----------+
| 9857786 |
| 9989696 |
| 89049443 |
+----------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1136,
"s": 1062,
"text": "Use the LPAD() function to left pad values. Let us first create a table −"
},
{
"code": null,
"e": 1236,
"s": 1136,
"text": "mysql> create table DemoTable\n -> (\n -> Number int\n -> );\nQuery OK, 0 rows affected (2.26 sec"
}... |
Creating custom user model API extending AbstractUser in Django - GeeksforGeeks | 25 Oct, 2021
Every new Django project should use a custom user model. The official Django documentation says it is “highly recommended” but I’ll go a step further and say without hesitation: You are straight up crazy not to use a custom user model up front.
Why do u need a custom user model in Django?
When you start your project with a custom user model, stop to consider if this is the right choice for your project. Keeping all user related information in one model removes the need for additional or more complex database queries to retrieve related models. On the other hand, it may be more suitable to store app-specific user information in a model that has a relation with your custom user model. That allows each app to specify its own user data requirements without potentially conflicting or breaking assumptions by other apps. It also means that you would keep your user model as simple as possible, focused on authentication, and following the minimum requirements Django expects custom user models to meet.
So i think its clear why we need a custom user model in django, here in this article we are going to learn how to create custom user model and its api in django now, lets begin with the coding part .
Setup –
Create and navigate into a dedicated directory called users for our code
Create and navigate into a dedicated directory called users for our code
make a new Django project called login
make a new Django project called login
make a new app users
make a new app users
start the local web server
start the local web server
Commands –
$ cd ~/Desktop$ mkdir code && cd code
$ pipenv install django
$ pipenv shell
$ django-admin startproject login
$ python manage.py startapp api
$ pipenv install rest_framework
Now, add following code in settings.py,
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Add these lines to to your # installed apps section in settings. py 'rest_framework', 'rest_framework.authtoken', 'api', 'rest_auth']AUTH_USER_MODEL ='api.urls'REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ),}
After this we need to create a custom user model. For this change your models.py file as following. Here we are extending AbstractUser and changing authentication credentials to Email. And we are also adding some extra fields in our custom user
from django.db import modelsfrom django.contrib.auth.models import AbstractUserfrom django.utils.translation import ugettext_lazy as _from django.conf import settingsfrom datetime import dateclass User(AbstractUser): username = models.CharField(max_length = 50, blank = True, null = True, unique = True) email = models.EmailField(_('email address'), unique = True) native_name = models.CharField(max_length = 5) phone_no = models.CharField(max_length = 10) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] def __str__(self): return "{}".format(self.email)
After this we need to save these changes to the admin panel as well. Add this code to the admin.py
from django.contrib import adminfrom django.utils.translation import ugettext_lazy as _from django.contrib.auth.admin import UserAdmin as BaseUserAdminfrom django.contrib.auth import get_user_modelfrom django.contrib.auth.admin import UserAdminfrom .models import Userclass UserAdmin(BaseUserAdmin): form = UserChangeForm fieldsets = ( (None, {'fields': ('email', 'password', )}), (_('Personal info'), {'fields': ('first_name', 'last_name')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), (_('user_info'), {'fields': ('native_name', 'phone_no')}), ) add_fieldsets = ( (None, { 'classes': ('wide', ), 'fields': ('email', 'password1', 'password2'), }), ) list_display = ['email', 'first_name', 'last_name', 'is_staff', 'native_name', 'phone_no'] search_fields = ('email', 'first_name', 'last_name') ordering = ('email', )admin.site.register(User, UserAdmin)
Now create a serializers.py file in your app. Add following code to your serializers. py
rom rest_framework import serializersfrom api.models import Userclass UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__"
Now create api/urls.py file inside you app and add following lines
from django.contrib import adminfrom django.urls import pathfrom django.conf.urls import includeurlpatterns = [ path('auth/', include('rest_auth.urls')),]
Now add following code to the login/urls.py of your project
from django.contrib import adminfrom django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path(" ", include("api.urls"))]
We are all set with the custom user model. Now save these changes to you project and makemigrations through CLI
$ python manage.py makemigrations users
$ python manage.py migrate
Now create a superuser
$ python manage.py createsuperuser
Email address: test@test.com
Password:
Password (again):
Superuser created successfully.
Now run server with.
$ python manage.py runserver
And go through the URL. You can check your custom user in the admin panel
Output –
surindertarika1234
Python Django
Project
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Twitter Sentiment Analysis using Python
OpenCV C++ Program for Face Detection
Java Swing | Simple User Registration Form
Face Detection using Python and OpenCV with webcam
Snake Game in C
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": 24976,
"s": 24948,
"text": "\n25 Oct, 2021"
},
{
"code": null,
"e": 25221,
"s": 24976,
"text": "Every new Django project should use a custom user model. The official Django documentation says it is “highly recommended” but I’ll go a step further and say witho... |
How to display the current working directory in the Linux system? | To print the current working directory, we use the pwd command in the Linux system.
pwd (print working directory) – The pwd command is used to display the name of the current working directory in the Linux system using the terminal. This is a shell building command that is available in most Unix shells such as Bourne shell, ash, bash, kash, and zsh.
The general syntax of the pwd command is as follows −
pwd [-LP]
A brief description of options available in the pwd command.
By default, the pwd works as if -L option was specified.
The pwd command returns true unless an invalid option supplied or the current directory could not be read.
To display the current working directory, we use the pwd command in the Linux/Unix system as shown below.
vikash@tutorialspoint:~ pwd
/home/vikash
To display the physical directory instead of symbolic links or soft links, we use -P option with the pwd command in the Linux/Unix system as shown below.
vikash@tutorialspoint:~ pwd -P
/home/vikash
To display more about the pwd command we use -help option with the pwd command as shown below.
vikash@tutorialspoint:~ pwd --help
After execution of above command. It will be prompt a short description with available options available in the pwd command. | [
{
"code": null,
"e": 1146,
"s": 1062,
"text": "To print the current working directory, we use the pwd command in the Linux system."
},
{
"code": null,
"e": 1414,
"s": 1146,
"text": "pwd (print working directory) – The pwd command is used to display the name of the current working... |
What is a final parameter in java? | You can pass final variables as the parameters to methods in Java.
A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object. However, the data within the object can be changed. So, the state of the object can be changed but not the reference. With variables, the final modifier often is used with static to make the constant a class variable.
Live Demo
public class Test{
public void sample(final int data){
System.out.println(data);
}
public static void main(String args[]) throws Exception{
Test t = new Test();
t.sample(500);
}
}
500 | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "You can pass final variables as the parameters to methods in Java."
},
{
"code": null,
"e": 1497,
"s": 1129,
"text": "A final variable can be explicitly initialized only once. A reference variable declared final can never be reassign... |
Assembly - File Management | The system considers any input or output data as stream of bytes. There are three standard file streams −
Standard input (stdin),
Standard output (stdout), and
Standard error (stderr).
A file descriptor is a 16-bit integer assigned to a file as a file id. When a new file is created or an existing file is opened, the file descriptor is used for accessing the file.
File descriptor of the standard file streams - stdin, stdout and stderr are 0, 1 and 2, respectively.
A file pointer specifies the location for a subsequent read/write operation in the file in terms of bytes. Each file is considered as a sequence of bytes. Each open file is associated with a file pointer that specifies an offset in bytes, relative to the beginning of the file. When a file is opened, the file pointer is set to zero.
The following table briefly describes the system calls related to file handling −
The steps required for using the system calls are same, as we discussed earlier −
Put the system call number in the EAX register.
Store the arguments to the system call in the registers EBX, ECX, etc.
Call the relevant interrupt (80h).
The result is usually returned in the EAX register.
For creating and opening a file, perform the following tasks −
Put the system call sys_creat() number 8, in the EAX register.
Put the filename in the EBX register.
Put the file permissions in the ECX register.
The system call returns the file descriptor of the created file in the EAX register, in case of error, the error code is in the EAX register.
For opening an existing file, perform the following tasks −
Put the system call sys_open() number 5, in the EAX register.
Put the filename in the EBX register.
Put the file access mode in the ECX register.
Put the file permissions in the EDX register.
The system call returns the file descriptor of the created file in the EAX register, in case of error, the error code is in the EAX register.
Among the file access modes, most commonly used are: read-only (0), write-only (1), and read-write (2).
For reading from a file, perform the following tasks −
Put the system call sys_read() number 3, in the EAX register.
Put the system call sys_read() number 3, in the EAX register.
Put the file descriptor in the EBX register.
Put the file descriptor in the EBX register.
Put the pointer to the input buffer in the ECX register.
Put the pointer to the input buffer in the ECX register.
Put the buffer size, i.e., the number of bytes to read, in the EDX register.
Put the buffer size, i.e., the number of bytes to read, in the EDX register.
The system call returns the number of bytes read in the EAX register, in case of error, the error code is in the EAX register.
For writing to a file, perform the following tasks −
Put the system call sys_write() number 4, in the EAX register.
Put the system call sys_write() number 4, in the EAX register.
Put the file descriptor in the EBX register.
Put the file descriptor in the EBX register.
Put the pointer to the output buffer in the ECX register.
Put the pointer to the output buffer in the ECX register.
Put the buffer size, i.e., the number of bytes to write, in the EDX register.
Put the buffer size, i.e., the number of bytes to write, in the EDX register.
The system call returns the actual number of bytes written in the EAX register, in case of error, the error code is in the EAX register.
For closing a file, perform the following tasks −
Put the system call sys_close() number 6, in the EAX register.
Put the file descriptor in the EBX register.
The system call returns, in case of error, the error code in the EAX register.
For updating a file, perform the following tasks −
Put the system call sys_lseek () number 19, in the EAX register.
Put the file descriptor in the EBX register.
Put the offset value in the ECX register.
Put the reference position for the offset in the EDX register.
The reference position could be:
Beginning of file - value 0
Current position - value 1
End of file - value 2
The system call returns, in case of error, the error code in the EAX register.
The following program creates and opens a file named myfile.txt, and writes a text 'Welcome to Tutorials Point' in this file. Next, the program reads from the file and stores the data into a buffer named info. Lastly, it displays the text as stored in info.
section .text
global _start ;must be declared for using gcc
_start: ;tell linker entry point
;create the file
mov eax, 8
mov ebx, file_name
mov ecx, 0777 ;read, write and execute by all
int 0x80 ;call kernel
mov [fd_out], eax
; write into the file
mov edx,len ;number of bytes
mov ecx, msg ;message to write
mov ebx, [fd_out] ;file descriptor
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel
; close the file
mov eax, 6
mov ebx, [fd_out]
; write the message indicating end of file write
mov eax, 4
mov ebx, 1
mov ecx, msg_done
mov edx, len_done
int 0x80
;open the file for reading
mov eax, 5
mov ebx, file_name
mov ecx, 0 ;for read only access
mov edx, 0777 ;read, write and execute by all
int 0x80
mov [fd_in], eax
;read from file
mov eax, 3
mov ebx, [fd_in]
mov ecx, info
mov edx, 26
int 0x80
; close the file
mov eax, 6
mov ebx, [fd_in]
int 0x80
; print the info
mov eax, 4
mov ebx, 1
mov ecx, info
mov edx, 26
int 0x80
mov eax,1 ;system call number (sys_exit)
int 0x80 ;call kernel
section .data
file_name db 'myfile.txt'
msg db 'Welcome to Tutorials Point'
len equ $-msg
msg_done db 'Written to file', 0xa
len_done equ $-msg_done
section .bss
fd_out resb 1
fd_in resb 1
info resb 26
When the above code is compiled and executed, it produces the following result −
Written to file
Welcome to Tutorials Point
46 Lectures
2 hours
Frahaan Hussain
23 Lectures
12 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2191,
"s": 2085,
"text": "The system considers any input or output data as stream of bytes. There are three standard file streams −"
},
{
"code": null,
"e": 2215,
"s": 2191,
"text": "Standard input (stdin),"
},
{
"code": null,
"e": 2245,
"s": ... |
Push() vs unshift() in JavaScript? | The methods push() and unshift() are used to add an element in an array. But they have a slight variation. The method push() is used to add an element at the end of the array, whereas the method unshift() is used to add the element at the start of the array. Let's discuss them in detail.
array.push("element");
In the following example, to a 3 element array, using push() method another element is added at the back of the array and the result is displayed in the output.
<html>
<body>
<script>
var companies = ["Spacex", "Hyperloop", "Solarcity"];
document.write("Before push:" +" "+ companies);
companies.push("Tesla");
document.write("</br>");
document.write("After push:" +" "+ companies);
</body>
</html>
Before push: Spacex,Hyperloop,Solarcity
After push: Spacex,Hyperloop,Solarcity,Tesla
array.unshift("element");
In the following example, to a 3 element array, using unshift() method another element is added at the start of the array and the result is displayed in the output.
<html>
<body>
<script>
var companies = ["Spacex", "Hyperloop", "Solarcity"];
document.write("Before unshift:" +" "+ companies);
companies.unshift("Tesla");
document.write("</br>");
document.write("After unshift:" +" "+ companies);
</script>
</body>
</html>
Before unshift: Spacex,Hyperloop,Solarcity
After unshift: Tesla,Spacex,Hyperloop,Solarcity | [
{
"code": null,
"e": 1351,
"s": 1062,
"text": "The methods push() and unshift() are used to add an element in an array. But they have a slight variation. The method push() is used to add an element at the end of the array, whereas the method unshift() is used to add the element at the start of the a... |
Tableau Server impact analysis reports: accessing metadata | by Elliott Stam | Towards Data Science | All good adventures begin with a first step. In this tutorial, the first step we take to build an impact analysis report for Tableau Server is collecting information about the relationships between our workbooks, visuals, and underlying database assets.
If you have no idea what I’m talking about, take a few minutes to check out the intro post, which kicks off this series of tutorials demonstrating how we can build impact analysis reporting for Tableau.
To summarize, our goal is to pull valuable metadata that exists in every Tableau ecosystem and provide an outline for how you can spin that data into insights. This is all about improving the productivity of our data teams and providing tailored visual information about our data lineage that anyone capable of clicking a mouse can easily interact with.
So let’s get started!
I want to get into the how as quickly as possible, but explaining the what is important. Our first step requires us to get our hands on some crucial information that will allow us to answer these types of questions:
How many of our visuals will be impacted if a specific database asset goes down? How can we know exactly what data feeds into our Tableau Server environment?Are the impacted visuals dashboards or just worksheets? What types of connections do they have, and are these connections embedded in individual workbooks or are they published?Do we have a lot of duplicated connections that could be consolidated into published datasources for better scalability and governance?Considering all the database connections we use, which specific tables are the most critical? How many Tableau workbooks reference those tables?
How many of our visuals will be impacted if a specific database asset goes down? How can we know exactly what data feeds into our Tableau Server environment?
Are the impacted visuals dashboards or just worksheets? What types of connections do they have, and are these connections embedded in individual workbooks or are they published?
Do we have a lot of duplicated connections that could be consolidated into published datasources for better scalability and governance?
Considering all the database connections we use, which specific tables are the most critical? How many Tableau workbooks reference those tables?
We could go on, but I think you get the point. The repeating themes of these questions are: workbooks, datasources, and database tables.
Let’s dive into this tutorial’s mission: pulling data from the Metadata API and shaping it into something that gets us closer to answering the questions above.
The saying goes, “there’s more than one way to skin a cat.” I’ve always liked cats, so I never loved this phrase. The reason I bring it up is that it’s wildly appropriate for the situation we find ourselves in with Tableau’s Metadata API.
For starters, you can take the no-code approach, or you can flip that on its head and do everything with code. Yep, there’s something for everyone.
We’ll begin with the no-code approach. You can use this to throw together a quick proof of concept or rely on it as your go-to data collection method if it provides exactly what you need and you don’t mind a bit of manual labor.
After covering the no-code approach, we’ll stretch our Python muscles and pave the way for you to integrate the Metadata API into automated workflows. Going the Python route will also allow us to do some nifty things such as enriching our metadata with contextual information available through other sources.
Regardless of your chosen method, you’re going to need to be on Tableau Server 2019.3 or later in order to use the Metadata API. If you use Tableau Online, you’re good to go. Did you know you can request a free Tableau Online sandbox site by joining their developer community? Now you know.
That covers the scope of this tutorial, though I think I’ll toss in one or two basic Tableau visuals at the end to prove that the data we pull is real and to highlight the value hiding within.
In future tutorials, Python will continue to emerge as a melting pot that will be our central focus for querying Metadata, the repository database, and the creation of .hyper extracts fueling our eventual impact analysis dashboards.
Without needing to write a script that authenticates into your Tableau Server environment and fetches information, you can go to this URL to access your metadata:
https://<your-tableau-server>.com/metadata/graphiql
You’ll be prompted to authenticate with your username and password as you normally would, but instead of seeing the usual interface you will land on the built-in GraphQL interface. By the way that is not a typo in the sample link above. It is ‘graphiql’ with an ‘i’ in it.
From here you can freestyle on building some basic GraphQL queries. Did I say no code earlier? Don’t worry, you’ll be fine. Feel free to just copy and paste these sample queries. If you’re the adventurous type, head over to the Metadata API documentation to master all the things.
For example, running this basic query will fetch you all of the workbook names, workbook IDs, and workbook owners on your site:
{ workbooks { name luid owner { name email } }}
The response will appear on the right half of your GraphQL interface in JSON format. My output looked like this:
Did you know you can connect Tableau Desktop directly to JSON files? Yep, getting Metadata into a dashboard can be that easy. Just copy the JSON output and paste it into a text file. Save the file with a .json extension, and you’re set.
Below you’ll find the whole process in action, using a more advanced query in place of the toy example provided above. The query can be found in this Github Gist:
After you store the resulting JSON data to a .json file, open Tableau Desktop and connect to the file.
Select all the schemas available in the .json file and click ‘OK’.
That’s all it took — the data is in your hands now!
Doing things manually doesn’t cut it for everyone, myself included. Let’s cover how you can land at the same results we see above, but using code. This will set us up for nearly limitless customization as we look ahead to future tutorials, so I highly recommend investing time into the Python route.
I use the tableau-api-lib and pandas Python packages extensively in my Tableau Server automation workflows, so if you are following along then you will want to run this command in your command line:
pip install --upgrade tableau-api-libpip install --upgrade pandas
The full Python script relevant to this section can be found in this GitHub Gist:
New to Python? Download it and begin this life anew.
To briefly summarize what’s happening in that Python code, we are establishing a connection to a Tableau Server (or Tableau Online) site and running GraphQL queries against the Metadata API. The queries in this tutorial target workbooks, views, and their underlying database assets. You could of course expand upon these queries, and I encourage you to do so. We will certainly revisit this in later tutorials and build upon what’s covered here.
The GraphQL queries return JSON data. While we can feed that directly into Tableau, let’s plan ahead to future milestones in this project of ours where we want to combine our metadata with other sources of data, such as the repository database, which will provide all sorts of context including the last time someone interacted with our visuals.
To set ourselves up for future success, it’s worth taking the time to flatten our JSON data into multiple normalized tables and then combine those into a single ‘denormalized’ table. This will play very nicely with other one-off Metadata API queries and the various PostgreSQL queries we will put to work in upcoming tutorials.
Now, let’s toss in some visual context and see what this data can do for us.
To get a feel for the value this data can provide to us in terms of creating impact analysis reports, we already have a lot of the raw ingredients we need to cook up something useful.
With thirty seconds of drag-and-drop action, we’ve created the worksheet shown above! We can use the underlying data to build out customized data lineage audits, shame our least favorite business unit for using more worksheets than dashboards, and more.
We are now well on our way to being able to answer the questions laid out earlier in this tutorial. We’ve built a flashlight that can cast light on the darkest corners of our Tableau ecosystem.
That’s a wrap for our first milestone on this adventure building detailed and interactive impact analysis reports in Tableau. We’ve tapped into Tableau’s Metadata API and pulled enough data to build visuals describing the underlying database assets feeding our Tableau visuals. We demonstrated two methods to collect that data: manually via the built-in ‘metadata/graphiql’ interface, or with repeatable processes like Python scripts.
I hope this tutorial leaves you in a better place than when you started! Tune in for the next tutorial, where we’ll shift our focus to the repository database (the internal PostgreSQL database) and squeeze some really useful information out of it, including the number of times content was accessed by our users and the most recent interaction dates for each workbook or view.
The data we’ve collected is already valuable, but marrying it to the outputs from the PostgreSQL database will allow us to paint a more complete portrait of what’s happening in our Tableau ecosystem.
Which views and databases do our end-users access the most? Has any content gone stale and unused? Is it safe to drop that old database table John built four years ago? The work we’ll do in the next tutorial will help us answer those questions!
Milestone 2 (ETA is 4/29/2020): build upon Milestone 1 with supplemental data from the Tableau Server Repository to provide the number of interactions associated with each workbook (views and dashboards), datasource, and flow.
Milestone 3 (ETA is 5/6/2020): convert the combined output of Milestones 1 & 2 into a .hyper extract using the Hyper API and publish the contents to Tableau Server (or Tableau Online).
Milestone 4 (ETA is 5/13/2020): build our first impact analysis dashboard using the datasource published in Milestone 3.
Milestone 5 (TBD) | [
{
"code": null,
"e": 426,
"s": 172,
"text": "All good adventures begin with a first step. In this tutorial, the first step we take to build an impact analysis report for Tableau Server is collecting information about the relationships between our workbooks, visuals, and underlying database assets."
... |
How to check if data is NULL in MySQL? | You can use IF() to check if data is NULL. Let us first create a table −
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name varchar(200),
Age int
);
Query OK, 0 rows affected (0.44 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable(Name,Age) values('John',23);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Name,Age) values('Sam',null);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Name,Age) values('Mike',23);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(Name,Age) values('David',21);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(Name,Age) values('Carol',null);
Query OK, 1 row affected (0.13 sec)
Display records from the table using select command −
mysql> select *from DemoTable;
This will produce the following output −
+----+-------+------+
| Id | Name | Age |
+----+-------+------+
| 1 | John | 23 |
| 2 | Sam | NULL |
| 3 | Mike | 23 |
| 4 | David | 21 |
| 5 | Carol | NULL |
+----+-------+------+
5 rows in set (0.00 sec)
Here is the query to check if data is NULL or not. This adds a message wherever NULL in the record is visible −
mysql> select if(Age IS NULL,'Age is missing',Age) from DemoTable;
This will produce the following output −
+--------------------------------------+
| if(Age IS NULL,'Age is missing',Age) |
+--------------------------------------+
| 23 |
| Age is missing |
| 23 |
| 21 |
| Age is missing |
+--------------------------------------+
5 rows in set (0.00 sec) | [
{
"code": null,
"e": 1136,
"s": 1062,
"text": "You can use IF() to check if data is NULL. Let us first create a table −"
},
{
"code": null,
"e": 1288,
"s": 1136,
"text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n Name varchar(200),\n ... |
Aptitude | GATE CS 1998 | Question 75 - GeeksforGeeks | 20 Mar, 2020
Let p be a pointer as shown in the figure in a single linked list.What do the following assignment statements achieve ?
q: = p → next
p → next:= q → next
q → next:=(q → next) → next
(p → next) → next:= q
Answer:Explanation: Initially p points to i and q points to i+1.
p ->next:= q ->next : i next points to i+2q ->next:=(q ->next) ? next : i+1 next points to i+3(p ->next) ->next:= q : i+2 next points to i+1
p ->next:= q ->next : i next points to i+2
q ->next:=(q ->next) ? next : i+1 next points to i+3
(p ->next) ->next:= q : i+2 next points to i+1
Deducing finally i->i+2->i+1->i+3.
So, it swaps the two nodes next to p in the linked list.
Quiz of this Question
abhinandanbr
Aptitude
Aptitude-GATE CS 1998
GATE CS 1998
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63 | [
{
"code": null,
"e": 24484,
"s": 24456,
"text": "\n20 Mar, 2020"
},
{
"code": null,
"e": 24604,
"s": 24484,
"text": "Let p be a pointer as shown in the figure in a single linked list.What do the following assignment statements achieve ?"
},
{
"code": null,
"e": 24690,... |
How to print number of words in textview in android? | This example demonstrate about How to print number of words in textview 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"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_marginTop="100dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
In the above code, we have taken textview to show paragraph and toast will show the information about number of words.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
text.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the
1500s, when an unknown printer took a galley of type and scrambled it to
make a type specimen book. It has survived not only five centuries, but
also the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets
containing Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum.");
String[] para = text.getText().toString().split("\\s+");
Toast.makeText(MainActivity.this, "" + para.length, Toast.LENGTH_LONG).show();
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code | [
{
"code": null,
"e": 1146,
"s": 1062,
"text": "This example demonstrate about How to print number of words in textview in android."
},
{
"code": null,
"e": 1275,
"s": 1146,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required de... |
How to skip every Nth index of NumPy array ? - GeeksforGeeks | 21 Apr, 2021
In this article, we will see how to skip every Nth index of the NumPy array. There are various ways to access and skip elements of a NumPy array :
Method 1: Naive Approach
A counter can be maintained to keep a count of the elements traversed so far, and then as soon as the Nth position is encountered, the element is skipped and the counter is reset to 0. All the elements are appended to a new list excluding the Nth index element encountered while traversal. The time required during this is equivalent to O(n), where n is the size of the numpy array. In case the elements need to be just printed and not stored, we can skip the declaration of creation of another array.
Example:
Python3
# importing required packagesimport numpy as np # declaring a numpy arrayx = np.array([1.2, 3.0, 6.7, 8.7, 8.2, 1.3, 4.5, 6.5, 1.2, 3.0, 6.7, 8.7, 8.2, 1.3, 4.5, 6.5]) # skipping every 4th elementn = 4 # declaring new listnew_arr = [] # maintaining cntrcntr = 0 # looping over arrayfor i in x: # checking if element is nth pos if(cntr % n != 0): new_arr.append(i) # incrementing counter cntr += 1 print("Array after skipping nth element")print(new_arr)
Output:
Array after skipping nth element
[3.0, 6.7, 8.7, 1.3, 4.5, 6.5, 3.0, 6.7, 8.7, 1.3, 4.5, 6.5]
Method 2: Using NumPy modulus method
The array can first be arranged into chunks of evenly spaced intervals, using the numpy.arange() method.
Syntax: np.arange(start,stop,step)
Parameter:
start: Start of the interval
stop: End of the interval
step: Steps between the start and end interval
Then, the np.mod() method is applied over the list’s intervals obtained and each element’s modulo is then computed with the nth index. The elements of the original array whose modulo output is not 0, are returned as the final list.
Example
Python3
# importing required packagesimport numpy as np # declaring a numpy arrayx = np.array([0, 1, 2, 3, 2, 5, 2, 7, 2, 9]) print("Original Array")print(x) # skipping third elementnew_arr = x[np.mod(np.arange(x.size), 3) != 0] print("Array after skipping elements : ")print(new_arr)
Output:
Original Array
[0 1 2 3 2 5 2 7 2 9]
Array after skipping elements :
[1 2 2 5 7 2]
Method 3: NumPy Slicing
NumPy slicing is basically data subsampling where we create a view of the original data, which incurs constant time. The changes are made to the original array and the entire original array is kept in memory. A copy of the data can also be made explicitly.
Syntax:
arr[start:end:st]
Here, where the start is the starting index, the end is the stopping index, and st is the step, where the step is not equivalent to 0. And, it returns a sub-array that contains the elements belonging to the st index respectively. The indexes of the array are assumed to be starting at 0.
Example
Python
# importing required packagesimport numpy as np # declaring a numpy arrayx = np.array([0, 1, 2, 3, 2, 5, 2, 7, 2, 9]) # calculating length of arraylength = len(x) # accessing every third element # from the arrayprint("List after n=3rd element access")print(x[0:length:3])
Output:
List after n=3rd element access
[0 3 2 9]
Picked
Python numpy-Indexing
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 24049,
"s": 23901,
"text": "In this article, we will see how to skip every Nth index of the NumPy array. There are various ways to access and skip elements of a NumPy array : "
},
{
"... |
PostgreSQL - Size of a Table - GeeksforGeeks | 22 Feb, 2021
In this article, we will look into the function that is used to get the size of the PostgreSQL database table. In this article, we will be using a sample database for reference which is described here and can be downloaded from here.
The pg_relation_size() function is used to get the size of a table.
Syntax: select pg_relation_size('table_name');
Example 1: Here we will query for the size “country” table from the sample dvdrental database using the below command:
select pg_relation_size('country');
Output:
To make the result readable, one can use the pg_size_pretty() function. The pg_size_pretty() function takes the result of another function and formats it using bytes, kB, MB, GB or TB as required.
SELECT pg_size_pretty (pg_relation_size('country'));
Output:
Example 2: Here we will query for the size “customer” table from the sample dvdrental database using the below command:
SELECT pg_size_pretty (pg_relation_size('customer'));
Output:
Example 3: Here we will query for the size “film” table from the sample dvdrental database using the below command:
SELECT pg_size_pretty (pg_relation_size('film'));
Output:
Example 4: Here we will query for the top 10 biggest tables in the dvdrental database.
SELECT
relname AS "tables",
pg_size_pretty (
pg_total_relation_size (X .oid)
) AS "size"
FROM
pg_class X
LEFT JOIN pg_namespace Y ON (Y.oid = X .relnamespace)
WHERE
nspname NOT IN (
'pg_catalog',
'information_schema'
)
AND X .relkind <> 'i'
AND nspname !~ '^pg_toast'
ORDER BY
pg_total_relation_size (X .oid) ASC
LIMIT 10;
Output:
RajuKumar19
PostgreSQL-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - GROUP BY clause
PostgreSQL - LEFT JOIN
PostgreSQL - Rename Table
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Record type variable
PostgreSQL - While Loops
PostgreSQL - Select Into
PostgreSQL - ROW_NUMBER Function | [
{
"code": null,
"e": 23952,
"s": 23924,
"text": "\n22 Feb, 2021"
},
{
"code": null,
"e": 24186,
"s": 23952,
"text": "In this article, we will look into the function that is used to get the size of the PostgreSQL database table. In this article, we will be using a sample database ... |
How to create and use a named pipe in Python? | FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with os.unlink()). Generally, FIFOs are used as rendezvous between “client” and “server” type processes: the server opens the FIFO for reading, and the client opens it for writing. Note that mkfifo() doesn’t open the FIFO — it just creates the rendezvous point. To create a FIFO(named pipe) and use it in Python, you can use the os.mkfifo(). But mkfifo fails with File exists exception if file already exists. In order to avoid that, you can put it in a try-except block.
import os, sys
# Path to be created
path = "/tmp/hourly"
try:
os.mkfifo(path)
except OSError, e:
print "Failed to create FIFO: %s" % e
else:
fifo = open(path, 'w')
print "Path is created"
When you run this program, you can expect the pipe to be created. | [
{
"code": null,
"e": 1639,
"s": 1062,
"text": "FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with os.unlink()). Generally, FIFOs are used as rendezvous between “client” and “server” type processes: the server opens the FIFO for reading, and ... |
How to add a delay in a JavaScript loop? - GeeksforGeeks | 27 Sep, 2019
JavaScript doesn’t offer any wait command to add a delay to the loops but we can do so using setTimeout method. This method executes a function, after waiting a specified number of milliseconds. Below given example illustrates how to add a delay to various loops:
For loop:for (let i=0; i<10; i++) { task(i);} function task(i) { setTimeout(function() { // Add tasks to do }, 2000 * i);}In the code given above you have to do 2000 * i at line 8 because setTimeout method inside the loop doesn’t makes the loop pause but actually adds a delay to each iteration. Remember that all the iteration start their time together. Thus if we only do 2000 there, that will make all the iterations execute together and it will just give 2000 ms delay in the first iteration and all other iteration will happen instantly after it. Thus to avoid that we add 0 to first, 2000 to second, 4000 to third and it goes on.Example: Below given program will print 0 to 9 in console after 2 seconds delay to each number using for loop.<script>for (let i=0; i<10; i++) { task(i);} function task(i) { setTimeout(function() { console.log(i); }, 2000 * i);}</script>Output:
for (let i=0; i<10; i++) { task(i);} function task(i) { setTimeout(function() { // Add tasks to do }, 2000 * i);}
In the code given above you have to do 2000 * i at line 8 because setTimeout method inside the loop doesn’t makes the loop pause but actually adds a delay to each iteration. Remember that all the iteration start their time together. Thus if we only do 2000 there, that will make all the iterations execute together and it will just give 2000 ms delay in the first iteration and all other iteration will happen instantly after it. Thus to avoid that we add 0 to first, 2000 to second, 4000 to third and it goes on.
Example: Below given program will print 0 to 9 in console after 2 seconds delay to each number using for loop.
<script>for (let i=0; i<10; i++) { task(i);} function task(i) { setTimeout(function() { console.log(i); }, 2000 * i);}</script>
Output:
While loop: Same concept is applied to make below given while loop.let i = 0;while (i < 10) { task(i); i++;}function task(i) { setTimeout(function() { // Add tasks to do }, 2000 * i);}Example: Below given program will print 0 to 9 in console after 2 seconds delay to each number using while loop.<script>let i = 0;while (i < 10) { task(i); i++;}function task(i) { setTimeout(function() { console.log(i); }, 2000 * i);}</script>Output:
let i = 0;while (i < 10) { task(i); i++;}function task(i) { setTimeout(function() { // Add tasks to do }, 2000 * i);}
Example: Below given program will print 0 to 9 in console after 2 seconds delay to each number using while loop.
<script>let i = 0;while (i < 10) { task(i); i++;}function task(i) { setTimeout(function() { console.log(i); }, 2000 * i);}</script>
Output:
Do-while loop: Same concept is applied to make below given do-while loop.let i = 0;do { task(i); i++;} while (i < 5);function task(i) { setTimeout(function() { // Add tasks to do }, 2000 * i);}Example: Below given program will print 0 to 9 in console after 2 seconds delay to each number using do-while loop.<script>let i = 0;do { task(i); i++;} while (i < 5);function task(i) { setTimeout(function() { console.log(i); }, 2000 * i);}</script>Output:
let i = 0;do { task(i); i++;} while (i < 5);function task(i) { setTimeout(function() { // Add tasks to do }, 2000 * i);}
Example: Below given program will print 0 to 9 in console after 2 seconds delay to each number using do-while loop.
<script>let i = 0;do { task(i); i++;} while (i < 5);function task(i) { setTimeout(function() { console.log(i); }, 2000 * i);}</script>
Output:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 29980,
"s": 29952,
"text": "\n27 Sep, 2019"
},
{
"code": null,
"e": 30244,
"s": 29980,
"text": "JavaScript doesn’t offer any wait command to add a delay to the loops but we can do so using setTimeout method. This method executes a function, after waiting a sp... |
HashSet in C# with Examples | 09 Dec, 2021
In C#, HashSet is an unordered collection of unique elements. This collection is introduced in .NET 3.5. It supports the implementation of sets and uses the hash table for storage. This collection is of the generic type collection and it is defined under System.Collections.Generic namespace. It is generally used when we want to prevent duplicate elements from being placed in the collection. The performance of the HashSet is much better in comparison to the list.
Important Points:
The HashSet class implements the ICollection, IEnumerable, IReadOnlyCollection, ISet, IEnumerable, IDeserializationCallback, and ISerializable interfaces.
In HashSet, the order of the element is not defined. You cannot sort the elements of HashSet.
In HashSet, the elements must be unique.
In HashSet, duplicate elements are not allowed.
Is provides many mathematical set operations, such as intersection, union, and difference.
The capacity of a HashSet is the number of elements it can hold.
A HashSet is a dynamic collection means the size of the HashSet is automatically increased when the new elements are added.
In HashSet, you can only store the same type of elements.
The HashSet class provides 7 different types of constructors which are used to create a HashSet, here we only use HashSet(), constructor. To read more about HashSet’s constructors you can refer to C# | HashSet Class.
HashSet(): It is used to create an instance of the HashSet class that is empty and uses the default equality comparer for the set type.
Step 1: Include System.Collections.Generic namespace in your program with the help of using keyword:
using System.Collections.Generic;
Step 2: Create a HashSet using the HashSet class as shown below:
HashSet<Type_of_hashset> Hashset_name = new HashSet<Type_of_hashset>();
Step 3: If you want to add elements in your HashSet, then use Add() method to add elements in your HashSet. And you can also store elements in your HashSet using collection initializer.
Step 4: The elements of HashSet is accessed by using a foreach loop. As shown in the below example.
Example:
C#
// C# program to illustrate how to// create hashsetusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating HashSet // Using HashSet class HashSet<string> myhash1 = new HashSet<string>(); // Add the elements in HashSet // Using Add method myhash1.Add("C"); myhash1.Add("C++"); myhash1.Add("C#"); myhash1.Add("Java"); myhash1.Add("Ruby"); Console.WriteLine("Elements of myhash1:"); // Accessing elements of HashSet // Using foreach loop foreach(var val in myhash1) { Console.WriteLine(val); } // Creating another HashSet // using collection initializer // to initialize HashSet HashSet<int> myhash2 = new HashSet<int>() {10, 100,1000,10000,100000}; // Display elements of myhash2 Console.WriteLine("Elements of myhash2:"); foreach(var value in myhash2) { Console.WriteLine(value); } }}
Elements of myhash1:
C
C++
C#
Java
Ruby
Elements of myhash2:
10
100
1000
10000
100000
In HashSet, you are allowed to remove elements from the HashSet. HashSet<T> class provides three different methods to remove elements and the methods are:
Remove(T): This method is used to remove the specified element from a HashSet object.
RemoveWhere(Predicate): This method is used to remove all elements that match the conditions defined by the specified predicate from a HashSet collection.
Clear: This method is used to remove all elements from a HashSet object.
Example 1:
C#
// C# program to illustrate how to// remove elements of HashSetusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating HashSet // Using HashSet class HashSet<string> myhash = new HashSet<string>(); // Add the elements in HashSet // Using Add method myhash.Add("C"); myhash.Add("C++"); myhash.Add("C#"); myhash.Add("Java"); myhash.Add("Ruby"); // Before using Remove method Console.WriteLine("Total number of elements present (Before Removal)"+ " in myhash: {0}", myhash.Count); // Remove element from HashSet // Using Remove method myhash.Remove("Ruby"); // After using Remove method Console.WriteLine("Total number of elements present (After Removal)"+ " in myhash: {0}", myhash.Count); // Remove all elements from HashSet // Using Clear method myhash.Clear(); Console.WriteLine("Total number of elements present"+ " in myhash:{0}", myhash.Count); }}
Total number of elements present in myhash: 5
Total number of elements present in myhash: 4
Total number of elements present in myhash:0
HashSet class also provides some methods that are used to perform different operations on sets and the methods are:
UnionWith(IEnumerable): This method is used to modify the current HashSet object to contain all elements that are present in itself, the specified collection, or both.Example:
C#
// C# program to illustrate set operationsusing System;using System.Collections.Generic; class GFG { static public void Main() { // Creating HashSet // Using HashSet class HashSet<string> myhash1 = new HashSet<string>(); // Add the elements in HashSet // Using Add method myhash1.Add("C"); myhash1.Add("C++"); myhash1.Add("C#"); myhash1.Add("Java"); myhash1.Add("Ruby"); // Creating another HashSet // Using HashSet class HashSet<string> myhash2 = new HashSet<string>(); // Add the elements in HashSet // Using Add method myhash2.Add("PHP"); myhash2.Add("C++"); myhash2.Add("Perl"); myhash2.Add("Java"); // Using UnionWith method myhash1.UnionWith(myhash2); foreach(var ele in myhash1) { Console.WriteLine(ele); } }}
C
C++
C#
Java
Ruby
PHP
Perl
IntersectWith(IEnumerable): This method is used to modify the current HashSet object to contain only elements that are present in that object and in the specified collection.Example:
C#
// C# program to illustrate set operationsusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating HashSet // Using HashSet class HashSet<string> myhash1 = new HashSet<string>(); // Add the elements in HashSet // Using Add method myhash1.Add("C"); myhash1.Add("C++"); myhash1.Add("C#"); myhash1.Add("Java"); myhash1.Add("Ruby"); // Creating another HashSet // Using HashSet class HashSet<string> myhash2 = new HashSet<string>(); // Add the elements in HashSet // Using Add method myhash2.Add("PHP"); myhash2.Add("C++"); myhash2.Add("Perl"); myhash2.Add("Java"); // Using IntersectWith method myhash1.IntersectWith(myhash2); foreach(var ele in myhash1) { Console.WriteLine(ele); } }}
C++
Java
ExceptWith(IEnumerable): This method is used to remove all elements in the specified collection from the current HashSet object.Example:
C#
// C# program to illustrate set operationsusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating HashSet // Using HashSet class HashSet<string> myhash1 = new HashSet<string>(); // Add the elements in HashSet // Using Add method myhash1.Add("C"); myhash1.Add("C++"); myhash1.Add("C#"); myhash1.Add("Java"); myhash1.Add("Ruby"); // Creating another HashSet // Using HashSet class HashSet<string> myhash2 = new HashSet<string>(); // Add the elements in HashSet // Using Add method myhash2.Add("PHP"); myhash2.Add("C++"); myhash2.Add("Perl"); myhash2.Add("Java"); // Using ExceptWith method myhash1.ExceptWith(myhash2); foreach(var ele in myhash1) { Console.WriteLine(ele); } }}
C
C#
Ruby
ramzcreativity
sagartomar9927
CSharp-Generic-HashSet
CSharp-Generic-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
C# | How to check whether a List contains a specified element
C# | Multiple inheritance using interfaces
C# | Arrays of Strings
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
Differences Between .NET Core and .NET Framework
C# | Delegates
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 522,
"s": 54,
"text": "In C#, HashSet is an unordered collection of unique elements. This collection is introduced in .NET 3.5. It supports the implementation of sets and uses the hash table for st... |
Date getTime() method in Java with Examples | 02 Jan, 2019
The getTime() method of Java Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GTM which is represented by Date object.
Syntax:
public long getTime()
Parameters: The function does not accept any parameter.
Return Value: It returns the number of milliseconds since January 1, 1970, 00:00:00 GTM.
Exception: The function does not throws any exception.
Program below demonstrates the above mentioned function:
// Java code to demonstrate// getTime() function of Date class import java.util.Date;import java.util.Calendar;public class GfG { // main method public static void main(String[] args) { // creating a Calendar object Calendar c1 = Calendar.getInstance(); // set Month // MONTH starts with 0 i.e. ( 0 - Jan) c1.set(Calendar.MONTH, 11); // set Date c1.set(Calendar.DATE, 05); // set Year c1.set(Calendar.YEAR, 1996); // creating a date object with specified time. Date dateOne = c1.getTime(); System.out.println("Date: " + dateOne); System.out.println(dateOne.getTime()); }}
Date: Thu Dec 05 09:29:39 UTC 1996
849778179420
// Java code to demonstrate// getTime() function of Date class import java.util.Date;import java.util.Calendar;public class GfG { // main method public static void main(String[] args) { // creating a Calendar object Calendar c1 = Calendar.getInstance(); // set Month // MONTH starts with 0 i.e. ( 0 - Jan) c1.set(Calendar.MONTH, 11); // set Date c1.set(Calendar.DATE, 05); // set Year c1.set(Calendar.YEAR, 2000); // creating a date object with specified time. Date dateOne = c1.getTime(); System.out.println("Date: " + dateOne); System.out.println(dateOne.getTime()); }}
Date: Tue Dec 05 09:29:40 UTC 2000
976008580370
Java - util package
Java-Functions
Java-util-Date
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n02 Jan, 2019"
},
{
"code": null,
"e": 201,
"s": 53,
"text": "The getTime() method of Java Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GTM which is represented by Date object."
},
{
"code": null... |
Python – Replace duplicate Occurrence in String | 08 May, 2020
Sometimes, while working with Python strings, we can have problem in which we need to perform the replace of a word. This is quite common task and has been discussed many times. But sometimes, the requirement is to replace occurrence of only duplicate, i.e from second occurrence. This has applications in many domains. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using split() + enumerate() + loopThe combination of above functions can be used to perform this task. In this, we separate the words using split. In this, we memoize the first occurrence in set and check if the value is saved before and then is replaced is already occurred.
# Python3 code to demonstrate working of # Replace duplicate Occurrence in String# Using split() + enumerate() + loop # initializing stringtest_str = 'Gfg is best . Gfg also has Classes now. \ Classes help understand better . ' # printing original stringprint("The original string is : " + str(test_str)) # initializing replace mapping repl_dict = {'Gfg' : 'It', 'Classes' : 'They' } # Replace duplicate Occurrence in String# Using split() + enumerate() + looptest_list = test_str.split(' ')res = set()for idx, ele in enumerate(test_list): if ele in repl_dict: if ele in res: test_list[idx] = repl_dict[ele] else: res.add(ele)res = ' '.join(test_list) # printing result print("The string after replacing : " + str(res))
The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better .The string after replacing : Gfg is best . It also has Classes now. They help understand better .
Method #2 : Using keys() + index() + list comprehensionThis is yet another way in which this task can be performed. In this, we don’t require memoization. This is one liner approach to solve this problem.
# Python3 code to demonstrate working of # Replace duplicate Occurrence in String# Using keys() + index() + list comprehension # initializing stringtest_str = 'Gfg is best . Gfg also has Classes now. Classes help understand better . ' # printing original stringprint("The original string is : " + str(test_str)) # initializing replace mapping repl_dict = {'Gfg' : 'It', 'Classes' : 'They' } # Replace duplicate Occurrence in String# Using keys() + index() + list comprehensiontest_list = test_str.split(' ')res = ' '.join([repl_dict.get(val) if val in repl_dict.keys() and test_list.index(val) != idx else val for idx, val in enumerate(test_list)]) # printing result print("The string after replacing : " + str(res))
The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better .The string after replacing : Gfg is best . It also has Classes now. They help understand better .
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 May, 2020"
},
{
"code": null,
"e": 438,
"s": 54,
"text": "Sometimes, while working with Python strings, we can have problem in which we need to perform the replace of a word. This is quite common task and has been discussed many tim... |
ToggleButton in Kotlin | 06 Jan, 2022
In Android, ToggleButton is just like a switch containing two states either ON or OFF which is represented using boolean values true and false respectively. ToggleButton unlike switch does not have a slider interface i.e we cannot slide to change the states. It is just like a button. In this article, we will be discussing how to create a ToggleButton in Kotlin.
Note: ToggleButton inherits the button class of android. Therefore, all the attributes of the button are also applicable here.
Following are some of the additional important attributes available along ToggleButton
To create a new project in Android Studio follow these steps:
Click on File, then New and then New Project and give name whatever you like.Choose “Empty Activity” for the project template.Then, select Kotlin language Support and click next button.Select minimum SDK, whatever you need
Click on File, then New and then New Project and give name whatever you like.
Choose “Empty Activity” for the project template.
Then, select Kotlin language Support and click next button.
Select minimum SDK, whatever you need
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ToggleButton android:id="@+id/toggleButton" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>
The toggle button in the layout can be accessed using the findViewById() function.
val toggle: ToggleButton = findViewById(R.id.toggleButton)
After accessing set a listener to perform actions based on the toggle state using setOnCheckedChangeListener() method.
toggle.setOnCheckedChangeListener { _, isChecked -> **Perform Any Action Here**}
Java
package com.example.togglebuttonsampleimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Toastimport android.widget.ToggleButton class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toggle: ToggleButton = findViewById(R.id.toggleButton) toggle.setOnCheckedChangeListener { _, isChecked -> Toast.makeText(this, if(isChecked) "Geek Mode ON" else "Geek Mode OFF", Toast.LENGTH_SHORT).show() } }}
sooda367
Android-Button
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
How to Communicate Between Fragments in Android?
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android UI Layouts
How to Communicate Between Fragments in Android?
Kotlin Array
Retrofit with Kotlin Coroutine in Android | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 392,
"s": 28,
"text": "In Android, ToggleButton is just like a switch containing two states either ON or OFF which is represented using boolean values true and false respectively. ToggleButton unlik... |
Why to get “Router may have only one child element” warning ? | 31 Oct, 2021
React Router Dom is a collection of navigational components that compose declaratively with your application. Whether you want to have bookmarkable URLs for your web app or a composable way to navigate in React Native, React Router Dom works in both places. We will be taking into consideration the latest version of React-router now available i.e. react-router-dom v5.3.0.
Features of React-router-dom:
Better support and optimization for React 16.
Does not show any warnings in <StrictMode>.
Introduction of a new context API.
Fully automated releases.
Bully backwards compatible with react-router-v4.
Syntax:
import { Route, Link, BrowserRouter as
Router } from 'react-router-dom'
<Router>
<div>
<Route path="/" component={App} /> </div>
</Router>
The above code snippet signifies how react-router works. We, first import the required tags from the react-router-dom dependency. Note that it is written BrowserRouter as Router. This is so we can use the tag <Router> to signify <BrowserRouter>. The <Router> tag is where the routing functionality of the app begins. If a path is stated inside the <Router> component then that path becomes accessible as a new page inside our react application that we can navigate to. In order to specify the path inside <Router>, we use the <Route> component that takes an argument called path, as you can see from the above example. This is where we create the route to a new webpage by passing it to the path argument. The component argument is used to constitute the data that the webpage will render upon going to the path specified in the path argument.
Note: The path “/” signifies default path or home, which means that upon specifying executing it, the router will route us to the starting point of the app or the home page of the app. To create a custom path simply put “/pathname” and a new path to a new webpage inside the app will be created, having the name “pathname”.
Advantages of React-router:
Viewing declarations in a standardized structure helps us to instantly understand what are our app views
Lazy loading of code.
Using the useHistory hook of React-router, we can navigate forwards and backwards and even restore the state of our app.
We have the facility to code CSS-transitions upon navigating from one page to another.
Provides a standardized application structure. Very helpful when working with large teams.
Reasons for getting the warning/error: So, coming to the motive of this article, novice developers often run into a very popular warning when working with react-router, simply known as “Router may have only one child“. Before knowing how to fix this problem, let us understand why it occurs. Generally, navigation in a React-based environment is used over the whole application. That is why React components like BrowserRouter or Router expect that only the top-level component that is <App> should be enclosed within them. Hence, they cannot work when multiple routes are listed within them as children.
Solution: The solution to this problem is, however, quite straightforward. You simply need to enclose the multiple routes in either a <div> tag or a <Switch> tag. The <Switch> tag is mostly preferred out of the two as <Switch> is unique and it is able to render a route exclusively.
Creating react application:
Step 1: To create a react project, open Command Prompt and write the following command:-
npx create-react-app test
Step 2: Now navigate to the new created directory by typing,
cd test
Project Structure: It will look like the following.
Project Structure
Step 3: Here we shall modify only the App.js file. This code snippet will throw the error, “Router may have only one child“, as you can see that multiple routes have been enclosed within a single <Router> tag, which is not supported.
App.js
import React from 'react';import './App.css';import { BrowserRouter as Router, Switch, Route, Redirect} from "react-router-dom"; function App() { return ( <div className="App"> <Router> <Route path='/child1'> <div> <p>This is child route 1</p> </div> </Route> <Route path='/child2'> <div> <p>This is child route 2</p> </div> </Route> </Router> </div> );} export default App;
Step 4: Here we are doing one significant change that is the multiple routes are now enclosed within a <Switch> tag and hence this code snippet will run flawlessly.
App.js
import React from "react";import "./App.css";import { BrowserRouter as Router, Switch, Route, Redirect,} from "react-router-dom"; function App() { return ( <div className="App"> <Router> <Switch> <Route path="/child1"> <div> <p>This is child route 1</p> </div> </Route> <Route path="/child2"> <div> <p>This is child route 2</p> </div> </Route> </Switch> </Router> </div> );} export default App;
Step to run the application: Open the terminal and type the following command.
npm start
Output:
Changing the route to display a new webpage
This is how you can solve the problem of “Router may have only one child” with ease.
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
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?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Oct, 2021"
},
{
"code": null,
"e": 402,
"s": 28,
"text": "React Router Dom is a collection of navigational components that compose declaratively with your application. Whether you want to have bookmarkable URLs for your web app or a ... |
Solidity – Mappings | 11 May, 2022
Mapping in Solidity acts like a hash table or dictionary in any other language. These are used to store the data in the form of key-value pairs, a key can be any of the built-in data types but reference types are not allowed while the value can be of any type. Mappings are mostly used to associate the unique Ethereum address with the associated value type.
Syntax:
mapping(key => value) <access specifier> <name>;
Mapping is defined as any other variable type, which accepts a key type and a value type.
Example: In the below example, the contract mapping_example a structure is defined and mapping is created.
Solidity
// Solidity program to // demonstrate mappingpragma solidity ^0.4.18; // Defining contract contract mapping_example { //Defining structure struct student { // Declaring different // structure elements string name; string subject; uint8 marks; } // Creating a mapping mapping ( address => student) result; address[] public student_result; }
Output :
As the mapping is created let’s try to add some values to the mapping for better understanding.
Example: In the below example, the contract mapping_example defines a structure, mapping is created and values are added to the mapping.
Solidity
// Solidity program to // demonstrate adding // values to mappingpragma solidity ^0.4.18; // Creating contractcontract mapping_example { //Defining structure struct student { //Declaring different // structure elements string name; string subject; uint8 marks; } // Creating mapping mapping ( address => student) result; address[] public student_result; // Function adding values to // the mapping function adding_values() public { var student = result[0xDEE7796E89C82C36BAdd1375076f39D69FafE252]; student.name = "John"; student.subject = "Chemistry"; student.marks = 88; student_result.push( 0xDEE7796E89C82C36BAdd1375076f39D69FafE252) -1; } }
Output :
We have added values to the mapping, to retrieve the values we have to create a function that returns the values added to the mapping.
Example: In the below example, the contract mapping_example defines a structure, mapping is created, values are added to the mapping, and values are retrieved from the mapping.
Solidity
// Solidity program to// demonstrate retrieve// values from the mapping pragma solidity ^0.4.18; contract mapping_example { // Defining Structure struct student { // Declaring different data types string name; string subject; uint8 marks; } // Creating mapping mapping ( address => student) result; address[] student_result; // Function adding values to the mapping function adding_values() public { var student = result[0xDEE7796E89C82C36BAdd1375076f39D69FafE252]; student.name = "John"; student.subject = "Chemistry"; student.marks = 88; student_result.push( 0xDEE7796E89C82C36BAdd1375076f39D69FafE252) -1; } // Function to retrieve // values from a mapping function get_student_result( ) view public returns (address[]) { return student_result; }}
Output :
Mappings can be counted so that we can know how many values are stored in mapping.
Example: In the below example, the contract mapping_example defines a structure, mapping is created, values are added to the mapping, and values are retrieved from the mapping.
Solidity
// Solidity program to// count number of // values in a mappingpragma solidity ^0.4.18; contract mapping_example { // Defining structure struct student { // Declaring different // structure elements string name; string subject; uint8 marks; } // Creating mapping mapping (address => student) result; address[] student_result; //Function adding values to the mapping function adding_values() public { var student = result[0xDEE7796E89C82C36BAdd1375076f39D69FafE252]; student.name = "John"; student.subject = "Chemistry"; student.marks = 88; student_result.push( 0xDEE7796E89C82C36BAdd1375076f39D69FafE252) -1; } // Function to retrieve // values from the mapping function get_student_result( ) view public returns (address[]) { return student_result; } // Function to count number // of values in a mapping function count_students( ) view public returns (uint) { return student_result.length; }}
Output :
Blockchain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect ReactJS with MetaMask ?
Introduction to Solidity
Proof of Work (PoW) Consensus
How to Install Solidity in Windows?
Features of Blockchain
Introduction to Solidity
How to Install Solidity in Windows?
Mathematical Operations in Solidity
Solidity - Inheritance
Solidity - Libraries | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 412,
"s": 53,
"text": "Mapping in Solidity acts like a hash table or dictionary in any other language. These are used to store the data in the form of key-value pairs, a key can be any of the built... |
Python | Ways to print list without quotes | 25 Jun, 2019
Whenever we print list in Python, we generally use str(list) because of which we have single quotes in the output list. Suppose if the problem requires to print solution without quotes. Let’s see some ways to print list without quotes.
Method #1: Using map()
# Python code to demonstrate # printing list in a proper way # Initialising listini_list = ['a', 'b', 'c', 'd'] # Printing initial list with strprint ("List with str", str(ini_list)) # Printing list using mapprint ("List in proper method", '[%s]' % ', '.join(map(str, ini_list)))
List with str ['a', 'b', 'c', 'd']
List in proper method [a, b, c, d]
Method #2: Using sep Method
# Python code to demonstrate # printing list in proper way # Initialising listini_list = ['a', 'b', 'c', 'd'] # Printing initial list with strprint ("List with str", str(ini_list)) # Printing list using sep Methodprint (*ini_list, sep =', ')
List with str ['a', 'b', 'c', 'd']
a, b, c, d
Method #3: Using .format()
# Python code to demonstrate # printing list in proper way # Initialising listini_list = ['a', 'b', 'c', 'd'] # Printing initial list with strprint ("List with str", str(ini_list)) # Printing list using .format()print ("Printing list without quotes", ("[{0}]".format( ', '.join(map(str, ini_list)))))
List with str ['a', 'b', 'c', 'd']
Printing list without quotes [a, b, c, d]
Method #4: Using translate Method
# Python code to demonstrate # printing list in proper way # Initialising listini_list = ['a', 'b', 'c', 'd'] # Printing initial list with strprint ("List with str", str(ini_list)) translation = {39: None}# Printing list using translate Methodprint ("Printing list without quotes", str(ini_list).translate(translation))
List with str ['a', 'b', 'c', 'd']
Printing list without quotes [a, b, c, d]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 264,
"s": 28,
"text": "Whenever we print list in Python, we generally use str(list) because of which we have single quotes in the output list. Suppose if the problem requires to print solution witho... |
Object.values( ) In JavaScript | 27 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.values() Method Object.values() method is used to return an array whose elements are the enumerable property values found on the object. The ordering of the properties is the same as that given by the object manually is a loop is applied to the properties. Object.values() takes the object as an argument of which the enumerable own property values are to be returned and returns an array containing all the enumerable property values of the given object.Applications:
Object.values() is used for returning enumerable property values of a simple array.
Object.values() is used for returning enumerable property values of an array like object.
Object.values() is used for returning enumerable property values of an array like object with random key ordering.
Syntax:
Object.values(obj)
Parameters Used:
obj : It is the object whose enumerable property values are to be returned.
obj : It is the object whose enumerable property values are to be returned.
Return Value: Object.values() returns an array containing all the enumerable property values of the given object.
Examples of the above function are provided below.Examples:
Input : var check = ['x', 'y', 'z'];
console.log(Object.values(check));
Output : Array ["x", "y", "z"]
Explanation: In this example, an array “check” has three property values [‘x’, ‘y’, ‘z’] and the object.values() method returns the enumerable property values of this array. The ordering of the properties is the same as that given by the object manually.
Input : var object = { 0: '23', 1: 'geeksforgeeks', 2: 'true' };
console.log(Object.values(object));
Output : Array ["23", "geeksforgeeks", "true"]
Explanation: In this example, an array like object “check” has three property values { 0: ’23’, 1: ‘geeksforgeeks’, 2: ‘true’ } and the object.values() method returns the enumerable property values of this array. The ordering of the properties is the same as that given by the object manually.
Input : var object = { 70: 'x', 21: 'y', 35: 'z' };
console.log(Object.values(object));
Output : Array ["y", "z", "x"]
Explanation: In this example, an array like object “check” has three property values { 70: ‘x’, 21: ‘y’, 35: ‘z’ } in random ordering and the object.values() method returns the enumerable property values of this array in the ascending order of the value of indices.Codes for the above function are provided below.Code 1:
javascript
<script> // Returning enumerable property values of a simple arrayvar check = ['x', 'y', 'z'];console.log(Object.values(check)); </script>
OUTPUT :
Array ["x", "y", "z"]
Code 2:
javascript
<script> // Returning enumerable property values// of an array like object.var object = { 0: '23', 1: 'geeksforgeeks', 2: 'true' };console.log(Object.values(object)); </script>
OUTPUT :
Array ["23", "geeksforgeeks", "true"]
Code 3:
javascript
<script> // Returning enumerable property values// of an array like object.var object = { 70: 'x', 21: 'y', 35: 'z' };console.log(Object.values(object)); </script>
OUTPUT :
Array ["y", "z", "x"]
Exceptions :
It causes a TypeError if the argument passed is not an object .
If an object is not passed as an argument to the method, then it persuades it and treats it as an object.
Supported Browser:
Chrome 54 and above
Edge 14 and above
Firefox 47 and above
Opera 41 and above
safari 10.1 and above
Reference :https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
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": 28,
"s": 0,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 416,
"s": 28,
"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 program... |
Fourier transform in MATLAB | 30 May, 2021
Fourier Transform is a mathematical technique that helps to transform Time Domain function x(t) to Frequency Domain function X(ω). In this article, we will see how to find Fourier Transform in MATLAB.
The mathematical expression for Fourier transform is:
Using the above function one can generate a Fourier Transform of any expression. In MATLAB, the Fourier command returns the Fourier transform of a given function. Input can be provided to the Fourier function using 3 different syntaxes.
Fourier(x): In this method, x is the time domain function whereas the independent variable is determined by symvar and the transformation variable is w by default.
Fourier(x,transvar): Here, x is the time domain function whereas transvar is the transformation variable instead of w.
Fourier(x,indepvar,transvar): In this syntax, x is the time domain function whereas indepvar is the independent variable and transvar is the transformation variable instead of symvar and w respectively.
Now we find the Fourier Transform of .
Example 1:
Matlab
% MATLAB code to specify the variable t % and u as symbolic ones The syms function% creates a variable dynamically and % automatically assigns to a MATLAB variable% with the same namesyms t u % define time domain function x(t)x = exp(-t^2-u^2); % fourier command to transform into % frequency domain function X(w) % using 1st syntax, where independent variable% is determined by symvar (u in this case)% and transformation variable is w by default.X = fourier(x); % using 2nd syntax, where transformation % variable = yX1=fourier(x,y); % using 3rd syntax, where independent % variable = t & transformation variable = y X2=fourier(x,t,y); % Display the output valuedisp('1. Fourier Transform of exp(-t^2-u^2) using fourier(x) :')disp(X); disp('2. Fourier Transform of exp(-t^2-u^2) using fourier(x,y) :')disp(X1); disp('3. Fourier Transform of exp(-t^2-u^2) using fourier(x,t,y) :')disp(X2);
Output:
Let’s take another example to find the Fourier Transform of a*abs(t).
Example 2:
Matlab
% MATLAB code for specify the variable% a and t as symbolic onessyms a t % define time domain function x(t) % where t=independent variable & a=constantx = a*abs(t); % fourier command to transform into frequency% domain function X(w)% using 1st syntaxX = fourier(x); % using 2nd syntax, where transformation % variable = yX1 = fourier(x,y); % using 3rd syntax, where transformation variable% = y & independent% variable = t (as t is the only other variable)X2 = fourier(x,t,y); % Display the output valuedisp('1. Fourier Transform of a*abs(t) using fourier(x):')disp(X); disp('2. Fourier Transform of a*abs(t) using fourier(x,y):')disp(X1); disp('3. Fourier Transform of a*abs(t) using fourier(x,t,y):')disp(X2);
Output:
MATLAB-Maths
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
MRI Image Segmentation in MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
Adaptive Histogram Equalization in Image Processing Using MATLAB
How to detect duplicate values and its indices within an array in MATLAB?
Classes and Object in MATLAB
How to Convert RGB Image to Binary Image Using MATLAB?
How to remove space in a string in MATLAB?
How to Iterate through each element in N-Dimensional matrix in MATLAB?
Double Integral in MATLAB | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 255,
"s": 54,
"text": "Fourier Transform is a mathematical technique that helps to transform Time Domain function x(t) to Frequency Domain function X(ω). In this article, we will see how to find Fo... |
Create Database in MS SQL Server | 28 Aug, 2020
Prerequisite – Introduction of MS SQL Server
Databases are a collection of objects like tables, views, stored procedures, functions, etc. In MS SQL Server, two sorts of databases are available.
System databases
User Databases
System Databases :System databases are created automatically once we install the MS SQL Server. Below is a list of system databases –
Master
Model
MSDB
Tempdb
User Databases :User databases are created by users (DBAs, and testers who have access to create database). To create a database, the below methods could be used –
SQL Server Management Studio.
Transact-SQL.
Using SQL Server Management Studio :Connect to an SQL instance of the SQL Server Database Engine then expand that instance.Right-click Databases, and then click New Database.Enter a database name.To create the database by with default values, click OK.Create New DatabaseOtherwise, continue with the following optional steps.To change the owner name, click (...) to pick another owner.To change the default values of the first data and transaction log files, within the Database files grid, click the editable cell and enter the new value.To change the collation of the database, select the Options page, then select a collation from the list.Database OptionsTo change the recovery model, select the Options page, and choose a recovery model from the list.To add more filegroup, click the Filegroups option. Click Add, then enter the values for the filegroup.Database FilegroupTo create the database, click OK.Using Transact-SQL :Connect to the Database Engine.Open New Query.Syntax –CREATE DATABASE databasename
[ ON
[ PRIMARY ] <filespec> [...n ]
[, <filegroup> [...n ] ]
[ LOG ON <filespec> [...n ] ]
]
[ COLLATE collation_name ]
[ WITH <option> [...n ] ]
[;]Example –Create database with default settings –CREATE DATABASE test;Create database with options –CREATE DATABASE test
ON (NAME = test_dat, --logical datafile name
FILENAME = 'D:\DATA\testdat.mdf', --physical datafile name
SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5)
LOG ON (NAME = test_log, --logical logfile name
FILENAME = 'L:\DATA\testlog.ldf', --physical logfile name
SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB ) ;
GO
Using SQL Server Management Studio :Connect to an SQL instance of the SQL Server Database Engine then expand that instance.Right-click Databases, and then click New Database.Enter a database name.To create the database by with default values, click OK.Create New DatabaseOtherwise, continue with the following optional steps.To change the owner name, click (...) to pick another owner.To change the default values of the first data and transaction log files, within the Database files grid, click the editable cell and enter the new value.To change the collation of the database, select the Options page, then select a collation from the list.Database OptionsTo change the recovery model, select the Options page, and choose a recovery model from the list.To add more filegroup, click the Filegroups option. Click Add, then enter the values for the filegroup.Database FilegroupTo create the database, click OK.
Connect to an SQL instance of the SQL Server Database Engine then expand that instance.
Right-click Databases, and then click New Database.
Enter a database name.
To create the database by with default values, click OK.
Create New Database
Otherwise, continue with the following optional steps.
To change the owner name, click (...) to pick another owner.
To change the default values of the first data and transaction log files, within the Database files grid, click the editable cell and enter the new value.
To change the collation of the database, select the Options page, then select a collation from the list.
Database Options
To change the recovery model, select the Options page, and choose a recovery model from the list.
To add more filegroup, click the Filegroups option. Click Add, then enter the values for the filegroup.
Database Filegroup
To create the database, click OK.
Using Transact-SQL :Connect to the Database Engine.Open New Query.Syntax –CREATE DATABASE databasename
[ ON
[ PRIMARY ] <filespec> [...n ]
[, <filegroup> [...n ] ]
[ LOG ON <filespec> [...n ] ]
]
[ COLLATE collation_name ]
[ WITH <option> [...n ] ]
[;]Example –Create database with default settings –CREATE DATABASE test;Create database with options –CREATE DATABASE test
ON (NAME = test_dat, --logical datafile name
FILENAME = 'D:\DATA\testdat.mdf', --physical datafile name
SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5)
LOG ON (NAME = test_log, --logical logfile name
FILENAME = 'L:\DATA\testlog.ldf', --physical logfile name
SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB ) ;
GO
Connect to the Database Engine.
Open New Query.
Syntax –
CREATE DATABASE databasename
[ ON
[ PRIMARY ] <filespec> [...n ]
[, <filegroup> [...n ] ]
[ LOG ON <filespec> [...n ] ]
]
[ COLLATE collation_name ]
[ WITH <option> [...n ] ]
[;]
Example –
Create database with default settings –
CREATE DATABASE test;
Create database with options –
CREATE DATABASE test
ON (NAME = test_dat, --logical datafile name
FILENAME = 'D:\DATA\testdat.mdf', --physical datafile name
SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5)
LOG ON (NAME = test_log, --logical logfile name
FILENAME = 'L:\DATA\testlog.ldf', --physical logfile name
SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB ) ;
GO
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
SQL Trigger | Student Database
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
Window functions in SQL
MySQL | Group_CONCAT() Function
SQL | GROUP BY | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 73,
"s": 28,
"text": "Prerequisite – Introduction of MS SQL Server"
},
{
"code": null,
"e": 222,
"s": 73,
"text": "Databases are a collection of objects like tables, views, store... |
Huffman Decoding | 11 Nov, 2017
We have discussed Huffman Encoding in a previous post. In this post decoding is discussed.
Examples:
Input Data : AAAAAABCCCCCCDDEEEEE
Frequencies : A: 6, B: 1, C: 6, D: 2, E: 5
Encoded Data :
0000000000001100101010101011111111010101010
Huffman Tree: '#' is the special character used
for internal nodes as character field
is not needed for internal nodes.
#(20)
/ \
#(12) #(8)
/ \ / \
A(6) C(6) E(5) #(3)
/ \
B(1) D(2)
Code of 'A' is '00', code of 'C' is '01', ..
Decoded Data : AAAAAABCCCCCCDDEEEEE
Input Data : GeeksforGeeks
Character With there Frequencies
e 10, f 1100, g 011, k 00, o 010, r 1101, s 111
Encoded Huffman data :
01110100011111000101101011101000111
Decoded Huffman Data
geeksforgeeks
To decode the encoded data we require the Huffman tree. We iterate through the binary encoded data. To find character corresponding to current bits, we use following simple steps.
We start from root and do following until a leaf is found.If current bit is 0, we move to left node of the tree.If the bit is 1, we move to right node of the tree.If during traversal, we encounter a leaf node, we print character of that particular leaf node and then again continue the iteration of the encoded data starting from step 1.
We start from root and do following until a leaf is found.
If current bit is 0, we move to left node of the tree.
If the bit is 1, we move to right node of the tree.
If during traversal, we encounter a leaf node, we print character of that particular leaf node and then again continue the iteration of the encoded data starting from step 1.
The below code takes a string as input, it encodes it and save in a variable encodedString. Then it decodes it and print the original string.
The below code performs full Huffman Encoding and Decoding of a given input data.
// C++ program to encode and decode a string using// Huffman Coding.#include <bits/stdc++.h>#define MAX_TREE_HT 256using namespace std; // to map each character its huffman valuemap<char, string> codes; // to store the frequency of character of the input datamap<char, int> freq; // A Huffman tree nodestruct MinHeapNode{ char data; // One of the input characters int freq; // Frequency of the character MinHeapNode *left, *right; // Left and right child MinHeapNode(char data, int freq) { left = right = NULL; this->data = data; this->freq = freq; }}; // utility function for the priority queuestruct compare{ bool operator()(MinHeapNode* l, MinHeapNode* r) { return (l->freq > r->freq); }}; // utility function to print characters along with// there huffman valuevoid printCodes(struct MinHeapNode* root, string str){ if (!root) return; if (root->data != '$') cout << root->data << ": " << str << "\n"; printCodes(root->left, str + "0"); printCodes(root->right, str + "1");} // utility function to store characters along with// there huffman value in a hash table, here we// have C++ STL mapvoid storeCodes(struct MinHeapNode* root, string str){ if (root==NULL) return; if (root->data != '$') codes[root->data]=str; storeCodes(root->left, str + "0"); storeCodes(root->right, str + "1");} // STL priority queue to store heap tree, with respect// to their heap root node valuepriority_queue<MinHeapNode*, vector<MinHeapNode*>, compare> minHeap; // function to build the Huffman tree and store it// in minHeapvoid HuffmanCodes(int size){ struct MinHeapNode *left, *right, *top; for (map<char, int>::iterator v=freq.begin(); v!=freq.end(); v++) minHeap.push(new MinHeapNode(v->first, v->second)); while (minHeap.size() != 1) { left = minHeap.top(); minHeap.pop(); right = minHeap.top(); minHeap.pop(); top = new MinHeapNode('$', left->freq + right->freq); top->left = left; top->right = right; minHeap.push(top); } storeCodes(minHeap.top(), "");} // utility function to store map each character with its// frequency in input stringvoid calcFreq(string str, int n){ for (int i=0; i<str.size(); i++) freq[str[i]]++;} // function iterates through the encoded string s// if s[i]=='1' then move to node->right// if s[i]=='0' then move to node->left// if leaf node append the node->data to our output stringstring decode_file(struct MinHeapNode* root, string s){ string ans = ""; struct MinHeapNode* curr = root; for (int i=0;i<s.size();i++) { if (s[i] == '0') curr = curr->left; else curr = curr->right; // reached leaf node if (curr->left==NULL and curr->right==NULL) { ans += curr->data; curr = root; } } // cout<<ans<<endl; return ans+'\0';} // Driver program to test above functionsint main(){ string str = "geeksforgeeks"; string encodedString, decodedString; calcFreq(str, str.length()); HuffmanCodes(str.length()); cout << "Character With there Frequencies:\n"; for (auto v=codes.begin(); v!=codes.end(); v++) cout << v->first <<' ' << v->second << endl; for (auto i: str) encodedString+=codes[i]; cout << "\nEncoded Huffman data:\n" << encodedString << endl; decodedString = decode_file(minHeap.top(), encodedString); cout << "\nDecoded Huffman Data:\n" << decodedString << endl; return 0;}
Output:
Character With there Frequencies
e 10
f 1100
g 011
k 00
o 010
r 1101
s 111
Encoded Huffman data
01110100011111000101101011101000111
Decoded Huffman Data
geeksforgeeks
Comparing Input file size and Output file size:Comparing the input file size and the Huffman encoded output file. We can calculate the size of the output data in a simple way. Lets say our input is a string “geeksforgeeks” and is stored in a file input.txt.Input File Size:
Input: "geeksforgeeks"
Total number of character i.e. input length: 13
Size: 13 character occurrences * 8 bits = 104 bits or 13 bytes.
Output File Size:
Input: "geeksforgeeks"
------------------------------------------------
Character | Frequency | Binary Huffman Value |
------------------------------------------------
e | 4 | 10 |
f | 1 | 1100 |
g | 2 | 011 |
k | 2 | 00 |
o | 1 | 010 |
r | 1 | 1101 |
s | 2 | 111 |
------------------------------------------------
So to calculate output size:
e: 4 occurrences * 2 bits = 8 bits
f: 1 occurrence * 4 bits = 4 bits
g: 2 occurrences * 3 bits = 6 bits
k: 2 occurrences * 2 bits = 4 bits
o: 1 occurrence * 3 bits = 3 bits
r: 1 occurrence * 4 bits = 4 bits
s: 2 occurrences * 3 bits = 6 bits
Total Sum: 35 bits approx 5 bytes
Hence, we could see that after encoding the data we have saved a large amount of data.The above method can also help us to determine the value of N i.e. the length of the encoded data.
This article is contributed by Harshit Sidhwa. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
encoding-decoding
Greedy
Heap
Greedy
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Nov, 2017"
},
{
"code": null,
"e": 143,
"s": 52,
"text": "We have discussed Huffman Encoding in a previous post. In this post decoding is discussed."
},
{
"code": null,
"e": 153,
"s": 143,
"text": "Examples:"
}... |
JSP - Internationalization| i18n| l10n | In this chapter, we will discuss the concept of Internationalization in JSP. Before we proceed, let us understand the following three important terms −
Internationalization (i18n) − This means enabling a website to provide different versions of content translated into the visitor's language or nationality.
Internationalization (i18n) − This means enabling a website to provide different versions of content translated into the visitor's language or nationality.
Localization (l10n) − This means adding resources to a website to adapt it to a particular geographical or cultural region for example Hindi translation to a web site.
Localization (l10n) − This means adding resources to a website to adapt it to a particular geographical or cultural region for example Hindi translation to a web site.
locale − This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which are separated by an underscore. For example, "en_US" represents english locale for US.
locale − This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which are separated by an underscore. For example, "en_US" represents english locale for US.
There are a number of items which should be taken care of while building up a global Website. This tutorial will not give you complete detail on this but it will give you a good example on how you can offer your Webpage in different languages to the internet community by differentiating their location, i.e., locale.
A JSP can pick up appropriate version of the site based on the requester's locale and provide appropriate site version according to the local language, culture and requirements. Following is the method of request object which returns the Locale object.
java.util.Locale request.getLocale()
Following are the important locale methods which you can use to detect requester's location, language and of course locale. All the below methods display the country name and language name set in the requester's browser.
String getCountry()
This method returns the country/region code in upper case for this locale in ISO 3166 2-letter format.
String getDisplayCountry()
This method returns a name for the locale's country that is appropriate for display to the user.
String getLanguage()
This method returns the language code in lower case for this locale in ISO 639 format.
String getDisplayLanguage()
This method returns a name for the locale's language that is appropriate for display to the user.
String getISO3Country()
This method returns a three-letter abbreviation for this locale's country.
String getISO3Language()
This method returns a three-letter abbreviation for this locale's language.
The following example shows how to display a language and associated country for a request in a JSP −
<%@ page import = "java.io.*,java.util.Locale" %>
<%@ page import = "javax.servlet.*,javax.servlet.http.* "%>
<%
//Get the client's Locale
Locale locale = request.getLocale();
String language = locale.getLanguage();
String country = locale.getCountry();
%>
<html>
<head>
<title>Detecting Locale</title>
</head>
<body>
<center>
<h1>Detecting Locale</h1>
</center>
<p align = "center">
<%
out.println("Language : " + language + "<br />");
out.println("Country : " + country + "<br />");
%>
</p>
</body>
</html>
A JSP can output a page written in a Western European language such as English, Spanish, German, French, Italian, Dutch etc. Here it is important to set Content-Language header to display all the characters properly.
Another important point is to display all the special characters using HTML entities; for example, "ñ" represents "ñ", and "¡" represents "¡" as follows −
<%@ page import = "java.io.*,java.util.Locale" %>
<%@ page import = "javax.servlet.*,javax.servlet.http.* "%>
<%
// Set response content type
response.setContentType("text/html");
// Set spanish language code.
response.setHeader("Content-Language", "es");
String title = "En Español";
%>
<html>
<head>
<title><% out.print(title); %></title>
</head>
<body>
<center>
<h1><% out.print(title); %></h1>
</center>
<div align = "center">
<p>En Español</p>
<p>¡Hola Mundo!</p>
</div>
</body>
</html>
You can use the java.text.DateFormat class and its static getDateTimeInstance( ) method to format date and time specific to locale. Following is the example which shows how to format dates specific to a given locale −
<%@ page import = "java.io.*,java.util.Locale" %>
<%@ page import = "javax.servlet.*,javax.servlet.http.* "%>
<%@ page import = "java.text.DateFormat,java.util.Date" %>
<%
String title = "Locale Specific Dates";
//Get the client's Locale
Locale locale = request.getLocale( );
String date = DateFormat.getDateTimeInstance(
DateFormat.FULL,
DateFormat.SHORT,
locale).format(new Date( ));
%>
<html>
<head>
<title><% out.print(title); %></title>
</head>
<body>
<center>
<h1><% out.print(title); %></h1>
</center>
<div align = "center">
<p>Local Date: <% out.print(date); %></p>
</div>
</body>
</html>
You can use the java.txt.NumberFormat class and its static getCurrencyInstance( ) method to format a number, such as a long or double type, in a locale specific curreny. Following is the example which shows how to format currency specific to a given locale −
<%@ page import = "java.io.*,java.util.Locale" %>
<%@ page import = "javax.servlet.*,javax.servlet.http.* "%>
<%@ page import = "java.text.NumberFormat,java.util.Date" %>
<%
String title = "Locale Specific Currency";
//Get the client's Locale
Locale locale = request.getLocale( );
NumberFormat nft = NumberFormat.getCurrencyInstance(locale);
String formattedCurr = nft.format(1000000);
%>
<html>
<head>
<title><% out.print(title); %></title>
</head>
<body>
<center>
<h1><% out.print(title); %></h1>
</center>
<div align = "center">
<p>Formatted Currency: <% out.print(formattedCurr); %></p>
</div>
</body>
</html>
You can use the java.txt.NumberFormat class and its static getPercentInstance( ) method to get locale specific percentage. Following example shows how to format percentage specific to a given locale −
<%@ page import = "java.io.*,java.util.Locale" %>
<%@ page import = "javax.servlet.*,javax.servlet.http.* "%>
<%@ page import = "java.text.NumberFormat,java.util.Date" %>
<%
String title = "Locale Specific Percentage";
//Get the client's Locale
Locale locale = request.getLocale( );
NumberFormat nft = NumberFormat.getPercentInstance(locale);
String formattedPerc = nft.format(0.51);
%>
<html>
<head>
<title><% out.print(title); %></title>
</head>
<body>
<center>
<h1><% out.print(title); %></h1>
</center>
<div align = "center">
<p>Formatted Percentage: <% out.print(formattedPerc); %></p> | [
{
"code": null,
"e": 2525,
"s": 2373,
"text": "In this chapter, we will discuss the concept of Internationalization in JSP. Before we proceed, let us understand the following three important terms −"
},
{
"code": null,
"e": 2681,
"s": 2525,
"text": "Internationalization (i18n) − ... |
Probability for three randomly chosen numbers to be in AP | 06 Apr, 2021
Given a number n and an array containing 1 to (2n+1) consecutive numbers. Three elements are chosen at random. Find the probability that the elements chosen are in A.P.Examples:
Input : n = 2
Output : 0.4
The array would be {1, 2, 3, 4, 5}
Out of all elements, triplets which
are in AP: {1, 2, 3}, {2, 3, 4},
{3, 4, 5}, {1, 3, 5}
No of ways to choose elements from
the array: 10 (5C3)
So, probability = 4/10 = 0.4
Input : n = 5
Output : 0.1515
The number of ways to select any 3 numbers from (2n+1) numbers are:(2n + 1) C 3 Now, for the numbers to be in AP: with common difference 1—{1, 2, 3}, {2, 3, 4}, {3, 4, 5}...{2n-1, 2n, 2n+1} with common difference 2—{1, 3, 5}, {2, 4, 6}, {3, 5, 7}...{2n-3, 2n-1, 2n+1} with common difference n— {1, n+1, 2n+1} Therefore, Total number of AP group of 3 numbers in (2n+1) numbers are: (2n – 1)+(2n – 3)+(2n – 5) +...+ 3 + 1 = n * n (Sum of first n odd numbers is n * n ) So, probability for 3 randomly chosen numbers in (2n + 1) consecutive numbers to be in AP = (n * n) / (2n + 1) C 3 = 3 n / (4 (n * n) – 1)
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find probability that// 3 randomly chosen numbers form AP.#include <bits/stdc++.h>using namespace std; // function to calculate probabilitydouble procal(int n){ return (3.0 * n) / (4.0 * (n * n) - 1);} // Driver code to run above functionint main(){ int a[] = { 1, 2, 3, 4, 5 }; int n = sizeof(a)/sizeof(a[0]); cout << procal(n); return 0;}
// Java program to find probability that// 3 randomly chosen numbers form AP. class GFG { // function to calculate probability static double procal(int n) { return (3.0 * n) / (4.0 * (n * n) - 1); } // Driver code to run above function public static void main(String arg[]) { int a[] = { 1, 2, 3, 4, 5 }; int n = a.length; System.out.print(Math.round(procal(n) * 1000000.0) / 1000000.0); }} // This code is contributed by Anant Agarwal.
# Python3 program to find probability that# 3 randomly chosen numbers form AP. # Function to calculate probabilitydef procal(n): return (3.0 * n) / (4.0 * (n * n) - 1) # Driver codea = [1, 2, 3, 4, 5]n = len(a)print(round(procal(n), 6)) # This code is contributed by Smitha Dinesh Semwal.
// C# program to find probability that// 3 randomly chosen numbers form AP.using System; class GFG { // function to calculate probability static double procal(int n) { return (3.0 * n) / (4.0 * (n * n) - 1); } // Driver code public static void Main() { int []a = { 1, 2, 3, 4, 5 }; int n = a.Length; Console.Write(Math.Round(procal(n) * 1000000.0) / 1000000.0); }} // This code is contributed by nitin mittal
<?php// PHP program to find probability that// 3 randomly chosen numbers form AP. // function to calculate probabilityfunction procal($n){ return (3.0 * $n) / (4.0 * ($n * $n) - 1);} // Driver code $a = array(1, 2, 3, 4, 5); $n = sizeof($a); echo procal($n); // This code is contributed by aj_36?>
<script>// Javascript program to find probability that// 3 randomly chosen numbers form AP. // function to calculate probabilityfunction procal(n){ return (3.0 * n) / (4.0 * (n * n) - 1);} // Driver code let a = [1, 2, 3, 4, 5]; let n = a.length; document.write(procal(n)); // This code is contributed by _saurabh_jaiswal</script>
Output:
0.151515
Time Complexity : O(1)
nitin mittal
jit_t
_saurabh_jaiswal
arithmetic progression
Probability
Combinatorial
Mathematical
Mathematical
Combinatorial
Probability
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Write a program to print all permutations of a given string
Permutation and Combination in Python
Factorial of a large number
itertools.combinations() module in Python to print all possible combinations
Count of subsets with sum equal to X
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Apr, 2021"
},
{
"code": null,
"e": 234,
"s": 54,
"text": "Given a number n and an array containing 1 to (2n+1) consecutive numbers. Three elements are chosen at random. Find the probability that the elements chosen are in A.P.Exampl... |
Python | Numpy fromarrays() method | 19 Sep, 2019
With the help of numpy.core.fromarrays() method, we can create the record array by using the list of different arrays by using numpy.core.fromarrays() method.
Syntax : numpy.core.fromarrays([li1, li2....], metadata)
Return : Return the record of an array.
Example #1 :
In this example we can see that using numpy.core.fromarrays() method, we are able to get the record array by using list of different arrays.
# import numpyimport numpy as np # using numpy.core.fromarrays() methodli1 = np.array([101, 102, 103, 104])li2 = np.array(['Jitender', 'Purnima', 'Ruhi', 'Varun'])li3 = np.array([21, 22, 12, 35]) gfg = np.core.records.fromarrays([li1, li2, li3], names ='Rollno, Name, Age') print(gfg[1])
Output :
(102, ‘Purnima’, 22)
Example #2 :
# import numpyimport numpy as np # using numpy.core.fromarrays() methodli1 = np.array([101, 102, 103, 104])li2 = np.array(['Jitender', 'Purnima', 'Ruhi', 'Varun'])li3 = np.array([21, 22, 12, 35]) gfg = np.core.records.fromarrays([li1, li2, li3], names ='Rollno, Name, Age') print(gfg.Rollno)print(gfg.Name)print(gfg.Age)
Output :
[101 102 103 104][‘Jitender’ ‘Purnima’ ‘Ruhi’ ‘Varun’][21 22 12 35]
Python-numpy
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 Sep, 2019"
},
{
"code": null,
"e": 187,
"s": 28,
"text": "With the help of numpy.core.fromarrays() method, we can create the record array by using the list of different arrays by using numpy.core.fromarrays() method."
},
{
"c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.