title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to get the applied azure resource tags using PowerShell?
To get all the applied tags to the Azure resources we need to use the Get-AZTag command and need to provide ResourceID to it. For example, We need to retrieve the Azure VM tags and we will use its resource ID. PS C:\> $vm = Get-AzVM -Name Testmachine2k16 PS C:\> Get-AzTag -ResourceId $vm.Id You can see the output in the properties window. Another simple method is to use the Tags property for that particular cmdlet. For example, Get-AzVM, Get-AZResourceGroup, etc use the tag property for displaying the applied tags. PS C:\> Get-AzVM -VMName TestMachine2k16 | Select -ExpandProperty Tags Key Value --- ----- Owner Chirag For Ansible Patching_Day Sunday Application SecretTag Similarly, to get the resource group tags, you can use either the Get-AZTag command with the ResourceID property of the resource group or the Get-AZResourceGroup command with the Tag property. PS C:\> $rg = Get-AzResourceGroup -ResourceGroupName TestRG PS C:\> Get-AzTag -ResourceId $rg.ResourceId Or, PS C:\> Get-AzResourceGroup -Name TestRG | Select -ExpandProperty Tags To search for the specific tags. We need to use -Name property of the Get-AZTag command. For example, we need to search the tag called Patching_Day then we can use the below command. It shows the Patching_Day tag from the entire subscription because we haven’t provided any specific resource or resource group. The count property shows the number of times the tag is applied to the resources and ValuesTable and values property shows the values associated with that tag key. PS C:\> Get-AzTag -Name Patching_Day | fl Name : Patching_Day ValuesTable : Name Count ====== ===== Sunday 2 Count : 2 Values : {Sunday}
[ { "code": null, "e": 1201, "s": 1062, "text": "To get all the applied tags to the Azure resources we need to use the Get-AZTag command and need to provide ResourceID to it. For example," }, { "code": null, "e": 1272, "s": 1201, "text": "We need to retrieve the Azure VM tags and we will use its resource ID." }, { "code": null, "e": 1354, "s": 1272, "text": "PS C:\\> $vm = Get-AzVM -Name Testmachine2k16\nPS C:\\> Get-AzTag -ResourceId $vm.Id" }, { "code": null, "e": 1583, "s": 1354, "text": "You can see the output in the properties window. Another simple method is to use the Tags property for that particular cmdlet. For example, Get-AzVM, Get-AZResourceGroup, etc use the tag property for displaying the applied tags." }, { "code": null, "e": 1794, "s": 1583, "text": "PS C:\\> Get-AzVM -VMName TestMachine2k16 | Select -ExpandProperty Tags\nKey Value\n--- -----\nOwner Chirag\nFor Ansible\nPatching_Day Sunday\nApplication SecretTag" }, { "code": null, "e": 1987, "s": 1794, "text": "Similarly, to get the resource group tags, you can use either the Get-AZTag command with the ResourceID property of the resource group or the Get-AZResourceGroup command with the Tag property." }, { "code": null, "e": 2092, "s": 1987, "text": "PS C:\\> $rg = Get-AzResourceGroup -ResourceGroupName TestRG\nPS C:\\> Get-AzTag -ResourceId $rg.ResourceId" }, { "code": null, "e": 2096, "s": 2092, "text": "Or," }, { "code": null, "e": 2167, "s": 2096, "text": "PS C:\\> Get-AzResourceGroup -Name TestRG | Select -ExpandProperty Tags" }, { "code": null, "e": 2478, "s": 2167, "text": "To search for the specific tags. We need to use -Name property of the Get-AZTag command. For example, we need to search the tag called Patching_Day then we can use the below command. It shows the Patching_Day tag from the entire subscription because we haven’t provided any specific resource or resource group." }, { "code": null, "e": 2642, "s": 2478, "text": "The count property shows the number of times the tag is applied to the resources and ValuesTable and values property shows the values associated with that tag key." }, { "code": null, "e": 2810, "s": 2642, "text": "PS C:\\> Get-AzTag -Name Patching_Day | fl\n\nName : Patching_Day\nValuesTable :\n Name Count\n ====== =====\n Sunday 2\n\nCount : 2\nValues : {Sunday}" } ]
Simple Android grid example using RecyclerView with GridLayoutManager
Before getting into grid Layout manager for recycler view example, we should know what is Recycler view in android. Recycler view is more advanced version of list view and it works based on View holder design pattern. Using recycler view we can show grids and list of items. This example demonstrate about how to integrate Recycler View with Grid layout manager by creating a beautiful student records app that displays student name with age. 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 − Open build.gradle and add Recycler view library dependency. apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.example.andy.tutorialspoint" minSdkVersion 19 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support:design:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' implementation 'com.android.support:recyclerview-v7:28.0.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } Step 3 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" xmlns:app = "http://schemas.android.com/apk/res-auto" android:layout_width = "match_parent" android:layout_height = "match_parent" app:layout_behavior = "@string/appbar_scrolling_view_behavior" tools:showIn = "@layout/activity_main" tools:context = ".MainActivity"> <android.support.v7.widget.RecyclerView android:id = "@+id/recycler_view" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:scrollbars = "vertical" /> </RelativeLayout> In the above code we have added recycler view to window manager as relative parent layout. Step 4 − Add the following code to src/MainActivity.java package com.example.andy.tutorialspoint; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private StudentAdapter studentAdapter; private List studentDataList = new ArrayList<>(); @TargetApi(Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.recycler_view); studentAdapter = new StudentAdapter(studentDataList); RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2); recyclerView.setLayoutManager(manager); recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); recyclerView.setAdapter(studentAdapter); StudentDataPrepare(); } @RequiresApi(api = Build.VERSION_CODES.N) private void StudentDataPrepare() { studentData data = new studentData("sai", 25); studentDataList.add(data); data = new studentData("sai", 25); studentDataList.add(data); data = new studentData("raghu", 20); studentDataList.add(data); data = new studentData("raj", 28); studentDataList.add(data); data = new studentData("amar", 15); studentDataList.add(data); data = new studentData("bapu", 19); studentDataList.add(data); data = new studentData("chandra", 52); studentDataList.add(data); data = new studentData("deraj", 30); studentDataList.add(data); data = new studentData("eshanth", 28); studentDataList.add(data); Collections.sort(studentDataList, new Comparator() { @Override public int compare(studentData o1, studentData o2) { return o1.name.compareTo(o2.name); } }); } } In the above code we have added recycler view and studentAdapter. In that student adapter we have passed studentDatalist as arraylist. In Student data list contains name of the student and age. To get the grids, we have to use grid layout manager as shown below - RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2); In the above code we have used layout manager as GridlayoutManger and added cells as 2.So It will show the result with two grids in each row. To compare recycler view items we have used collections framework and sort method as shown below - Collections.sort(studentDataList, new Comparator() { @Override public int compare(studentData o1, studentData o2) { return o1.name.compareTo(o2.name); } }); In the above code we are comparing elements by using name. Step 5 − Following is the content of the modified file src/ StudentAdapter.java. package com.example.andy.tutorialspoint; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import java.util.Random; class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.MyViewHolder> { List<studentData> studentDataList; public StudentAdapter(List<studentData> studentDataList) { this.studentDataList = studentDataList; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View itemView = LayoutInflater.from(viewGroup.getContext()) .inflate(R.layout.student_list_row, viewGroup, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder viewHolder, int i) { studentData data=studentDataList.get(i); Random rnd = new Random(); int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); viewHolder.parent.setBackgroundColor(currentColor); viewHolder.name.setText(data.name); viewHolder.age.setText(String.valueOf(data.age)); } @Override public int getItemCount() { return studentDataList.size(); } class MyViewHolder extends RecyclerView.ViewHolder { TextView name,age; LinearLayout parent; public MyViewHolder(View itemView) { super(itemView); parent = itemView.findViewById(R.id.parent); name = itemView.findViewById(R.id.name); age = itemView.findViewById(R.id.age); } } } In the adapter class we have four methods as shown below - onCreateViewHolder() :- It is used to create a view holder and it returns a view. onCreateViewHolder() :- It is used to create a view holder and it returns a view. onBindViewHolder() - it going to bind with created view holder. onBindViewHolder() - it going to bind with created view holder. getItemCount() - it contains size of list. getItemCount() - it contains size of list. MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder To set random background for recycler view items, we have generated random colors using random class(which is predefined class in Android) and added color to parent of view item as shown below - Random rnd = new Random(); int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); viewHolder.parent.setBackgroundColor(currentColor); Step 6 − Following is the modified content of the xml res/layout/student_list_row.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "horizontal" android:layout_width="match_parent" android:weightSum =" 1" android:layout_height="wrap_content"> <TextView android:id = "@+id/name" android:layout_width = "0dp" android:layout_weight = "0.5" android:gravity = "center" android:textSize = "15sp" android:layout_height = "100dp" /> <TextView android:id = "@+id/age" android:layout_width = "0dp" android:layout_weight = "0.5" android:gravity = "center" android:textSize = "15sp" android:layout_height = "100dp" /> </LinearLayout> In the above list view we have created two text views for name and age. Step 7 − Following is the content of the modified file src/ studentData.java. package com.example.andy.tutorialspoint; class studentData { String name; int age; public studentData(String name, int age) { this.name = name; this.age = age; } } In the above informs about student data object. 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": 1337, "s": 1062, "text": "Before getting into grid Layout manager for recycler view example, we should know what is Recycler view in android. Recycler view is more advanced version of list view and it works based on View holder design pattern. Using recycler view we can show grids and list of items." }, { "code": null, "e": 1505, "s": 1337, "text": "This example demonstrate about how to integrate Recycler View with Grid layout manager by creating a beautiful student records app that displays student name with age." }, { "code": null, "e": 1634, "s": 1505, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1703, "s": 1634, "text": "Step 2 − Open build.gradle and add Recycler view library dependency." }, { "code": null, "e": 2721, "s": 1703, "text": "apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.tutorialspoint\"\n minSdkVersion 19\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support:design:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n implementation 'com.android.support:recyclerview-v7:28.0.0'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}" }, { "code": null, "e": 2786, "s": 2721, "text": "Step 3 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 3476, "s": 2786, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout\n xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n app:layout_behavior = \"@string/appbar_scrolling_view_behavior\"\n tools:showIn = \"@layout/activity_main\"\n tools:context = \".MainActivity\">\n <android.support.v7.widget.RecyclerView\n android:id = \"@+id/recycler_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:scrollbars = \"vertical\" />\n</RelativeLayout>" }, { "code": null, "e": 3567, "s": 3476, "text": "In the above code we have added recycler view to window manager as relative parent layout." }, { "code": null, "e": 3624, "s": 3567, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5961, "s": 3624, "text": "package com.example.andy.tutorialspoint;\n\nimport android.annotation.TargetApi;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.DividerItemDecoration;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\n\n\npublic class MainActivity extends AppCompatActivity {\n private RecyclerView recyclerView;\n private StudentAdapter studentAdapter;\n private List studentDataList = new ArrayList<>();\n @TargetApi(Build.VERSION_CODES.O)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n recyclerView = findViewById(R.id.recycler_view);\n studentAdapter = new StudentAdapter(studentDataList);\n RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2);\n recyclerView.setLayoutManager(manager);\n recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));\n recyclerView.setAdapter(studentAdapter);\n StudentDataPrepare();\n }\n @RequiresApi(api = Build.VERSION_CODES.N)\n private void StudentDataPrepare() {\n studentData data = new studentData(\"sai\", 25);\n studentDataList.add(data);\n data = new studentData(\"sai\", 25);\n studentDataList.add(data);\n data = new studentData(\"raghu\", 20);\n studentDataList.add(data);\n data = new studentData(\"raj\", 28);\n studentDataList.add(data);\n data = new studentData(\"amar\", 15);\n studentDataList.add(data);\n data = new studentData(\"bapu\", 19);\n studentDataList.add(data);\n data = new studentData(\"chandra\", 52);\n studentDataList.add(data);\n data = new studentData(\"deraj\", 30);\n studentDataList.add(data);\n data = new studentData(\"eshanth\", 28);\n studentDataList.add(data);\n Collections.sort(studentDataList, new Comparator() {\n @Override\n public int compare(studentData o1, studentData o2) {\n return o1.name.compareTo(o2.name);\n }\n });\n }\n}" }, { "code": null, "e": 6155, "s": 5961, "text": "In the above code we have added recycler view and studentAdapter. In that student adapter we have passed studentDatalist as arraylist. In Student data list contains name of the student and age." }, { "code": null, "e": 6225, "s": 6155, "text": "To get the grids, we have to use grid layout manager as shown below -" }, { "code": null, "e": 6294, "s": 6225, "text": "RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2);" }, { "code": null, "e": 6436, "s": 6294, "text": "In the above code we have used layout manager as GridlayoutManger and added cells as 2.So It will show the result with two grids in each row." }, { "code": null, "e": 6535, "s": 6436, "text": "To compare recycler view items we have used collections framework and sort method as shown below -" }, { "code": null, "e": 6707, "s": 6535, "text": "Collections.sort(studentDataList, new Comparator() {\n @Override\n public int compare(studentData o1, studentData o2) {\n return o1.name.compareTo(o2.name);\n }\n});" }, { "code": null, "e": 6766, "s": 6707, "text": "In the above code we are comparing elements by using name." }, { "code": null, "e": 6847, "s": 6766, "text": "Step 5 − Following is the content of the modified file src/ StudentAdapter.java." }, { "code": null, "e": 8578, "s": 6847, "text": "package com.example.andy.tutorialspoint;\n\nimport android.graphics.Color;\nimport android.support.annotation.NonNull;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport java.util.List;\nimport java.util.Random;\n\nclass StudentAdapter extends RecyclerView.Adapter<StudentAdapter.MyViewHolder> {\n List<studentData> studentDataList;\n public StudentAdapter(List<studentData> studentDataList) {\n this.studentDataList = studentDataList;\n }\n @NonNull\n @Override\n public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {\n View itemView = LayoutInflater.from(viewGroup.getContext())\n .inflate(R.layout.student_list_row, viewGroup, false);\n return new MyViewHolder(itemView);\n }\n @Override\n public void onBindViewHolder(MyViewHolder viewHolder, int i) {\n studentData data=studentDataList.get(i);\n Random rnd = new Random();\n int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));\n viewHolder.parent.setBackgroundColor(currentColor);\n viewHolder.name.setText(data.name);\n viewHolder.age.setText(String.valueOf(data.age));\n }\n @Override\n public int getItemCount() {\n return studentDataList.size();\n }\n class MyViewHolder extends RecyclerView.ViewHolder {\n TextView name,age;\n LinearLayout parent;\n public MyViewHolder(View itemView) {\n super(itemView);\n parent = itemView.findViewById(R.id.parent);\n name = itemView.findViewById(R.id.name);\n age = itemView.findViewById(R.id.age);\n }\n }\n}" }, { "code": null, "e": 8637, "s": 8578, "text": "In the adapter class we have four methods as shown below -" }, { "code": null, "e": 8719, "s": 8637, "text": "onCreateViewHolder() :- It is used to create a view holder and it returns a view." }, { "code": null, "e": 8801, "s": 8719, "text": "onCreateViewHolder() :- It is used to create a view holder and it returns a view." }, { "code": null, "e": 8865, "s": 8801, "text": "onBindViewHolder() - it going to bind with created view holder." }, { "code": null, "e": 8929, "s": 8865, "text": "onBindViewHolder() - it going to bind with created view holder." }, { "code": null, "e": 8972, "s": 8929, "text": "getItemCount() - it contains size of list." }, { "code": null, "e": 9015, "s": 8972, "text": "getItemCount() - it contains size of list." }, { "code": null, "e": 9110, "s": 9015, "text": "MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder" }, { "code": null, "e": 9205, "s": 9110, "text": "MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder" }, { "code": null, "e": 9400, "s": 9205, "text": "To set random background for recycler view items, we have generated random colors using random class(which is predefined class in Android) and added color to parent of view item as shown below -" }, { "code": null, "e": 9569, "s": 9400, "text": "Random rnd = new Random();\nint currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));\nviewHolder.parent.setBackgroundColor(currentColor);" }, { "code": null, "e": 9656, "s": 9569, "text": "Step 6 − Following is the modified content of the xml res/layout/student_list_row.xml." }, { "code": null, "e": 10376, "s": 9656, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:orientation = \"horizontal\" android:layout_width=\"match_parent\"\n android:weightSum =\" 1\"\n android:layout_height=\"wrap_content\">\n <TextView\n android:id = \"@+id/name\"\n android:layout_width = \"0dp\"\n android:layout_weight = \"0.5\"\n android:gravity = \"center\"\n android:textSize = \"15sp\"\n android:layout_height = \"100dp\" />\n <TextView\n android:id = \"@+id/age\"\n android:layout_width = \"0dp\"\n android:layout_weight = \"0.5\"\n android:gravity = \"center\"\n android:textSize = \"15sp\"\n android:layout_height = \"100dp\" />\n</LinearLayout>" }, { "code": null, "e": 10448, "s": 10376, "text": "In the above list view we have created two text views for name and age." }, { "code": null, "e": 10526, "s": 10448, "text": "Step 7 − Following is the content of the modified file src/ studentData.java." }, { "code": null, "e": 10715, "s": 10526, "text": "package com.example.andy.tutorialspoint;\n\nclass studentData {\n String name;\n int age;\n public studentData(String name, int age) {\n this.name = name;\n this.age = age;\n }\n}" }, { "code": null, "e": 11110, "s": 10715, "text": "In the above informs about student data object. Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 11150, "s": 11110, "text": "Click here to download the project code" } ]
Height of a generic tree from parent array - GeeksforGeeks
24 Nov, 2021 We are given a tree of size n as array parent[0..n-1] where every index i in the parent[] represents a node and the value at i represents the immediate parent of that node. For root node value will be -1. Find the height of the generic tree given the parent links.Examples: Input : parent[] = {-1, 0, 0, 0, 3, 1, 1, 2} Output : 2 Input : parent[] = {-1, 0, 1, 2, 3} Output : 4 Approach 1: One solution is to traverse up the tree from the node till the root node is reached with node value -1. While Traversing for each node stores maximum path length. The Time Complexity of this solution is O(n^2).Approach 2: Build graph for N-ary Tree in O(n) time and apply BFS on the stored graph in O(n) time and while doing BFS store maximum reached level. This solution does two iterations to find the height of N-ary tree. C++ Java Python3 C# Javascript // C++ code to find height of N-ary// tree in O(n)#include <bits/stdc++.h>#define MAX 1001using namespace std; // Adjacency list to// store N-ary treevector<int> adj[MAX]; // Build tree in tree in O(n)int build_tree(int arr[], int n){ int root_index = 0; // Iterate for all nodes for (int i = 0; i < n; i++) { // if root node, store index if (arr[i] == -1) root_index = i; else { adj[i].push_back(arr[i]); adj[arr[i]].push_back(i); } } return root_index;} // Applying BFSint BFS(int start){ // map is used as visited array map<int, int> vis; queue<pair<int, int> > q; int max_level_reached = 0; // height of root node is zero q.push({ start, 0 }); // p.first denotes node in adjacency list // p.second denotes level of p.first pair<int, int> p; while (!q.empty()) { p = q.front(); vis[p.first] = 1; // store the maximum level reached max_level_reached = max(max_level_reached, p.second); q.pop(); for (int i = 0; i < adj[p.first].size(); i++) // adding 1 to previous level // stored on node p.first // which is parent of node adj[p.first][i] // if adj[p.first][i] is not visited if (!vis[adj[p.first][i]]) q.push({ adj[p.first][i], p.second + 1 }); } return max_level_reached;} // Driver Functionint main(){ // node 0 to node n-1 int parent[] = { -1, 0, 1, 2, 3 }; // Number of nodes in tree int n = sizeof(parent) / sizeof(parent[0]); int root_index = build_tree(parent, n); int ma = BFS(root_index); cout << "Height of N-ary Tree=" << ma; return 0;} // Java code to find height of N-ary// tree in O(n)import java.io.*;import java.util.*; class GFG { static int MAX = 1001; // Adjacency list to // store N-ary tree static ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(); // Build tree in tree in O(n) static int build_tree(int arr[], int n) { int root_index = 0; // Iterate for all nodes for (int i = 0; i < n; i++) { // if root node, store index if (arr[i] == -1) root_index = i; else { adj.get(i).add(arr[i]); adj.get(arr[i]).add(i); } } return root_index; } // Applying BFS static int BFS(int start) { // map is used as visited array Map<Integer, Integer> vis = new HashMap<Integer, Integer>(); ArrayList<ArrayList<Integer>> q = new ArrayList<ArrayList<Integer>>(); int max_level_reached = 0; // height of root node is zero q.add(new ArrayList<Integer>(Arrays.asList(start, 0 ))); // p.first denotes node in adjacency list // p.second denotes level of p.first ArrayList<Integer> p = new ArrayList<Integer>(); while(q.size() != 0) { p = q.get(0); vis.put(p.get(0),1); // store the maximum level reached max_level_reached = Math.max(max_level_reached,p.get(1)); q.remove(0); for(int i = 0; i < adj.get(p.get(0)).size(); i++) { // adding 1 to previous level // stored on node p.first // which is parent of node adj[p.first][i] // if adj[p.first][i] is not visited if(!vis.containsKey(adj.get(p.get(0)).get(i))) { q.add(new ArrayList<Integer>(Arrays.asList(adj.get(p.get(0)).get(i), p.get(1)+1))); } } } return max_level_reached; } // Driver Function public static void main (String[] args) { for(int i = 0; i < MAX; i++) { adj.add(new ArrayList<Integer>()); } // node 0 to node n-1 int parent[] = { -1, 0, 1, 2, 3 }; // Number of nodes in tree int n = parent.length; int root_index = build_tree(parent, n); int ma = BFS(root_index); System.out.println( "Height of N-ary Tree=" + ma); }} // This code is contributed by rag2127 # Python3 code to find height # of N-ary tree in O(n)from collections import deque MAX = 1001 # Adjacency list to# store N-ary treeadj = [[] for i in range(MAX)] # Build tree in tree in O(n)def build_tree(arr, n): root_index = 0 # Iterate for all nodes for i in range(n): # if root node, store # index if (arr[i] == -1): root_index = i else: adj[i].append(arr[i]) adj[arr[i]].append(i) return root_index # Applying BFSdef BFS(start): # map is used as visited # array vis = {} q = deque() max_level_reached = 0 # height of root node is # zero q.append([start, 0]) # p.first denotes node in # adjacency list # p.second denotes level of # p.first p = [] while (len(q) > 0): p = q.popleft() vis[p[0]] = 1 # store the maximum level # reached max_level_reached = max(max_level_reached, p[1]) for i in range(len(adj[p[0]])): # adding 1 to previous level # stored on node p.first # which is parent of node # adj[p.first][i] # if adj[p.first][i] is not visited if (adj[p[0]][i] not in vis ): q.append([adj[p[0]][i], p[1] + 1]) return max_level_reached # Driver codeif __name__ == '__main__': # node 0 to node n-1 parent = [-1, 0, 1, 2, 3] # Number of nodes in tree n = len(parent) root_index = build_tree(parent, n) ma = BFS(root_index) print("Height of N-ary Tree=", ma) # This code is contributed by Mohit Kumar 29 // C# code to find height of N-ary// tree in O(n)using System;using System.Collections.Generic; public class GFG{ static int MAX = 1001; // Adjacency list to // store N-ary tree static List<List<int>> adj = new List<List<int>>(); // Build tree in tree in O(n) static int build_tree(int[] arr, int n) { int root_index = 0; // Iterate for all nodes for (int i = 0; i < n; i++) { // if root node, store index if (arr[i] == -1) root_index = i; else { adj[i].Add(arr[i]); adj[arr[i]].Add(i); } } return root_index; } // Applying BFS static int BFS(int start) { // map is used as visited array Dictionary<int, int> vis = new Dictionary<int, int>(); List<List<int>> q= new List<List<int>>(); int max_level_reached = 0; // height of root node is zero q.Add(new List<int>(){start, 0}); // p.first denotes node in adjacency list // p.second denotes level of p.first List<int> p = new List<int>(); while(q.Count != 0) { p = q[0]; vis.Add(p[0], 1); // store the maximum level reached max_level_reached = Math.Max(max_level_reached, p[1]); q.RemoveAt(0); for(int i = 0; i < adj[p[0]].Count; i++) { // adding 1 to previous level // stored on node p.first // which is parent of node adj[p.first][i] // if adj[p.first][i] is not visited if(!vis.ContainsKey(adj[p[0]][i])) { q.Add(new List<int>(){adj[p[0]][i], p[1] + 1 }); } } } return max_level_reached; } // Driver Function static public void Main () { for(int i = 0; i < MAX; i++) { adj.Add(new List<int>()); } // node 0 to node n-1 int[] parent = { -1, 0, 1, 2, 3 }; // Number of nodes in tree int n = parent.Length; int root_index = build_tree(parent, n); int ma = BFS(root_index); Console.Write("Height of N-ary Tree=" + ma); }} // This code is contributed by avanitrachhadiya2155 <script> // JavaScript code to find height of N-ary// tree in O(n) let MAX = 1001; let adj = []; // Adjacency list to // store N-ary tree function build_tree(arr,n) { let root_index = 0; // Iterate for all nodes for (let i = 0; i < n; i++) { // if root node, store index if (arr[i] == -1) root_index = i; else { adj[i].push(arr[i]); adj[arr[i]].push(i); } } return root_index; } // Applying BFS function BFS(start) { // map is used as visited array let vis = new Map(); let q = []; let max_level_reached = 0; // height of root node is zero q.push([start, 0 ]); // p.first denotes node in adjacency list // p.second denotes level of p.first let p = []; while(q.length != 0) { p = q[0]; vis.set(p[0],1); // store the maximum level reached max_level_reached = Math.max(max_level_reached,p[1]); q.shift(); for(let i = 0; i < adj[p[0]].length; i++) { // adding 1 to previous level // stored on node p.first // which is parent of node adj[p.first][i] // if adj[p.first][i] is not visited if(!vis.has(adj[p[0]][i])) { q.push([adj[p[0]][i], p[1]+1]); } } } return max_level_reached; } // Driver Function for(let i = 0; i < MAX; i++) { adj.push([]); } // node 0 to node n-1 let parent = [ -1, 0, 1, 2, 3 ]; // Number of nodes in tree let n = parent.length; let root_index = build_tree(parent, n); let ma = BFS(root_index); document.write( "Height of N-ary Tree=" + ma); // This code is contributed by unknown2108 </script> Height of N-ary Tree=4 The Time Complexity of this solution is O(2n) which converges to O(n) for very large n.Approach 3: We can find the height of the N-ary Tree in only one iteration. We visit nodes from 0 to n-1 iteratively and mark the unvisited ancestors recursively if they are not visited before till we reach a node which is visited, or we reach the root node. If we reach the visited node while traversing up the tree using parent links, then we use its height and will not go further in recursion.Explanation For Example 1:: For node 0: Check for Root node is true, Return 0 as height, Mark node 0 as visited For node 1: Recur for an immediate ancestor, i.e 0, which is already visited So, Use its height and return height(node 0) +1 Mark node 1 as visited For node 2: Recur for an immediate ancestor, i.e 0, which is already visited So, Use its height and return height(node 0) +1 Mark node 2 as visited For node 3: Recur for an immediate ancestor, i.e 0, which is already visited So, Use its height and return height(node 0) +1 Mark node 3 as visited For node 4: Recur for an immediate ancestor, i.e 3, which is already visited So, Use its height and return height(node 3) +1 Mark node 3 as visited For node 5: Recur for an immediate ancestor, i.e 1, which is already visited So, Use its height and return height(node 1) +1 Mark node 5 as visited For node 6: Recur for an immediate ancestor, i.e 1, which is already visited So, Use its height and return height(node 1) +1 Mark node 6 as visited For node 7: Recur for an immediate ancestor, i.e 2, which is already visited So, Use its height and return height(node 2) +1 Mark node 7 as visitedHence, we processed each node in the N-ary tree only once. C++ Java Python3 C# Javascript // C++ code to find height of N-ary// tree in O(n) (Efficient Approach)#include <bits/stdc++.h>using namespace std; // Recur For Ancestors of node and// store height of node at lastint fillHeight(int p[], int node, int visited[], int height[]){ // If root node if (p[node] == -1) { // mark root node as visited visited[node] = 1; return 0; } // If node is already visited if (visited[node]) return height[node]; // Visit node and calculate its height visited[node] = 1; // recur for the parent node height[node] = 1 + fillHeight(p, p[node], visited, height); // return calculated height for node return height[node];} int findHeight(int parent[], int n){ // To store max height int ma = 0; // To check whether or not node is visited before int visited[n]; // For Storing Height of node int height[n]; memset(visited, 0, sizeof(visited)); memset(height, 0, sizeof(height)); for (int i = 0; i < n; i++) { // If not visited before if (!visited[i]) height[i] = fillHeight(parent, i, visited, height); // store maximum height so far ma = max(ma, height[i]); } return ma;} // Driver Functionint main(){ int parent[] = { -1, 0, 0, 0, 3, 1, 1, 2 }; int n = sizeof(parent) / sizeof(parent[0]); cout << "Height of N-ary Tree = " << findHeight(parent, n); return 0;} // Java code to find height of N-ary// tree in O(n) (Efficient Approach)import java.util.*;class GFG{ // Recur For Ancestors of node and// store height of node at laststatic int fillHeight(int p[], int node, int visited[], int height[]){ // If root node if (p[node] == -1) { // mark root node as visited visited[node] = 1; return 0; } // If node is already visited if (visited[node] == 1) return height[node]; // Visit node and calculate its height visited[node] = 1; // recur for the parent node height[node] = 1 + fillHeight(p, p[node], visited, height); // return calculated height for node return height[node];} static int findHeight(int parent[], int n){ // To store max height int ma = 0; // To check whether or not node is visited before int []visited = new int[n]; // For Storing Height of node int []height = new int[n]; for(int i = 0; i < n; i++) { visited[i] = 0; height[i] = 0; } for (int i = 0; i < n; i++) { // If not visited before if (visited[i] != 1) height[i] = fillHeight(parent, i, visited, height); // store maximum height so far ma = Math.max(ma, height[i]); } return ma;} // Driver Codepublic static void main(String[] args) { int parent[] = { -1, 0, 0, 0, 3, 1, 1, 2 }; int n = parent.length; System.out.println("Height of N-ary Tree = " + findHeight(parent, n));}} // This code is contributed by 29AjayKumar # Python3 code to find height of N-ary # tree in O(n) (Efficient Approach) # Recur For Ancestors of node and # store height of node at last def fillHeight(p, node, visited, height): # If root node if (p[node] == -1): # mark root node as visited visited[node] = 1 return 0 # If node is already visited if (visited[node]): return height[node] # Visit node and calculate its height visited[node] = 1 # recur for the parent node height[node] = 1 + fillHeight(p, p[node], visited, height) # return calculated height for node return height[node] def findHeight(parent, n): # To store max height ma = 0 # To check whether or not node is # visited before visited = [0] * n # For Storing Height of node height = [0] * n for i in range(n): # If not visited before if (not visited[i]): height[i] = fillHeight(parent, i, visited, height) # store maximum height so far ma = max(ma, height[i]) return ma # Driver Codeif __name__ == '__main__': parent = [-1, 0, 0, 0, 3, 1, 1, 2] n = len(parent) print("Height of N-ary Tree =", findHeight(parent, n)) # This code is contributed by PranchalK // C# code to find height of N-ary// tree in O(n) (Efficient Approach)using System; class GFG{ // Recur For Ancestors of node and// store height of node at laststatic int fillHeight(int []p, int node, int []visited, int []height){ // If root node if (p[node] == -1) { // mark root node as visited visited[node] = 1; return 0; } // If node is already visited if (visited[node] == 1) return height[node]; // Visit node and calculate its height visited[node] = 1; // recur for the parent node height[node] = 1 + fillHeight(p, p[node], visited, height); // return calculated height for node return height[node];} static int findHeight(int []parent, int n){ // To store max height int ma = 0; // To check whether or not // node is visited before int []visited = new int[n]; // For Storing Height of node int []height = new int[n]; for(int i = 0; i < n; i++) { visited[i] = 0; height[i] = 0; } for (int i = 0; i < n; i++) { // If not visited before if (visited[i] != 1) height[i] = fillHeight(parent, i, visited, height); // store maximum height so far ma = Math.Max(ma, height[i]); } return ma;} // Driver Codepublic static void Main(String[] args) { int []parent = { -1, 0, 0, 0, 3, 1, 1, 2 }; int n = parent.Length; Console.WriteLine("Height of N-ary Tree = " + findHeight(parent, n));}} // This code contributed by Rajput-Ji <script>// Javascript code to find height of N-ary// tree in O(n) (Efficient Approach) // Recur For Ancestors of node and// store height of node at lastfunction fillHeight(p, node, visited, height){ // If root node if (p[node] == -1) { // mark root node as visited visited[node] = 1; return 0; } // If node is already visited if (visited[node] == 1) return height[node]; // Visit node and calculate its height visited[node] = 1; // recur for the parent node height[node] = 1 + fillHeight(p, p[node], visited, height); // return calculated height for node return height[node];} function findHeight(parent,n){ // To store max height let ma = 0; // To check whether or not node is visited before let visited = new Array(n); // For Storing Height of node let height = new Array(n); for(let i = 0; i < n; i++) { visited[i] = 0; height[i] = 0; } for (let i = 0; i < n; i++) { // If not visited before if (visited[i] != 1) height[i] = fillHeight(parent, i, visited, height); // store maximum height so far ma = Math.max(ma, height[i]); } return ma;} // Driver Codelet parent = [ -1, 0, 0, 0, 3, 1, 1, 2 ];let n = parent.length;document.write("Height of N-ary Tree = " + findHeight(parent, n)); // This code is contributed by ab2127</script> Height of N-ary Tree = 2 Time Complexity: O(n) PranchalKatiyar 29AjayKumar Rajput-Ji mohit kumar 29 rag2127 avanitrachhadiya2155 unknown2108 ab2127 rajutsav1234 n-ary-tree Graph Tree Graph Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Traveling Salesman Problem (TSP) Implementation Binary Tree | Set 1 (Introduction) AVL Tree | Set 1 (Insertion) Binary Tree | Set 3 (Types of Binary Tree) Write a Program to Find the Maximum Depth or Height of a Tree Binary Tree | Set 2 (Properties)
[ { "code": null, "e": 25046, "s": 25018, "text": "\n24 Nov, 2021" }, { "code": null, "e": 25321, "s": 25046, "text": "We are given a tree of size n as array parent[0..n-1] where every index i in the parent[] represents a node and the value at i represents the immediate parent of that node. For root node value will be -1. Find the height of the generic tree given the parent links.Examples: " }, { "code": null, "e": 25377, "s": 25321, "text": "Input : parent[] = {-1, 0, 0, 0, 3, 1, 1, 2}\nOutput : 2" }, { "code": null, "e": 25425, "s": 25377, "text": "Input : parent[] = {-1, 0, 1, 2, 3}\nOutput : 4" }, { "code": null, "e": 25864, "s": 25425, "text": "Approach 1: One solution is to traverse up the tree from the node till the root node is reached with node value -1. While Traversing for each node stores maximum path length. The Time Complexity of this solution is O(n^2).Approach 2: Build graph for N-ary Tree in O(n) time and apply BFS on the stored graph in O(n) time and while doing BFS store maximum reached level. This solution does two iterations to find the height of N-ary tree. " }, { "code": null, "e": 25868, "s": 25864, "text": "C++" }, { "code": null, "e": 25873, "s": 25868, "text": "Java" }, { "code": null, "e": 25881, "s": 25873, "text": "Python3" }, { "code": null, "e": 25884, "s": 25881, "text": "C#" }, { "code": null, "e": 25895, "s": 25884, "text": "Javascript" }, { "code": "// C++ code to find height of N-ary// tree in O(n)#include <bits/stdc++.h>#define MAX 1001using namespace std; // Adjacency list to// store N-ary treevector<int> adj[MAX]; // Build tree in tree in O(n)int build_tree(int arr[], int n){ int root_index = 0; // Iterate for all nodes for (int i = 0; i < n; i++) { // if root node, store index if (arr[i] == -1) root_index = i; else { adj[i].push_back(arr[i]); adj[arr[i]].push_back(i); } } return root_index;} // Applying BFSint BFS(int start){ // map is used as visited array map<int, int> vis; queue<pair<int, int> > q; int max_level_reached = 0; // height of root node is zero q.push({ start, 0 }); // p.first denotes node in adjacency list // p.second denotes level of p.first pair<int, int> p; while (!q.empty()) { p = q.front(); vis[p.first] = 1; // store the maximum level reached max_level_reached = max(max_level_reached, p.second); q.pop(); for (int i = 0; i < adj[p.first].size(); i++) // adding 1 to previous level // stored on node p.first // which is parent of node adj[p.first][i] // if adj[p.first][i] is not visited if (!vis[adj[p.first][i]]) q.push({ adj[p.first][i], p.second + 1 }); } return max_level_reached;} // Driver Functionint main(){ // node 0 to node n-1 int parent[] = { -1, 0, 1, 2, 3 }; // Number of nodes in tree int n = sizeof(parent) / sizeof(parent[0]); int root_index = build_tree(parent, n); int ma = BFS(root_index); cout << \"Height of N-ary Tree=\" << ma; return 0;}", "e": 27662, "s": 25895, "text": null }, { "code": "// Java code to find height of N-ary// tree in O(n)import java.io.*;import java.util.*; class GFG { static int MAX = 1001; // Adjacency list to // store N-ary tree static ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(); // Build tree in tree in O(n) static int build_tree(int arr[], int n) { int root_index = 0; // Iterate for all nodes for (int i = 0; i < n; i++) { // if root node, store index if (arr[i] == -1) root_index = i; else { adj.get(i).add(arr[i]); adj.get(arr[i]).add(i); } } return root_index; } // Applying BFS static int BFS(int start) { // map is used as visited array Map<Integer, Integer> vis = new HashMap<Integer, Integer>(); ArrayList<ArrayList<Integer>> q = new ArrayList<ArrayList<Integer>>(); int max_level_reached = 0; // height of root node is zero q.add(new ArrayList<Integer>(Arrays.asList(start, 0 ))); // p.first denotes node in adjacency list // p.second denotes level of p.first ArrayList<Integer> p = new ArrayList<Integer>(); while(q.size() != 0) { p = q.get(0); vis.put(p.get(0),1); // store the maximum level reached max_level_reached = Math.max(max_level_reached,p.get(1)); q.remove(0); for(int i = 0; i < adj.get(p.get(0)).size(); i++) { // adding 1 to previous level // stored on node p.first // which is parent of node adj[p.first][i] // if adj[p.first][i] is not visited if(!vis.containsKey(adj.get(p.get(0)).get(i))) { q.add(new ArrayList<Integer>(Arrays.asList(adj.get(p.get(0)).get(i), p.get(1)+1))); } } } return max_level_reached; } // Driver Function public static void main (String[] args) { for(int i = 0; i < MAX; i++) { adj.add(new ArrayList<Integer>()); } // node 0 to node n-1 int parent[] = { -1, 0, 1, 2, 3 }; // Number of nodes in tree int n = parent.length; int root_index = build_tree(parent, n); int ma = BFS(root_index); System.out.println( \"Height of N-ary Tree=\" + ma); }} // This code is contributed by rag2127", "e": 30242, "s": 27662, "text": null }, { "code": "# Python3 code to find height # of N-ary tree in O(n)from collections import deque MAX = 1001 # Adjacency list to# store N-ary treeadj = [[] for i in range(MAX)] # Build tree in tree in O(n)def build_tree(arr, n): root_index = 0 # Iterate for all nodes for i in range(n): # if root node, store # index if (arr[i] == -1): root_index = i else: adj[i].append(arr[i]) adj[arr[i]].append(i) return root_index # Applying BFSdef BFS(start): # map is used as visited # array vis = {} q = deque() max_level_reached = 0 # height of root node is # zero q.append([start, 0]) # p.first denotes node in # adjacency list # p.second denotes level of # p.first p = [] while (len(q) > 0): p = q.popleft() vis[p[0]] = 1 # store the maximum level # reached max_level_reached = max(max_level_reached, p[1]) for i in range(len(adj[p[0]])): # adding 1 to previous level # stored on node p.first # which is parent of node # adj[p.first][i] # if adj[p.first][i] is not visited if (adj[p[0]][i] not in vis ): q.append([adj[p[0]][i], p[1] + 1]) return max_level_reached # Driver codeif __name__ == '__main__': # node 0 to node n-1 parent = [-1, 0, 1, 2, 3] # Number of nodes in tree n = len(parent) root_index = build_tree(parent, n) ma = BFS(root_index) print(\"Height of N-ary Tree=\", ma) # This code is contributed by Mohit Kumar 29", "e": 31928, "s": 30242, "text": null }, { "code": "// C# code to find height of N-ary// tree in O(n)using System;using System.Collections.Generic; public class GFG{ static int MAX = 1001; // Adjacency list to // store N-ary tree static List<List<int>> adj = new List<List<int>>(); // Build tree in tree in O(n) static int build_tree(int[] arr, int n) { int root_index = 0; // Iterate for all nodes for (int i = 0; i < n; i++) { // if root node, store index if (arr[i] == -1) root_index = i; else { adj[i].Add(arr[i]); adj[arr[i]].Add(i); } } return root_index; } // Applying BFS static int BFS(int start) { // map is used as visited array Dictionary<int, int> vis = new Dictionary<int, int>(); List<List<int>> q= new List<List<int>>(); int max_level_reached = 0; // height of root node is zero q.Add(new List<int>(){start, 0}); // p.first denotes node in adjacency list // p.second denotes level of p.first List<int> p = new List<int>(); while(q.Count != 0) { p = q[0]; vis.Add(p[0], 1); // store the maximum level reached max_level_reached = Math.Max(max_level_reached, p[1]); q.RemoveAt(0); for(int i = 0; i < adj[p[0]].Count; i++) { // adding 1 to previous level // stored on node p.first // which is parent of node adj[p.first][i] // if adj[p.first][i] is not visited if(!vis.ContainsKey(adj[p[0]][i])) { q.Add(new List<int>(){adj[p[0]][i], p[1] + 1 }); } } } return max_level_reached; } // Driver Function static public void Main () { for(int i = 0; i < MAX; i++) { adj.Add(new List<int>()); } // node 0 to node n-1 int[] parent = { -1, 0, 1, 2, 3 }; // Number of nodes in tree int n = parent.Length; int root_index = build_tree(parent, n); int ma = BFS(root_index); Console.Write(\"Height of N-ary Tree=\" + ma); }} // This code is contributed by avanitrachhadiya2155", "e": 33938, "s": 31928, "text": null }, { "code": "<script> // JavaScript code to find height of N-ary// tree in O(n) let MAX = 1001; let adj = []; // Adjacency list to // store N-ary tree function build_tree(arr,n) { let root_index = 0; // Iterate for all nodes for (let i = 0; i < n; i++) { // if root node, store index if (arr[i] == -1) root_index = i; else { adj[i].push(arr[i]); adj[arr[i]].push(i); } } return root_index; } // Applying BFS function BFS(start) { // map is used as visited array let vis = new Map(); let q = []; let max_level_reached = 0; // height of root node is zero q.push([start, 0 ]); // p.first denotes node in adjacency list // p.second denotes level of p.first let p = []; while(q.length != 0) { p = q[0]; vis.set(p[0],1); // store the maximum level reached max_level_reached = Math.max(max_level_reached,p[1]); q.shift(); for(let i = 0; i < adj[p[0]].length; i++) { // adding 1 to previous level // stored on node p.first // which is parent of node adj[p.first][i] // if adj[p.first][i] is not visited if(!vis.has(adj[p[0]][i])) { q.push([adj[p[0]][i], p[1]+1]); } } } return max_level_reached; } // Driver Function for(let i = 0; i < MAX; i++) { adj.push([]); } // node 0 to node n-1 let parent = [ -1, 0, 1, 2, 3 ]; // Number of nodes in tree let n = parent.length; let root_index = build_tree(parent, n); let ma = BFS(root_index); document.write( \"Height of N-ary Tree=\" + ma); // This code is contributed by unknown2108 </script>", "e": 36032, "s": 33938, "text": null }, { "code": null, "e": 36055, "s": 36032, "text": "Height of N-ary Tree=4" }, { "code": null, "e": 36570, "s": 36057, "text": "The Time Complexity of this solution is O(2n) which converges to O(n) for very large n.Approach 3: We can find the height of the N-ary Tree in only one iteration. We visit nodes from 0 to n-1 iteratively and mark the unvisited ancestors recursively if they are not visited before till we reach a node which is visited, or we reach the root node. If we reach the visited node while traversing up the tree using parent links, then we use its height and will not go further in recursion.Explanation For Example 1:: " }, { "code": null, "e": 37750, "s": 36570, "text": "For node 0: Check for Root node is true, Return 0 as height, Mark node 0 as visited For node 1: Recur for an immediate ancestor, i.e 0, which is already visited So, Use its height and return height(node 0) +1 Mark node 1 as visited For node 2: Recur for an immediate ancestor, i.e 0, which is already visited So, Use its height and return height(node 0) +1 Mark node 2 as visited For node 3: Recur for an immediate ancestor, i.e 0, which is already visited So, Use its height and return height(node 0) +1 Mark node 3 as visited For node 4: Recur for an immediate ancestor, i.e 3, which is already visited So, Use its height and return height(node 3) +1 Mark node 3 as visited For node 5: Recur for an immediate ancestor, i.e 1, which is already visited So, Use its height and return height(node 1) +1 Mark node 5 as visited For node 6: Recur for an immediate ancestor, i.e 1, which is already visited So, Use its height and return height(node 1) +1 Mark node 6 as visited For node 7: Recur for an immediate ancestor, i.e 2, which is already visited So, Use its height and return height(node 2) +1 Mark node 7 as visitedHence, we processed each node in the N-ary tree only once. " }, { "code": null, "e": 37754, "s": 37750, "text": "C++" }, { "code": null, "e": 37759, "s": 37754, "text": "Java" }, { "code": null, "e": 37767, "s": 37759, "text": "Python3" }, { "code": null, "e": 37770, "s": 37767, "text": "C#" }, { "code": null, "e": 37781, "s": 37770, "text": "Javascript" }, { "code": "// C++ code to find height of N-ary// tree in O(n) (Efficient Approach)#include <bits/stdc++.h>using namespace std; // Recur For Ancestors of node and// store height of node at lastint fillHeight(int p[], int node, int visited[], int height[]){ // If root node if (p[node] == -1) { // mark root node as visited visited[node] = 1; return 0; } // If node is already visited if (visited[node]) return height[node]; // Visit node and calculate its height visited[node] = 1; // recur for the parent node height[node] = 1 + fillHeight(p, p[node], visited, height); // return calculated height for node return height[node];} int findHeight(int parent[], int n){ // To store max height int ma = 0; // To check whether or not node is visited before int visited[n]; // For Storing Height of node int height[n]; memset(visited, 0, sizeof(visited)); memset(height, 0, sizeof(height)); for (int i = 0; i < n; i++) { // If not visited before if (!visited[i]) height[i] = fillHeight(parent, i, visited, height); // store maximum height so far ma = max(ma, height[i]); } return ma;} // Driver Functionint main(){ int parent[] = { -1, 0, 0, 0, 3, 1, 1, 2 }; int n = sizeof(parent) / sizeof(parent[0]); cout << \"Height of N-ary Tree = \" << findHeight(parent, n); return 0;}", "e": 39308, "s": 37781, "text": null }, { "code": "// Java code to find height of N-ary// tree in O(n) (Efficient Approach)import java.util.*;class GFG{ // Recur For Ancestors of node and// store height of node at laststatic int fillHeight(int p[], int node, int visited[], int height[]){ // If root node if (p[node] == -1) { // mark root node as visited visited[node] = 1; return 0; } // If node is already visited if (visited[node] == 1) return height[node]; // Visit node and calculate its height visited[node] = 1; // recur for the parent node height[node] = 1 + fillHeight(p, p[node], visited, height); // return calculated height for node return height[node];} static int findHeight(int parent[], int n){ // To store max height int ma = 0; // To check whether or not node is visited before int []visited = new int[n]; // For Storing Height of node int []height = new int[n]; for(int i = 0; i < n; i++) { visited[i] = 0; height[i] = 0; } for (int i = 0; i < n; i++) { // If not visited before if (visited[i] != 1) height[i] = fillHeight(parent, i, visited, height); // store maximum height so far ma = Math.max(ma, height[i]); } return ma;} // Driver Codepublic static void main(String[] args) { int parent[] = { -1, 0, 0, 0, 3, 1, 1, 2 }; int n = parent.length; System.out.println(\"Height of N-ary Tree = \" + findHeight(parent, n));}} // This code is contributed by 29AjayKumar", "e": 40947, "s": 39308, "text": null }, { "code": "# Python3 code to find height of N-ary # tree in O(n) (Efficient Approach) # Recur For Ancestors of node and # store height of node at last def fillHeight(p, node, visited, height): # If root node if (p[node] == -1): # mark root node as visited visited[node] = 1 return 0 # If node is already visited if (visited[node]): return height[node] # Visit node and calculate its height visited[node] = 1 # recur for the parent node height[node] = 1 + fillHeight(p, p[node], visited, height) # return calculated height for node return height[node] def findHeight(parent, n): # To store max height ma = 0 # To check whether or not node is # visited before visited = [0] * n # For Storing Height of node height = [0] * n for i in range(n): # If not visited before if (not visited[i]): height[i] = fillHeight(parent, i, visited, height) # store maximum height so far ma = max(ma, height[i]) return ma # Driver Codeif __name__ == '__main__': parent = [-1, 0, 0, 0, 3, 1, 1, 2] n = len(parent) print(\"Height of N-ary Tree =\", findHeight(parent, n)) # This code is contributed by PranchalK", "e": 42298, "s": 40947, "text": null }, { "code": "// C# code to find height of N-ary// tree in O(n) (Efficient Approach)using System; class GFG{ // Recur For Ancestors of node and// store height of node at laststatic int fillHeight(int []p, int node, int []visited, int []height){ // If root node if (p[node] == -1) { // mark root node as visited visited[node] = 1; return 0; } // If node is already visited if (visited[node] == 1) return height[node]; // Visit node and calculate its height visited[node] = 1; // recur for the parent node height[node] = 1 + fillHeight(p, p[node], visited, height); // return calculated height for node return height[node];} static int findHeight(int []parent, int n){ // To store max height int ma = 0; // To check whether or not // node is visited before int []visited = new int[n]; // For Storing Height of node int []height = new int[n]; for(int i = 0; i < n; i++) { visited[i] = 0; height[i] = 0; } for (int i = 0; i < n; i++) { // If not visited before if (visited[i] != 1) height[i] = fillHeight(parent, i, visited, height); // store maximum height so far ma = Math.Max(ma, height[i]); } return ma;} // Driver Codepublic static void Main(String[] args) { int []parent = { -1, 0, 0, 0, 3, 1, 1, 2 }; int n = parent.Length; Console.WriteLine(\"Height of N-ary Tree = \" + findHeight(parent, n));}} // This code contributed by Rajput-Ji", "e": 43957, "s": 42298, "text": null }, { "code": "<script>// Javascript code to find height of N-ary// tree in O(n) (Efficient Approach) // Recur For Ancestors of node and// store height of node at lastfunction fillHeight(p, node, visited, height){ // If root node if (p[node] == -1) { // mark root node as visited visited[node] = 1; return 0; } // If node is already visited if (visited[node] == 1) return height[node]; // Visit node and calculate its height visited[node] = 1; // recur for the parent node height[node] = 1 + fillHeight(p, p[node], visited, height); // return calculated height for node return height[node];} function findHeight(parent,n){ // To store max height let ma = 0; // To check whether or not node is visited before let visited = new Array(n); // For Storing Height of node let height = new Array(n); for(let i = 0; i < n; i++) { visited[i] = 0; height[i] = 0; } for (let i = 0; i < n; i++) { // If not visited before if (visited[i] != 1) height[i] = fillHeight(parent, i, visited, height); // store maximum height so far ma = Math.max(ma, height[i]); } return ma;} // Driver Codelet parent = [ -1, 0, 0, 0, 3, 1, 1, 2 ];let n = parent.length;document.write(\"Height of N-ary Tree = \" + findHeight(parent, n)); // This code is contributed by ab2127</script>", "e": 45478, "s": 43957, "text": null }, { "code": null, "e": 45503, "s": 45478, "text": "Height of N-ary Tree = 2" }, { "code": null, "e": 45527, "s": 45505, "text": "Time Complexity: O(n)" }, { "code": null, "e": 45543, "s": 45527, "text": "PranchalKatiyar" }, { "code": null, "e": 45555, "s": 45543, "text": "29AjayKumar" }, { "code": null, "e": 45565, "s": 45555, "text": "Rajput-Ji" }, { "code": null, "e": 45580, "s": 45565, "text": "mohit kumar 29" }, { "code": null, "e": 45588, "s": 45580, "text": "rag2127" }, { "code": null, "e": 45609, "s": 45588, "text": "avanitrachhadiya2155" }, { "code": null, "e": 45621, "s": 45609, "text": "unknown2108" }, { "code": null, "e": 45628, "s": 45621, "text": "ab2127" }, { "code": null, "e": 45641, "s": 45628, "text": "rajutsav1234" }, { "code": null, "e": 45652, "s": 45641, "text": "n-ary-tree" }, { "code": null, "e": 45658, "s": 45652, "text": "Graph" }, { "code": null, "e": 45663, "s": 45658, "text": "Tree" }, { "code": null, "e": 45669, "s": 45663, "text": "Graph" }, { "code": null, "e": 45674, "s": 45669, "text": "Tree" }, { "code": null, "e": 45772, "s": 45674, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45803, "s": 45772, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 45836, "s": 45803, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 45911, "s": 45836, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 45979, "s": 45911, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 46027, "s": 45979, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 46062, "s": 46027, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 46091, "s": 46062, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 46134, "s": 46091, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 46196, "s": 46134, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" } ]
PHP - Error & Exception Handling
Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences. Its very simple in PHP to handle an errors. While writing your PHP program you should check all possible error condition before going ahead and take appropriate action when required. Try following example without having /tmp/test.xt file and with this file. <?php if(!file_exists("/tmp/test.txt")) { die("File not found"); }else { $file = fopen("/tmp/test.txt","r"); print "Opend file sucessfully"; } // Test of the code here. ?> This way you can write an efficient code. Using above technique you can stop your program whenever it errors out and display more meaningful and user friendly message. You can write your own function to handling any error. PHP provides you a framework to define error handling function. This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context) − error_function(error_level,error_message, error_file,error_line,error_context); error_level Required - Specifies the error report level for the user-defined error. Must be a value number. error_message Required - Specifies the error message for the user-defined error error_file Optional - Specifies the file name in which the error occurred error_line Optional - Specifies the line number in which the error occurred error_context Optional - Specifies an array containing every variable and their values in use when the error occurred These error report levels are the different types of error the user-defined error handler can be used for. These values cab used in combination using | operator .E_ERROR Fatal run-time errors. Execution of the script is halted E_WARNING Non-fatal run-time errors. Execution of the script is not halted E_PARSE Compile-time parse errors. Parse errors should only be generated by the parser. E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally E_CORE_ERROR Fatal errors that occur during PHP's initial start-up. E_CORE_WARNING Non-fatal run-time errors. This occurs during PHP's initial start-up. E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error() E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error() E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error() E_STRICT Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler()) E_ALL All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0) All the above error level can be set using following PHP built-in library function where level cab be any of the value defined in above table. int error_reporting ( [int $level] ) Following is the way you can create one error handling function − <?php function handleError($errno, $errstr,$error_file,$error_line) { echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line"; echo "<br />"; echo "Terminating PHP Script"; die(); } ?> Once you define your custom error handler you need to set it using PHP built-in library set_error_handler function. Now lets examine our example by calling a function which does not exist. <?php error_reporting( E_ERROR ); function handleError($errno, $errstr,$error_file,$error_line) { echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line"; echo "<br />"; echo "Terminating PHP Script"; die(); } //set error handler set_error_handler("handleError"); //trigger error myFunction(); ?> PHP 5 has an exception model similar to that of other programming languages. Exceptions are important and provides a better control over error handling. Lets explain there new keyword related to exceptions. Try − A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown". Try − A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown". Throw − This is how you trigger an exception. Each "throw" must have at least one "catch". Throw − This is how you trigger an exception. Each "throw" must have at least one "catch". Catch − A "catch" block retrieves an exception and creates an object containing the exception information. Catch − A "catch" block retrieves an exception and creates an object containing the exception information. When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ... An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions. Exceptions can be thrown (or re-thrown) within a catch block. Exceptions can be thrown (or re-thrown) within a catch block. Following is the piece of code, copy and paste this code into a file and verify the result. <?php try { $error = 'Always throw this error'; throw new Exception($error); // Code following an exception is not executed. echo 'Never executed'; }catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Continue execution echo 'Hello World'; ?> In the above example $e->getMessage function is used to get error message. There are following functions which can be used from Exception class. getMessage() − message of exception getMessage() − message of exception getCode() − code of exception getCode() − code of exception getFile() − source filename getFile() − source filename getLine() − source line getLine() − source line getTrace() − n array of the backtrace() getTrace() − n array of the backtrace() getTraceAsString() − formated string of trace getTraceAsString() − formated string of trace You can define your own custom exception handler. Use following function to set a user-defined exception handler function. string set_exception_handler ( callback $exception_handler ) Here exception_handler is the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler(). <?php function exception_handler($exception) { echo "Uncaught exception: " , $exception->getMessage(), "\n"; } set_exception_handler('exception_handler'); throw new Exception('Uncaught Exception'); echo "Not Executed\n"; ?> Check complete set of error handling functions at PHP Error Handling Functions 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": 2951, "s": 2757, "text": "Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences." }, { "code": null, "e": 2995, "s": 2951, "text": "Its very simple in PHP to handle an errors." }, { "code": null, "e": 3134, "s": 2995, "text": "While writing your PHP program you should check all possible error condition before going ahead and take appropriate action when required." }, { "code": null, "e": 3209, "s": 3134, "text": "Try following example without having /tmp/test.xt file and with this file." }, { "code": null, "e": 3411, "s": 3209, "text": "<?php\n if(!file_exists(\"/tmp/test.txt\")) {\n die(\"File not found\");\n }else {\n $file = fopen(\"/tmp/test.txt\",\"r\");\n print \"Opend file sucessfully\";\n }\n // Test of the code here.\n?>" }, { "code": null, "e": 3579, "s": 3411, "text": "This way you can write an efficient code. Using above technique you can stop your program whenever it errors out and display more meaningful and user friendly message." }, { "code": null, "e": 3698, "s": 3579, "text": "You can write your own function to handling any error. PHP provides you a framework to define error handling function." }, { "code": null, "e": 3889, "s": 3698, "text": "This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context) −" }, { "code": null, "e": 3970, "s": 3889, "text": "error_function(error_level,error_message, error_file,error_line,error_context);\n" }, { "code": null, "e": 3982, "s": 3970, "text": "error_level" }, { "code": null, "e": 4078, "s": 3982, "text": "Required - Specifies the error report level for the user-defined error. Must be a value number." }, { "code": null, "e": 4092, "s": 4078, "text": "error_message" }, { "code": null, "e": 4158, "s": 4092, "text": "Required - Specifies the error message for the user-defined error" }, { "code": null, "e": 4169, "s": 4158, "text": "error_file" }, { "code": null, "e": 4232, "s": 4169, "text": "Optional - Specifies the file name in which the error occurred" }, { "code": null, "e": 4243, "s": 4232, "text": "error_line" }, { "code": null, "e": 4308, "s": 4243, "text": "Optional - Specifies the line number in which the error occurred" }, { "code": null, "e": 4322, "s": 4308, "text": "error_context" }, { "code": null, "e": 4426, "s": 4322, "text": "Optional - Specifies an array containing every variable and their values in use when the error occurred" }, { "code": null, "e": 4587, "s": 4426, "text": "These error report levels are the different types of error the user-defined error handler can be used for. These values cab used in combination using | operator" }, { "code": null, "e": 4596, "s": 4587, "text": ".E_ERROR" }, { "code": null, "e": 4653, "s": 4596, "text": "Fatal run-time errors. Execution of the script is halted" }, { "code": null, "e": 4663, "s": 4653, "text": "E_WARNING" }, { "code": null, "e": 4728, "s": 4663, "text": "Non-fatal run-time errors. Execution of the script is not halted" }, { "code": null, "e": 4736, "s": 4728, "text": "E_PARSE" }, { "code": null, "e": 4816, "s": 4736, "text": "Compile-time parse errors. Parse errors should only be generated by the parser." }, { "code": null, "e": 4825, "s": 4816, "text": "E_NOTICE" }, { "code": null, "e": 4947, "s": 4825, "text": "Run-time notices. The script found something that might be an error, but could also happen when running a script normally" }, { "code": null, "e": 4960, "s": 4947, "text": "E_CORE_ERROR" }, { "code": null, "e": 5015, "s": 4960, "text": "Fatal errors that occur during PHP's initial start-up." }, { "code": null, "e": 5030, "s": 5015, "text": "E_CORE_WARNING" }, { "code": null, "e": 5100, "s": 5030, "text": "Non-fatal run-time errors. This occurs during PHP's initial start-up." }, { "code": null, "e": 5113, "s": 5100, "text": "E_USER_ERROR" }, { "code": null, "e": 5226, "s": 5113, "text": "Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()" }, { "code": null, "e": 5241, "s": 5226, "text": "E_USER_WARNING" }, { "code": null, "e": 5362, "s": 5241, "text": "Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()" }, { "code": null, "e": 5376, "s": 5362, "text": "E_USER_NOTICE" }, { "code": null, "e": 5485, "s": 5376, "text": "User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()" }, { "code": null, "e": 5494, "s": 5485, "text": "E_STRICT" }, { "code": null, "e": 5644, "s": 5494, "text": "Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code." }, { "code": null, "e": 5664, "s": 5644, "text": "E_RECOVERABLE_ERROR" }, { "code": null, "e": 5785, "s": 5664, "text": "Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())" }, { "code": null, "e": 5791, "s": 5785, "text": "E_ALL" }, { "code": null, "e": 5885, "s": 5791, "text": "All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)" }, { "code": null, "e": 6028, "s": 5885, "text": "All the above error level can be set using following PHP built-in library function where level cab be any of the value defined in above table." }, { "code": null, "e": 6066, "s": 6028, "text": "int error_reporting ( [int $level] )\n" }, { "code": null, "e": 6132, "s": 6066, "text": "Following is the way you can create one error handling function −" }, { "code": null, "e": 6362, "s": 6132, "text": "<?php\n function handleError($errno, $errstr,$error_file,$error_line) {\n echo \"<b>Error:</b> [$errno] $errstr - $error_file:$error_line\";\n echo \"<br />\";\n echo \"Terminating PHP Script\";\n \n die();\n }\n?>" }, { "code": null, "e": 6551, "s": 6362, "text": "Once you define your custom error handler you need to set it using PHP built-in library set_error_handler function. Now lets examine our example by calling a function which does not exist." }, { "code": null, "e": 6920, "s": 6551, "text": "<?php\n error_reporting( E_ERROR );\n \n function handleError($errno, $errstr,$error_file,$error_line) {\n echo \"<b>Error:</b> [$errno] $errstr - $error_file:$error_line\";\n echo \"<br />\";\n echo \"Terminating PHP Script\";\n \n die();\n }\n \n //set error handler\n set_error_handler(\"handleError\");\n \n //trigger error\n myFunction();\n?>" }, { "code": null, "e": 7073, "s": 6920, "text": "PHP 5 has an exception model similar to that of other programming languages. Exceptions are important and provides a better control over error handling." }, { "code": null, "e": 7127, "s": 7073, "text": "Lets explain there new keyword related to exceptions." }, { "code": null, "e": 7321, "s": 7127, "text": "Try − A function using an exception should be in a \"try\" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is \"thrown\"." }, { "code": null, "e": 7515, "s": 7321, "text": "Try − A function using an exception should be in a \"try\" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is \"thrown\"." }, { "code": null, "e": 7606, "s": 7515, "text": "Throw − This is how you trigger an exception. Each \"throw\" must have at least one \"catch\"." }, { "code": null, "e": 7697, "s": 7606, "text": "Throw − This is how you trigger an exception. Each \"throw\" must have at least one \"catch\"." }, { "code": null, "e": 7804, "s": 7697, "text": "Catch − A \"catch\" block retrieves an exception and creates an object containing the exception information." }, { "code": null, "e": 7911, "s": 7804, "text": "Catch − A \"catch\" block retrieves an exception and creates an object containing the exception information." }, { "code": null, "e": 8148, "s": 7911, "text": "When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an \"Uncaught Exception ..." }, { "code": null, "e": 8250, "s": 8148, "text": "An exception can be thrown, and caught (\"catched\") within PHP. Code may be surrounded in a try block." }, { "code": null, "e": 8352, "s": 8250, "text": "An exception can be thrown, and caught (\"catched\") within PHP. Code may be surrounded in a try block." }, { "code": null, "e": 8487, "s": 8352, "text": "Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions." }, { "code": null, "e": 8622, "s": 8487, "text": "Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions." }, { "code": null, "e": 8684, "s": 8622, "text": "Exceptions can be thrown (or re-thrown) within a catch block." }, { "code": null, "e": 8746, "s": 8684, "text": "Exceptions can be thrown (or re-thrown) within a catch block." }, { "code": null, "e": 8838, "s": 8746, "text": "Following is the piece of code, copy and paste this code into a file and verify the result." }, { "code": null, "e": 9165, "s": 8838, "text": "<?php\n try {\n $error = 'Always throw this error';\n throw new Exception($error);\n \n // Code following an exception is not executed.\n echo 'Never executed';\n }catch (Exception $e) {\n echo 'Caught exception: ', $e->getMessage(), \"\\n\";\n }\n \n // Continue execution\n echo 'Hello World';\n?>" }, { "code": null, "e": 9310, "s": 9165, "text": "In the above example $e->getMessage function is used to get error message. There are following functions which can be used from Exception class." }, { "code": null, "e": 9347, "s": 9310, "text": "getMessage() − message of exception " }, { "code": null, "e": 9384, "s": 9347, "text": "getMessage() − message of exception " }, { "code": null, "e": 9414, "s": 9384, "text": "getCode() − code of exception" }, { "code": null, "e": 9444, "s": 9414, "text": "getCode() − code of exception" }, { "code": null, "e": 9472, "s": 9444, "text": "getFile() − source filename" }, { "code": null, "e": 9500, "s": 9472, "text": "getFile() − source filename" }, { "code": null, "e": 9524, "s": 9500, "text": "getLine() − source line" }, { "code": null, "e": 9548, "s": 9524, "text": "getLine() − source line" }, { "code": null, "e": 9588, "s": 9548, "text": "getTrace() − n array of the backtrace()" }, { "code": null, "e": 9628, "s": 9588, "text": "getTrace() − n array of the backtrace()" }, { "code": null, "e": 9674, "s": 9628, "text": "getTraceAsString() − formated string of trace" }, { "code": null, "e": 9720, "s": 9674, "text": "getTraceAsString() − formated string of trace" }, { "code": null, "e": 9843, "s": 9720, "text": "You can define your own custom exception handler. Use following function to set a user-defined exception handler function." }, { "code": null, "e": 9905, "s": 9843, "text": "string set_exception_handler ( callback $exception_handler )\n" }, { "code": null, "e": 10074, "s": 9905, "text": "Here exception_handler is the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler()." }, { "code": null, "e": 10325, "s": 10074, "text": "<?php\n function exception_handler($exception) {\n echo \"Uncaught exception: \" , $exception->getMessage(), \"\\n\";\n }\n\t\n set_exception_handler('exception_handler');\n throw new Exception('Uncaught Exception');\n \n echo \"Not Executed\\n\";\n?>" }, { "code": null, "e": 10404, "s": 10325, "text": "Check complete set of error handling functions at PHP Error Handling Functions" }, { "code": null, "e": 10437, "s": 10404, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 10453, "s": 10437, "text": " Malhar Lathkar" }, { "code": null, "e": 10486, "s": 10453, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 10497, "s": 10486, "text": " Syed Raza" }, { "code": null, "e": 10532, "s": 10497, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 10549, "s": 10532, "text": " Frahaan Hussain" }, { "code": null, "e": 10582, "s": 10549, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 10597, "s": 10582, "text": " Nivedita Jain" }, { "code": null, "e": 10632, "s": 10597, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 10644, "s": 10632, "text": " Azaz Patel" }, { "code": null, "e": 10679, "s": 10644, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 10707, "s": 10679, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 10714, "s": 10707, "text": " Print" }, { "code": null, "e": 10725, "s": 10714, "text": " Add Notes" } ]
ML | Data Preprocessing in Python - GeeksforGeeks
15 Jul, 2021 Pre-processing refers to the transformations applied to our data before feeding it to the algorithm. Data Preprocessing is a technique that is used to convert the raw data into a clean data set. In other words, whenever the data is gathered from different sources it is collected in raw format which is not feasible for the analysis. Need of Data Preprocessing For achieving better results from the applied model in Machine Learning projects the format of the data has to be in a proper manner. Some specified Machine Learning model needs information in a specified format, for example, Random Forest algorithm does not support null values, therefore to execute random forest algorithm null values have to be managed from the original raw data set. Another aspect is that the data set should be formatted in such a way that more than one Machine Learning and Deep Learning algorithm are executed in one data set, and best out of them is chosen. This article contains 3 different data preprocessing techniques for machine learning. The Pima Indian diabetes dataset is used in each technique. This is a binary classification problem where all of the attributes are numeric and have different scales. It is a great example of a dataset that can benefit from pre-processing. You can find this dataset on the UCI Machine Learning Repository webpage. Note that the program might not run on Geeksforgeeks IDE, but it can run easily on your local python interpreter, provided, you have installed the required libraries. 1. Rescale Data When our data is comprised of attributes with varying scales, many machine learning algorithms can benefit from rescaling the attributes to all have the same scale. This is useful for optimization algorithms in used in the core of machine learning algorithms like gradient descent. It is also useful for algorithms that weight inputs like regression and neural networks and algorithms that use distance measures like K-Nearest Neighbors. We can rescale your data using scikit-learn using the MinMaxScaler class. Code: Python code to Rescale data (between 0 and 1) Python # importing librariesimport pandasimport scipyimport numpyfrom sklearn.preprocessing import MinMaxScaler # data set linkurl = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data"# data parametersnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] # preparating of dataframe using the data at given link and defined columns listdataframe = pandas.read_csv(url, names = names)array = dataframe.values # separate array into input and output componentsX = array[:,0:8]Y = array[:,8] # initialising the MinMaxScalerscaler = MinMaxScaler(feature_range=(0, 1))# learning the statistical parameters for each of the data and transformingrescaledX = scaler.fit_transform(X) # summarize transformed datanumpy.set_printoptions(precision=3)print(rescaledX[0:5,:]) After rescaling see that all of the values are in the range between 0 and 1. Output: [[ 0.353 0.744 0.59 0.354 0.0 0.501 0.234 0.483] [ 0.059 0.427 0.541 0.293 0.0 0.396 0.117 0.167] [ 0.471 0.92 0.525 0. 0.0 0.347 0.254 0.183] [ 0.059 0.447 0.541 0.232 0.111 0.419 0.038 0.0 ] [ 0.0 0.688 0.328 0.354 0.199 0.642 0.944 0.2 ]] 2. Binarize Data (Make Binary) We can transform our data using a binary threshold. All values above the threshold are marked 1 and all equal to or below are marked as 0. This is called binarizing your data or threshold your data. It can be useful when you have probabilities that you want to make crisp values. It is also useful when feature engineering and you want to add new features that indicate something meaningful. We can create new binary attributes in Python using scikit-learn with the Binarizer class. Code: Python code for binarization Python # import librariesfrom sklearn.preprocessing import Binarizerimport pandasimport numpy # data set linkurl = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data"# data parametersnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] # preparating of dataframe using the data at given link and defined columns listdataframe = pandas.read_csv(url, names = names)array = dataframe.values # separate array into input and output componentsX = array[:, 0:8]Y = array[:, 8]binarizer = Binarizer(threshold = 0.0).fit(X)binaryX = binarizer.transform(X) # summarize transformed datanumpy.set_printoptions(precision = 3)print(binaryX[0:5,:]) We can see that all values equal or less than 0 are marked 0 and all of those above 0 are marked 1. Output: [[ 1. 1. 1. 1. 0. 1. 1. 1.] [ 1. 1. 1. 1. 0. 1. 1. 1.] [ 1. 1. 1. 0. 0. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1. 1. 1.] [ 0. 1. 1. 1. 1. 1. 1. 1.]] 3. Standardize Data Standardization is a useful technique to transform attributes with a Gaussian distribution and differing means and standard deviations to a standard Gaussian distribution with a mean of 0 and a standard deviation of 1. We can standardize data using scikit-learn with the StandardScaler class. Code: Python code to Standardize data (0 mean, 1 stdev) Python # importing librariesfrom sklearn.preprocessing import StandardScalerimport pandasimport numpy # data set linkurl = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data"# data parametersnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] # preparating of dataframe using the data at given link and defined columns listdataframe = pandas.read_csv(url, names = names)array = dataframe.values # separate array into input and output componentsX = array[:, 0:8]Y = array[:, 8]scaler = StandardScaler().fit(X)rescaledX = scaler.transform(X) # summarize transformed datanumpy.set_printoptions(precision = 3)print(rescaledX[0:5,:]) The values for each attribute now have a mean value of 0 and a standard deviation of 1. Output: [[ 0.64 0.848 0.15 0.907 -0.693 0.204 0.468 1.426] [-0.845 -1.123 -0.161 0.531 -0.693 -0.684 -0.365 -0.191] [ 1.234 1.944 -0.264 -1.288 -0.693 -1.103 0.604 -0.106] [-0.845 -0.998 -0.161 0.155 0.123 -0.494 -0.921 -1.042] [-1.142 0.504 -1.505 0.907 0.766 1.41 5.485 -0.02 ]] References: https://www.analyticsvidhya.com/blog/2016/07/practical-guide-data-preprocessing-python-scikit-learn/ https://www.xenonstack.com/blog/data-preprocessing-data-wrangling-in-machine-learning-deep-learning anikakapoor Advanced Computer Subject Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments ML | Linear Regression Copying Files to and from Docker Containers System Design Tutorial Python | Decision tree implementation Reinforcement learning ML | Linear Regression Agents in Artificial Intelligence Search Algorithms in AI Python | Decision tree implementation
[ { "code": null, "e": 24414, "s": 24386, "text": "\n15 Jul, 2021" }, { "code": null, "e": 24748, "s": 24414, "text": "Pre-processing refers to the transformations applied to our data before feeding it to the algorithm. Data Preprocessing is a technique that is used to convert the raw data into a clean data set. In other words, whenever the data is gathered from different sources it is collected in raw format which is not feasible for the analysis." }, { "code": null, "e": 24776, "s": 24748, "text": "Need of Data Preprocessing " }, { "code": null, "e": 25164, "s": 24776, "text": "For achieving better results from the applied model in Machine Learning projects the format of the data has to be in a proper manner. Some specified Machine Learning model needs information in a specified format, for example, Random Forest algorithm does not support null values, therefore to execute random forest algorithm null values have to be managed from the original raw data set." }, { "code": null, "e": 25360, "s": 25164, "text": "Another aspect is that the data set should be formatted in such a way that more than one Machine Learning and Deep Learning algorithm are executed in one data set, and best out of them is chosen." }, { "code": null, "e": 25447, "s": 25360, "text": "This article contains 3 different data preprocessing techniques for machine learning. " }, { "code": null, "e": 25930, "s": 25447, "text": "The Pima Indian diabetes dataset is used in each technique. This is a binary classification problem where all of the attributes are numeric and have different scales. It is a great example of a dataset that can benefit from pre-processing. You can find this dataset on the UCI Machine Learning Repository webpage. Note that the program might not run on Geeksforgeeks IDE, but it can run easily on your local python interpreter, provided, you have installed the required libraries. " }, { "code": null, "e": 25948, "s": 25930, "text": "1. Rescale Data " }, { "code": null, "e": 26113, "s": 25948, "text": "When our data is comprised of attributes with varying scales, many machine learning algorithms can benefit from rescaling the attributes to all have the same scale." }, { "code": null, "e": 26230, "s": 26113, "text": "This is useful for optimization algorithms in used in the core of machine learning algorithms like gradient descent." }, { "code": null, "e": 26386, "s": 26230, "text": "It is also useful for algorithms that weight inputs like regression and neural networks and algorithms that use distance measures like K-Nearest Neighbors." }, { "code": null, "e": 26460, "s": 26386, "text": "We can rescale your data using scikit-learn using the MinMaxScaler class." }, { "code": null, "e": 26514, "s": 26460, "text": "Code: Python code to Rescale data (between 0 and 1) " }, { "code": null, "e": 26521, "s": 26514, "text": "Python" }, { "code": "# importing librariesimport pandasimport scipyimport numpyfrom sklearn.preprocessing import MinMaxScaler # data set linkurl = \"https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data\"# data parametersnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] # preparating of dataframe using the data at given link and defined columns listdataframe = pandas.read_csv(url, names = names)array = dataframe.values # separate array into input and output componentsX = array[:,0:8]Y = array[:,8] # initialising the MinMaxScalerscaler = MinMaxScaler(feature_range=(0, 1))# learning the statistical parameters for each of the data and transformingrescaledX = scaler.fit_transform(X) # summarize transformed datanumpy.set_printoptions(precision=3)print(rescaledX[0:5,:])", "e": 27357, "s": 26521, "text": null }, { "code": null, "e": 27435, "s": 27357, "text": "After rescaling see that all of the values are in the range between 0 and 1. " }, { "code": null, "e": 27444, "s": 27435, "text": "Output: " }, { "code": null, "e": 27740, "s": 27444, "text": "[[ 0.353 0.744 0.59 0.354 0.0 0.501 0.234 0.483]\n [ 0.059 0.427 0.541 0.293 0.0 0.396 0.117 0.167]\n [ 0.471 0.92 0.525 0. 0.0 0.347 0.254 0.183]\n [ 0.059 0.447 0.541 0.232 0.111 0.419 0.038 0.0 ]\n [ 0.0 0.688 0.328 0.354 0.199 0.642 0.944 0.2 ]]" }, { "code": null, "e": 27773, "s": 27740, "text": "2. Binarize Data (Make Binary) " }, { "code": null, "e": 27912, "s": 27773, "text": "We can transform our data using a binary threshold. All values above the threshold are marked 1 and all equal to or below are marked as 0." }, { "code": null, "e": 28165, "s": 27912, "text": "This is called binarizing your data or threshold your data. It can be useful when you have probabilities that you want to make crisp values. It is also useful when feature engineering and you want to add new features that indicate something meaningful." }, { "code": null, "e": 28256, "s": 28165, "text": "We can create new binary attributes in Python using scikit-learn with the Binarizer class." }, { "code": null, "e": 28293, "s": 28256, "text": "Code: Python code for binarization " }, { "code": null, "e": 28300, "s": 28293, "text": "Python" }, { "code": "# import librariesfrom sklearn.preprocessing import Binarizerimport pandasimport numpy # data set linkurl = \"https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data\"# data parametersnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] # preparating of dataframe using the data at given link and defined columns listdataframe = pandas.read_csv(url, names = names)array = dataframe.values # separate array into input and output componentsX = array[:, 0:8]Y = array[:, 8]binarizer = Binarizer(threshold = 0.0).fit(X)binaryX = binarizer.transform(X) # summarize transformed datanumpy.set_printoptions(precision = 3)print(binaryX[0:5,:])", "e": 29012, "s": 28300, "text": null }, { "code": null, "e": 29113, "s": 29012, "text": "We can see that all values equal or less than 0 are marked 0 and all of those above 0 are marked 1. " }, { "code": null, "e": 29122, "s": 29113, "text": "Output: " }, { "code": null, "e": 29298, "s": 29122, "text": "[[ 1. 1. 1. 1. 0. 1. 1. 1.]\n [ 1. 1. 1. 1. 0. 1. 1. 1.]\n [ 1. 1. 1. 0. 0. 1. 1. 1.]\n [ 1. 1. 1. 1. 1. 1. 1. 1.]\n [ 0. 1. 1. 1. 1. 1. 1. 1.]]" }, { "code": null, "e": 29320, "s": 29298, "text": "3. Standardize Data " }, { "code": null, "e": 29539, "s": 29320, "text": "Standardization is a useful technique to transform attributes with a Gaussian distribution and differing means and standard deviations to a standard Gaussian distribution with a mean of 0 and a standard deviation of 1." }, { "code": null, "e": 29613, "s": 29539, "text": "We can standardize data using scikit-learn with the StandardScaler class." }, { "code": null, "e": 29671, "s": 29613, "text": "Code: Python code to Standardize data (0 mean, 1 stdev) " }, { "code": null, "e": 29678, "s": 29671, "text": "Python" }, { "code": "# importing librariesfrom sklearn.preprocessing import StandardScalerimport pandasimport numpy # data set linkurl = \"https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data\"# data parametersnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] # preparating of dataframe using the data at given link and defined columns listdataframe = pandas.read_csv(url, names = names)array = dataframe.values # separate array into input and output componentsX = array[:, 0:8]Y = array[:, 8]scaler = StandardScaler().fit(X)rescaledX = scaler.transform(X) # summarize transformed datanumpy.set_printoptions(precision = 3)print(rescaledX[0:5,:])", "e": 30386, "s": 29678, "text": null }, { "code": null, "e": 30475, "s": 30386, "text": "The values for each attribute now have a mean value of 0 and a standard deviation of 1. " }, { "code": null, "e": 30484, "s": 30475, "text": "Output: " }, { "code": null, "e": 30780, "s": 30484, "text": "[[ 0.64 0.848 0.15 0.907 -0.693 0.204 0.468 1.426]\n [-0.845 -1.123 -0.161 0.531 -0.693 -0.684 -0.365 -0.191]\n [ 1.234 1.944 -0.264 -1.288 -0.693 -1.103 0.604 -0.106]\n [-0.845 -0.998 -0.161 0.155 0.123 -0.494 -0.921 -1.042]\n [-1.142 0.504 -1.505 0.907 0.766 1.41 5.485 -0.02 ]]" }, { "code": null, "e": 30794, "s": 30780, "text": "References: " }, { "code": null, "e": 30895, "s": 30794, "text": "https://www.analyticsvidhya.com/blog/2016/07/practical-guide-data-preprocessing-python-scikit-learn/" }, { "code": null, "e": 30995, "s": 30895, "text": "https://www.xenonstack.com/blog/data-preprocessing-data-wrangling-in-machine-learning-deep-learning" }, { "code": null, "e": 31009, "s": 30997, "text": "anikakapoor" }, { "code": null, "e": 31035, "s": 31009, "text": "Advanced Computer Subject" }, { "code": null, "e": 31052, "s": 31035, "text": "Machine Learning" }, { "code": null, "e": 31059, "s": 31052, "text": "Python" }, { "code": null, "e": 31076, "s": 31059, "text": "Machine Learning" }, { "code": null, "e": 31174, "s": 31076, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31183, "s": 31174, "text": "Comments" }, { "code": null, "e": 31196, "s": 31183, "text": "Old Comments" }, { "code": null, "e": 31219, "s": 31196, "text": "ML | Linear Regression" }, { "code": null, "e": 31263, "s": 31219, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 31286, "s": 31263, "text": "System Design Tutorial" }, { "code": null, "e": 31324, "s": 31286, "text": "Python | Decision tree implementation" }, { "code": null, "e": 31347, "s": 31324, "text": "Reinforcement learning" }, { "code": null, "e": 31370, "s": 31347, "text": "ML | Linear Regression" }, { "code": null, "e": 31404, "s": 31370, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 31428, "s": 31404, "text": "Search Algorithms in AI" } ]
C program to print characters without using format specifiers - GeeksforGeeks
29 Oct, 2017 As we know that there are various format specifiers in C like %d, %f, %c etc, to help us print characters or other data types. We normally use these specifiers along with the printf() function to print any variables. But there is also a way to print characters specifically without the use of %c format specifier. This can be obtained by using the below-shown method to get the character value of any ASCII codes of any particular character.Example: // Prints characters without format specifiers#include <stdio.h> int main(){ printf("\x47 \n"); printf("\x45 \n"); printf("\x45 \n"); printf("\x4b \n"); printf("\x53"); return 0;} Output: G E E K S This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. c-puzzle C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ UDP Server-Client implementation in C Arrow operator -> in C/C++ with Examples Understanding "extern" keyword in C Storage Classes in C Smart Pointers in C++ and How to Use Them Switch Statement in C/C++
[ { "code": null, "e": 24233, "s": 24205, "text": "\n29 Oct, 2017" }, { "code": null, "e": 24683, "s": 24233, "text": "As we know that there are various format specifiers in C like %d, %f, %c etc, to help us print characters or other data types. We normally use these specifiers along with the printf() function to print any variables. But there is also a way to print characters specifically without the use of %c format specifier. This can be obtained by using the below-shown method to get the character value of any ASCII codes of any particular character.Example:" }, { "code": "// Prints characters without format specifiers#include <stdio.h> int main(){ printf(\"\\x47 \\n\"); printf(\"\\x45 \\n\"); printf(\"\\x45 \\n\"); printf(\"\\x4b \\n\"); printf(\"\\x53\"); return 0;}", "e": 24882, "s": 24683, "text": null }, { "code": null, "e": 24890, "s": 24882, "text": "Output:" }, { "code": null, "e": 24905, "s": 24890, "text": "G \nE \nE \nK \nS\n" }, { "code": null, "e": 25206, "s": 24905, "text": "This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 25331, "s": 25206, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25340, "s": 25331, "text": "c-puzzle" }, { "code": null, "e": 25351, "s": 25340, "text": "C Language" }, { "code": null, "e": 25449, "s": 25351, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25458, "s": 25449, "text": "Comments" }, { "code": null, "e": 25471, "s": 25458, "text": "Old Comments" }, { "code": null, "e": 25509, "s": 25471, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 25535, "s": 25509, "text": "Exception Handling in C++" }, { "code": null, "e": 25555, "s": 25535, "text": "Multithreading in C" }, { "code": null, "e": 25577, "s": 25555, "text": "'this' pointer in C++" }, { "code": null, "e": 25615, "s": 25577, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 25656, "s": 25615, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 25692, "s": 25656, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 25713, "s": 25692, "text": "Storage Classes in C" }, { "code": null, "e": 25755, "s": 25713, "text": "Smart Pointers in C++ and How to Use Them" } ]
Maximizing Profit Using Linear Programming in Python | by Luciano Vilas Boas | Towards Data Science
The Simplex Method was designed to help solve LP problems and it is basically what we will see here. With advances in the technological field, this method started to be used, not only in the Military, but in a vast myriad of industries. Today, I will present you an example of how we can take advantage of this algorithm. I’ll cover the following: 1- Basic Concepts of Linear Programming 2- How to Formulate a LP Problem 3- How to Solve a LP using Python 4- A Graphical Way to Look at LP Problem Linear Programming and linear inequalities go side by side. That is, many real-life problems are subject to some restrictions, e.g. number of raw material to produce a chair. In order words, there are some limitations that prevent us to manufacture an item without compromising the production of others. For example, let’s say you need wood to make chairs and tables, so the amount of wood that you have available imposes a limit on the number of chairs and tables you can produce. In essence, this is the very problem LP attempts to solve: how to systematically allocate the resources in order to get the most out of the restriction (constraints) that we have, while considering, for example, the potential maximization of the profit you get from their sales. On that note, we can use LP to Maximize a profit, or Minimize a cost, like said previously. Funny thing is that we can convert a maximization problem into minimization, and vice-versa. But this won’t be the focus here. In LP, when I say “solve” that does not mean we will find a solution (like 2 + 2 = 4) all the time. We can formulate a LP problem, do some Math, and come to the conclusion that the particular LP problem does not have an Optimal Solution, which is the main goal of solving a LP: trying to land a unique optimal solution. This can occur because some problems may have too many different optimal solutions or even no optimal solution at all. Some of the reasons we may encounter a LP without an optimal solution may be out of our control. In many cases, the problems are simply way too complex to be solved (finding a unique optimal solution). A question we may want to ask ourselves when working on a LP problem may be: Is the problem feasible or infeasible? Some problems can even have many feasible solutions, and ended up being unbounded. To sum up, we can classify a LP problem into three classes: optimal solution, infeasible, and unbounded. Here, you are going to see an example of a LP problem that give us an Optimal Solution. But before we start working on our problem, I want to show you an example of how a traditional LP problem looks like: The first line says “maximize” and that is where our objective function is located. That could also say “minimize”, and that would indicate our problem was a minimization problem. The second and third lines are our constraints. This is basically what prevent us from, let’s say, maximizing our profit to the infinite. Like I mentioned already, this is the part where we can spot the linear inequalities (≤, =, ≥). I also have to disclose that there are different ways to solve a LP problem, like for instance, BigM, Dual, Two Phased method etc. Unfortunately, it’s counterproductive trying to cover all the nuts and bolts of LP here, I hope you got some basic foundation to move on to our example. If not, I’m dropping some references at the end of this post so you can refer to. True Optimization it the revolutionary contribution of modern research to decision processes — George Dantzig Let’s say we work on a Data Science team for a manufacturing firm. The problem we are going to tackle here is named “The Activity-Analysis Problem” (Gass 1970). The Data Science team’s goal is to maximize the profit of the manufacturing company by defining how many different products to produce, taking into consideration, the limitation of resources available. By improving the operations of the firm and its resources allocation, we can potentially maximize the profit, which is the focus of our discussion here. The company produces four furniture items: chairs, tables, desks, and bookcases. The principal component is mahogany, but they also use glue, leather, glass, and man-hours. For example, when we see a chair, what really takes to make a single one is 5 board-feet of mahogany, 10 man-hours of labor, 3 ounces of glue, and 4 square feet of leather. To produce a table we need 20 board-feet, 15 man-hours, 8 ounces of glue. A desk is made by 15 board-feet, 25 man-hours, 15 ounces of glue, and 20 square feet of leather. Lastly, the bookcase is produce using 22 board-feet, 20 man-hours, 10 ounces of glue, and 20 square feet of glass. Here is an illustration of what we need to make a single chair: The bottom neck is that all these material have the following total quantities available, per week: - 20,000 board-feet of mahogany - 4,000 man-hours - 2,000 ounces of glue - 3,000 square feet of leather - 500 square feet of glass As you can see, the restricted amount of materials prevent us to produce all products with unlimited quantities at the same time. That is to say, our job is to decide how to better allocate these resources together in order to make the most profit. This is an exercise of how to develop a data-driven decision making process. But in order to set up this problem, we need to know the profit that each product brings to the firm. Hint: this is what we want to Maximize. Here they are: - $45 per Chair - $ 80 per Table - $110 per Desk - $55 per Bookcase Wait! One may decide to produce only desks, because this item alone has the highest profit ($110). But, why should we not embrace this approach? I will leave that answer for you figure out. Since we want to manufacture all these four items, and offer a good mix of products to our customers, while splitting the risk at the same time, what we really want to know is how many units of each item we have to produce in order to get the most profit. That is where LP modeling can help us square this problem out. For this Maximization LP problem, we are going to represent the items by the first letter of its name. Likewise, c for chair, t for table, d for desk, and b for bookcase. Just like we did in the previous example of what would take to produce a single chair, we will follow a similar schema for all the other items. Below we can see the amount of resources needed to make every single one of them. Note that the total amount for making these products must be less or equal to the total resources available. Take your time to read this schema. I just put together the data for making every single one of our four products, plus the constraints, which are the resources available (last column). Now, in order to formulate our LP in a more conventional way, all we have to do is bring the profit to be made by the items (the Objective Function). Here is how it looks like the final formulation of this LP problem: We did it. Congratulations! Tap yourself on the back because, usually, formulating a LP problem is the hardest part of this processing. Remember “garbage in, garbage out”, so if a LP is not formulated properly, it will not bring much value. Now that we have formulated the problem, we will use Python, and more specifically, the library called PuLP to solve this LP. Without further due, let’s do that. Linear Programming is a generalization of Linear Algebra. It is capable of handling a variety of problems, ranging from finding schedules for airlines or movies in a theater to distributing oil from refineries to markets. The reason for this great versatility is the ease at which constraints can be incorporated into the model-Steven J. Miller Instructions on how to install PuLP on Anaconda can be found here. Because this is simple example, and we are not working with many variables, constraints etc, we will not be using and importing any file (like csv) into Python, we are rather just entering these few variables. We could also create a Python program to request the user to do that in a more high level and organized way, but I’ll leave that up to you. I will break this section in two parts: in Part 1 we are going to set up this previous problem in Python using PuLP, and in Part 2 we are going to solve it. After you have installed PuLP you’ll we need to import PuLP library as following below: # import the library PuLP as p import pulp as p Next we will set up the Maximization problem and initiate the variables: # Set Up a LP Maximization Problem:Lp_prob = p.LpProblem('Activity-Analysis_1', p.LpMaximize) # Here we named the Problem "Acitity-Analysis_1". # Set Up Problem Variables: c = p.LpVariable("c", lowBound = 0) # "c" for chairt = p.LpVariable("t", lowBound = 0) # "t" for tabled = p.LpVariable("d", lowBound = 0) # "d" for deskb = p.LpVariable("b", lowBound = 0) # "b" for bookcase Now, that’s the part we will create the Objective Function (what we are trying to Maximize), and the Constraints. # Create Objective Function:Lp_prob += 45 * c + 80 * t + 110 * d + 55 * b # Create Constraints: Lp_prob += 5 * c + 20 * t + 15 * d + 22 * b <= 20000Lp_prob += 10 * c + 15 * t + 25 * d + 20 * b <= 4000Lp_prob += 3 * c + 8 * t + 15 * d + 10 * b <= 2000Lp_prob += 4 * c + 20 * d <= 3000Lp_prob += 20 * b <= 500 Finally, we will display this problem in order to make sure things look good. # Show the problem:print(Lp_prob) # note that it's shown in alphabetical order After running this previous code, this is how your LP problem should look like: As you can see the displayed problem looks like the one I wrote before, except the fact that PuLP organize the variables alphabetically, which has no impact in the solution whatsoever. So far, all we did was enter the variables we talked earlier and modeling the LP problem in Python. For the sake of simplicity and easier the understanding, we won’t be solving it now, but in Phase 2. Here we are going to create a new and simplified problem, which derivates from the one we just saw. The reason for that is just to make easier to convey the solution and it also helps to get additional intuition on solving these type of problems. Alright, in this new problem, we are still working with the same variables, but now we brought it down to only two variables (chair, and table), and we changed some numbers. Here is how our new Maximization problem looks like: As matter of fact, we kept most of the numbers without change, but now, the total of mahogany is 400, and the total of man-hours is 450. The second constraint was also changed from “15t” to “20t”. Now we will solve this problem in Python as following: ### Simplifying the Problem and Solving it #### Generate a New LP Maximization Problem:Lp_prob2 = p.LpProblem('Activity-Analysis_2', p.LpMaximize) # Generate Problem Variables (>= 0): c = p.LpVariable("c", lowBound = 0)t = p.LpVariable("t", lowBound = 0)# Create Objective Function:Lp_prob2 += 45 * c + 80 * t #+ 110 * d + 55 * b # Set Up the Constraints: Lp_prob2 += 5 * c + 20 * t <= 400Lp_prob2 += 10 * c + 15 * t <= 450# Show the problem:print(Lp_prob2) # note that it's shown in alphabetical order Again, let’s check how this new problem is displayed in Python: It looks just fine, so now we can proceed to solve it. Below is the code you need to do so. Note that will we print the “status” of the solution, which just tells us if the solution is Optimal (or not). In this example, we got an Optimal Solution. # Solve the Problem:status = Lp_prob2.solve()print(p.LpStatus[status]) # Display Solution Status Keep in mind that not all LP problems have an Optimal solution. Now, to really see the actual numbers we need to print the result as following. # Printing the final solution print(p.value(c), p.value(t), p.value(Lp_prob2.objective))# Result: 24.0 14.0 2200.0 So we got “24”, “14”, and “2200”. One may be wondering what those numbers are, right? It turns out that 24 and 14 are the optimal number of chairs and tables, respectively, that we need to produce in order to get the Optimal profit of $2,200. Hint: Linear Programming is all about Optimization. If you want to, you can create a loop to display this result. Here is an example: # Printing Number of Chairs and Tables:for var in (c,t): print('Optimal number of {} to produce is: {:1.0f}' .format(var.name, var.value()))# Output:# Optimal number of c to produce is: 24# Optimal number of t to produce is: 14 In order words, the optimum combination to produce for these two items, and making the most profit, considering the restrictions we have on the number of mahogany and man-hour available is: c=24 chairs, t=14 tables, and to find the optimal profit, we have to bring the objective function in this equation. This will look like: $45 x 24 + $80 x 14 = $2,200. We just used the Simplex algorithm to solve this problem. Now we can make a decision based on data, and supported by the results we got. Not based on gut feeling, right?! One more thing I need to point it out is that the Simplex can be quite challenging and tricky to solve. Although, it looked like a piece of cake here, if you attempt to solve it by hand, you can have a hard time if you don’t know what and how to actually do it. Thank God that nowadays we have the capabilities to do that using a solution like Python/PuLP. Before resting my case, I want to show you how this problem can be plotted into a chart. There are many ways to solve a Linear Programming problem, and the graphical method is one of them. So, I went to the white board and drew the Simplex Graph to take our discussion one step further. Here is the plot (which can be done using Matplotlib on Python): It looks nice, right?! Let me explain to you how we got there. First, we start looking at the first inequality (5c + 20t ≤ 400) of our LP problem, in this case, represented by the orange color. What we need is to find two points, one for c axis and other on the t axis (remember c for chair, and t for table). The simplest way to come up with that is to assume that if c = 0, we must get t = 20, and mark that “dot” on the t axis; and if t = 0, then we get c = 80, which we plot on the c axis. Second, we plot the last constrain (10c + 15t ≤ 450), represented by the green line. Following the same approach as before, we got the points on the axes as following: 45,0 and 0,30. In this plot, what we see is the superimposition of these two inequalities. By overlapping them, we can figure out the required solution space, which is the highlighted area in yellow. Any points in this region will satisfy the constraints of this problem, and this combination represents the different set ups of tables and chairs that we can produce considering the resources we have available (mahogany and man-hours). When both lines cross each other, we get the Optimal value of 24,14 (in red). This means that c=24, and t=14 satisfies both constraints precisely. We also found this same result using PuLP, but you can work with some algebra if you want to confirm that as well. Finally, we look at the Objective Function (45c + 80t = 0). This is represented by the gray line. Now, let’s think for a second. If the firm does not make any chairs and tables what would be its profit? Zero, right?! That would mean that c =0, and t=0. This is our starting point with the Simplex method, and we can move that gray line from zero up to the point that intersects c and t (24, 14), but not out of the boundary of that yellow area. By doing so, we eventually get to the Optimum formulation, which we have seen before: $45 x 24 + $80 x 14 = $2,200. By now you may have gotten the intuition that you could experiment with different values, and ended up testing multiple optimum solutions based on changes in the objective function, for instance. I hope this was useful for you. This example was extracted and adapted from the book “An Illustrated Guide to Linear Programming” by Saul I. Gass. You can find the codes on my GitHub here. Get started, but don’t try to eat the elephant in one meal. Start small with a pilot project and build your first dashboard. From there you can learn, improve, and expand into other areas-Rupert Bonham-Carter In this article you were introduced to some basic concepts of LP, you saw how to formulate a LP problem, and how to solve it. Optimization of resources will always be part of the agenda in many companies around the world. There will be always problems to Maximize and/or Minimize, depending on the scope of the project. Data Scientists need to have, at least, a very basic idea of how LP can be useful and the resources that we have available today to help us out. I hope this post has inspired you to perform your own experiments. Good Luck. Thank you! [1] Lial, Greenwell, and Ritchey, 2012: Finite Mathematics. Boston, Massachusets: Pearson. [2] Chvatal, Vasek, 1983: Linear Programming. USA: Freeman. [3] Gass, Saul I., 1970: An Illustrated Guide to Linear Programming. Canada: Dover.
[ { "code": null, "e": 395, "s": 47, "text": "The Simplex Method was designed to help solve LP problems and it is basically what we will see here. With advances in the technological field, this method started to be used, not only in the Military, but in a vast myriad of industries. Today, I will present you an example of how we can take advantage of this algorithm. I’ll cover the following:" }, { "code": null, "e": 435, "s": 395, "text": "1- Basic Concepts of Linear Programming" }, { "code": null, "e": 468, "s": 435, "text": "2- How to Formulate a LP Problem" }, { "code": null, "e": 502, "s": 468, "text": "3- How to Solve a LP using Python" }, { "code": null, "e": 543, "s": 502, "text": "4- A Graphical Way to Look at LP Problem" }, { "code": null, "e": 847, "s": 543, "text": "Linear Programming and linear inequalities go side by side. That is, many real-life problems are subject to some restrictions, e.g. number of raw material to produce a chair. In order words, there are some limitations that prevent us to manufacture an item without compromising the production of others." }, { "code": null, "e": 1025, "s": 847, "text": "For example, let’s say you need wood to make chairs and tables, so the amount of wood that you have available imposes a limit on the number of chairs and tables you can produce." }, { "code": null, "e": 1523, "s": 1025, "text": "In essence, this is the very problem LP attempts to solve: how to systematically allocate the resources in order to get the most out of the restriction (constraints) that we have, while considering, for example, the potential maximization of the profit you get from their sales. On that note, we can use LP to Maximize a profit, or Minimize a cost, like said previously. Funny thing is that we can convert a maximization problem into minimization, and vice-versa. But this won’t be the focus here." }, { "code": null, "e": 1962, "s": 1523, "text": "In LP, when I say “solve” that does not mean we will find a solution (like 2 + 2 = 4) all the time. We can formulate a LP problem, do some Math, and come to the conclusion that the particular LP problem does not have an Optimal Solution, which is the main goal of solving a LP: trying to land a unique optimal solution. This can occur because some problems may have too many different optimal solutions or even no optimal solution at all." }, { "code": null, "e": 2468, "s": 1962, "text": "Some of the reasons we may encounter a LP without an optimal solution may be out of our control. In many cases, the problems are simply way too complex to be solved (finding a unique optimal solution). A question we may want to ask ourselves when working on a LP problem may be: Is the problem feasible or infeasible? Some problems can even have many feasible solutions, and ended up being unbounded. To sum up, we can classify a LP problem into three classes: optimal solution, infeasible, and unbounded." }, { "code": null, "e": 2674, "s": 2468, "text": "Here, you are going to see an example of a LP problem that give us an Optimal Solution. But before we start working on our problem, I want to show you an example of how a traditional LP problem looks like:" }, { "code": null, "e": 2854, "s": 2674, "text": "The first line says “maximize” and that is where our objective function is located. That could also say “minimize”, and that would indicate our problem was a minimization problem." }, { "code": null, "e": 3219, "s": 2854, "text": "The second and third lines are our constraints. This is basically what prevent us from, let’s say, maximizing our profit to the infinite. Like I mentioned already, this is the part where we can spot the linear inequalities (≤, =, ≥). I also have to disclose that there are different ways to solve a LP problem, like for instance, BigM, Dual, Two Phased method etc." }, { "code": null, "e": 3454, "s": 3219, "text": "Unfortunately, it’s counterproductive trying to cover all the nuts and bolts of LP here, I hope you got some basic foundation to move on to our example. If not, I’m dropping some references at the end of this post so you can refer to." }, { "code": null, "e": 3564, "s": 3454, "text": "True Optimization it the revolutionary contribution of modern research to decision processes — George Dantzig" }, { "code": null, "e": 4080, "s": 3564, "text": "Let’s say we work on a Data Science team for a manufacturing firm. The problem we are going to tackle here is named “The Activity-Analysis Problem” (Gass 1970). The Data Science team’s goal is to maximize the profit of the manufacturing company by defining how many different products to produce, taking into consideration, the limitation of resources available. By improving the operations of the firm and its resources allocation, we can potentially maximize the profit, which is the focus of our discussion here." }, { "code": null, "e": 4712, "s": 4080, "text": "The company produces four furniture items: chairs, tables, desks, and bookcases. The principal component is mahogany, but they also use glue, leather, glass, and man-hours. For example, when we see a chair, what really takes to make a single one is 5 board-feet of mahogany, 10 man-hours of labor, 3 ounces of glue, and 4 square feet of leather. To produce a table we need 20 board-feet, 15 man-hours, 8 ounces of glue. A desk is made by 15 board-feet, 25 man-hours, 15 ounces of glue, and 20 square feet of leather. Lastly, the bookcase is produce using 22 board-feet, 20 man-hours, 10 ounces of glue, and 20 square feet of glass." }, { "code": null, "e": 4776, "s": 4712, "text": "Here is an illustration of what we need to make a single chair:" }, { "code": null, "e": 4876, "s": 4776, "text": "The bottom neck is that all these material have the following total quantities available, per week:" }, { "code": null, "e": 4908, "s": 4876, "text": "- 20,000 board-feet of mahogany" }, { "code": null, "e": 4926, "s": 4908, "text": "- 4,000 man-hours" }, { "code": null, "e": 4949, "s": 4926, "text": "- 2,000 ounces of glue" }, { "code": null, "e": 4980, "s": 4949, "text": "- 3,000 square feet of leather" }, { "code": null, "e": 5007, "s": 4980, "text": "- 500 square feet of glass" }, { "code": null, "e": 5333, "s": 5007, "text": "As you can see, the restricted amount of materials prevent us to produce all products with unlimited quantities at the same time. That is to say, our job is to decide how to better allocate these resources together in order to make the most profit. This is an exercise of how to develop a data-driven decision making process." }, { "code": null, "e": 5475, "s": 5333, "text": "But in order to set up this problem, we need to know the profit that each product brings to the firm. Hint: this is what we want to Maximize." }, { "code": null, "e": 5490, "s": 5475, "text": "Here they are:" }, { "code": null, "e": 5506, "s": 5490, "text": "- $45 per Chair" }, { "code": null, "e": 5523, "s": 5506, "text": "- $ 80 per Table" }, { "code": null, "e": 5539, "s": 5523, "text": "- $110 per Desk" }, { "code": null, "e": 5558, "s": 5539, "text": "- $55 per Bookcase" }, { "code": null, "e": 5748, "s": 5558, "text": "Wait! One may decide to produce only desks, because this item alone has the highest profit ($110). But, why should we not embrace this approach? I will leave that answer for you figure out." }, { "code": null, "e": 6067, "s": 5748, "text": "Since we want to manufacture all these four items, and offer a good mix of products to our customers, while splitting the risk at the same time, what we really want to know is how many units of each item we have to produce in order to get the most profit. That is where LP modeling can help us square this problem out." }, { "code": null, "e": 6238, "s": 6067, "text": "For this Maximization LP problem, we are going to represent the items by the first letter of its name. Likewise, c for chair, t for table, d for desk, and b for bookcase." }, { "code": null, "e": 6573, "s": 6238, "text": "Just like we did in the previous example of what would take to produce a single chair, we will follow a similar schema for all the other items. Below we can see the amount of resources needed to make every single one of them. Note that the total amount for making these products must be less or equal to the total resources available." }, { "code": null, "e": 6759, "s": 6573, "text": "Take your time to read this schema. I just put together the data for making every single one of our four products, plus the constraints, which are the resources available (last column)." }, { "code": null, "e": 6977, "s": 6759, "text": "Now, in order to formulate our LP in a more conventional way, all we have to do is bring the profit to be made by the items (the Objective Function). Here is how it looks like the final formulation of this LP problem:" }, { "code": null, "e": 7218, "s": 6977, "text": "We did it. Congratulations! Tap yourself on the back because, usually, formulating a LP problem is the hardest part of this processing. Remember “garbage in, garbage out”, so if a LP is not formulated properly, it will not bring much value." }, { "code": null, "e": 7380, "s": 7218, "text": "Now that we have formulated the problem, we will use Python, and more specifically, the library called PuLP to solve this LP. Without further due, let’s do that." }, { "code": null, "e": 7725, "s": 7380, "text": "Linear Programming is a generalization of Linear Algebra. It is capable of handling a variety of problems, ranging from finding schedules for airlines or movies in a theater to distributing oil from refineries to markets. The reason for this great versatility is the ease at which constraints can be incorporated into the model-Steven J. Miller" }, { "code": null, "e": 7792, "s": 7725, "text": "Instructions on how to install PuLP on Anaconda can be found here." }, { "code": null, "e": 8142, "s": 7792, "text": "Because this is simple example, and we are not working with many variables, constraints etc, we will not be using and importing any file (like csv) into Python, we are rather just entering these few variables. We could also create a Python program to request the user to do that in a more high level and organized way, but I’ll leave that up to you." }, { "code": null, "e": 8299, "s": 8142, "text": "I will break this section in two parts: in Part 1 we are going to set up this previous problem in Python using PuLP, and in Part 2 we are going to solve it." }, { "code": null, "e": 8387, "s": 8299, "text": "After you have installed PuLP you’ll we need to import PuLP library as following below:" }, { "code": null, "e": 8435, "s": 8387, "text": "# import the library PuLP as p import pulp as p" }, { "code": null, "e": 8508, "s": 8435, "text": "Next we will set up the Maximization problem and initiate the variables:" }, { "code": null, "e": 8888, "s": 8508, "text": "# Set Up a LP Maximization Problem:Lp_prob = p.LpProblem('Activity-Analysis_1', p.LpMaximize) # Here we named the Problem \"Acitity-Analysis_1\". # Set Up Problem Variables: c = p.LpVariable(\"c\", lowBound = 0) # \"c\" for chairt = p.LpVariable(\"t\", lowBound = 0) # \"t\" for tabled = p.LpVariable(\"d\", lowBound = 0) # \"d\" for deskb = p.LpVariable(\"b\", lowBound = 0) # \"b\" for bookcase" }, { "code": null, "e": 9002, "s": 8888, "text": "Now, that’s the part we will create the Objective Function (what we are trying to Maximize), and the Constraints." }, { "code": null, "e": 9315, "s": 9002, "text": "# Create Objective Function:Lp_prob += 45 * c + 80 * t + 110 * d + 55 * b # Create Constraints: Lp_prob += 5 * c + 20 * t + 15 * d + 22 * b <= 20000Lp_prob += 10 * c + 15 * t + 25 * d + 20 * b <= 4000Lp_prob += 3 * c + 8 * t + 15 * d + 10 * b <= 2000Lp_prob += 4 * c + 20 * d <= 3000Lp_prob += 20 * b <= 500" }, { "code": null, "e": 9393, "s": 9315, "text": "Finally, we will display this problem in order to make sure things look good." }, { "code": null, "e": 9472, "s": 9393, "text": "# Show the problem:print(Lp_prob) # note that it's shown in alphabetical order" }, { "code": null, "e": 9552, "s": 9472, "text": "After running this previous code, this is how your LP problem should look like:" }, { "code": null, "e": 9938, "s": 9552, "text": "As you can see the displayed problem looks like the one I wrote before, except the fact that PuLP organize the variables alphabetically, which has no impact in the solution whatsoever. So far, all we did was enter the variables we talked earlier and modeling the LP problem in Python. For the sake of simplicity and easier the understanding, we won’t be solving it now, but in Phase 2." }, { "code": null, "e": 10185, "s": 9938, "text": "Here we are going to create a new and simplified problem, which derivates from the one we just saw. The reason for that is just to make easier to convey the solution and it also helps to get additional intuition on solving these type of problems." }, { "code": null, "e": 10412, "s": 10185, "text": "Alright, in this new problem, we are still working with the same variables, but now we brought it down to only two variables (chair, and table), and we changed some numbers. Here is how our new Maximization problem looks like:" }, { "code": null, "e": 10664, "s": 10412, "text": "As matter of fact, we kept most of the numbers without change, but now, the total of mahogany is 400, and the total of man-hours is 450. The second constraint was also changed from “15t” to “20t”. Now we will solve this problem in Python as following:" }, { "code": null, "e": 11173, "s": 10664, "text": "### Simplifying the Problem and Solving it #### Generate a New LP Maximization Problem:Lp_prob2 = p.LpProblem('Activity-Analysis_2', p.LpMaximize) # Generate Problem Variables (>= 0): c = p.LpVariable(\"c\", lowBound = 0)t = p.LpVariable(\"t\", lowBound = 0)# Create Objective Function:Lp_prob2 += 45 * c + 80 * t #+ 110 * d + 55 * b # Set Up the Constraints: Lp_prob2 += 5 * c + 20 * t <= 400Lp_prob2 += 10 * c + 15 * t <= 450# Show the problem:print(Lp_prob2) # note that it's shown in alphabetical order" }, { "code": null, "e": 11237, "s": 11173, "text": "Again, let’s check how this new problem is displayed in Python:" }, { "code": null, "e": 11485, "s": 11237, "text": "It looks just fine, so now we can proceed to solve it. Below is the code you need to do so. Note that will we print the “status” of the solution, which just tells us if the solution is Optimal (or not). In this example, we got an Optimal Solution." }, { "code": null, "e": 11584, "s": 11485, "text": "# Solve the Problem:status = Lp_prob2.solve()print(p.LpStatus[status]) # Display Solution Status" }, { "code": null, "e": 11728, "s": 11584, "text": "Keep in mind that not all LP problems have an Optimal solution. Now, to really see the actual numbers we need to print the result as following." }, { "code": null, "e": 11843, "s": 11728, "text": "# Printing the final solution print(p.value(c), p.value(t), p.value(Lp_prob2.objective))# Result: 24.0 14.0 2200.0" }, { "code": null, "e": 12138, "s": 11843, "text": "So we got “24”, “14”, and “2200”. One may be wondering what those numbers are, right? It turns out that 24 and 14 are the optimal number of chairs and tables, respectively, that we need to produce in order to get the Optimal profit of $2,200. Hint: Linear Programming is all about Optimization." }, { "code": null, "e": 12220, "s": 12138, "text": "If you want to, you can create a loop to display this result. Here is an example:" }, { "code": null, "e": 12460, "s": 12220, "text": "# Printing Number of Chairs and Tables:for var in (c,t): print('Optimal number of {} to produce is: {:1.0f}' .format(var.name, var.value()))# Output:# Optimal number of c to produce is: 24# Optimal number of t to produce is: 14" }, { "code": null, "e": 12817, "s": 12460, "text": "In order words, the optimum combination to produce for these two items, and making the most profit, considering the restrictions we have on the number of mahogany and man-hour available is: c=24 chairs, t=14 tables, and to find the optimal profit, we have to bring the objective function in this equation. This will look like: $45 x 24 + $80 x 14 = $2,200." }, { "code": null, "e": 12988, "s": 12817, "text": "We just used the Simplex algorithm to solve this problem. Now we can make a decision based on data, and supported by the results we got. Not based on gut feeling, right?!" }, { "code": null, "e": 13345, "s": 12988, "text": "One more thing I need to point it out is that the Simplex can be quite challenging and tricky to solve. Although, it looked like a piece of cake here, if you attempt to solve it by hand, you can have a hard time if you don’t know what and how to actually do it. Thank God that nowadays we have the capabilities to do that using a solution like Python/PuLP." }, { "code": null, "e": 13534, "s": 13345, "text": "Before resting my case, I want to show you how this problem can be plotted into a chart. There are many ways to solve a Linear Programming problem, and the graphical method is one of them." }, { "code": null, "e": 13697, "s": 13534, "text": "So, I went to the white board and drew the Simplex Graph to take our discussion one step further. Here is the plot (which can be done using Matplotlib on Python):" }, { "code": null, "e": 13760, "s": 13697, "text": "It looks nice, right?! Let me explain to you how we got there." }, { "code": null, "e": 14191, "s": 13760, "text": "First, we start looking at the first inequality (5c + 20t ≤ 400) of our LP problem, in this case, represented by the orange color. What we need is to find two points, one for c axis and other on the t axis (remember c for chair, and t for table). The simplest way to come up with that is to assume that if c = 0, we must get t = 20, and mark that “dot” on the t axis; and if t = 0, then we get c = 80, which we plot on the c axis." }, { "code": null, "e": 14374, "s": 14191, "text": "Second, we plot the last constrain (10c + 15t ≤ 450), represented by the green line. Following the same approach as before, we got the points on the axes as following: 45,0 and 0,30." }, { "code": null, "e": 15058, "s": 14374, "text": "In this plot, what we see is the superimposition of these two inequalities. By overlapping them, we can figure out the required solution space, which is the highlighted area in yellow. Any points in this region will satisfy the constraints of this problem, and this combination represents the different set ups of tables and chairs that we can produce considering the resources we have available (mahogany and man-hours). When both lines cross each other, we get the Optimal value of 24,14 (in red). This means that c=24, and t=14 satisfies both constraints precisely. We also found this same result using PuLP, but you can work with some algebra if you want to confirm that as well." }, { "code": null, "e": 15619, "s": 15058, "text": "Finally, we look at the Objective Function (45c + 80t = 0). This is represented by the gray line. Now, let’s think for a second. If the firm does not make any chairs and tables what would be its profit? Zero, right?! That would mean that c =0, and t=0. This is our starting point with the Simplex method, and we can move that gray line from zero up to the point that intersects c and t (24, 14), but not out of the boundary of that yellow area. By doing so, we eventually get to the Optimum formulation, which we have seen before: $45 x 24 + $80 x 14 = $2,200." }, { "code": null, "e": 15847, "s": 15619, "text": "By now you may have gotten the intuition that you could experiment with different values, and ended up testing multiple optimum solutions based on changes in the objective function, for instance. I hope this was useful for you." }, { "code": null, "e": 16004, "s": 15847, "text": "This example was extracted and adapted from the book “An Illustrated Guide to Linear Programming” by Saul I. Gass. You can find the codes on my GitHub here." }, { "code": null, "e": 16213, "s": 16004, "text": "Get started, but don’t try to eat the elephant in one meal. Start small with a pilot project and build your first dashboard. From there you can learn, improve, and expand into other areas-Rupert Bonham-Carter" }, { "code": null, "e": 16533, "s": 16213, "text": "In this article you were introduced to some basic concepts of LP, you saw how to formulate a LP problem, and how to solve it. Optimization of resources will always be part of the agenda in many companies around the world. There will be always problems to Maximize and/or Minimize, depending on the scope of the project." }, { "code": null, "e": 16756, "s": 16533, "text": "Data Scientists need to have, at least, a very basic idea of how LP can be useful and the resources that we have available today to help us out. I hope this post has inspired you to perform your own experiments. Good Luck." }, { "code": null, "e": 16767, "s": 16756, "text": "Thank you!" }, { "code": null, "e": 16858, "s": 16767, "text": "[1] Lial, Greenwell, and Ritchey, 2012: Finite Mathematics. Boston, Massachusets: Pearson." }, { "code": null, "e": 16918, "s": 16858, "text": "[2] Chvatal, Vasek, 1983: Linear Programming. USA: Freeman." } ]
MySQL GROUP BY Statement
The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns. Below is a selection from the "Customers" table in the Northwind sample database: The following SQL statement lists the number of customers in each country: The following SQL statement lists the number of customers in each country, sorted high to low: Below is a selection from the "Orders" table in the Northwind sample database: And a selection from the "Shippers" table: The following SQL statement lists the number of orders sent by each shipper: List the number of customers in each country. SELECT (CustomerID), Country FROM Customers ; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 134, "s": 0, "text": "The GROUP BY statement groups rows that have the same values into summary \nrows, like \"find the number of customers in each country\"." }, { "code": null, "e": 285, "s": 134, "text": "The GROUP BY statement is often used with aggregate functions (COUNT(), \nMAX(), \nMIN(), SUM(), \nAVG()) to group the result-set by one or more columns." }, { "code": null, "e": 368, "s": 285, "text": "Below is a selection from the \"Customers\" table in the Northwind sample \ndatabase:" }, { "code": null, "e": 443, "s": 368, "text": "The following SQL statement lists the number of customers in each country:" }, { "code": null, "e": 539, "s": 443, "text": "The following SQL statement lists the number of customers in each country, \nsorted high to low:" }, { "code": null, "e": 618, "s": 539, "text": "Below is a selection from the \"Orders\" table in the Northwind sample database:" }, { "code": null, "e": 661, "s": 618, "text": "And a selection from the \"Shippers\" table:" }, { "code": null, "e": 738, "s": 661, "text": "The following SQL statement lists the number of orders sent by each shipper:" }, { "code": null, "e": 784, "s": 738, "text": "List the number of customers in each country." }, { "code": null, "e": 831, "s": 784, "text": "SELECT (CustomerID),\nCountry\nFROM Customers\n;\n" }, { "code": null, "e": 850, "s": 831, "text": "Start the Exercise" }, { "code": null, "e": 883, "s": 850, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 925, "s": 883, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1032, "s": 925, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1051, "s": 1032, "text": "[email protected]" } ]
Python 3 - time time() Method
The method time() returns the time as a floating point number expressed in seconds since the epoch, in UTC. Note − Even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls. Following is the syntax for time() method − time.time() NA This method returns the time as a floating point number expressed in seconds since the epoch, in UTC. The following example shows the usage of time() method. #!/usr/bin/python3 import time print ("time.time(): %f " % time.time()) print (time.localtime( time.time() )) print (time.asctime( time.localtime(time.time()) )) When we run the above program, it produces the following result − time.time(): 1455519806.011433 time.struct_time(tm_year = 2016, tm_mon = 2, tm_mday = 15, tm_hour = 12, tm_min = 33, tm_sec = 26, tm_wday = 0, tm_yday = 46, tm_isdst = 0) Mon Feb 15 12:33:26 2016 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": 2448, "s": 2340, "text": "The method time() returns the time as a floating point number expressed in seconds since the epoch, in UTC." }, { "code": null, "e": 2761, "s": 2448, "text": "Note − Even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls." }, { "code": null, "e": 2805, "s": 2761, "text": "Following is the syntax for time() method −" }, { "code": null, "e": 2817, "s": 2805, "text": "time.time()" }, { "code": null, "e": 2820, "s": 2817, "text": "NA" }, { "code": null, "e": 2922, "s": 2820, "text": "This method returns the time as a floating point number expressed in seconds since the epoch, in UTC." }, { "code": null, "e": 2978, "s": 2922, "text": "The following example shows the usage of time() method." }, { "code": null, "e": 3142, "s": 2978, "text": "#!/usr/bin/python3\nimport time\n\nprint (\"time.time(): %f \" % time.time())\nprint (time.localtime( time.time() ))\nprint (time.asctime( time.localtime(time.time()) ))" }, { "code": null, "e": 3208, "s": 3142, "text": "When we run the above program, it produces the following result −" }, { "code": null, "e": 3410, "s": 3208, "text": "time.time(): 1455519806.011433 \ntime.struct_time(tm_year = 2016, tm_mon = 2, tm_mday = 15, tm_hour = 12, tm_min = 33, \n tm_sec = 26, tm_wday = 0, tm_yday = 46, tm_isdst = 0)\nMon Feb 15 12:33:26 2016\n" }, { "code": null, "e": 3447, "s": 3410, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3463, "s": 3447, "text": " Malhar Lathkar" }, { "code": null, "e": 3496, "s": 3463, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3515, "s": 3496, "text": " Arnab Chakraborty" }, { "code": null, "e": 3550, "s": 3515, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3572, "s": 3550, "text": " In28Minutes Official" }, { "code": null, "e": 3606, "s": 3572, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3634, "s": 3606, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3669, "s": 3634, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3683, "s": 3669, "text": " Lets Kode It" }, { "code": null, "e": 3716, "s": 3683, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3733, "s": 3716, "text": " Abhilash Nelson" }, { "code": null, "e": 3740, "s": 3733, "text": " Print" }, { "code": null, "e": 3751, "s": 3740, "text": " Add Notes" } ]
Longest Palindromic Subsequence | DP-12 - GeeksforGeeks
25 Apr, 2022 Given a sequence, find the length of the longest palindromic subsequence in it. As another example, if the given sequence is “BBABCBCAB”, then the output should be 7 as “BABCBAB” is the longest palindromic subsequence in it. “BBBBB” and “BBCBB” are also palindromic subsequences of the given sequence, but not the longest ones.The naive solution for this problem is to generate all subsequences of the given sequence and find the longest palindromic subsequence. This solution is exponential in terms of time complexity. Let us see how this problem possesses both important properties of a Dynamic Programming (DP) Problem and can efficiently be solved using Dynamic Programming.1) Optimal Substructure: Let X[0..n-1] be the input sequence of length n and L(0, n-1) be the length of the longest palindromic subsequence of X[0..n-1]. If last and first characters of X are same, then L(0, n-1) = L(1, n-2) + 2. Else L(0, n-1) = MAX (L(1, n-1), L(0, n-2)). Following is a general recursive solution with all cases handled. // Every single character is a palindrome of length 1 L(i, i) = 1 for all indexes i in given sequence // IF first and last characters are not same If (X[i] != X[j]) L(i, j) = max{L(i + 1, j),L(i, j - 1)} // If there are only 2 characters and both are same Else if (j == i + 1) L(i, j) = 2 // If there are more than two characters, and first and last // characters are same Else L(i, j) = L(i + 1, j - 1) + 2 2) Overlapping Subproblems Following is a simple recursive implementation of the LPS problem. The implementation simply follows the recursive structure mentioned above. C++ C Java Python3 C# PHP Javascript // C++ program of above approach#include<bits/stdc++.h>using namespace std; // A utility function to get max of two integersint max (int x, int y) { return (x > y)? x : y; } // Returns the length of the longest palindromic subsequence in seqint lps(char *seq, int i, int j){// Base Case 1: If there is only 1 characterif (i == j) return 1; // Base Case 2: If there are only 2// characters and both are sameif (seq[i] == seq[j] && i + 1 == j) return 2; // If the first and last characters matchif (seq[i] == seq[j]) return lps (seq, i+1, j-1) + 2; // If the first and last characters do not matchreturn max( lps(seq, i, j-1), lps(seq, i+1, j) );} /* Driver program to test above functions */int main(){ char seq[] = "GEEKSFORGEEKS"; int n = strlen(seq); cout << "The length of the LPS is " << lps(seq, 0, n-1); return 0;} // This code is contributed// by Akanksha Rai // C program of above approach#include<stdio.h>#include<string.h> // A utility function to get max of two integersint max (int x, int y) { return (x > y)? x : y; } // Returns the length of the longest palindromic subsequence in seqint lps(char *seq, int i, int j){ // Base Case 1: If there is only 1 character if (i == j) return 1; // Base Case 2: If there are only 2 characters and both are same if (seq[i] == seq[j] && i + 1 == j) return 2; // If the first and last characters match if (seq[i] == seq[j]) return lps (seq, i+1, j-1) + 2; // If the first and last characters do not match return max( lps(seq, i, j-1), lps(seq, i+1, j) );} /* Driver program to test above functions */int main(){ char seq[] = "GEEKSFORGEEKS"; int n = strlen(seq); printf ("The length of the LPS is %d", lps(seq, 0, n-1)); getchar(); return 0;} //Java program of above approach class GFG { // A utility function to get max of two integers static int max(int x, int y) { return (x > y) ? x : y; } // Returns the length of the longest palindromic subsequence in seq static int lps(char seq[], int i, int j) { // Base Case 1: If there is only 1 character if (i == j) { return 1; } // Base Case 2: If there are only 2 characters and both are same if (seq[i] == seq[j] && i + 1 == j) { return 2; } // If the first and last characters match if (seq[i] == seq[j]) { return lps(seq, i + 1, j - 1) + 2; } // If the first and last characters do not match return max(lps(seq, i, j - 1), lps(seq, i + 1, j)); } /* Driver program to test above function */ public static void main(String[] args) { String seq = "GEEKSFORGEEKS"; int n = seq.length(); System.out.printf("The length of the LPS is %d", lps(seq.toCharArray(), 0, n - 1)); }} # Python 3 program of above approach # A utility function to get max# of two integersdef max(x, y): if(x > y): return x return y # Returns the length of the longest# palindromic subsequence in seqdef lps(seq, i, j): # Base Case 1: If there is # only 1 character if (i == j): return 1 # Base Case 2: If there are only 2 # characters and both are same if (seq[i] == seq[j] and i + 1 == j): return 2 # If the first and last characters match if (seq[i] == seq[j]): return lps(seq, i + 1, j - 1) + 2 # If the first and last characters # do not match return max(lps(seq, i, j - 1), lps(seq, i + 1, j)) # Driver Codeif __name__ == '__main__': seq = "GEEKSFORGEEKS" n = len(seq) print("The length of the LPS is", lps(seq, 0, n - 1)) # This code contributed by Rajput-Ji // C# program of the above approachusing System; public class GFG{ // A utility function to get max of two integers static int max(int x, int y) { return (x > y) ? x : y; } // Returns the length of the longest palindromic subsequence in seq static int lps(char []seq, int i, int j) { // Base Case 1: If there is only 1 character if (i == j) { return 1; } // Base Case 2: If there are only 2 characters and both are same if (seq[i] == seq[j] && i + 1 == j) { return 2; } // If the first and last characters match if (seq[i] == seq[j]) { return lps(seq, i + 1, j - 1) + 2; } // If the first and last characters do not match return max(lps(seq, i, j - 1), lps(seq, i + 1, j)); } /* Driver program to test above function */ public static void Main() { String seq = "GEEKSFORGEEKS"; int n = seq.Length; Console.Write("The length of the LPS is "+lps(seq.ToCharArray(), 0, n - 1)); }} // This code is contributed by Rajput-Ji <?php// PHP program of above approach // Returns the length of the longest// palindromic subsequence in seqfunction lps($seq, $i, $j){ // Base Case 1: If there is // only 1 character if ($i == $j) return 1; // Base Case 2: If there are only 2 // characters and both are same if ($seq[$i] == $seq[$j] && $i + 1 == $j) return 2; // If the first and last characters match if ($seq[$i] == $seq[$j]) return lps ($seq, $i + 1, $j - 1) + 2; // If the first and last characters // do not match return max(lps($seq, $i, $j - 1), lps($seq, $i + 1, $j));} // Driver Code$seq = "GEEKSFORGEEKS";$n = strlen($seq);echo "The length of the LPS is ". lps($seq, 0, $n - 1); // This code is contributed by ita_c?> <script> // A utility function to get max of two integers function max(x, y) { return (x > y) ? x : y; } // Returns the length of the longest palindromic subsequence in seq function lps(seq, i, j) { // Base Case 1: If there is only 1 character if (i == j) { return 1; } // Base Case 2: If there are only 2 characters and both are same if (seq[i] == seq[j] && i + 1 == j) { return 2; } // If the first and last characters match if (seq[i] == seq[j]) { return lps(seq, i + 1, j - 1) + 2; } // If the first and last characters do not match return max(lps(seq, i, j - 1), lps(seq, i + 1, j)); } /* Driver program to test above function */ let seq = "GEEKSFORGEEKS"; let n = seq.length; document.write("The length of the LPS is ", lps(seq.split(""), 0, n - 1)); // This code is contributed by avanitrachhadiya2155</script> The length of the LPS is 5 Considering the above implementation, the following is a partial recursion tree for a sequence of length 6 with all different characters. L(0, 5) / \ / \ L(1,5) L(0,4) / \ / \ / \ / \ L(2,5) L(1,4) L(1,4) L(0,3) In the above partial recursion tree, L(1, 4) is being solved twice. If we draw the complete recursion tree, then we can see that there are many subproblems that are solved again and again. Since the same subproblems are called again, this problem has the Overlapping Subproblems property. So LPS problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of the same subproblems can be avoided by constructing a temporary array L[][] in a bottom-up manner.Dynamic Programming Solution C++ Java Python3 C# PHP Javascript // A Dynamic Programming based C++ program for LPS problem// Returns the length of the longest palindromic subsequence in seq#include<stdio.h>#include<string.h> // A utility function to get max of two integersint max (int x, int y) { return (x > y)? x : y; } // Returns the length of the longest palindromic subsequence in seqint lps(char *str){ int n = strlen(str); int i, j, cl; int L[n][n]; // Create a table to store results of subproblems // Strings of length 1 are palindrome of length 1 for (i = 0; i < n; i++) L[i][i] = 1; // Build the table. Note that the lower diagonal values of table are // useless and not filled in the process. The values are filled in a // manner similar to Matrix Chain Multiplication DP solution (See // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). cl is length of // substring for (cl=2; cl<=n; cl++) { for (i=0; i<n-cl+1; i++) { j = i+cl-1; if (str[i] == str[j] && cl == 2) L[i][j] = 2; else if (str[i] == str[j]) L[i][j] = L[i+1][j-1] + 2; else L[i][j] = max(L[i][j-1], L[i+1][j]); } } return L[0][n-1];} /* Driver program to test above functions */int main(){ char seq[] = "GEEKS FOR GEEKS"; int n = strlen(seq); printf ("The length of the LPS is %d", lps(seq)); getchar(); return 0;} // A Dynamic Programming based Java// Program for the Egg Dropping Puzzleclass LPS{ // A utility function to get max of two integers static int max (int x, int y) { return (x > y)? x : y; } // Returns the length of the longest // palindromic subsequence in seq static int lps(String seq) { int n = seq.length(); int i, j, cl; // Create a table to store results of subproblems int L[][] = new int[n][n]; // Strings of length 1 are palindrome of length 1 for (i = 0; i < n; i++) L[i][i] = 1; // Build the table. Note that the lower // diagonal values of table are // useless and not filled in the process. // The values are filled in a manner similar // to Matrix Chain Multiplication DP solution (See // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). // cl is length of substring for (cl=2; cl<=n; cl++) { for (i=0; i<n-cl+1; i++) { j = i+cl-1; if (seq.charAt(i) == seq.charAt(j) && cl == 2) L[i][j] = 2; else if (seq.charAt(i) == seq.charAt(j)) L[i][j] = L[i+1][j-1] + 2; else L[i][j] = max(L[i][j-1], L[i+1][j]); } } return L[0][n-1]; } /* Driver program to test above functions */ public static void main(String args[]) { String seq = "GEEKSFORGEEKS"; int n = seq.length(); System.out.println("The length of the lps is "+ lps(seq)); }}/* This code is contributed by Rajat Mishra */ # A Dynamic Programming based Python# program for LPS problem Returns the length# of the longest palindromic subsequence in seqdef lps(str): n = len(str) # Create a table to store results of subproblems L = [[0 for x in range(n)] for x in range(n)] # Strings of length 1 are palindrome of length 1 for i in range(n): L[i][i] = 1 # Build the table. Note that the lower # diagonal values of table are # useless and not filled in the process. # The values are filled in a # manner similar to Matrix Chain # Multiplication DP solution (See # https://www.geeksforgeeks.org/dynamic-programming-set-8-matrix-chain-multiplication/ # cl is length of substring for cl in range(2, n+1): for i in range(n-cl+1): j = i+cl-1 if str[i] == str[j] and cl == 2: L[i][j] = 2 elif str[i] == str[j]: L[i][j] = L[i+1][j-1] + 2 else: L[i][j] = max(L[i][j-1], L[i+1][j]); return L[0][n-1] # Driver program to test above functionsseq = "GEEKS FOR GEEKS"n = len(seq)print("The length of the LPS is " + str(lps(seq))) # This code is contributed by Bhavya Jain // A Dynamic Programming based C# Program// for the Egg Dropping Puzzleusing System; class GFG { // A utility function to get max of // two integers static int max (int x, int y) { return (x > y)? x : y; } // Returns the length of the longest // palindromic subsequence in seq static int lps(string seq) { int n = seq.Length; int i, j, cl; // Create a table to store results // of subproblems int [,]L = new int[n,n]; // Strings of length 1 are // palindrome of length 1 for (i = 0; i < n; i++) L[i,i] = 1; // Build the table. Note that the // lower diagonal values of table // are useless and not filled in // the process. The values are // filled in a manner similar to // Matrix Chain Multiplication DP // solution (See // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/ // cl is length of substring for (cl = 2; cl <= n; cl++) { for (i = 0; i < n-cl+1; i++) { j = i + cl - 1; if (seq[i] == seq[j] && cl == 2) L[i,j] = 2; else if (seq[i] == seq[j]) L[i,j] = L[i+1,j-1] + 2; else L[i,j] = max(L[i,j-1], L[i+1,j]); } } return L[0,n-1]; } /* Driver program to test above functions */ public static void Main() { string seq = "GEEKS FOR GEEKS"; int n = seq.Length; Console.Write("The length of the " + "lps is "+ lps(seq)); }} // This code is contributed by nitin mittal. <?php// A Dynamic Programming based// PHP program for LPS problem// Returns the length of the// longest palindromic// subsequence in seq // A utility function to get// max of two integers// function max( $x, $y)// { return ($x > $y)? $x : $y; } // Returns the length of the// longest palindromic// subsequence in seqfunction lps($str){$n = strlen($str);$i; $j; $cl; // Create a table to store// results of subproblems$L[][] = array(array()); // Strings of length 1 are// palindrome of length 1for ($i = 0; $i < $n; $i++) $L[$i][$i] = 1; // Build the table. Note that // the lower diagonal values // of table are useless and // not filled in the process. // The values are filled in a // manner similar to Matrix // Chain Multiplication DP // solution (See // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). // cl is length of substring for ($cl = 2; $cl <= $n; $cl++) { for ($i = 0; $i < $n - $cl + 1; $i++) { $j = $i + $cl - 1; if ($str[$i] == $str[$j] && $cl == 2) $L[$i][$j] = 2; else if ($str[$i] == $str[$j]) $L[$i][$j] = $L[$i + 1][$j - 1] + 2; else $L[$i][$j] = max($L[$i][$j - 1], $L[$i + 1][$j]); } } return $L[0][$n - 1];} // Driver Code$seq = 'GEEKS FOR GEEKS';$n = strlen($seq);echo "The length of the " . "LPS is ", lps($seq); // This code is contributed// by shiv_bhakt.?> <script>// A Dynamic Programming based Javascript// Program for the Egg Dropping Puzzle // A utility function to get max of two integersfunction max(x,y){ return (x > y)? x : y;} // Returns the length of the longest // palindromic subsequence in seqfunction lps(seq){ let n = seq.length; let i, j, cl; // Create a table to store results of subproblems let L = new Array(n); for(let x=0;x<n;x++) { L[x] = new Array(n); for(let y = 0; y < n; y++) L[x][y] = 0; } // Strings of length 1 are palindrome of length 1 for (i = 0; i < n; i++) L[i][i] = 1; // Build the table. Note that the lower // diagonal values of table are // useless and not filled in the process. // The values are filled in a manner similar // to Matrix Chain Multiplication DP solution (See // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). // cl is length of substring for (cl = 2; cl <= n; cl++) { for (i = 0; i < n -cl + 1; i++) { j = i + cl - 1; if (seq[i] == seq[j] && cl == 2) L[i][j] = 2; else if (seq[i] == seq[j]) L[i][j] = L[i + 1][j - 1] + 2; else L[i][j] = max(L[i][j - 1], L[i + 1][j]); } } return L[0][n - 1];} /* Driver program to test above functions */let seq = "GEEKS FOR GEEKS";let n = seq.length;document.write("The length of the lps is "+ lps(seq)); // This code is contributed by rag2127</script> The length of the LPS is 7 The Time Complexity of the above implementation is O(n^2) which is much better than the worst-case time complexity of Naive Recursive implementation. The idea used here is to reverse the given input string and check the length of the longest common subsequence. That would be the answer for the longest palindromic subsequence. C++ Java Python3 Javascript // A Dynamic Programming based C++ program for LPS problem// Returns the length of the longest palindromic subsequence// in seq#include <bits/stdc++.h>using namespace std; int dp[1001][1001]; // Returns the length of the longest palindromic subsequence// in seqint lps(string& s1, string& s2, int n1, int n2){ if (n1 == 0 || n2 == 0) { return 0; } if (dp[n1][n2] != -1) { return dp[n1][n2]; } if (s1[n1 - 1] == s2[n2 - 1]) { return dp[n1][n2] = 1 + lps(s1, s2, n1 - 1, n2 - 1); } else { return dp[n1][n2] = max(lps(s1, s2, n1 - 1, n2), lps(s1, s2, n1, n2 - 1)); }} /* Driver program to test above functions */int main(){ string seq = "GEEKS FOR GEEKS"; int n = seq.size(); dp[n][n]; memset(dp, -1, sizeof(dp)); string s2 = seq; reverse(s2.begin(), s2.end()); cout << "The length of the LPS is " << lps(s2, seq, n, n) << endl; return 0;} // This code is contributed by Arun Bang // Java program of above approachclass GFG { // A utility function to get max of two integers static int max(int x, int y) { return (x > y) ? x : y; } // Returns the length of the longest palindromic subsequence in seq static int lps(char seq[], int i, int j) { // Base Case 1: If there is only 1 character if (i == j) { return 1; } // Base Case 2: If there are only 2 characters and both are same if (seq[i] == seq[j] && i + 1 == j) { return 2; } // If the first and last characters match if (seq[i] == seq[j]) { return lps(seq, i + 1, j - 1) + 2; } // If the first and last characters do not match return max(lps(seq, i, j - 1), lps(seq, i + 1, j)); } /* Driver program to test above function */ public static void main(String[] args) { String seq = "GEEKS FOR GEEKS"; int n = seq.length(); System.out.printf("The length of the LPS is %d", lps(seq.toCharArray(), 0, n - 1)); }} // This code is contributed by gauravrajput1 # A Dynamic Programming based Python program for LPS problem# Returns the length of the longest palindromic subsequence# in seq dp = [[-1 for i in range(1001)]for j in range(1001)] # Returns the length of the longest palindromic subsequence# in seqdef lps(s1, s2, n1, n2): if (n1 == 0 or n2 == 0): return 0 if (dp[n1][n2] != -1): return dp[n1][n2] if (s1[n1 - 1] == s2[n2 - 1]): dp[n1][n2] = 1 + lps(s1, s2, n1 - 1, n2 - 1) return dp[n1][n2] else: dp[n1][n2] = max(lps(s1, s2, n1 - 1, n2),lps(s1, s2, n1, n2 - 1)) return dp[n1][n2] # Driver program to test above functions seq = "GEEKS FOR GEEKS"n = len(seq) s2 = seqs2 = s2[::-1]print(f"The length of the LPS is {lps(s2, seq, n, n)}") # This code is contributed by shinjanpatra <script> // A Dynamic Programming based JavaScript program for LPS problem// Returns the length of the longest palindromic subsequence// in seqlet dp; // Returns the length of the longest palindromic subsequence// in seqfunction lps(s1, s2, n1, n2){ if (n1 == 0 || n2 == 0) { return 0; } if (dp[n1][n2] != -1) { return dp[n1][n2]; } if (s1[n1 - 1] == s2[n2 - 1]) { return dp[n1][n2] = 1 + lps(s1, s2, n1 - 1, n2 - 1); } else { return dp[n1][n2] = Math.max(lps(s1, s2, n1 - 1, n2), lps(s1, s2, n1, n2 - 1)); }} /* Driver program to test above functions */ let seq = "GEEKS FOR GEEKS";let n = seq.length;dp = new Array(1001);for(let i=0;i<1001;i++){ dp[i] = new Array(1001).fill(-1);}let s2 = seq;s2 = s2.split('').reverse().join('');document.write("The length of the LPS is " + lps(s2, seq, n, n),"</br>"); // This code is contributed by shinjanpatra </script> The length of the LPS is 7 Time Complexity: O(n*n) YouTubeGeeksforGeeks502K subscribersLongest Palindromic Subsequence | Dynamic Programming | Set 12 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=TLaGwTnd3HY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Print Longest Palindromic Subsequence Longest palindrome subsequence with O(n) spacePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.References: http://users.eecs.northwestern.edu/~dda902/336/hw6-sol.pdf nitin mittal Vishal_Khoda Rajput-Ji Akanksha_Rai ukasp paperdosa avanitrachhadiya2155 rag2127 sumitgumber28 arunbang17 amartyaghoshgfg simmytarika5 shinjanpatra GauravRajput1 Amazon Linkedin palindrome PayPal Rivigo subsequence Dynamic Programming Strings Amazon Linkedin PayPal Rivigo Strings Dynamic Programming palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Subset Sum Problem | DP-25 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 24960, "s": 24932, "text": "\n25 Apr, 2022" }, { "code": null, "e": 25041, "s": 24960, "text": "Given a sequence, find the length of the longest palindromic subsequence in it. " }, { "code": null, "e": 25917, "s": 25041, "text": "As another example, if the given sequence is “BBABCBCAB”, then the output should be 7 as “BABCBAB” is the longest palindromic subsequence in it. “BBBBB” and “BBCBB” are also palindromic subsequences of the given sequence, but not the longest ones.The naive solution for this problem is to generate all subsequences of the given sequence and find the longest palindromic subsequence. This solution is exponential in terms of time complexity. Let us see how this problem possesses both important properties of a Dynamic Programming (DP) Problem and can efficiently be solved using Dynamic Programming.1) Optimal Substructure: Let X[0..n-1] be the input sequence of length n and L(0, n-1) be the length of the longest palindromic subsequence of X[0..n-1]. If last and first characters of X are same, then L(0, n-1) = L(1, n-2) + 2. Else L(0, n-1) = MAX (L(1, n-1), L(0, n-2)). " }, { "code": null, "e": 25985, "s": 25917, "text": "Following is a general recursive solution with all cases handled. " }, { "code": null, "e": 26404, "s": 25985, "text": "// Every single character is a palindrome of length 1\nL(i, i) = 1 for all indexes i in given sequence\n\n// IF first and last characters are not same\nIf (X[i] != X[j]) L(i, j) = max{L(i + 1, j),L(i, j - 1)} \n\n// If there are only 2 characters and both are same\nElse if (j == i + 1) L(i, j) = 2 \n\n// If there are more than two characters, and first and last \n// characters are same\nElse L(i, j) = L(i + 1, j - 1) + 2 " }, { "code": null, "e": 26575, "s": 26404, "text": "2) Overlapping Subproblems Following is a simple recursive implementation of the LPS problem. The implementation simply follows the recursive structure mentioned above. " }, { "code": null, "e": 26579, "s": 26575, "text": "C++" }, { "code": null, "e": 26581, "s": 26579, "text": "C" }, { "code": null, "e": 26586, "s": 26581, "text": "Java" }, { "code": null, "e": 26594, "s": 26586, "text": "Python3" }, { "code": null, "e": 26597, "s": 26594, "text": "C#" }, { "code": null, "e": 26601, "s": 26597, "text": "PHP" }, { "code": null, "e": 26612, "s": 26601, "text": "Javascript" }, { "code": "// C++ program of above approach#include<bits/stdc++.h>using namespace std; // A utility function to get max of two integersint max (int x, int y) { return (x > y)? x : y; } // Returns the length of the longest palindromic subsequence in seqint lps(char *seq, int i, int j){// Base Case 1: If there is only 1 characterif (i == j) return 1; // Base Case 2: If there are only 2// characters and both are sameif (seq[i] == seq[j] && i + 1 == j) return 2; // If the first and last characters matchif (seq[i] == seq[j]) return lps (seq, i+1, j-1) + 2; // If the first and last characters do not matchreturn max( lps(seq, i, j-1), lps(seq, i+1, j) );} /* Driver program to test above functions */int main(){ char seq[] = \"GEEKSFORGEEKS\"; int n = strlen(seq); cout << \"The length of the LPS is \" << lps(seq, 0, n-1); return 0;} // This code is contributed// by Akanksha Rai", "e": 27508, "s": 26612, "text": null }, { "code": "// C program of above approach#include<stdio.h>#include<string.h> // A utility function to get max of two integersint max (int x, int y) { return (x > y)? x : y; } // Returns the length of the longest palindromic subsequence in seqint lps(char *seq, int i, int j){ // Base Case 1: If there is only 1 character if (i == j) return 1; // Base Case 2: If there are only 2 characters and both are same if (seq[i] == seq[j] && i + 1 == j) return 2; // If the first and last characters match if (seq[i] == seq[j]) return lps (seq, i+1, j-1) + 2; // If the first and last characters do not match return max( lps(seq, i, j-1), lps(seq, i+1, j) );} /* Driver program to test above functions */int main(){ char seq[] = \"GEEKSFORGEEKS\"; int n = strlen(seq); printf (\"The length of the LPS is %d\", lps(seq, 0, n-1)); getchar(); return 0;}", "e": 28381, "s": 27508, "text": null }, { "code": "//Java program of above approach class GFG { // A utility function to get max of two integers static int max(int x, int y) { return (x > y) ? x : y; } // Returns the length of the longest palindromic subsequence in seq static int lps(char seq[], int i, int j) { // Base Case 1: If there is only 1 character if (i == j) { return 1; } // Base Case 2: If there are only 2 characters and both are same if (seq[i] == seq[j] && i + 1 == j) { return 2; } // If the first and last characters match if (seq[i] == seq[j]) { return lps(seq, i + 1, j - 1) + 2; } // If the first and last characters do not match return max(lps(seq, i, j - 1), lps(seq, i + 1, j)); } /* Driver program to test above function */ public static void main(String[] args) { String seq = \"GEEKSFORGEEKS\"; int n = seq.length(); System.out.printf(\"The length of the LPS is %d\", lps(seq.toCharArray(), 0, n - 1)); }}", "e": 29416, "s": 28381, "text": null }, { "code": "# Python 3 program of above approach # A utility function to get max# of two integersdef max(x, y): if(x > y): return x return y # Returns the length of the longest# palindromic subsequence in seqdef lps(seq, i, j): # Base Case 1: If there is # only 1 character if (i == j): return 1 # Base Case 2: If there are only 2 # characters and both are same if (seq[i] == seq[j] and i + 1 == j): return 2 # If the first and last characters match if (seq[i] == seq[j]): return lps(seq, i + 1, j - 1) + 2 # If the first and last characters # do not match return max(lps(seq, i, j - 1), lps(seq, i + 1, j)) # Driver Codeif __name__ == '__main__': seq = \"GEEKSFORGEEKS\" n = len(seq) print(\"The length of the LPS is\", lps(seq, 0, n - 1)) # This code contributed by Rajput-Ji", "e": 30305, "s": 29416, "text": null }, { "code": "// C# program of the above approachusing System; public class GFG{ // A utility function to get max of two integers static int max(int x, int y) { return (x > y) ? x : y; } // Returns the length of the longest palindromic subsequence in seq static int lps(char []seq, int i, int j) { // Base Case 1: If there is only 1 character if (i == j) { return 1; } // Base Case 2: If there are only 2 characters and both are same if (seq[i] == seq[j] && i + 1 == j) { return 2; } // If the first and last characters match if (seq[i] == seq[j]) { return lps(seq, i + 1, j - 1) + 2; } // If the first and last characters do not match return max(lps(seq, i, j - 1), lps(seq, i + 1, j)); } /* Driver program to test above function */ public static void Main() { String seq = \"GEEKSFORGEEKS\"; int n = seq.Length; Console.Write(\"The length of the LPS is \"+lps(seq.ToCharArray(), 0, n - 1)); }} // This code is contributed by Rajput-Ji", "e": 31408, "s": 30305, "text": null }, { "code": "<?php// PHP program of above approach // Returns the length of the longest// palindromic subsequence in seqfunction lps($seq, $i, $j){ // Base Case 1: If there is // only 1 character if ($i == $j) return 1; // Base Case 2: If there are only 2 // characters and both are same if ($seq[$i] == $seq[$j] && $i + 1 == $j) return 2; // If the first and last characters match if ($seq[$i] == $seq[$j]) return lps ($seq, $i + 1, $j - 1) + 2; // If the first and last characters // do not match return max(lps($seq, $i, $j - 1), lps($seq, $i + 1, $j));} // Driver Code$seq = \"GEEKSFORGEEKS\";$n = strlen($seq);echo \"The length of the LPS is \". lps($seq, 0, $n - 1); // This code is contributed by ita_c?>", "e": 32214, "s": 31408, "text": null }, { "code": "<script> // A utility function to get max of two integers function max(x, y) { return (x > y) ? x : y; } // Returns the length of the longest palindromic subsequence in seq function lps(seq, i, j) { // Base Case 1: If there is only 1 character if (i == j) { return 1; } // Base Case 2: If there are only 2 characters and both are same if (seq[i] == seq[j] && i + 1 == j) { return 2; } // If the first and last characters match if (seq[i] == seq[j]) { return lps(seq, i + 1, j - 1) + 2; } // If the first and last characters do not match return max(lps(seq, i, j - 1), lps(seq, i + 1, j)); } /* Driver program to test above function */ let seq = \"GEEKSFORGEEKS\"; let n = seq.length; document.write(\"The length of the LPS is \", lps(seq.split(\"\"), 0, n - 1)); // This code is contributed by avanitrachhadiya2155</script>", "e": 33290, "s": 32214, "text": null }, { "code": null, "e": 33317, "s": 33290, "text": "The length of the LPS is 5" }, { "code": null, "e": 33457, "s": 33317, "text": "Considering the above implementation, the following is a partial recursion tree for a sequence of length 6 with all different characters. " }, { "code": null, "e": 33663, "s": 33457, "text": " L(0, 5)\n / \\ \n / \\ \n L(1,5) L(0,4)\n / \\ / \\\n / \\ / \\\n L(2,5) L(1,4) L(1,4) L(0,3)" }, { "code": null, "e": 34241, "s": 33663, "text": "In the above partial recursion tree, L(1, 4) is being solved twice. If we draw the complete recursion tree, then we can see that there are many subproblems that are solved again and again. Since the same subproblems are called again, this problem has the Overlapping Subproblems property. So LPS problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of the same subproblems can be avoided by constructing a temporary array L[][] in a bottom-up manner.Dynamic Programming Solution " }, { "code": null, "e": 34245, "s": 34241, "text": "C++" }, { "code": null, "e": 34250, "s": 34245, "text": "Java" }, { "code": null, "e": 34258, "s": 34250, "text": "Python3" }, { "code": null, "e": 34261, "s": 34258, "text": "C#" }, { "code": null, "e": 34265, "s": 34261, "text": "PHP" }, { "code": null, "e": 34276, "s": 34265, "text": "Javascript" }, { "code": "// A Dynamic Programming based C++ program for LPS problem// Returns the length of the longest palindromic subsequence in seq#include<stdio.h>#include<string.h> // A utility function to get max of two integersint max (int x, int y) { return (x > y)? x : y; } // Returns the length of the longest palindromic subsequence in seqint lps(char *str){ int n = strlen(str); int i, j, cl; int L[n][n]; // Create a table to store results of subproblems // Strings of length 1 are palindrome of length 1 for (i = 0; i < n; i++) L[i][i] = 1; // Build the table. Note that the lower diagonal values of table are // useless and not filled in the process. The values are filled in a // manner similar to Matrix Chain Multiplication DP solution (See // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). cl is length of // substring for (cl=2; cl<=n; cl++) { for (i=0; i<n-cl+1; i++) { j = i+cl-1; if (str[i] == str[j] && cl == 2) L[i][j] = 2; else if (str[i] == str[j]) L[i][j] = L[i+1][j-1] + 2; else L[i][j] = max(L[i][j-1], L[i+1][j]); } } return L[0][n-1];} /* Driver program to test above functions */int main(){ char seq[] = \"GEEKS FOR GEEKS\"; int n = strlen(seq); printf (\"The length of the LPS is %d\", lps(seq)); getchar(); return 0;}", "e": 35689, "s": 34276, "text": null }, { "code": "// A Dynamic Programming based Java// Program for the Egg Dropping Puzzleclass LPS{ // A utility function to get max of two integers static int max (int x, int y) { return (x > y)? x : y; } // Returns the length of the longest // palindromic subsequence in seq static int lps(String seq) { int n = seq.length(); int i, j, cl; // Create a table to store results of subproblems int L[][] = new int[n][n]; // Strings of length 1 are palindrome of length 1 for (i = 0; i < n; i++) L[i][i] = 1; // Build the table. Note that the lower // diagonal values of table are // useless and not filled in the process. // The values are filled in a manner similar // to Matrix Chain Multiplication DP solution (See // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). // cl is length of substring for (cl=2; cl<=n; cl++) { for (i=0; i<n-cl+1; i++) { j = i+cl-1; if (seq.charAt(i) == seq.charAt(j) && cl == 2) L[i][j] = 2; else if (seq.charAt(i) == seq.charAt(j)) L[i][j] = L[i+1][j-1] + 2; else L[i][j] = max(L[i][j-1], L[i+1][j]); } } return L[0][n-1]; } /* Driver program to test above functions */ public static void main(String args[]) { String seq = \"GEEKSFORGEEKS\"; int n = seq.length(); System.out.println(\"The length of the lps is \"+ lps(seq)); }}/* This code is contributed by Rajat Mishra */", "e": 37333, "s": 35689, "text": null }, { "code": "# A Dynamic Programming based Python# program for LPS problem Returns the length# of the longest palindromic subsequence in seqdef lps(str): n = len(str) # Create a table to store results of subproblems L = [[0 for x in range(n)] for x in range(n)] # Strings of length 1 are palindrome of length 1 for i in range(n): L[i][i] = 1 # Build the table. Note that the lower # diagonal values of table are # useless and not filled in the process. # The values are filled in a # manner similar to Matrix Chain # Multiplication DP solution (See # https://www.geeksforgeeks.org/dynamic-programming-set-8-matrix-chain-multiplication/ # cl is length of substring for cl in range(2, n+1): for i in range(n-cl+1): j = i+cl-1 if str[i] == str[j] and cl == 2: L[i][j] = 2 elif str[i] == str[j]: L[i][j] = L[i+1][j-1] + 2 else: L[i][j] = max(L[i][j-1], L[i+1][j]); return L[0][n-1] # Driver program to test above functionsseq = \"GEEKS FOR GEEKS\"n = len(seq)print(\"The length of the LPS is \" + str(lps(seq))) # This code is contributed by Bhavya Jain", "e": 38519, "s": 37333, "text": null }, { "code": "// A Dynamic Programming based C# Program// for the Egg Dropping Puzzleusing System; class GFG { // A utility function to get max of // two integers static int max (int x, int y) { return (x > y)? x : y; } // Returns the length of the longest // palindromic subsequence in seq static int lps(string seq) { int n = seq.Length; int i, j, cl; // Create a table to store results // of subproblems int [,]L = new int[n,n]; // Strings of length 1 are // palindrome of length 1 for (i = 0; i < n; i++) L[i,i] = 1; // Build the table. Note that the // lower diagonal values of table // are useless and not filled in // the process. The values are // filled in a manner similar to // Matrix Chain Multiplication DP // solution (See // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/ // cl is length of substring for (cl = 2; cl <= n; cl++) { for (i = 0; i < n-cl+1; i++) { j = i + cl - 1; if (seq[i] == seq[j] && cl == 2) L[i,j] = 2; else if (seq[i] == seq[j]) L[i,j] = L[i+1,j-1] + 2; else L[i,j] = max(L[i,j-1], L[i+1,j]); } } return L[0,n-1]; } /* Driver program to test above functions */ public static void Main() { string seq = \"GEEKS FOR GEEKS\"; int n = seq.Length; Console.Write(\"The length of the \" + \"lps is \"+ lps(seq)); }} // This code is contributed by nitin mittal.", "e": 40289, "s": 38519, "text": null }, { "code": "<?php// A Dynamic Programming based// PHP program for LPS problem// Returns the length of the// longest palindromic// subsequence in seq // A utility function to get// max of two integers// function max( $x, $y)// { return ($x > $y)? $x : $y; } // Returns the length of the// longest palindromic// subsequence in seqfunction lps($str){$n = strlen($str);$i; $j; $cl; // Create a table to store// results of subproblems$L[][] = array(array()); // Strings of length 1 are// palindrome of length 1for ($i = 0; $i < $n; $i++) $L[$i][$i] = 1; // Build the table. Note that // the lower diagonal values // of table are useless and // not filled in the process. // The values are filled in a // manner similar to Matrix // Chain Multiplication DP // solution (See // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). // cl is length of substring for ($cl = 2; $cl <= $n; $cl++) { for ($i = 0; $i < $n - $cl + 1; $i++) { $j = $i + $cl - 1; if ($str[$i] == $str[$j] && $cl == 2) $L[$i][$j] = 2; else if ($str[$i] == $str[$j]) $L[$i][$j] = $L[$i + 1][$j - 1] + 2; else $L[$i][$j] = max($L[$i][$j - 1], $L[$i + 1][$j]); } } return $L[0][$n - 1];} // Driver Code$seq = 'GEEKS FOR GEEKS';$n = strlen($seq);echo \"The length of the \" . \"LPS is \", lps($seq); // This code is contributed// by shiv_bhakt.?>", "e": 41800, "s": 40289, "text": null }, { "code": "<script>// A Dynamic Programming based Javascript// Program for the Egg Dropping Puzzle // A utility function to get max of two integersfunction max(x,y){ return (x > y)? x : y;} // Returns the length of the longest // palindromic subsequence in seqfunction lps(seq){ let n = seq.length; let i, j, cl; // Create a table to store results of subproblems let L = new Array(n); for(let x=0;x<n;x++) { L[x] = new Array(n); for(let y = 0; y < n; y++) L[x][y] = 0; } // Strings of length 1 are palindrome of length 1 for (i = 0; i < n; i++) L[i][i] = 1; // Build the table. Note that the lower // diagonal values of table are // useless and not filled in the process. // The values are filled in a manner similar // to Matrix Chain Multiplication DP solution (See // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). // cl is length of substring for (cl = 2; cl <= n; cl++) { for (i = 0; i < n -cl + 1; i++) { j = i + cl - 1; if (seq[i] == seq[j] && cl == 2) L[i][j] = 2; else if (seq[i] == seq[j]) L[i][j] = L[i + 1][j - 1] + 2; else L[i][j] = max(L[i][j - 1], L[i + 1][j]); } } return L[0][n - 1];} /* Driver program to test above functions */let seq = \"GEEKS FOR GEEKS\";let n = seq.length;document.write(\"The length of the lps is \"+ lps(seq)); // This code is contributed by rag2127</script>", "e": 43432, "s": 41800, "text": null }, { "code": null, "e": 43459, "s": 43432, "text": "The length of the LPS is 7" }, { "code": null, "e": 43609, "s": 43459, "text": "The Time Complexity of the above implementation is O(n^2) which is much better than the worst-case time complexity of Naive Recursive implementation." }, { "code": null, "e": 43787, "s": 43609, "text": "The idea used here is to reverse the given input string and check the length of the longest common subsequence. That would be the answer for the longest palindromic subsequence." }, { "code": null, "e": 43791, "s": 43787, "text": "C++" }, { "code": null, "e": 43796, "s": 43791, "text": "Java" }, { "code": null, "e": 43804, "s": 43796, "text": "Python3" }, { "code": null, "e": 43815, "s": 43804, "text": "Javascript" }, { "code": "// A Dynamic Programming based C++ program for LPS problem// Returns the length of the longest palindromic subsequence// in seq#include <bits/stdc++.h>using namespace std; int dp[1001][1001]; // Returns the length of the longest palindromic subsequence// in seqint lps(string& s1, string& s2, int n1, int n2){ if (n1 == 0 || n2 == 0) { return 0; } if (dp[n1][n2] != -1) { return dp[n1][n2]; } if (s1[n1 - 1] == s2[n2 - 1]) { return dp[n1][n2] = 1 + lps(s1, s2, n1 - 1, n2 - 1); } else { return dp[n1][n2] = max(lps(s1, s2, n1 - 1, n2), lps(s1, s2, n1, n2 - 1)); }} /* Driver program to test above functions */int main(){ string seq = \"GEEKS FOR GEEKS\"; int n = seq.size(); dp[n][n]; memset(dp, -1, sizeof(dp)); string s2 = seq; reverse(s2.begin(), s2.end()); cout << \"The length of the LPS is \" << lps(s2, seq, n, n) << endl; return 0;} // This code is contributed by Arun Bang", "e": 44808, "s": 43815, "text": null }, { "code": "// Java program of above approachclass GFG { // A utility function to get max of two integers static int max(int x, int y) { return (x > y) ? x : y; } // Returns the length of the longest palindromic subsequence in seq static int lps(char seq[], int i, int j) { // Base Case 1: If there is only 1 character if (i == j) { return 1; } // Base Case 2: If there are only 2 characters and both are same if (seq[i] == seq[j] && i + 1 == j) { return 2; } // If the first and last characters match if (seq[i] == seq[j]) { return lps(seq, i + 1, j - 1) + 2; } // If the first and last characters do not match return max(lps(seq, i, j - 1), lps(seq, i + 1, j)); } /* Driver program to test above function */ public static void main(String[] args) { String seq = \"GEEKS FOR GEEKS\"; int n = seq.length(); System.out.printf(\"The length of the LPS is %d\", lps(seq.toCharArray(), 0, n - 1)); }} // This code is contributed by gauravrajput1", "e": 45818, "s": 44808, "text": null }, { "code": "# A Dynamic Programming based Python program for LPS problem# Returns the length of the longest palindromic subsequence# in seq dp = [[-1 for i in range(1001)]for j in range(1001)] # Returns the length of the longest palindromic subsequence# in seqdef lps(s1, s2, n1, n2): if (n1 == 0 or n2 == 0): return 0 if (dp[n1][n2] != -1): return dp[n1][n2] if (s1[n1 - 1] == s2[n2 - 1]): dp[n1][n2] = 1 + lps(s1, s2, n1 - 1, n2 - 1) return dp[n1][n2] else: dp[n1][n2] = max(lps(s1, s2, n1 - 1, n2),lps(s1, s2, n1, n2 - 1)) return dp[n1][n2] # Driver program to test above functions seq = \"GEEKS FOR GEEKS\"n = len(seq) s2 = seqs2 = s2[::-1]print(f\"The length of the LPS is {lps(s2, seq, n, n)}\") # This code is contributed by shinjanpatra", "e": 46605, "s": 45818, "text": null }, { "code": "<script> // A Dynamic Programming based JavaScript program for LPS problem// Returns the length of the longest palindromic subsequence// in seqlet dp; // Returns the length of the longest palindromic subsequence// in seqfunction lps(s1, s2, n1, n2){ if (n1 == 0 || n2 == 0) { return 0; } if (dp[n1][n2] != -1) { return dp[n1][n2]; } if (s1[n1 - 1] == s2[n2 - 1]) { return dp[n1][n2] = 1 + lps(s1, s2, n1 - 1, n2 - 1); } else { return dp[n1][n2] = Math.max(lps(s1, s2, n1 - 1, n2), lps(s1, s2, n1, n2 - 1)); }} /* Driver program to test above functions */ let seq = \"GEEKS FOR GEEKS\";let n = seq.length;dp = new Array(1001);for(let i=0;i<1001;i++){ dp[i] = new Array(1001).fill(-1);}let s2 = seq;s2 = s2.split('').reverse().join('');document.write(\"The length of the LPS is \" + lps(s2, seq, n, n),\"</br>\"); // This code is contributed by shinjanpatra </script>", "e": 47552, "s": 46605, "text": null }, { "code": null, "e": 47579, "s": 47552, "text": "The length of the LPS is 7" }, { "code": null, "e": 47604, "s": 47579, "text": "Time Complexity: O(n*n) " }, { "code": null, "e": 48465, "s": 47604, "text": "YouTubeGeeksforGeeks502K subscribersLongest Palindromic Subsequence | Dynamic Programming | Set 12 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=TLaGwTnd3HY\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 48745, "s": 48465, "text": "Print Longest Palindromic Subsequence Longest palindrome subsequence with O(n) spacePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.References: http://users.eecs.northwestern.edu/~dda902/336/hw6-sol.pdf " }, { "code": null, "e": 48758, "s": 48745, "text": "nitin mittal" }, { "code": null, "e": 48771, "s": 48758, "text": "Vishal_Khoda" }, { "code": null, "e": 48781, "s": 48771, "text": "Rajput-Ji" }, { "code": null, "e": 48794, "s": 48781, "text": "Akanksha_Rai" }, { "code": null, "e": 48800, "s": 48794, "text": "ukasp" }, { "code": null, "e": 48810, "s": 48800, "text": "paperdosa" }, { "code": null, "e": 48831, "s": 48810, "text": "avanitrachhadiya2155" }, { "code": null, "e": 48839, "s": 48831, "text": "rag2127" }, { "code": null, "e": 48853, "s": 48839, "text": "sumitgumber28" }, { "code": null, "e": 48864, "s": 48853, "text": "arunbang17" }, { "code": null, "e": 48880, "s": 48864, "text": "amartyaghoshgfg" }, { "code": null, "e": 48893, "s": 48880, "text": "simmytarika5" }, { "code": null, "e": 48906, "s": 48893, "text": "shinjanpatra" }, { "code": null, "e": 48920, "s": 48906, "text": "GauravRajput1" }, { "code": null, "e": 48927, "s": 48920, "text": "Amazon" }, { "code": null, "e": 48936, "s": 48927, "text": "Linkedin" }, { "code": null, "e": 48947, "s": 48936, "text": "palindrome" }, { "code": null, "e": 48954, "s": 48947, "text": "PayPal" }, { "code": null, "e": 48961, "s": 48954, "text": "Rivigo" }, { "code": null, "e": 48973, "s": 48961, "text": "subsequence" }, { "code": null, "e": 48993, "s": 48973, "text": "Dynamic Programming" }, { "code": null, "e": 49001, "s": 48993, "text": "Strings" }, { "code": null, "e": 49008, "s": 49001, "text": "Amazon" }, { "code": null, "e": 49017, "s": 49008, "text": "Linkedin" }, { "code": null, "e": 49024, "s": 49017, "text": "PayPal" }, { "code": null, "e": 49031, "s": 49024, "text": "Rivigo" }, { "code": null, "e": 49039, "s": 49031, "text": "Strings" }, { "code": null, "e": 49059, "s": 49039, "text": "Dynamic Programming" }, { "code": null, "e": 49070, "s": 49059, "text": "palindrome" }, { "code": null, "e": 49168, "s": 49070, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49199, "s": 49168, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 49232, "s": 49199, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 49267, "s": 49232, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 49294, "s": 49267, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 49362, "s": 49294, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 49408, "s": 49362, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 49433, "s": 49408, "text": "Reverse a string in Java" }, { "code": null, "e": 49493, "s": 49433, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 49508, "s": 49493, "text": "C++ Data Types" } ]
C# Program to Convert Binary to Decimal
Firstly, set the binary value − int num = 101; Now assign the binary to a new variable − binVal = num; Till the value is greater than 0, loop through the binary number and base value like this, while (num > 0) { rem = num % 10; decVal = decVal + rem * baseVal; num = num / 10; baseVal = baseVal * 2; } The following is the code to convert binary to decimal. Live Demo using System; using System.Collections.Generic; using System.Text; namespace Demo { class MyApplication { static void Main(string[] args) { int num, binVal, decVal = 0, baseVal = 1, rem; num = 101; binVal = num; while (num > 0) { rem = num % 10; decVal = decVal + rem * baseVal; num = num / 10 ; baseVal = baseVal * 2; } Console.Write("Binary Number: "+binVal); Console.Write("\nDecimal: "+decVal); Console.ReadLine(); } } } Binary Number: 101 Decimal: 5
[ { "code": null, "e": 1094, "s": 1062, "text": "Firstly, set the binary value −" }, { "code": null, "e": 1109, "s": 1094, "text": "int num = 101;" }, { "code": null, "e": 1151, "s": 1109, "text": "Now assign the binary to a new variable −" }, { "code": null, "e": 1165, "s": 1151, "text": "binVal = num;" }, { "code": null, "e": 1256, "s": 1165, "text": "Till the value is greater than 0, loop through the binary number and base value like this," }, { "code": null, "e": 1376, "s": 1256, "text": "while (num > 0) {\n rem = num % 10;\n decVal = decVal + rem * baseVal;\n num = num / 10;\n baseVal = baseVal * 2;\n}" }, { "code": null, "e": 1432, "s": 1376, "text": "The following is the code to convert binary to decimal." }, { "code": null, "e": 1442, "s": 1432, "text": "Live Demo" }, { "code": null, "e": 2005, "s": 1442, "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nnamespace Demo {\n class MyApplication {\n static void Main(string[] args) {\n int num, binVal, decVal = 0, baseVal = 1, rem;\n num = 101;\n binVal = num;\n while (num > 0) {\n rem = num % 10;\n decVal = decVal + rem * baseVal;\n num = num / 10 ;\n baseVal = baseVal * 2;\n }\n Console.Write(\"Binary Number: \"+binVal);\n Console.Write(\"\\nDecimal: \"+decVal);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2035, "s": 2005, "text": "Binary Number: 101\nDecimal: 5" } ]
Program to check if the given list has Pythagorean Triplets or not in Python
Suppose we have a list of numbers called nums, we have to check whether there exist three numbers a, b, and c such that a^2 + b^2 = c^2. So, if the input is like [10, 2, 8, 5, 6], then the output will be True, as 8^2 + 6^2 = 64+36 = 100 = 10^2. To solve this, we will follow these steps − tmp := list of square of all numbers in nums in descending order for each index i and corresponding number n in tmp, dobase := nleft := i+1, right := size of tmp -1while left <= right, dot := join two lists tmp[left] and tmp[right]if t is same as base, thenreturn Trueotherwise when t > base, thenleft := left + 1otherwise,right := right - 1 base := n left := i+1, right := size of tmp -1 while left <= right, dot := join two lists tmp[left] and tmp[right]if t is same as base, thenreturn Trueotherwise when t > base, thenleft := left + 1otherwise,right := right - 1 t := join two lists tmp[left] and tmp[right] if t is same as base, thenreturn True return True otherwise when t > base, thenleft := left + 1 left := left + 1 otherwise,right := right - 1 right := right - 1 return False Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, nums): tmp = sorted([n*n for n in nums], reverse = True) for i, n in enumerate(tmp): base = n left = i+1; right = len(tmp)-1 while left <= right: t = tmp[left]+tmp[right] if t == base: return True elif t > base: left += 1 else: right -= 1 return False ob = Solution() print(ob.solve([10, 2, 8, 5, 6])) [10, 2, 8, 5, 6] True
[ { "code": null, "e": 1199, "s": 1062, "text": "Suppose we have a list of numbers called nums, we have to check whether there exist three\nnumbers a, b, and c such that a^2 + b^2 = c^2." }, { "code": null, "e": 1307, "s": 1199, "text": "So, if the input is like [10, 2, 8, 5, 6], then the output will be True, as 8^2 + 6^2 = 64+36 = 100 =\n10^2." }, { "code": null, "e": 1351, "s": 1307, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1416, "s": 1351, "text": "tmp := list of square of all numbers in nums in descending order" }, { "code": null, "e": 1693, "s": 1416, "text": "for each index i and corresponding number n in tmp, dobase := nleft := i+1, right := size of tmp -1while left <= right, dot := join two lists tmp[left] and tmp[right]if t is same as base, thenreturn Trueotherwise when t > base, thenleft := left + 1otherwise,right := right - 1" }, { "code": null, "e": 1703, "s": 1693, "text": "base := n" }, { "code": null, "e": 1740, "s": 1703, "text": "left := i+1, right := size of tmp -1" }, { "code": null, "e": 1918, "s": 1740, "text": "while left <= right, dot := join two lists tmp[left] and tmp[right]if t is same as base, thenreturn Trueotherwise when t > base, thenleft := left + 1otherwise,right := right - 1" }, { "code": null, "e": 1963, "s": 1918, "text": "t := join two lists tmp[left] and tmp[right]" }, { "code": null, "e": 2001, "s": 1963, "text": "if t is same as base, thenreturn True" }, { "code": null, "e": 2013, "s": 2001, "text": "return True" }, { "code": null, "e": 2059, "s": 2013, "text": "otherwise when t > base, thenleft := left + 1" }, { "code": null, "e": 2076, "s": 2059, "text": "left := left + 1" }, { "code": null, "e": 2105, "s": 2076, "text": "otherwise,right := right - 1" }, { "code": null, "e": 2124, "s": 2105, "text": "right := right - 1" }, { "code": null, "e": 2137, "s": 2124, "text": "return False" }, { "code": null, "e": 2207, "s": 2137, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2218, "s": 2207, "text": " Live Demo" }, { "code": null, "e": 2693, "s": 2218, "text": "class Solution:\n def solve(self, nums):\n tmp = sorted([n*n for n in nums], reverse = True)\n for i, n in enumerate(tmp):\n base = n\n left = i+1; right = len(tmp)-1\n while left <= right:\n t = tmp[left]+tmp[right]\n if t == base:\n return True\n elif t > base:\n left += 1\n else:\n right -= 1\n return False\nob = Solution()\nprint(ob.solve([10, 2, 8, 5, 6]))" }, { "code": null, "e": 2710, "s": 2693, "text": "[10, 2, 8, 5, 6]" }, { "code": null, "e": 2715, "s": 2710, "text": "True" } ]
Data Visualization with Julia and VSCode | by Alan Jones | Towards Data Science
A while ago I wrote about data visualization using Julia and an online environment called JuliaBox. At the time JuliaBox was a free service; unfortunately, it has since been withdrawn. This is a shame as it was a great service. So here is a new version of that article where you use Microsoft’s VSCode IDE (which is not only free but is also unlikely to go away any time soon). You’ll need to install VSCode, the Julia language and then the VSCode extension for Julia. If that sounds complicated, don’t worry, it isn’t. Julia is a relatively new language for data analysis. It has a high-level syntax and designed to be easy to use and understand. Some have called it the new Python. Unlike Python, though, it is a compiled language, which means that while it is as easy to write as Python, it runs much faster because it is converted to low-level code that is more easily understood by a computer. This is great if you have to deal with large data sets that require a lot of processing. Julia is also much less fussy about how a program is laid out than Python. Julia has all the features that you would expect of a modern programming language but, here, we are going to take a look at Julia’s data visualization capabilities. These are both impressive and easy to use. Once you’ve installed Julia and VSCode, you can run Julia code and save your visualizations as standard png files. To install Julia you need to go to https://julialang.org/ and download the appropriate version for your operating system. Installation is straightforward, just follow the instructions. For VSCode the advice is the same except you go to https://code.visualstudio.com and download it from there. When you are ready start VSCode and load the Julia extension. You do this by clicking on the the extensions symbol in the leftmost panel (the one that is four rectangles with one slightly offset from the others) and type julia in the search bar. Now click on install. That should be all you need to do if you have installed Julia normally. If you done something different, you need to click on the settings icon (the cogwheel) and manually type in the location of julia.exe. You can also find the settings in the File|Preferences|Extensions menu. Before going any further, I must tell you that the instructions and the code in this article were developed on a Windows 10 laptop. I know of no reason why it should be any different on Linux or on a Mac but I have not tested in those environments. Before we write any programs, we need to load the libraries that we want to use. You only need to do this once, once you’ve loaded the libraries they are there forever. Do this by opening a Julia terminal (also known as a REPL- for Read, Evaluate, Print Loop). You can start the REPL in a number of ways. Find the Command Palette from the View menu and click that or press Ctrl+Shift+P. This will give you a list of commands, one of which is ‘Julia: Start REPL’ (if you can’t see it scroll down or start typing ‘julia’ in the search bar and the commands will show up), so click that and you’ll get a terminal window. At the Julia prompt in the REPL window, type the following julia> using Pkg this tells Julia that you are going to use the package manager. Then type the following and hit <return>: julia> Pkg.add("Plots") Now you need to add a couple more packages that we are going to use in the tutorial. Type in these lines: julia> Pkg.add("CSV") and julia> Pkg.add("DataFrames") You’ll be using each of these packages later. Now you are ready to start! So, open a new file, call it ‘myPlots.jl’ or something similar but make sure it has the extension ‘.jl’ so VSCode knows what sort of file it is. You should now have two panels open, the file and the REPL. You still want to keep the REPL open as this is where any output from your program will be printed. Your screen should look something like this: Julia, as with most other languages, relies on libraries of code for particular specialist purposes and we’ve just downloaded the ones we need. The one that we are initially interested in is called Plots. This provides us with the capability to create visualizations of data. So the first piece of code that we need to execute is this: using Plots This tells Julia to load the library that we will use to create our visualizations. Here is a simple program to make sure everything is working ok. using Plotsx = 1:10; y = rand(10); # These are the plotting data plot(x,y, label="my label") Running it will produce something like the following graph in a new tab in VSCode (to run the code, find the command in the Command Palette (Ctrl+Alt+P) there will be a number of options but you want to execute the whole file): That may have taken a little while because when you execute code for the first time, the Julia code is compiled on the fly, which slows things down the first time you run something but makes it really quick the next time. So subsequent code runs are quicker. Let me explain what’s going on with the code. x = 1:10; y = rand(10); # These are the plotting data This bit of code creates two bits of data, one is called x and the other y. x is given the value of a range of numbers from 1 to 10, while y is given a range of 10 pseudo-random numbers (each will have a value between 0 and 1). So, we have the basis of a graph here: an x-axis that ranges from 1 to 10 and y values for each of the points on the x axis. The next bit is easy. plot(x,y, label=”my label”) This code calls a function to plot the graph and all we do is give it the x and y values — and, as an extra, we’ve given it a label, too. That was easy but, course, we really want to visualize some real data. I have a couple of tables that I have used for other articles. It’s a set of data about the weather in London, UK, over the last few decades. I derived it from public tables provided by the UK Met Office. The data records the maximum temperature, minimum temperature, rainfall and hours of sunshine recorded in each month. I have two files, one is the complete data set and the other is for 2018, only. They are in CSV format, such as you might import into a spreadsheet. To deal with these files we need another library that allows us to read CSV files. We can see the library referenced in the next chunk of code, i.e. “using CSV” and the following line actually reads in the data to a variable d. using CSVd = CSV.read("D:notebooks/juliaplot/london2018.csv")print(d) The result of running the code is that we now have a table of data that looks like this: Of course, you will need to change the path for the file name to whereever you have downloaded it to. The data that we have downloaded is formed of a table with 6 columns: Year, Month, Tmax (maximum temperature), Tmin (minimum temperature), Rain (rainfall in millimeters) and Sun (the number of hours of sunshine). This is a subset of the data (for 2018, only) so the Year column has the same value in all the rows. So, what we have is the data for each month of 2018. If we wanted to plot the maximum temperature in each month in a bar chart we would do this: using Plotsusing CSVd = CSV.read("D:notebooks/juliaplot/london2018.csv")bar(d.Month,d.Tmax) bar is a function that draws a bar chart (what else?) and we provide the columns for the x and y axes. We do this by using the name of the data table, followed by the name of the column. The two names are separated with a dot. Here we have the column Month as the x axis and Tmax as the y axis- so we are plotting the maximum recorded temperature for each of the 12 months in the table. Put this in a new code cell and run it and you will be pleasantly surprised (I hope) to see this chart: If you wanted to produce a line chart, you do much the same thing but use the function plot plot(d.Month, d.Tmax) And, if you wanted to plot both maximum and minimum temperatures on the same graph, you could do this: plot(d.Month, [d.Tmax, d.Tmin], label=["Tmax","Tmin"]) Note that the two values, d.Tmax and d.Tmin, are grouped together in square brackets and separated by a comma. This is the notation for a vector, or singled dimensional array. Additionally, we have added labels for the lines and these are grouped in the same way. We get a graph like this: Or how about a scatter chart? A scatter chart is often used to see if a pattern can be detected in the data. Here we plot the maximum temperature against the hours of sunshine. As you might expect there is a pattern: a visible correlation — the more hours of sunshine there are, the higher the temperature. scatter(d.Tmax, d.Sun) The data we have doesn’t really lend itself to being depicted as a pie chart, so we are going to generate some random data, again — 5 random numbers. x = 1:5; y = rand(5); # These are the plotting datapie(x,y) Now we are going to load in a bit more data: d2 = CSV.read("londonweather.csv") This is similar to the data table that we have been using but rather bigger as it covers several decades of data rather than just one year. This gives us plenty of rainfall data so that we can see the distribution of the levels of rain that occur in London over a longish period. To create a histogram we run this code: histogram(d2.Rain, label="Rainfall") So the whole program looks like this: using Plotsusing CSVd2 = CSV.read("d:notebooks/juliaplot/londonweather.csv")histogram(d2.Rain, label="Rainfall") Here’s the result. It’s all very well seeing these charts in the VSCode environment but to be useful, we need to be able to save them so as to use them in our documents. You can save the chart like this: histogram(d2.Rain, label="Rainfall") savefig("d:notebooks/juliaplot/myhistogram.png") When this code is run the chart will not be displayed but it will be saved with the file name given. I hope that was useful — we’ve looked at the basic charts available in Julia Plots. There is a great deal more to Julia than we have seen in this short article and a lot more that you can do with Plots too, but I hope you have found that this introduction has whetted your appetite to find out more. Right click on the links below to download the files and then copy them in the directory that Julia will use. The data files are here: london2018.csv and londonweather.csv As always, thanks for reading. If you would like to know when I publish new articles, please consider signing up for an email alert here. If you are not a Medium subscriber, how about signing up so you can read as many articles as you like for $5 a month. Sign up here and I’ll earn a small commision.
[ { "code": null, "e": 399, "s": 171, "text": "A while ago I wrote about data visualization using Julia and an online environment called JuliaBox. At the time JuliaBox was a free service; unfortunately, it has since been withdrawn. This is a shame as it was a great service." }, { "code": null, "e": 691, "s": 399, "text": "So here is a new version of that article where you use Microsoft’s VSCode IDE (which is not only free but is also unlikely to go away any time soon). You’ll need to install VSCode, the Julia language and then the VSCode extension for Julia. If that sounds complicated, don’t worry, it isn’t." }, { "code": null, "e": 855, "s": 691, "text": "Julia is a relatively new language for data analysis. It has a high-level syntax and designed to be easy to use and understand. Some have called it the new Python." }, { "code": null, "e": 1159, "s": 855, "text": "Unlike Python, though, it is a compiled language, which means that while it is as easy to write as Python, it runs much faster because it is converted to low-level code that is more easily understood by a computer. This is great if you have to deal with large data sets that require a lot of processing." }, { "code": null, "e": 1234, "s": 1159, "text": "Julia is also much less fussy about how a program is laid out than Python." }, { "code": null, "e": 1442, "s": 1234, "text": "Julia has all the features that you would expect of a modern programming language but, here, we are going to take a look at Julia’s data visualization capabilities. These are both impressive and easy to use." }, { "code": null, "e": 1557, "s": 1442, "text": "Once you’ve installed Julia and VSCode, you can run Julia code and save your visualizations as standard png files." }, { "code": null, "e": 1742, "s": 1557, "text": "To install Julia you need to go to https://julialang.org/ and download the appropriate version for your operating system. Installation is straightforward, just follow the instructions." }, { "code": null, "e": 1851, "s": 1742, "text": "For VSCode the advice is the same except you go to https://code.visualstudio.com and download it from there." }, { "code": null, "e": 1913, "s": 1851, "text": "When you are ready start VSCode and load the Julia extension." }, { "code": null, "e": 2097, "s": 1913, "text": "You do this by clicking on the the extensions symbol in the leftmost panel (the one that is four rectangles with one slightly offset from the others) and type julia in the search bar." }, { "code": null, "e": 2119, "s": 2097, "text": "Now click on install." }, { "code": null, "e": 2398, "s": 2119, "text": "That should be all you need to do if you have installed Julia normally. If you done something different, you need to click on the settings icon (the cogwheel) and manually type in the location of julia.exe. You can also find the settings in the File|Preferences|Extensions menu." }, { "code": null, "e": 2647, "s": 2398, "text": "Before going any further, I must tell you that the instructions and the code in this article were developed on a Windows 10 laptop. I know of no reason why it should be any different on Linux or on a Mac but I have not tested in those environments." }, { "code": null, "e": 2816, "s": 2647, "text": "Before we write any programs, we need to load the libraries that we want to use. You only need to do this once, once you’ve loaded the libraries they are there forever." }, { "code": null, "e": 2908, "s": 2816, "text": "Do this by opening a Julia terminal (also known as a REPL- for Read, Evaluate, Print Loop)." }, { "code": null, "e": 3264, "s": 2908, "text": "You can start the REPL in a number of ways. Find the Command Palette from the View menu and click that or press Ctrl+Shift+P. This will give you a list of commands, one of which is ‘Julia: Start REPL’ (if you can’t see it scroll down or start typing ‘julia’ in the search bar and the commands will show up), so click that and you’ll get a terminal window." }, { "code": null, "e": 3323, "s": 3264, "text": "At the Julia prompt in the REPL window, type the following" }, { "code": null, "e": 3340, "s": 3323, "text": "julia> using Pkg" }, { "code": null, "e": 3446, "s": 3340, "text": "this tells Julia that you are going to use the package manager. Then type the following and hit <return>:" }, { "code": null, "e": 3470, "s": 3446, "text": "julia> Pkg.add(\"Plots\")" }, { "code": null, "e": 3576, "s": 3470, "text": "Now you need to add a couple more packages that we are going to use in the tutorial. Type in these lines:" }, { "code": null, "e": 3598, "s": 3576, "text": "julia> Pkg.add(\"CSV\")" }, { "code": null, "e": 3602, "s": 3598, "text": "and" }, { "code": null, "e": 3631, "s": 3602, "text": "julia> Pkg.add(\"DataFrames\")" }, { "code": null, "e": 3677, "s": 3631, "text": "You’ll be using each of these packages later." }, { "code": null, "e": 4010, "s": 3677, "text": "Now you are ready to start! So, open a new file, call it ‘myPlots.jl’ or something similar but make sure it has the extension ‘.jl’ so VSCode knows what sort of file it is. You should now have two panels open, the file and the REPL. You still want to keep the REPL open as this is where any output from your program will be printed." }, { "code": null, "e": 4055, "s": 4010, "text": "Your screen should look something like this:" }, { "code": null, "e": 4331, "s": 4055, "text": "Julia, as with most other languages, relies on libraries of code for particular specialist purposes and we’ve just downloaded the ones we need. The one that we are initially interested in is called Plots. This provides us with the capability to create visualizations of data." }, { "code": null, "e": 4391, "s": 4331, "text": "So the first piece of code that we need to execute is this:" }, { "code": null, "e": 4403, "s": 4391, "text": "using Plots" }, { "code": null, "e": 4487, "s": 4403, "text": "This tells Julia to load the library that we will use to create our visualizations." }, { "code": null, "e": 4551, "s": 4487, "text": "Here is a simple program to make sure everything is working ok." }, { "code": null, "e": 4644, "s": 4551, "text": "using Plotsx = 1:10; y = rand(10); # These are the plotting data plot(x,y, label=\"my label\")" }, { "code": null, "e": 4872, "s": 4644, "text": "Running it will produce something like the following graph in a new tab in VSCode (to run the code, find the command in the Command Palette (Ctrl+Alt+P) there will be a number of options but you want to execute the whole file):" }, { "code": null, "e": 5131, "s": 4872, "text": "That may have taken a little while because when you execute code for the first time, the Julia code is compiled on the fly, which slows things down the first time you run something but makes it really quick the next time. So subsequent code runs are quicker." }, { "code": null, "e": 5177, "s": 5131, "text": "Let me explain what’s going on with the code." }, { "code": null, "e": 5231, "s": 5177, "text": "x = 1:10; y = rand(10); # These are the plotting data" }, { "code": null, "e": 5307, "s": 5231, "text": "This bit of code creates two bits of data, one is called x and the other y." }, { "code": null, "e": 5584, "s": 5307, "text": "x is given the value of a range of numbers from 1 to 10, while y is given a range of 10 pseudo-random numbers (each will have a value between 0 and 1). So, we have the basis of a graph here: an x-axis that ranges from 1 to 10 and y values for each of the points on the x axis." }, { "code": null, "e": 5606, "s": 5584, "text": "The next bit is easy." }, { "code": null, "e": 5634, "s": 5606, "text": "plot(x,y, label=”my label”)" }, { "code": null, "e": 5772, "s": 5634, "text": "This code calls a function to plot the graph and all we do is give it the x and y values — and, as an extra, we’ve given it a label, too." }, { "code": null, "e": 5843, "s": 5772, "text": "That was easy but, course, we really want to visualize some real data." }, { "code": null, "e": 6048, "s": 5843, "text": "I have a couple of tables that I have used for other articles. It’s a set of data about the weather in London, UK, over the last few decades. I derived it from public tables provided by the UK Met Office." }, { "code": null, "e": 6315, "s": 6048, "text": "The data records the maximum temperature, minimum temperature, rainfall and hours of sunshine recorded in each month. I have two files, one is the complete data set and the other is for 2018, only. They are in CSV format, such as you might import into a spreadsheet." }, { "code": null, "e": 6398, "s": 6315, "text": "To deal with these files we need another library that allows us to read CSV files." }, { "code": null, "e": 6543, "s": 6398, "text": "We can see the library referenced in the next chunk of code, i.e. “using CSV” and the following line actually reads in the data to a variable d." }, { "code": null, "e": 6613, "s": 6543, "text": "using CSVd = CSV.read(\"D:notebooks/juliaplot/london2018.csv\")print(d)" }, { "code": null, "e": 6702, "s": 6613, "text": "The result of running the code is that we now have a table of data that looks like this:" }, { "code": null, "e": 6804, "s": 6702, "text": "Of course, you will need to change the path for the file name to whereever you have downloaded it to." }, { "code": null, "e": 7017, "s": 6804, "text": "The data that we have downloaded is formed of a table with 6 columns: Year, Month, Tmax (maximum temperature), Tmin (minimum temperature), Rain (rainfall in millimeters) and Sun (the number of hours of sunshine)." }, { "code": null, "e": 7118, "s": 7017, "text": "This is a subset of the data (for 2018, only) so the Year column has the same value in all the rows." }, { "code": null, "e": 7263, "s": 7118, "text": "So, what we have is the data for each month of 2018. If we wanted to plot the maximum temperature in each month in a bar chart we would do this:" }, { "code": null, "e": 7355, "s": 7263, "text": "using Plotsusing CSVd = CSV.read(\"D:notebooks/juliaplot/london2018.csv\")bar(d.Month,d.Tmax)" }, { "code": null, "e": 7582, "s": 7355, "text": "bar is a function that draws a bar chart (what else?) and we provide the columns for the x and y axes. We do this by using the name of the data table, followed by the name of the column. The two names are separated with a dot." }, { "code": null, "e": 7742, "s": 7582, "text": "Here we have the column Month as the x axis and Tmax as the y axis- so we are plotting the maximum recorded temperature for each of the 12 months in the table." }, { "code": null, "e": 7846, "s": 7742, "text": "Put this in a new code cell and run it and you will be pleasantly surprised (I hope) to see this chart:" }, { "code": null, "e": 7938, "s": 7846, "text": "If you wanted to produce a line chart, you do much the same thing but use the function plot" }, { "code": null, "e": 7960, "s": 7938, "text": "plot(d.Month, d.Tmax)" }, { "code": null, "e": 8063, "s": 7960, "text": "And, if you wanted to plot both maximum and minimum temperatures on the same graph, you could do this:" }, { "code": null, "e": 8118, "s": 8063, "text": "plot(d.Month, [d.Tmax, d.Tmin], label=[\"Tmax\",\"Tmin\"])" }, { "code": null, "e": 8408, "s": 8118, "text": "Note that the two values, d.Tmax and d.Tmin, are grouped together in square brackets and separated by a comma. This is the notation for a vector, or singled dimensional array. Additionally, we have added labels for the lines and these are grouped in the same way. We get a graph like this:" }, { "code": null, "e": 8715, "s": 8408, "text": "Or how about a scatter chart? A scatter chart is often used to see if a pattern can be detected in the data. Here we plot the maximum temperature against the hours of sunshine. As you might expect there is a pattern: a visible correlation — the more hours of sunshine there are, the higher the temperature." }, { "code": null, "e": 8738, "s": 8715, "text": "scatter(d.Tmax, d.Sun)" }, { "code": null, "e": 8888, "s": 8738, "text": "The data we have doesn’t really lend itself to being depicted as a pie chart, so we are going to generate some random data, again — 5 random numbers." }, { "code": null, "e": 8948, "s": 8888, "text": "x = 1:5; y = rand(5); # These are the plotting datapie(x,y)" }, { "code": null, "e": 8993, "s": 8948, "text": "Now we are going to load in a bit more data:" }, { "code": null, "e": 9028, "s": 8993, "text": "d2 = CSV.read(\"londonweather.csv\")" }, { "code": null, "e": 9348, "s": 9028, "text": "This is similar to the data table that we have been using but rather bigger as it covers several decades of data rather than just one year. This gives us plenty of rainfall data so that we can see the distribution of the levels of rain that occur in London over a longish period. To create a histogram we run this code:" }, { "code": null, "e": 9385, "s": 9348, "text": "histogram(d2.Rain, label=\"Rainfall\")" }, { "code": null, "e": 9423, "s": 9385, "text": "So the whole program looks like this:" }, { "code": null, "e": 9536, "s": 9423, "text": "using Plotsusing CSVd2 = CSV.read(\"d:notebooks/juliaplot/londonweather.csv\")histogram(d2.Rain, label=\"Rainfall\")" }, { "code": null, "e": 9555, "s": 9536, "text": "Here’s the result." }, { "code": null, "e": 9706, "s": 9555, "text": "It’s all very well seeing these charts in the VSCode environment but to be useful, we need to be able to save them so as to use them in our documents." }, { "code": null, "e": 9740, "s": 9706, "text": "You can save the chart like this:" }, { "code": null, "e": 9826, "s": 9740, "text": "histogram(d2.Rain, label=\"Rainfall\") savefig(\"d:notebooks/juliaplot/myhistogram.png\")" }, { "code": null, "e": 9927, "s": 9826, "text": "When this code is run the chart will not be displayed but it will be saved with the file name given." }, { "code": null, "e": 10227, "s": 9927, "text": "I hope that was useful — we’ve looked at the basic charts available in Julia Plots. There is a great deal more to Julia than we have seen in this short article and a lot more that you can do with Plots too, but I hope you have found that this introduction has whetted your appetite to find out more." }, { "code": null, "e": 10399, "s": 10227, "text": "Right click on the links below to download the files and then copy them in the directory that Julia will use. The data files are here: london2018.csv and londonweather.csv" }, { "code": null, "e": 10537, "s": 10399, "text": "As always, thanks for reading. If you would like to know when I publish new articles, please consider signing up for an email alert here." } ]
Check for balanced parentheses in Python
Many times we are required to find if an expression is balanced with respect to the brackets present in it. By balanced we mean for each left bracket there is a corresponding right bracket and the sequence of brackets is properly ordered. This has importance in writing a program or a mathematical expression where brackets are heavily used. In this topic, we will see how we can programmatically find out if an expression containing brackets is balanced or not. In this method, we find out the innermost pair of brackets and replace them with null values. We keep doing this till all the pairs of brackets are replaced. If still some bracket is left then the expression is not balanced otherwise the expression is found to be balanced. def brackets(expression): all_br = ['()', '{}', '[]'] while any(x in expression for x in all_br): for br in all_br: expression = expression.replace(br, '') return not expression # calling the function input_string = "([]{}()" if brackets(input_string): print(input_string,"balanced") else: print(input_string,"Not balanced") Running the above code gives us the following result − ([]{}() Not balanced
[ { "code": null, "e": 1525, "s": 1062, "text": "Many times we are required to find if an expression is balanced with respect to the brackets present in it. By balanced we mean for each left bracket there is a corresponding right bracket and the sequence of brackets is properly ordered. This has importance in writing a program or a mathematical expression where brackets are heavily used. In this topic, we will see how we can programmatically find out if an expression containing brackets is balanced or not." }, { "code": null, "e": 1799, "s": 1525, "text": "In this method, we find out the innermost pair of brackets and replace them with null values. We keep doing this till all the pairs of brackets are replaced. If still some bracket is left then the expression is not balanced otherwise the expression is found to be balanced." }, { "code": null, "e": 2155, "s": 1799, "text": "def brackets(expression):\n all_br = ['()', '{}', '[]']\n while any(x in expression for x in all_br):\n for br in all_br:\n expression = expression.replace(br, '')\n return not expression\n\n# calling the function\ninput_string = \"([]{}()\"\nif brackets(input_string):\n print(input_string,\"balanced\")\nelse:\n print(input_string,\"Not balanced\")" }, { "code": null, "e": 2210, "s": 2155, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2231, "s": 2210, "text": "([]{}() Not balanced" } ]
How to load huge CSV datasets in Python Pandas | by Angelica Lo Duca | Towards Data Science
It may happen that you have a huge CSV dataset which occupies 4 or 5 GBytes (or even more) in your hard disk and you want to process it with Python pandas. Maybe you don't need all the data contained in the dataset, but only some records satisfying some criteria. In this short tutorial I show you how to deal with huge datasets in Python Pandas. We can apply four strategies: vertical filter horizontal filter bursts memory. You can download the full jupyter notebook from my Github repository. In this case we load only some columns of the whole dataset. We can use the parameter usecols of the read_csv() function to select only some columns. import pandas as pddf = pd.read_csv('hepatitis.csv', usecols=['age','sex']) In this case we load only some rows of the dataset. We can choose the starting row and how many rows we must load. Keep in mind that if we skip the first row, we must pass the names of the columns as further parameter. srow = 5nrows = 50columns = ['age','sex','steroid','antivirals','fatigue','malaise','anorexia','liver_big','liver_firm','spleen_palpable','spiders','ascites','varices','bilirubin','alk_phosphate','sgot','albumin','protime','histology','class']df = pd.read_csv('hepatitis.csv', skiprows=srow, nrows=nrows, names=columns)df.head() It may happen that we need to load the full dataset, but we don’t have enough memory to load it. Thus we can load it in bursts, then we apply some filters and store the results into another (smaller) dataset. Filters may include dropping operations and conversion from bigger to smaller types. Firstly, we define a function called read_burst() which reads the i-th burst, performs some filters and then stores the results into another output csv file. In our case we can drop rows where malaise = False. We pass the starting row srow, the burst size burst the names of columns columns as parameters of the read_burst() function. When the starting row is equal to ,1 we must also write the header to the output csv file. Thus we define a variable called header, which is set to True if srow = 1. def read_burst(srow,burst,columns): header = False if srow == 1: header = True df = pd.read_csv('hepatitis.csv', skiprows=srow, nrows=burst, names=columns) df = df.drop(df[df['malaise'] == False].index) df.to_csv('hepatitis_small.csv', mode='a',header=header) Now we can loop throughout the dataset. Note that we must know in advance the number of lines of the csv file. This can be done by using a command line tick. We can use the wc unix shell command. In order to run this command within the jupyther notebook, we must use the ! operator. ! wc -l hepatitis.csv which gives the following output: 156 hepatitis.csv Our file contains 156 rows, thus we can set the maximum number of lines to be read to 156, since the first line corresponds to the header. We set burst = 10. Thus we read 100 at times. At the end, we run again the read_burst() function to load the last remaining rows. burst =10srow = 1nrows = 156columns = ['age','sex','steroid','antivirals','fatigue','malaise','anorexia','liver_big','liver_firm','spleen_palpable','spiders','ascites','varices','bilirubin','alk_phosphate','sgot','albumin','protime','histology','class']while srow < nrows: print('srow: ' + str(srow)) read_burst(srow,burst,columns) srow = srow + burstread_burst(srow,nrows,columns) Now we can load the smaller dataset. df = pd.read_csv('hepatitis_small.csv')df.head() We can drop the Unnamed: 0 column. df.drop(columns=['Unnamed: 0'],axis=1,inplace=True) Another option while reading huge datasets in Python pandas could be increasing the memory associated to the reading operation. This can be done through the low_memory parameter. df = pd.read_csv('hepatitis.csv', low_memory=False) In this short tutorial I have illustrated how to deal with huge datasets in Python pandas. We have learnt that four strategies could be applied: vertical filter horizontal filter bursts memory configuration. If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube and and Github.
[ { "code": null, "e": 519, "s": 172, "text": "It may happen that you have a huge CSV dataset which occupies 4 or 5 GBytes (or even more) in your hard disk and you want to process it with Python pandas. Maybe you don't need all the data contained in the dataset, but only some records satisfying some criteria. In this short tutorial I show you how to deal with huge datasets in Python Pandas." }, { "code": null, "e": 549, "s": 519, "text": "We can apply four strategies:" }, { "code": null, "e": 565, "s": 549, "text": "vertical filter" }, { "code": null, "e": 583, "s": 565, "text": "horizontal filter" }, { "code": null, "e": 590, "s": 583, "text": "bursts" }, { "code": null, "e": 598, "s": 590, "text": "memory." }, { "code": null, "e": 668, "s": 598, "text": "You can download the full jupyter notebook from my Github repository." }, { "code": null, "e": 818, "s": 668, "text": "In this case we load only some columns of the whole dataset. We can use the parameter usecols of the read_csv() function to select only some columns." }, { "code": null, "e": 894, "s": 818, "text": "import pandas as pddf = pd.read_csv('hepatitis.csv', usecols=['age','sex'])" }, { "code": null, "e": 1113, "s": 894, "text": "In this case we load only some rows of the dataset. We can choose the starting row and how many rows we must load. Keep in mind that if we skip the first row, we must pass the names of the columns as further parameter." }, { "code": null, "e": 1442, "s": 1113, "text": "srow = 5nrows = 50columns = ['age','sex','steroid','antivirals','fatigue','malaise','anorexia','liver_big','liver_firm','spleen_palpable','spiders','ascites','varices','bilirubin','alk_phosphate','sgot','albumin','protime','histology','class']df = pd.read_csv('hepatitis.csv', skiprows=srow, nrows=nrows, names=columns)df.head()" }, { "code": null, "e": 1736, "s": 1442, "text": "It may happen that we need to load the full dataset, but we don’t have enough memory to load it. Thus we can load it in bursts, then we apply some filters and store the results into another (smaller) dataset. Filters may include dropping operations and conversion from bigger to smaller types." }, { "code": null, "e": 2237, "s": 1736, "text": "Firstly, we define a function called read_burst() which reads the i-th burst, performs some filters and then stores the results into another output csv file. In our case we can drop rows where malaise = False. We pass the starting row srow, the burst size burst the names of columns columns as parameters of the read_burst() function. When the starting row is equal to ,1 we must also write the header to the output csv file. Thus we define a variable called header, which is set to True if srow = 1." }, { "code": null, "e": 2519, "s": 2237, "text": "def read_burst(srow,burst,columns): header = False if srow == 1: header = True df = pd.read_csv('hepatitis.csv', skiprows=srow, nrows=burst, names=columns) df = df.drop(df[df['malaise'] == False].index) df.to_csv('hepatitis_small.csv', mode='a',header=header)" }, { "code": null, "e": 2802, "s": 2519, "text": "Now we can loop throughout the dataset. Note that we must know in advance the number of lines of the csv file. This can be done by using a command line tick. We can use the wc unix shell command. In order to run this command within the jupyther notebook, we must use the ! operator." }, { "code": null, "e": 2824, "s": 2802, "text": "! wc -l hepatitis.csv" }, { "code": null, "e": 2858, "s": 2824, "text": "which gives the following output:" }, { "code": null, "e": 2876, "s": 2858, "text": "156 hepatitis.csv" }, { "code": null, "e": 3145, "s": 2876, "text": "Our file contains 156 rows, thus we can set the maximum number of lines to be read to 156, since the first line corresponds to the header. We set burst = 10. Thus we read 100 at times. At the end, we run again the read_burst() function to load the last remaining rows." }, { "code": null, "e": 3536, "s": 3145, "text": "burst =10srow = 1nrows = 156columns = ['age','sex','steroid','antivirals','fatigue','malaise','anorexia','liver_big','liver_firm','spleen_palpable','spiders','ascites','varices','bilirubin','alk_phosphate','sgot','albumin','protime','histology','class']while srow < nrows: print('srow: ' + str(srow)) read_burst(srow,burst,columns) srow = srow + burstread_burst(srow,nrows,columns)" }, { "code": null, "e": 3573, "s": 3536, "text": "Now we can load the smaller dataset." }, { "code": null, "e": 3622, "s": 3573, "text": "df = pd.read_csv('hepatitis_small.csv')df.head()" }, { "code": null, "e": 3657, "s": 3622, "text": "We can drop the Unnamed: 0 column." }, { "code": null, "e": 3709, "s": 3657, "text": "df.drop(columns=['Unnamed: 0'],axis=1,inplace=True)" }, { "code": null, "e": 3888, "s": 3709, "text": "Another option while reading huge datasets in Python pandas could be increasing the memory associated to the reading operation. This can be done through the low_memory parameter." }, { "code": null, "e": 3940, "s": 3888, "text": "df = pd.read_csv('hepatitis.csv', low_memory=False)" }, { "code": null, "e": 4085, "s": 3940, "text": "In this short tutorial I have illustrated how to deal with huge datasets in Python pandas. We have learnt that four strategies could be applied:" }, { "code": null, "e": 4101, "s": 4085, "text": "vertical filter" }, { "code": null, "e": 4119, "s": 4101, "text": "horizontal filter" }, { "code": null, "e": 4126, "s": 4119, "text": "bursts" }, { "code": null, "e": 4148, "s": 4126, "text": "memory configuration." } ]
MongoDB - Query Document
In this chapter, we will learn how to query document from MongoDB collection. To query data from MongoDB collection, you need to use MongoDB's find() method. The basic syntax of find() method is as follows − >db.COLLECTION_NAME.find() find() method will display all the documents in a non-structured way. Assume we have created a collection named mycol as − > use sampleDB switched to db sampleDB > db.createCollection("mycol") { "ok" : 1 } > And inserted 3 documents in it using the insert() method as shown below − > db.mycol.insert([ { title: "MongoDB Overview", description: "MongoDB is no SQL database", by: "tutorials point", url: "http://www.tutorialspoint.com", tags: ["mongodb", "database", "NoSQL"], likes: 100 }, { title: "NoSQL Database", description: "NoSQL database doesn't have tables", by: "tutorials point", url: "http://www.tutorialspoint.com", tags: ["mongodb", "database", "NoSQL"], likes: 20, comments: [ { user:"user1", message: "My first comment", dateCreated: new Date(2013,11,10,2,35), like: 0 } ] } ]) Following method retrieves all the documents in the collection − > db.mycol.find() { "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview", "description" : "MongoDB is no SQL database", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } { "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "title" : "NoSQL Database", "description" : "NoSQL database doesn't have tables", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 20, "comments" : [ { "user" : "user1", "message" : "My first comment", "dateCreated" : ISODate("2013-12-09T21:05:00Z"), "like" : 0 } ] } > To display the results in a formatted way, you can use pretty() method. >db.COLLECTION_NAME.find().pretty() Following example retrieves all the documents from the collection named mycol and arranges them in an easy-to-read format. > db.mycol.find().pretty() { "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview", "description" : "MongoDB is no SQL database", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } { "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "title" : "NoSQL Database", "description" : "NoSQL database doesn't have tables", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 20, "comments" : [ { "user" : "user1", "message" : "My first comment", "dateCreated" : ISODate("2013-12-09T21:05:00Z"), "like" : 0 } ] } Apart from the find() method, there is findOne() method, that returns only one document. >db.COLLECTIONNAME.findOne() Following example retrieves the document with title MongoDB Overview. > db.mycol.findOne({title: "MongoDB Overview"}) { "_id" : ObjectId("5dd6542170fb13eec3963bf0"), "title" : "MongoDB Overview", "description" : "MongoDB is no SQL database", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } To query the document on the basis of some condition, you can use following operations. To query documents based on the AND condition, you need to use $and keyword. Following is the basic syntax of AND − >db.mycol.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>} ] }) Following example will show all the tutorials written by 'tutorials point' and whose title is 'MongoDB Overview'. > db.mycol.find({$and:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty() { "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview", "description" : "MongoDB is no SQL database", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } > For the above given example, equivalent where clause will be ' where by = 'tutorials point' AND title = 'MongoDB Overview' '. You can pass any number of key, value pairs in find clause. To query documents based on the OR condition, you need to use $or keyword. Following is the basic syntax of OR − >db.mycol.find( { $or: [ {key1: value1}, {key2:value2} ] } ).pretty() Following example will show all the tutorials written by 'tutorials point' or whose title is 'MongoDB Overview'. >db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty() { "_id": ObjectId(7df78ad8902c), "title": "MongoDB Overview", "description": "MongoDB is no sql database", "by": "tutorials point", "url": "http://www.tutorialspoint.com", "tags": ["mongodb", "database", "NoSQL"], "likes": "100" } > The following example will show the documents that have likes greater than 10 and whose title is either 'MongoDB Overview' or by is 'tutorials point'. Equivalent SQL where clause is 'where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')' >db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"}, {"title": "MongoDB Overview"}]}).pretty() { "_id": ObjectId(7df78ad8902c), "title": "MongoDB Overview", "description": "MongoDB is no sql database", "by": "tutorials point", "url": "http://www.tutorialspoint.com", "tags": ["mongodb", "database", "NoSQL"], "likes": "100" } > To query documents based on the NOT condition, you need to use $not keyword. Following is the basic syntax of NOT − >db.COLLECTION_NAME.find( { $not: [ {key1: value1}, {key2:value2} ] } ) Assume we have inserted 3 documents in the collection empDetails as shown below − db.empDetails.insertMany( [ { First_Name: "Radhika", Last_Name: "Sharma", Age: "26", e_mail: "[email protected]", phone: "9000012345" }, { First_Name: "Rachel", Last_Name: "Christopher", Age: "27", e_mail: "[email protected]", phone: "9000054321" }, { First_Name: "Fathima", Last_Name: "Sheik", Age: "24", e_mail: "[email protected]", phone: "9000054321" } ] ) Following example will retrieve the document(s) whose first name is not "Radhika" and last name is not "Christopher" > db.empDetails.find( { $nor:[ 40 {"First_Name": "Radhika"}, {"Last_Name": "Christopher"} ] } ).pretty() { "_id" : ObjectId("5dd631f270fb13eec3963bef"), "First_Name" : "Fathima", "Last_Name" : "Sheik", "Age" : "24", "e_mail" : "[email protected]", "phone" : "9000054321" } To query documents based on the NOT condition, you need to use $not keyword following is the basic syntax of NOT − >db.COLLECTION_NAME.find( { $NOT: [ {key1: value1}, {key2:value2} ] } ).pretty() Following example will retrieve the document(s) whose age is not greater than 25 > db.empDetails.find( { "Age": { $not: { $gt: "25" } } } ) { "_id" : ObjectId("5dd6636870fb13eec3963bf7"), "First_Name" : "Fathima", "Last_Name" : "Sheik", "Age" : "24", "e_mail" : "[email protected]", "phone" : "9000054321" } 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": 2631, "s": 2553, "text": "In this chapter, we will learn how to query document from MongoDB collection." }, { "code": null, "e": 2711, "s": 2631, "text": "To query data from MongoDB collection, you need to use MongoDB's find() method." }, { "code": null, "e": 2761, "s": 2711, "text": "The basic syntax of find() method is as follows −" }, { "code": null, "e": 2789, "s": 2761, "text": ">db.COLLECTION_NAME.find()\n" }, { "code": null, "e": 2859, "s": 2789, "text": "find() method will display all the documents in a non-structured way." }, { "code": null, "e": 2912, "s": 2859, "text": "Assume we have created a collection named mycol as −" }, { "code": null, "e": 2997, "s": 2912, "text": "> use sampleDB\nswitched to db sampleDB\n> db.createCollection(\"mycol\")\n{ \"ok\" : 1 }\n>" }, { "code": null, "e": 3071, "s": 2997, "text": "And inserted 3 documents in it using the insert() method as shown below −" }, { "code": null, "e": 3636, "s": 3071, "text": "> db.mycol.insert([\n\t{\n\t\ttitle: \"MongoDB Overview\",\n\t\tdescription: \"MongoDB is no SQL database\",\n\t\tby: \"tutorials point\",\n\t\turl: \"http://www.tutorialspoint.com\",\n\t\ttags: [\"mongodb\", \"database\", \"NoSQL\"],\n\t\tlikes: 100\n\t},\n\t{\n\t\ttitle: \"NoSQL Database\",\n\t\tdescription: \"NoSQL database doesn't have tables\",\n\t\tby: \"tutorials point\",\n\t\turl: \"http://www.tutorialspoint.com\",\n\t\ttags: [\"mongodb\", \"database\", \"NoSQL\"],\n\t\tlikes: 20,\n\t\tcomments: [\n\t\t\t{\n\t\t\t\tuser:\"user1\",\n\t\t\t\tmessage: \"My first comment\",\n\t\t\t\tdateCreated: new Date(2013,11,10,2,35),\n\t\t\t\tlike: 0\n\t\t\t}\n\t\t]\n\t}\n])" }, { "code": null, "e": 3701, "s": 3636, "text": "Following method retrieves all the documents in the collection −" }, { "code": null, "e": 4362, "s": 3701, "text": "> db.mycol.find()\n{ \"_id\" : ObjectId(\"5dd4e2cc0821d3b44607534c\"), \"title\" : \"MongoDB Overview\", \"description\" : \"MongoDB is no SQL database\", \"by\" : \"tutorials point\", \"url\" : \"http://www.tutorialspoint.com\", \"tags\" : [ \"mongodb\", \"database\", \"NoSQL\" ], \"likes\" : 100 }\n{ \"_id\" : ObjectId(\"5dd4e2cc0821d3b44607534d\"), \"title\" : \"NoSQL Database\", \"description\" : \"NoSQL database doesn't have tables\", \"by\" : \"tutorials point\", \"url\" : \"http://www.tutorialspoint.com\", \"tags\" : [ \"mongodb\", \"database\", \"NoSQL\" ], \"likes\" : 20, \"comments\" : [ { \"user\" : \"user1\", \"message\" : \"My first comment\", \"dateCreated\" : ISODate(\"2013-12-09T21:05:00Z\"), \"like\" : 0 } ] }\n>" }, { "code": null, "e": 4434, "s": 4362, "text": "To display the results in a formatted way, you can use pretty() method." }, { "code": null, "e": 4471, "s": 4434, "text": ">db.COLLECTION_NAME.find().pretty()\n" }, { "code": null, "e": 4594, "s": 4471, "text": "Following example retrieves all the documents from the collection named mycol and arranges them in an easy-to-read format." }, { "code": null, "e": 5308, "s": 4594, "text": "> db.mycol.find().pretty()\n{\n\t\"_id\" : ObjectId(\"5dd4e2cc0821d3b44607534c\"),\n\t\"title\" : \"MongoDB Overview\",\n\t\"description\" : \"MongoDB is no SQL database\",\n\t\"by\" : \"tutorials point\",\n\t\"url\" : \"http://www.tutorialspoint.com\",\n\t\"tags\" : [\n\t\t\"mongodb\",\n\t\t\"database\",\n\t\t\"NoSQL\"\n\t],\n\t\"likes\" : 100\n}\n{\n\t\"_id\" : ObjectId(\"5dd4e2cc0821d3b44607534d\"),\n\t\"title\" : \"NoSQL Database\",\n\t\"description\" : \"NoSQL database doesn't have tables\",\n\t\"by\" : \"tutorials point\",\n\t\"url\" : \"http://www.tutorialspoint.com\",\n\t\"tags\" : [\n\t\t\"mongodb\",\n\t\t\"database\",\n\t\t\"NoSQL\"\n\t],\n\t\"likes\" : 20,\n\t\"comments\" : [\n\t\t{\n\t\t\t\"user\" : \"user1\",\n\t\t\t\"message\" : \"My first comment\",\n\t\t\t\"dateCreated\" : ISODate(\"2013-12-09T21:05:00Z\"),\n\t\t\t\"like\" : 0\n\t\t}\n\t]\n}" }, { "code": null, "e": 5397, "s": 5308, "text": "Apart from the find() method, there is findOne() method, that returns only one document." }, { "code": null, "e": 5427, "s": 5397, "text": ">db.COLLECTIONNAME.findOne()\n" }, { "code": null, "e": 5497, "s": 5427, "text": "Following example retrieves the document with title MongoDB Overview." }, { "code": null, "e": 5811, "s": 5497, "text": "> db.mycol.findOne({title: \"MongoDB Overview\"})\n{\n\t\"_id\" : ObjectId(\"5dd6542170fb13eec3963bf0\"),\n\t\"title\" : \"MongoDB Overview\",\n\t\"description\" : \"MongoDB is no SQL database\",\n\t\"by\" : \"tutorials point\",\n\t\"url\" : \"http://www.tutorialspoint.com\",\n\t\"tags\" : [\n\t\t\"mongodb\",\n\t\t\"database\",\n\t\t\"NoSQL\"\n\t],\n\t\"likes\" : 100\n}" }, { "code": null, "e": 5899, "s": 5811, "text": "To query the document on the basis of some condition, you can use following operations." }, { "code": null, "e": 6015, "s": 5899, "text": "To query documents based on the AND condition, you need to use $and keyword. Following is the basic syntax of AND −" }, { "code": null, "e": 6084, "s": 6015, "text": ">db.mycol.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>} ] })\n" }, { "code": null, "e": 6198, "s": 6084, "text": "Following example will show all the tutorials written by 'tutorials point' and whose title is 'MongoDB Overview'." }, { "code": null, "e": 6556, "s": 6198, "text": "> db.mycol.find({$and:[{\"by\":\"tutorials point\"},{\"title\": \"MongoDB Overview\"}]}).pretty()\n{\n\t\"_id\" : ObjectId(\"5dd4e2cc0821d3b44607534c\"),\n\t\"title\" : \"MongoDB Overview\",\n\t\"description\" : \"MongoDB is no SQL database\",\n\t\"by\" : \"tutorials point\",\n\t\"url\" : \"http://www.tutorialspoint.com\",\n\t\"tags\" : [\n\t\t\"mongodb\",\n\t\t\"database\",\n\t\t\"NoSQL\"\n\t],\n\t\"likes\" : 100\n}\n>" }, { "code": null, "e": 6742, "s": 6556, "text": "For the above given example, equivalent where clause will be ' where by = 'tutorials point' AND title = 'MongoDB Overview' '. You can pass any number of key, value pairs in find clause." }, { "code": null, "e": 6855, "s": 6742, "text": "To query documents based on the OR condition, you need to use $or keyword. Following is the basic syntax of OR −" }, { "code": null, "e": 6953, "s": 6855, "text": ">db.mycol.find(\n {\n $or: [\n {key1: value1}, {key2:value2}\n ]\n }\n).pretty()\n" }, { "code": null, "e": 7066, "s": 6953, "text": "Following example will show all the tutorials written by 'tutorials point' or whose title is 'MongoDB Overview'." }, { "code": null, "e": 7409, "s": 7066, "text": ">db.mycol.find({$or:[{\"by\":\"tutorials point\"},{\"title\": \"MongoDB Overview\"}]}).pretty()\n{\n \"_id\": ObjectId(7df78ad8902c),\n \"title\": \"MongoDB Overview\", \n \"description\": \"MongoDB is no sql database\",\n \"by\": \"tutorials point\",\n \"url\": \"http://www.tutorialspoint.com\",\n \"tags\": [\"mongodb\", \"database\", \"NoSQL\"],\n \"likes\": \"100\"\n}\n>" }, { "code": null, "e": 7667, "s": 7409, "text": "The following example will show the documents that have likes greater than 10 and whose title is either 'MongoDB Overview' or by is 'tutorials point'. Equivalent SQL where clause is 'where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')'" }, { "code": null, "e": 8035, "s": 7667, "text": ">db.mycol.find({\"likes\": {$gt:10}, $or: [{\"by\": \"tutorials point\"},\n {\"title\": \"MongoDB Overview\"}]}).pretty()\n{\n \"_id\": ObjectId(7df78ad8902c),\n \"title\": \"MongoDB Overview\", \n \"description\": \"MongoDB is no sql database\",\n \"by\": \"tutorials point\",\n \"url\": \"http://www.tutorialspoint.com\",\n \"tags\": [\"mongodb\", \"database\", \"NoSQL\"],\n \"likes\": \"100\"\n}\n>" }, { "code": null, "e": 8151, "s": 8035, "text": "To query documents based on the NOT condition, you need to use $not keyword. Following is the basic syntax of NOT −" }, { "code": null, "e": 8233, "s": 8151, "text": ">db.COLLECTION_NAME.find(\n\t{\n\t\t$not: [\n\t\t\t{key1: value1}, {key2:value2}\n\t\t]\n\t}\n)\n" }, { "code": null, "e": 8315, "s": 8233, "text": "Assume we have inserted 3 documents in the collection empDetails as shown below −" }, { "code": null, "e": 8771, "s": 8315, "text": "db.empDetails.insertMany(\n\t[\n\t\t{\n\t\t\tFirst_Name: \"Radhika\",\n\t\t\tLast_Name: \"Sharma\",\n\t\t\tAge: \"26\",\n\t\t\te_mail: \"[email protected]\",\n\t\t\tphone: \"9000012345\"\n\t\t},\n\t\t{\n\t\t\tFirst_Name: \"Rachel\",\n\t\t\tLast_Name: \"Christopher\",\n\t\t\tAge: \"27\",\n\t\t\te_mail: \"[email protected]\",\n\t\t\tphone: \"9000054321\"\n\t\t},\n\t\t{\n\t\t\tFirst_Name: \"Fathima\",\n\t\t\tLast_Name: \"Sheik\",\n\t\t\tAge: \"24\",\n\t\t\te_mail: \"[email protected]\",\n\t\t\tphone: \"9000054321\"\n\t\t}\n\t]\n)" }, { "code": null, "e": 8888, "s": 8771, "text": "Following example will retrieve the document(s) whose first name is not \"Radhika\" and last name is not \"Christopher\"" }, { "code": null, "e": 9192, "s": 8888, "text": "> db.empDetails.find(\n\t{\n\t\t$nor:[\n\t\t\t40\n\t\t\t{\"First_Name\": \"Radhika\"},\n\t\t\t{\"Last_Name\": \"Christopher\"}\n\t\t]\n\t}\n).pretty()\n{\n\t\"_id\" : ObjectId(\"5dd631f270fb13eec3963bef\"),\n\t\"First_Name\" : \"Fathima\",\n\t\"Last_Name\" : \"Sheik\",\n\t\"Age\" : \"24\",\n\t\"e_mail\" : \"[email protected]\",\n\t\"phone\" : \"9000054321\"\n}" }, { "code": null, "e": 9307, "s": 9192, "text": "To query documents based on the NOT condition, you need to use $not keyword following is the basic syntax of NOT −" }, { "code": null, "e": 9398, "s": 9307, "text": ">db.COLLECTION_NAME.find(\n\t{\n\t\t$NOT: [\n\t\t\t{key1: value1}, {key2:value2}\n\t\t]\n\t}\n).pretty()\n" }, { "code": null, "e": 9479, "s": 9398, "text": "Following example will retrieve the document(s) whose age is not greater than 25" }, { "code": null, "e": 9722, "s": 9479, "text": "> db.empDetails.find( { \"Age\": { $not: { $gt: \"25\" } } } )\n{\n\t\"_id\" : ObjectId(\"5dd6636870fb13eec3963bf7\"),\n\t\"First_Name\" : \"Fathima\",\n\t\"Last_Name\" : \"Sheik\",\n\t\"Age\" : \"24\",\n\t\"e_mail\" : \"[email protected]\",\n\t\"phone\" : \"9000054321\"\n}" }, { "code": null, "e": 9755, "s": 9722, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 9774, "s": 9755, "text": " Arnab Chakraborty" }, { "code": null, "e": 9809, "s": 9774, "text": "\n 54 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9837, "s": 9809, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9872, "s": 9837, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9895, "s": 9872, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 9930, "s": 9895, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9947, "s": 9930, "text": " University Code" }, { "code": null, "e": 9980, "s": 9947, "text": "\n 26 Lectures \n 8 hours \n" }, { "code": null, "e": 9999, "s": 9980, "text": " Bassir Jafarzadeh" }, { "code": null, "e": 10034, "s": 9999, "text": "\n 70 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10054, "s": 10034, "text": " Skillbakerystudios" }, { "code": null, "e": 10061, "s": 10054, "text": " Print" }, { "code": null, "e": 10072, "s": 10061, "text": " Add Notes" } ]
Smallest root of the equation x^2 + s(x)*x - n = 0, where s(x) is the sum of digits of root x. - GeeksforGeeks
10 Jan, 2022 You are given an integer n, find the smallest positive integer root of equation x, or else print -1 if no roots are found.Equation: x^2 + s(x)*x – n = 0where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system. 1 <= N <= 10^18 Examples: Input: N = 110 Output: 10 Explanation: x = 10 is the minimum root. As s(10) = 1 + 0 = 1 and 102 + 1*10 - 110=0. Input: N = 4 Output: -1 Explanation: there are no roots of the equation possible A naive approach will be to iterate through all the possible values of X and find out if any such root exists but this won’t be possible as the value of n is very large. An efficient approach will be as follows Firstly let’s find the interval of possible values of s(x). Hence x^2 <= N and N <= 10^18, x <= 109. In other words, for every considerable solution x the decimal length of x does not extend 10 digits. So Smax = s(9999999999) = 10*9 = 90. Let’s brute force the value of s(x) (0 <= s(x) <= 90). Now we have an ordinary square equation. The deal is to solve the equation and to check that the current brute forced value of s(x) is equal to sum of digits of the solution. If the solution exists and the equality holds, we should get the answer and store the minimum of the roots possible. Below is the implementation of the above approach C++ Java Python3 C# PHP Javascript // CPP program to find smallest value of root// of an equation under given constraints.#include <bits/stdc++.h>using namespace std; // function to check if the sum of digits is// equal to the summation assumedbool check(long long a, long long b){ long long int c = 0; // calculate the sum of digit while (a != 0) { c = c + a % 10; a = a / 10; } return (c == b);} // function to find the largest root possible.long long root(long long n){ bool found = 0; long long mx = 1e18; // iterate for all possible sum of digits. for (long long i = 0; i <= 90; i++) { // check if discriminant is a perfect square. long long s = i * i + 4 * n; long long sq = sqrt(s); // check if discriminant is a perfect square and // if it as perfect root of the equation if (sq * sq == s && check((sq - i) / 2, i)) { found = 1; mx = min(mx, (sq - i) / 2); } } // function returns answer if (found) return mx; else return -1;} // driver program to check the above functionint main(){ long long n = 110; cout << root(n);} // Java program to find smallest value of root// of an equation under given constraints. class GFG{// function to check if the sum of digits is// equal to the summation assumedstatic boolean check(long a, long b){ long c = 0; // calculate the sum of digit while (a != 0) { c = c + a % 10; a = a / 10; } return (c == b);} // function to find the largest root possible.static long root(long n){ boolean found = false; long mx = (long)1E18; // iterate for all possible sum of digits. for (long i = 0; i <= 90; i++) { // check if discriminant is a perfect square. long s = i * i + 4 * n; long sq = (long)Math.sqrt(s); // check if discriminant is a perfect square and // if it as perfect root of the equation if (sq * sq == s && check((sq - i) / 2, i)) { found = true; mx = Math.min(mx, (sq - i) / 2); } } // function returns answer if (found) return mx; else return -1;} // driver program to check the above functionpublic static void main(String[] args){ long n = 110; System.out.println(root(n));}}// This code is contributed by mits # Python3 program to find smallest # value of root of an equation# under given constraints.import math # function to check if the sum # of digits is equal to the# summation assumeddef check(a, b): c = 0; # calculate the # sum of digit while (a != 0): c = c + a % 10; a = int(a / 10); return True if(c == b) else False; # function to find the# largest root possible.def root(n): found = False; # float(1E+18) mx = 1000000000000000001; # iterate for all # possible sum of digits. for i in range(91): # check if discriminant # is a perfect square. s = i * i + 4 * n; sq = int(math.sqrt(s)); # check if discriminant is # a perfect square and # if it as perfect root # of the equation if (sq * sq == s and check(int((sq - i) / 2), i)): found = True; mx = min(mx, int((sq-i) / 2)); # function returns answer if (found): return mx; else: return -1; # Driver Coden = 110;print(root(n)); # This code is contributed by mits //C# program to find smallest value of root // of an equation under given constraints. using System;public class GFG{ // function to check if the sum of digits is // equal to the summation assumed static bool check(long a, long b) { long c = 0; // calculate the sum of digit while (a != 0) { c = c + a % 10; a = a / 10; } return (c == b); } // function to find the largest root possible. static long root(long n) { bool found = false; long mx = (long)1E18; // iterate for all possible sum of digits. for (long i = 0; i <= 90; i++) { // check if discriminant is a perfect square. long s = i * i + 4 * n; long sq = (long)Math.Sqrt(s); // check if discriminant is a perfect square and // if it as perfect root of the equation if (sq * sq == s && check((sq - i) / 2, i)) { found = true; mx = Math.Min(mx, (sq - i) / 2); } } // function returns answer if (found) return mx; else return -1; } // driver program to check the above function public static void Main() { long n = 110; Console.Write(root(n)); } } // This code is contributed by Raput-Ji <?php// PHP program to find // smallest value of root// of an equation under // given constraints. // function to check if// the sum of digits is// equal to the summation// assumedfunction check($a, $b){ $c = 0; // calculate the // sum of digit while ($a != 0) { $c = $c + $a % 10; $a = (int)($a / 10); } return ($c == $b) ? true : false;} // function to find the// largest root possible.function root($n){ $found = false; // float(1E+18) $mx = 1000000000000000001; // iterate for all // possible sum of digits. for ($i = 0; $i <= 90; $i++) { // check if discriminant // is a perfect square. $s = $i * $i + 4 * $n; $sq = (int)(sqrt($s)); // check if discriminant is // a perfect square and // if it as perfect root // of the equation if ($sq * $sq == $s && check((int)(($sq - $i) / 2), $i)) { $found = true; $mx = min($mx, (int)(($sq - $i) / 2)); } } // function returns answer if ($found) return $mx; else return -1;} // Driver Code$n = 110;echo root($n); // This code is contributed by mits?> <script> // Javascript program to find smallest // value of root of an equation under // given constraints. // Function to check if the sum of digits is// equal to the summation assumedfunction check(a, b){ var c = 0; // Calculate the sum of digit while (a != 0) { c = c + a % 10; a = parseInt(a / 10); } return (c == b);} // Function to find the largest root possible.function root(n) { var found = false; var mx = 1E18; // Iterate for all possible // sum of digits. for(i = 0; i <= 90; i++) { // Check if discriminant is a // perfect square. var s = i * i + 4 * n; var sq = Math.sqrt(s); // Check if discriminant is a // perfect square and if it as // perfect root of the equation if (sq * sq == s && check((sq - i) / 2, i)) { found = true; mx = Math.min(mx, (sq - i) / 2); } } // Function returns answer if (found) return mx; else return -1;} // Driver codevar n = 110; document.write(root(n)); // This code is contributed by todaysgaurav </script> Output: 10 Mithun Kumar Rajput-Ji todaysgaurav rajeev0719singh arorakashish0911 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Modular multiplicative inverse Algorithm to solve Rubik's Cube Count ways to reach the n'th stair Program to multiply two matrices Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Singular Value Decomposition (SVD) Program to convert a given number to words GCD of more than two (or array) numbers Program to calculate Electricity Bill Segment Tree | Set 1 (Sum of given range)
[ { "code": null, "e": 24301, "s": 24273, "text": "\n10 Jan, 2022" }, { "code": null, "e": 24594, "s": 24301, "text": "You are given an integer n, find the smallest positive integer root of equation x, or else print -1 if no roots are found.Equation: x^2 + s(x)*x – n = 0where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system. 1 <= N <= 10^18" }, { "code": null, "e": 24605, "s": 24594, "text": "Examples: " }, { "code": null, "e": 24833, "s": 24605, "text": "Input: N = 110 \nOutput: 10 \nExplanation: x = 10 is the minimum root. \n As s(10) = 1 + 0 = 1 and \n 102 + 1*10 - 110=0. \n\nInput: N = 4\nOutput: -1 \nExplanation: there are no roots of the \nequation possible" }, { "code": null, "e": 25003, "s": 24833, "text": "A naive approach will be to iterate through all the possible values of X and find out if any such root exists but this won’t be possible as the value of n is very large." }, { "code": null, "e": 25630, "s": 25003, "text": "An efficient approach will be as follows Firstly let’s find the interval of possible values of s(x). Hence x^2 <= N and N <= 10^18, x <= 109. In other words, for every considerable solution x the decimal length of x does not extend 10 digits. So Smax = s(9999999999) = 10*9 = 90. Let’s brute force the value of s(x) (0 <= s(x) <= 90). Now we have an ordinary square equation. The deal is to solve the equation and to check that the current brute forced value of s(x) is equal to sum of digits of the solution. If the solution exists and the equality holds, we should get the answer and store the minimum of the roots possible." }, { "code": null, "e": 25682, "s": 25630, "text": "Below is the implementation of the above approach " }, { "code": null, "e": 25686, "s": 25682, "text": "C++" }, { "code": null, "e": 25691, "s": 25686, "text": "Java" }, { "code": null, "e": 25699, "s": 25691, "text": "Python3" }, { "code": null, "e": 25702, "s": 25699, "text": "C#" }, { "code": null, "e": 25706, "s": 25702, "text": "PHP" }, { "code": null, "e": 25717, "s": 25706, "text": "Javascript" }, { "code": "// CPP program to find smallest value of root// of an equation under given constraints.#include <bits/stdc++.h>using namespace std; // function to check if the sum of digits is// equal to the summation assumedbool check(long long a, long long b){ long long int c = 0; // calculate the sum of digit while (a != 0) { c = c + a % 10; a = a / 10; } return (c == b);} // function to find the largest root possible.long long root(long long n){ bool found = 0; long long mx = 1e18; // iterate for all possible sum of digits. for (long long i = 0; i <= 90; i++) { // check if discriminant is a perfect square. long long s = i * i + 4 * n; long long sq = sqrt(s); // check if discriminant is a perfect square and // if it as perfect root of the equation if (sq * sq == s && check((sq - i) / 2, i)) { found = 1; mx = min(mx, (sq - i) / 2); } } // function returns answer if (found) return mx; else return -1;} // driver program to check the above functionint main(){ long long n = 110; cout << root(n);}", "e": 26870, "s": 25717, "text": null }, { "code": "// Java program to find smallest value of root// of an equation under given constraints. class GFG{// function to check if the sum of digits is// equal to the summation assumedstatic boolean check(long a, long b){ long c = 0; // calculate the sum of digit while (a != 0) { c = c + a % 10; a = a / 10; } return (c == b);} // function to find the largest root possible.static long root(long n){ boolean found = false; long mx = (long)1E18; // iterate for all possible sum of digits. for (long i = 0; i <= 90; i++) { // check if discriminant is a perfect square. long s = i * i + 4 * n; long sq = (long)Math.sqrt(s); // check if discriminant is a perfect square and // if it as perfect root of the equation if (sq * sq == s && check((sq - i) / 2, i)) { found = true; mx = Math.min(mx, (sq - i) / 2); } } // function returns answer if (found) return mx; else return -1;} // driver program to check the above functionpublic static void main(String[] args){ long n = 110; System.out.println(root(n));}}// This code is contributed by mits", "e": 28061, "s": 26870, "text": null }, { "code": "# Python3 program to find smallest # value of root of an equation# under given constraints.import math # function to check if the sum # of digits is equal to the# summation assumeddef check(a, b): c = 0; # calculate the # sum of digit while (a != 0): c = c + a % 10; a = int(a / 10); return True if(c == b) else False; # function to find the# largest root possible.def root(n): found = False; # float(1E+18) mx = 1000000000000000001; # iterate for all # possible sum of digits. for i in range(91): # check if discriminant # is a perfect square. s = i * i + 4 * n; sq = int(math.sqrt(s)); # check if discriminant is # a perfect square and # if it as perfect root # of the equation if (sq * sq == s and check(int((sq - i) / 2), i)): found = True; mx = min(mx, int((sq-i) / 2)); # function returns answer if (found): return mx; else: return -1; # Driver Coden = 110;print(root(n)); # This code is contributed by mits", "e": 29170, "s": 28061, "text": null }, { "code": "//C# program to find smallest value of root // of an equation under given constraints. using System;public class GFG{ // function to check if the sum of digits is // equal to the summation assumed static bool check(long a, long b) { long c = 0; // calculate the sum of digit while (a != 0) { c = c + a % 10; a = a / 10; } return (c == b); } // function to find the largest root possible. static long root(long n) { bool found = false; long mx = (long)1E18; // iterate for all possible sum of digits. for (long i = 0; i <= 90; i++) { // check if discriminant is a perfect square. long s = i * i + 4 * n; long sq = (long)Math.Sqrt(s); // check if discriminant is a perfect square and // if it as perfect root of the equation if (sq * sq == s && check((sq - i) / 2, i)) { found = true; mx = Math.Min(mx, (sq - i) / 2); } } // function returns answer if (found) return mx; else return -1; } // driver program to check the above function public static void Main() { long n = 110; Console.Write(root(n)); } } // This code is contributed by Raput-Ji", "e": 30564, "s": 29170, "text": null }, { "code": "<?php// PHP program to find // smallest value of root// of an equation under // given constraints. // function to check if// the sum of digits is// equal to the summation// assumedfunction check($a, $b){ $c = 0; // calculate the // sum of digit while ($a != 0) { $c = $c + $a % 10; $a = (int)($a / 10); } return ($c == $b) ? true : false;} // function to find the// largest root possible.function root($n){ $found = false; // float(1E+18) $mx = 1000000000000000001; // iterate for all // possible sum of digits. for ($i = 0; $i <= 90; $i++) { // check if discriminant // is a perfect square. $s = $i * $i + 4 * $n; $sq = (int)(sqrt($s)); // check if discriminant is // a perfect square and // if it as perfect root // of the equation if ($sq * $sq == $s && check((int)(($sq - $i) / 2), $i)) { $found = true; $mx = min($mx, (int)(($sq - $i) / 2)); } } // function returns answer if ($found) return $mx; else return -1;} // Driver Code$n = 110;echo root($n); // This code is contributed by mits?>", "e": 31814, "s": 30564, "text": null }, { "code": "<script> // Javascript program to find smallest // value of root of an equation under // given constraints. // Function to check if the sum of digits is// equal to the summation assumedfunction check(a, b){ var c = 0; // Calculate the sum of digit while (a != 0) { c = c + a % 10; a = parseInt(a / 10); } return (c == b);} // Function to find the largest root possible.function root(n) { var found = false; var mx = 1E18; // Iterate for all possible // sum of digits. for(i = 0; i <= 90; i++) { // Check if discriminant is a // perfect square. var s = i * i + 4 * n; var sq = Math.sqrt(s); // Check if discriminant is a // perfect square and if it as // perfect root of the equation if (sq * sq == s && check((sq - i) / 2, i)) { found = true; mx = Math.min(mx, (sq - i) / 2); } } // Function returns answer if (found) return mx; else return -1;} // Driver codevar n = 110; document.write(root(n)); // This code is contributed by todaysgaurav </script>", "e": 32970, "s": 31814, "text": null }, { "code": null, "e": 32979, "s": 32970, "text": "Output: " }, { "code": null, "e": 32983, "s": 32979, "text": "10 " }, { "code": null, "e": 32998, "s": 32985, "text": "Mithun Kumar" }, { "code": null, "e": 33008, "s": 32998, "text": "Rajput-Ji" }, { "code": null, "e": 33021, "s": 33008, "text": "todaysgaurav" }, { "code": null, "e": 33037, "s": 33021, "text": "rajeev0719singh" }, { "code": null, "e": 33054, "s": 33037, "text": "arorakashish0911" }, { "code": null, "e": 33067, "s": 33054, "text": "Mathematical" }, { "code": null, "e": 33080, "s": 33067, "text": "Mathematical" }, { "code": null, "e": 33178, "s": 33080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33187, "s": 33178, "text": "Comments" }, { "code": null, "e": 33200, "s": 33187, "text": "Old Comments" }, { "code": null, "e": 33231, "s": 33200, "text": "Modular multiplicative inverse" }, { "code": null, "e": 33263, "s": 33231, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 33298, "s": 33263, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 33331, "s": 33298, "text": "Program to multiply two matrices" }, { "code": null, "e": 33384, "s": 33331, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 33419, "s": 33384, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 33462, "s": 33419, "text": "Program to convert a given number to words" }, { "code": null, "e": 33502, "s": 33462, "text": "GCD of more than two (or array) numbers" }, { "code": null, "e": 33540, "s": 33502, "text": "Program to calculate Electricity Bill" } ]
Data visualization with D3.js for beginners | by Uditha Maduranga | Towards Data Science
Have you ever walked into a packed stadium or a musical show and tried to guess how many people were surrounding you? Were you way off? Analyzing high-volume data can be overwhelming. But, when you take abstract data points and convert them into an accurate, sizable visual, you will be able able to see things analytically. This is the era of information where we have more than enough data, but only few know what to do with those data. People rely on their sight far more than on anything else. That’s why data presented visually is more convincing than plain numbers. Excellent visualization can grab attention of the people, while endless columns and rows of numbers can only confuse them. To make these visualizations and analytics possible we need frameworks or libraries to existing languages to make this possible. That where D3.js comes in to play. D3 stands for Data-Driven Documents. If you are planning to create custom visualizations on the web, chances are that you’d have already heard about D3.js. A web based visualization library that features a plethora of APIs to handle the heavy lifting of creating advanced, dynamic and beautiful visualization content on the web. D3.js is a JavaScript library for manipulating documents based on data. D3.js helps you bring data to life using HTML, SVG, and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation. The main task that’s done by D3 is that it allows to bind any kind of data you want to DOM and then making the data-driven transformations to it resulting in easy to build and interactive data visualizations in your application. The Github repository of D3 and the API documentation which is used by D3 is also good sources if you are interested to have a deep dive. Let’s start using D3.js now. You can open your IDE or editor and create a file named index.html just to play around with D3.js. Using this library for our application is as easy as adding the link directly to get the latest release as below in index.html you created: <script src="https://d3js.org/d3.v5.min.js"></script> So now you’re ready to use D3.js and all of it’s features in your sample application. Selection means selecting the html element from their name or css selectors. (eg: h2, p ) Then after selecting the elements we can use D3 to manipulate and transform those html elements the way we want. Selections allow powerful data-driven transformation of the document object model (DOM): set attributes, styles, properties, HTML or text content, and more. Using the data join’s enter and exit selections, you can also add or remove elements to correspond to data. Imagine we have a simple html page as following. <html> <head> <title>My sample HTML page</title> </head> <body> <h1>D3.js</h3> <p>I'm using D3.js here !</p> <p>We all are using D3.js here !</p> <script src="https://d3js.org/d3.v5.min.js"></script> <script> d3.select('h1').style('color', 'green'); d3.selectAll('p').style('font-size', '30px'); </script> </body></html> There are few important thing that you should notice here. So there are two keywords used here. Both of those use the element name as the parameter. First one d3.select() method returns the first selection of DOM element matching the given parameter. So in the above example it will be <h1>D3.js</h3>. The second method is d3.selectAll() which returns all the html elements corresponding to the given parameter. If it does not find any <p> tags, it will return an empty selection. In the given example <p>I’m using D3.js here !</p> and <p>We all are using D3.js here !</p> both will be returned. Further you can get a look at the manipulations that are done as well after selecting the DOM elements. We can change the styling or even the text displayed. So in our example, when this is rendered the header “D3.js” would be in green color. You can look in to more details on selection here. Another main concept of D3 is mapping a set of data to the DOM elements in a dynamic manner. Here we can introduce a datasets and then we can update, append and display the DOM elements using those datasets, realtime. let dataset = [1,2,3,4,5] d3.selectAll(‘p’) //Select 'p' element.data(dataset) //data()puts data into waiting for processing.enter() //take data elements one by one.append(‘p’) //for each data item appending <p>.text(‘Sample text’); //add sample text to each This will render the text “sample text” 5 times in the front end. This is only a simple example to show that we can use data to manipulate the elements dynamically and real time. There are a lot of things that can be done using this same concept. Since we are now quite comfortable with the basic concepts of D3 we can go for the data visualization components which consists of various types of graphs, data tables and other visualizations. Scalable Vector Graphics (SVG) is a way to render graphical elements and images in the DOM. As SVG is vector-based, it’s both lightweight and scalable. D3 uses SVG to create all its visuals such as graphs. The great thing about using SVGs is we don’t have to worry about distortion in scaling the visuals unlike in other formats. Basically D3 helps us to bridge the gap between the data and the relevant visualizations to give the users meaningful information. Let’s start with creating a simple Bar chart using D3.js. You need two files named index.html, script.js and style.css as below to try this out. index.html <html><head><link rel=”stylesheet” href=”style.css”><title>My sample D3.js App</title></head><body><h1>Bar Chart using D3.js</h1><svg width=”500" height=”800" class=”bar-chart”></svg><script src=”https://d3js.org/d3.v5.min.js"></script><script src=”script.js”></script></body></html> script.js var dataset = [28, 40, 56, 50, 75, 90, 120, 120, 100];var chartWidth = 500, chartHeight = 300, barPadding = 5;var barWidth = (chartWidth / dataset.length);var svg = d3.select(‘svg’).attr(“width”, chartWidth).attr(“height”, chartHeight);var barChart = svg.selectAll(“rect”).data(dataset).enter().append(“rect”).attr(“y”, function(d) {return chartHeight — d}).attr(“height”, function(d) {return d;}).attr(“width”, barWidth — barPadding).attr(“fill”, ‘#F2BF23’).attr(“transform”, function (d, i) {var translate = [barWidth * i, 0];return “translate(“+ translate +”)”;}); style.css .bar-chart {background-color: #071B52;} The resulting bar chart would like something like this. This shows the visualization but there is no precise information other than the trend. So our next task is to add some labels so that the values of each bar will be visible giving more information on visuals. For that you can add following code snippet add the end of the script.js file. script.js var text = svg.selectAll(“text”).data(dataset).enter().append(“text”).text(function(d) {return d;}).attr(“y”, function(d, i) {return chartHeight — d — 2;}).attr(“x”, function(d, i) {return barWidth * i + 10;}).attr(“fill”, “#A64C38”); This will result something like below showing the values. Now what are going to do is add scaling to our chart. You can have various values in your data set; some can be really small and some can be really large. So for better visualizations with consistency it’s important to have scaling in your chart. If we rearrange our dataset as below you can see how the bar chart is rendered. var dataset = [2, 4, 5, 5, 7, 9, 12, 9, 10]; So this way we can barely see the bars in the chart. So we have to scale it up according to the chart height. If you have larger values in your dataset it will be not shown the accurate height within the given chart height. So the solution for this is scaling accordingly. For that we can use a scaler like this and change the bar chart. script.js var dataset = [2, 4, 5, 5, 7, 9, 12, 9, 10];var chartWidth = 500, chartHeight = 300, barPadding = 5;var barWidth = (chartWidth / dataset.length);var svg = d3.select(‘svg’).attr(“width”, chartWidth).attr(“height”, chartHeight);var yScale = d3.scaleLinear().domain([0, d3.max(dataset)]).range([0, chartHeight])var barChart = svg.selectAll(“rect”).data(dataset).enter().append(“rect”).attr(“y”, function(d) {return chartHeight — yScale(d);}).attr(“height”, function(d) {return yScale(d);}).attr(“width”, barWidth — barPadding).attr(“fill”, ‘#F2BF23’).attr(“transform”, function (d, i) {var translate = [barWidth * i, 0];return “translate(“+ translate +”)”;});var text = svg.selectAll(“text”).data(dataset).enter().append(“text”).text(function(d) {return d;}).attr(“y”, function(d, i) {return chartHeight — yScale(d) — 2;}).attr(“x”, function(d, i) {return barWidth * i + 10;}).attr(“fill”, “#A64C38”); So now it’s quite obvious that axes are missing out in our chart. So it’s really simple to add axes to our graph using D3.js. You can create x-axis and y-axis using x-scale and y-scale in D3.js. You can create a scaled graph with labels using following code snippet. script.js var dataset = [2, 4, 5, 5, 7, 9, 12, 9, 10];var chartWidth = 500, chartHeight = 300, barPadding = 6;var barWidth = (chartWidth / dataset.length -14);var svg = d3.select(‘svg’).attr(“width”, chartWidth).attr(“height”, chartHeight);var xScale = d3.scaleLinear().domain([0, d3.max(dataset)]).range([0, chartWidth]);var yScale = d3.scaleLinear().domain([0, d3.max(dataset)]).range([0,chartHeight — 28]);var yScaleChart = d3.scaleLinear().domain([0, d3.max(dataset)]).range([chartHeight — 28, 0]);var barChart = svg.selectAll(“rect”).data(dataset).enter().append(“rect”).attr(“y”, function(d) {return chartHeight — yScale(d) — 20;}).attr(“height”, function(d) {return yScale(d);}).attr(“width”, barWidth — barPadding).attr(“fill”, ‘#F2BF23’).attr(“transform”, function (d, i) {var translate = [barWidth * i +55, 0];return “translate(“+ translate +”)”;});var text = svg.selectAll(“text”).data(dataset).enter().append(“text”).text(function(d) {return d;}).attr(“y”, function(d, i) {return chartHeight — yScale(d) — 20;}).attr(“x”, function(d, i) {return barWidth * i + 70;}).attr(“fill”, “#A64C38”);var x_axis = d3.axisBottom().scale(xScale);var y_axis = d3.axisLeft().scale(yScaleChart);svg.append(“g”).attr(“transform”, “translate(50, 10)”).call(y_axis);var xAxisTranslate = chartHeight — 20;svg.append(“g”).attr(“transform”, “translate(50, “ + xAxisTranslate +”)”).call(x_axis); style.css .bar-chart {background-color: beige;} So like above simple bar chart we can create many types of graphs we want. The best thing here is the control we have over what we create. Unlike other ready-made graphs which has are limited-customizable, we can have the freedom of creating our own graphs using SVGs in D3.js. D3 solves the cause of the problem: efficient manipulation of documents based on data. This avoids proprietary representation and affords extraordinary flexibility, exposing the full capabilities of web standards such as HTML, SVG, and CSS. With minimal overhead, D3 is extremely fast, supporting large datasets and dynamic behaviors for interaction and animation. You can have a look at the already created complex and attractive graphs at D3.js graph gallery. Whereas most people will refer to D3.js as a data visualization library, it’s not. D3 is more of a framework comprising different parts such as jQuery parts (which help us select and manipulate DOM elements), Lodash parts, animation parts, data analysis parts, and data visualization parts. Try data visualizations with D3.js and share the results with me!
[ { "code": null, "e": 497, "s": 172, "text": "Have you ever walked into a packed stadium or a musical show and tried to guess how many people were surrounding you? Were you way off? Analyzing high-volume data can be overwhelming. But, when you take abstract data points and convert them into an accurate, sizable visual, you will be able able to see things analytically." }, { "code": null, "e": 1031, "s": 497, "text": "This is the era of information where we have more than enough data, but only few know what to do with those data. People rely on their sight far more than on anything else. That’s why data presented visually is more convincing than plain numbers. Excellent visualization can grab attention of the people, while endless columns and rows of numbers can only confuse them. To make these visualizations and analytics possible we need frameworks or libraries to existing languages to make this possible. That where D3.js comes in to play." }, { "code": null, "e": 1360, "s": 1031, "text": "D3 stands for Data-Driven Documents. If you are planning to create custom visualizations on the web, chances are that you’d have already heard about D3.js. A web based visualization library that features a plethora of APIs to handle the heavy lifting of creating advanced, dynamic and beautiful visualization content on the web." }, { "code": null, "e": 1718, "s": 1360, "text": "D3.js is a JavaScript library for manipulating documents based on data. D3.js helps you bring data to life using HTML, SVG, and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation." }, { "code": null, "e": 1947, "s": 1718, "text": "The main task that’s done by D3 is that it allows to bind any kind of data you want to DOM and then making the data-driven transformations to it resulting in easy to build and interactive data visualizations in your application." }, { "code": null, "e": 2085, "s": 1947, "text": "The Github repository of D3 and the API documentation which is used by D3 is also good sources if you are interested to have a deep dive." }, { "code": null, "e": 2353, "s": 2085, "text": "Let’s start using D3.js now. You can open your IDE or editor and create a file named index.html just to play around with D3.js. Using this library for our application is as easy as adding the link directly to get the latest release as below in index.html you created:" }, { "code": null, "e": 2407, "s": 2353, "text": "<script src=\"https://d3js.org/d3.v5.min.js\"></script>" }, { "code": null, "e": 2493, "s": 2407, "text": "So now you’re ready to use D3.js and all of it’s features in your sample application." }, { "code": null, "e": 2961, "s": 2493, "text": "Selection means selecting the html element from their name or css selectors. (eg: h2, p ) Then after selecting the elements we can use D3 to manipulate and transform those html elements the way we want. Selections allow powerful data-driven transformation of the document object model (DOM): set attributes, styles, properties, HTML or text content, and more. Using the data join’s enter and exit selections, you can also add or remove elements to correspond to data." }, { "code": null, "e": 3010, "s": 2961, "text": "Imagine we have a simple html page as following." }, { "code": null, "e": 3417, "s": 3010, "text": "<html> <head> <title>My sample HTML page</title> </head> <body> <h1>D3.js</h3> <p>I'm using D3.js here !</p> <p>We all are using D3.js here !</p> <script src=\"https://d3js.org/d3.v5.min.js\"></script> <script> d3.select('h1').style('color', 'green'); d3.selectAll('p').style('font-size', '30px'); </script> </body></html>" }, { "code": null, "e": 4013, "s": 3417, "text": "There are few important thing that you should notice here. So there are two keywords used here. Both of those use the element name as the parameter. First one d3.select() method returns the first selection of DOM element matching the given parameter. So in the above example it will be <h1>D3.js</h3>. The second method is d3.selectAll() which returns all the html elements corresponding to the given parameter. If it does not find any <p> tags, it will return an empty selection. In the given example <p>I’m using D3.js here !</p> and <p>We all are using D3.js here !</p> both will be returned." }, { "code": null, "e": 4256, "s": 4013, "text": "Further you can get a look at the manipulations that are done as well after selecting the DOM elements. We can change the styling or even the text displayed. So in our example, when this is rendered the header “D3.js” would be in green color." }, { "code": null, "e": 4307, "s": 4256, "text": "You can look in to more details on selection here." }, { "code": null, "e": 4525, "s": 4307, "text": "Another main concept of D3 is mapping a set of data to the DOM elements in a dynamic manner. Here we can introduce a datasets and then we can update, append and display the DOM elements using those datasets, realtime." }, { "code": null, "e": 4823, "s": 4525, "text": "let dataset = [1,2,3,4,5] d3.selectAll(‘p’) //Select 'p' element.data(dataset) //data()puts data into waiting for processing.enter() //take data elements one by one.append(‘p’) //for each data item appending <p>.text(‘Sample text’); //add sample text to each" }, { "code": null, "e": 5070, "s": 4823, "text": "This will render the text “sample text” 5 times in the front end. This is only a simple example to show that we can use data to manipulate the elements dynamically and real time. There are a lot of things that can be done using this same concept." }, { "code": null, "e": 5264, "s": 5070, "text": "Since we are now quite comfortable with the basic concepts of D3 we can go for the data visualization components which consists of various types of graphs, data tables and other visualizations." }, { "code": null, "e": 5725, "s": 5264, "text": "Scalable Vector Graphics (SVG) is a way to render graphical elements and images in the DOM. As SVG is vector-based, it’s both lightweight and scalable. D3 uses SVG to create all its visuals such as graphs. The great thing about using SVGs is we don’t have to worry about distortion in scaling the visuals unlike in other formats. Basically D3 helps us to bridge the gap between the data and the relevant visualizations to give the users meaningful information." }, { "code": null, "e": 5870, "s": 5725, "text": "Let’s start with creating a simple Bar chart using D3.js. You need two files named index.html, script.js and style.css as below to try this out." }, { "code": null, "e": 5881, "s": 5870, "text": "index.html" }, { "code": null, "e": 6165, "s": 5881, "text": "<html><head><link rel=”stylesheet” href=”style.css”><title>My sample D3.js App</title></head><body><h1>Bar Chart using D3.js</h1><svg width=”500\" height=”800\" class=”bar-chart”></svg><script src=”https://d3js.org/d3.v5.min.js\"></script><script src=”script.js”></script></body></html>" }, { "code": null, "e": 6175, "s": 6165, "text": "script.js" }, { "code": null, "e": 6743, "s": 6175, "text": "var dataset = [28, 40, 56, 50, 75, 90, 120, 120, 100];var chartWidth = 500, chartHeight = 300, barPadding = 5;var barWidth = (chartWidth / dataset.length);var svg = d3.select(‘svg’).attr(“width”, chartWidth).attr(“height”, chartHeight);var barChart = svg.selectAll(“rect”).data(dataset).enter().append(“rect”).attr(“y”, function(d) {return chartHeight — d}).attr(“height”, function(d) {return d;}).attr(“width”, barWidth — barPadding).attr(“fill”, ‘#F2BF23’).attr(“transform”, function (d, i) {var translate = [barWidth * i, 0];return “translate(“+ translate +”)”;});" }, { "code": null, "e": 6753, "s": 6743, "text": "style.css" }, { "code": null, "e": 6793, "s": 6753, "text": ".bar-chart {background-color: #071B52;}" }, { "code": null, "e": 6849, "s": 6793, "text": "The resulting bar chart would like something like this." }, { "code": null, "e": 7058, "s": 6849, "text": "This shows the visualization but there is no precise information other than the trend. So our next task is to add some labels so that the values of each bar will be visible giving more information on visuals." }, { "code": null, "e": 7137, "s": 7058, "text": "For that you can add following code snippet add the end of the script.js file." }, { "code": null, "e": 7147, "s": 7137, "text": "script.js" }, { "code": null, "e": 7382, "s": 7147, "text": "var text = svg.selectAll(“text”).data(dataset).enter().append(“text”).text(function(d) {return d;}).attr(“y”, function(d, i) {return chartHeight — d — 2;}).attr(“x”, function(d, i) {return barWidth * i + 10;}).attr(“fill”, “#A64C38”);" }, { "code": null, "e": 7440, "s": 7382, "text": "This will result something like below showing the values." }, { "code": null, "e": 7687, "s": 7440, "text": "Now what are going to do is add scaling to our chart. You can have various values in your data set; some can be really small and some can be really large. So for better visualizations with consistency it’s important to have scaling in your chart." }, { "code": null, "e": 7767, "s": 7687, "text": "If we rearrange our dataset as below you can see how the bar chart is rendered." }, { "code": null, "e": 7812, "s": 7767, "text": "var dataset = [2, 4, 5, 5, 7, 9, 12, 9, 10];" }, { "code": null, "e": 8150, "s": 7812, "text": "So this way we can barely see the bars in the chart. So we have to scale it up according to the chart height. If you have larger values in your dataset it will be not shown the accurate height within the given chart height. So the solution for this is scaling accordingly. For that we can use a scaler like this and change the bar chart." }, { "code": null, "e": 8160, "s": 8150, "text": "script.js" }, { "code": null, "e": 9059, "s": 8160, "text": "var dataset = [2, 4, 5, 5, 7, 9, 12, 9, 10];var chartWidth = 500, chartHeight = 300, barPadding = 5;var barWidth = (chartWidth / dataset.length);var svg = d3.select(‘svg’).attr(“width”, chartWidth).attr(“height”, chartHeight);var yScale = d3.scaleLinear().domain([0, d3.max(dataset)]).range([0, chartHeight])var barChart = svg.selectAll(“rect”).data(dataset).enter().append(“rect”).attr(“y”, function(d) {return chartHeight — yScale(d);}).attr(“height”, function(d) {return yScale(d);}).attr(“width”, barWidth — barPadding).attr(“fill”, ‘#F2BF23’).attr(“transform”, function (d, i) {var translate = [barWidth * i, 0];return “translate(“+ translate +”)”;});var text = svg.selectAll(“text”).data(dataset).enter().append(“text”).text(function(d) {return d;}).attr(“y”, function(d, i) {return chartHeight — yScale(d) — 2;}).attr(“x”, function(d, i) {return barWidth * i + 10;}).attr(“fill”, “#A64C38”);" }, { "code": null, "e": 9326, "s": 9059, "text": "So now it’s quite obvious that axes are missing out in our chart. So it’s really simple to add axes to our graph using D3.js. You can create x-axis and y-axis using x-scale and y-scale in D3.js. You can create a scaled graph with labels using following code snippet." }, { "code": null, "e": 9336, "s": 9326, "text": "script.js" }, { "code": null, "e": 10711, "s": 9336, "text": "var dataset = [2, 4, 5, 5, 7, 9, 12, 9, 10];var chartWidth = 500, chartHeight = 300, barPadding = 6;var barWidth = (chartWidth / dataset.length -14);var svg = d3.select(‘svg’).attr(“width”, chartWidth).attr(“height”, chartHeight);var xScale = d3.scaleLinear().domain([0, d3.max(dataset)]).range([0, chartWidth]);var yScale = d3.scaleLinear().domain([0, d3.max(dataset)]).range([0,chartHeight — 28]);var yScaleChart = d3.scaleLinear().domain([0, d3.max(dataset)]).range([chartHeight — 28, 0]);var barChart = svg.selectAll(“rect”).data(dataset).enter().append(“rect”).attr(“y”, function(d) {return chartHeight — yScale(d) — 20;}).attr(“height”, function(d) {return yScale(d);}).attr(“width”, barWidth — barPadding).attr(“fill”, ‘#F2BF23’).attr(“transform”, function (d, i) {var translate = [barWidth * i +55, 0];return “translate(“+ translate +”)”;});var text = svg.selectAll(“text”).data(dataset).enter().append(“text”).text(function(d) {return d;}).attr(“y”, function(d, i) {return chartHeight — yScale(d) — 20;}).attr(“x”, function(d, i) {return barWidth * i + 70;}).attr(“fill”, “#A64C38”);var x_axis = d3.axisBottom().scale(xScale);var y_axis = d3.axisLeft().scale(yScaleChart);svg.append(“g”).attr(“transform”, “translate(50, 10)”).call(y_axis);var xAxisTranslate = chartHeight — 20;svg.append(“g”).attr(“transform”, “translate(50, “ + xAxisTranslate +”)”).call(x_axis);" }, { "code": null, "e": 10721, "s": 10711, "text": "style.css" }, { "code": null, "e": 10759, "s": 10721, "text": ".bar-chart {background-color: beige;}" }, { "code": null, "e": 11037, "s": 10759, "text": "So like above simple bar chart we can create many types of graphs we want. The best thing here is the control we have over what we create. Unlike other ready-made graphs which has are limited-customizable, we can have the freedom of creating our own graphs using SVGs in D3.js." }, { "code": null, "e": 11402, "s": 11037, "text": "D3 solves the cause of the problem: efficient manipulation of documents based on data. This avoids proprietary representation and affords extraordinary flexibility, exposing the full capabilities of web standards such as HTML, SVG, and CSS. With minimal overhead, D3 is extremely fast, supporting large datasets and dynamic behaviors for interaction and animation." }, { "code": null, "e": 11499, "s": 11402, "text": "You can have a look at the already created complex and attractive graphs at D3.js graph gallery." }, { "code": null, "e": 11790, "s": 11499, "text": "Whereas most people will refer to D3.js as a data visualization library, it’s not. D3 is more of a framework comprising different parts such as jQuery parts (which help us select and manipulate DOM elements), Lodash parts, animation parts, data analysis parts, and data visualization parts." } ]
Java ResultSet afterLast() method with example
When we execute certain SQL queries (SELECT query in general) they return tabular data. The java.sql.ResultSet interface represents such tabular data returned by the SQL statements. i.e. the ResultSet object holds the tabular data returned by the methods that execute the statements which quires the database (executeQuery() method of the Statement interface in general). The ResultSet object has a cursor/pointer which points to the current row. Initially this cursor is positioned before first row. The afterLast() method of the ResultSet interface moves the pointer/cursor of the current ResultSet object to next position of the last row. rs.afterLast(); Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below: CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), PRIMARY KEY (ID) ); Now, we will insert 7 records in MyPlayers table using INSERT statements: insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England'); Following JDBC program establishes connection with the database, retrieves the contents of the table MyPlayers into a ResultSet object moves the position of the ResultSet pointer next to the last row using the afterLast() method and, prints the contents of the table form last to first. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ResultSet_afterLast { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating the Statement Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); //Query to retrieve records String query = "Select * from MyPlayers"; //Executing the query ResultSet rs = stmt.executeQuery(query); //Moving the cursor position to next to the last row rs.afterLast(); System.out.println("Contents of the MyPlayers table from last to first: "); //Printing the contents of the ResultSet object from last to first while(rs.previous()) { System.out.print("ID: "+rs.getInt("ID")+", "); System.out.print("Name: "+rs.getString("First_Name")+", "); System.out.print("Age: "+rs.getString("Last_Name")+", "); System.out.print("Salary: "+rs.getDate("Date_Of_Birth")+", "); System.out.print("Country: "+rs.getString("Place_Of_Birth")+", "); System.out.print("Address: "+rs.getString("Country")); System.out.println(); } System.out.println(); } } Connection established...... Contents of the MyPlayers table: Contents of the MyPlayers table from last to first: ID: 8, Name: Ryan, Age: McLaren, Salary: 1983-02-09, Country: Kumberly, Address: null ID: 7, Name: James, Age: Anderson, Salary: 1982-06-30, Country: Burnley , Address: England ID: 6, Name: Ravindra, Age: Jadeja, Salary: 1988-12-06, Country: Nagpur, Address: India ID: 5, Name: Rohit, Age: Sharma, Salary: 1987-04-30, Country: Nagpur, Address: India ID: 4, Name: Virat, Age: Kohli, Salary: 1988-11-05, Country: Mumbai, Address: India ID: 3, Name: Kumara, Age: Sangakkara, Salary: 1977-10-27, Country: Matale, Address: Srilanka ID: 2, Name: Jonathan, Age: Trott, Salary: 1981-04-22, Country: CapeTown, Address: SouthAfrica ID: 1, Name: Shikhar, Age: Dhawan, Salary: 1981-12-05, Country: Delhi, Address: India
[ { "code": null, "e": 1150, "s": 1062, "text": "When we execute certain SQL queries (SELECT query in general) they return tabular data." }, { "code": null, "e": 1244, "s": 1150, "text": "The java.sql.ResultSet interface represents such tabular data returned by the SQL statements." }, { "code": null, "e": 1434, "s": 1244, "text": "i.e. the ResultSet object holds the tabular data returned by the methods that execute the statements which quires the database (executeQuery() method of the Statement interface in general)." }, { "code": null, "e": 1563, "s": 1434, "text": "The ResultSet object has a cursor/pointer which points to the current row. Initially this cursor is positioned before first row." }, { "code": null, "e": 1704, "s": 1563, "text": "The afterLast() method of the ResultSet interface moves the pointer/cursor of the current ResultSet object to next position of the last row." }, { "code": null, "e": 1720, "s": 1704, "text": "rs.afterLast();" }, { "code": null, "e": 1820, "s": 1720, "text": "Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below: " }, { "code": null, "e": 2013, "s": 1820, "text": "CREATE TABLE MyPlayers(\n ID INT,\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Date_Of_Birth date,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255),\n PRIMARY KEY (ID)\n);" }, { "code": null, "e": 2087, "s": 2013, "text": "Now, we will insert 7 records in MyPlayers table using INSERT statements:" }, { "code": null, "e": 2749, "s": 2087, "text": "insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\ninsert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\ninsert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\ninsert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\ninsert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');\ninsert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');\ninsert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');" }, { "code": null, "e": 3036, "s": 2749, "text": "Following JDBC program establishes connection with the database, retrieves the contents of the table MyPlayers into a ResultSet object moves the position of the ResultSet pointer next to the last row using the afterLast() method and, prints the contents of the table form last to first." }, { "code": null, "e": 4644, "s": 3036, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class ResultSet_afterLast {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);\n //Query to retrieve records\n String query = \"Select * from MyPlayers\";\n //Executing the query\n ResultSet rs = stmt.executeQuery(query);\n //Moving the cursor position to next to the last row\n rs.afterLast();\n System.out.println(\"Contents of the MyPlayers table from last to first: \");\n //Printing the contents of the ResultSet object from last to first\n while(rs.previous()) {\n System.out.print(\"ID: \"+rs.getInt(\"ID\")+\", \");\n System.out.print(\"Name: \"+rs.getString(\"First_Name\")+\", \");\n System.out.print(\"Age: \"+rs.getString(\"Last_Name\")+\", \");\n System.out.print(\"Salary: \"+rs.getDate(\"Date_Of_Birth\")+\", \");\n System.out.print(\"Country: \"+rs.getString(\"Place_Of_Birth\")+\", \");\n System.out.print(\"Address: \"+rs.getString(\"Country\"));\n System.out.println();\n }\n System.out.println();\n }\n}" }, { "code": null, "e": 5466, "s": 4644, "text": "Connection established......\nContents of the MyPlayers table:\nContents of the MyPlayers table from last to first:\nID: 8, Name: Ryan, Age: McLaren, Salary: 1983-02-09, Country: Kumberly, Address: null\nID: 7, Name: James, Age: Anderson, Salary: 1982-06-30, Country: Burnley , Address: England\nID: 6, Name: Ravindra, Age: Jadeja, Salary: 1988-12-06, Country: Nagpur, Address: India\nID: 5, Name: Rohit, Age: Sharma, Salary: 1987-04-30, Country: Nagpur, Address: India\nID: 4, Name: Virat, Age: Kohli, Salary: 1988-11-05, Country: Mumbai, Address: India\nID: 3, Name: Kumara, Age: Sangakkara, Salary: 1977-10-27, Country: Matale, Address: Srilanka\nID: 2, Name: Jonathan, Age: Trott, Salary: 1981-04-22, Country: CapeTown, Address: SouthAfrica\nID: 1, Name: Shikhar, Age: Dhawan, Salary: 1981-12-05, Country: Delhi, Address: India" } ]
Find All Four Sum Numbers | Practice | GeeksforGeeks
Given an array of integers and another number. Find all the unique quadruple from the given array that sums up to the given number. Example 1: Input: N = 5, K = 3 A[] = {0,0,2,1,1} Output: 0 0 1 2 $ Explanation: Sum of 0, 0, 1, 2 is equal to K. Example 2: Input: N = 7, K = 23 A[] = {10,2,3,4,5,7,8} Output: 2 3 8 10 $2 4 7 10 $3 5 7 8 $ Explanation: Sum of 2, 3, 8, 10 = 23, sum of 2, 4, 7, 10 = 23 and sum of 3, 5, 7, 8 = 23. Your Task: You don't need to read input or print anything. Your task is to complete the function fourSum() which takes the array arr[] and the integer k as its input and returns an array containing all the quadruples in a lexicographical manner. Also note that all the quadruples should be internally sorted, ie for any quadruple [q1, q2, q3, q4] the following should follow: q1 <= q2 <= q3 <= q4. (In the output each quadruple is separate by $. The printing is done by the driver's code) Expected Time Complexity: O(N3). Expected Auxiliary Space: O(N2). Constraints: 1 <= N <= 100 -1000 <= K <= 1000 -100 <= A[] <= 100 0 ashwini12920034 days ago #include<stdio.h> void main() { int a,b,c,d; printf("enter the four values to be added"); scanf("%d",&a,&b,&c,&d); sum=a+b+c+d; printf("the sum of four numbers are",sum) } 0 sahum67031 week ago vector<vector<int> > fourSum(vector<int> &arr, int k) { sort(arr.begin(),arr.end()); vector<vector<int>> ans; unordered_map<int,int> mp; set<vector<int>> st; int n=arr.size(); for(int i=0;i+3<n;i++){ for(int j=i+1;j+2<n;j++){ for(int k=j+1;k+1<n;k++){ int b=k-arr[i]+arr[j]+arr[k]; if(mp[b]){ vector<int> v; v.push_back(arr[i]); v.push_back(arr[j]); v.push_back(arr[k]); v.push_back(b); st.insert(v); } } } mp[arr[i]]++; } for(auto it: st) ans.push_back(it); return ans; } ``` why is this giving seg fault? 0 peehugandhi2 weeks ago it is giving wrong output vector<vector<int> > fourSum(vector<int> &arr, int k) { sort(arr.begin(),arr.end()); set<vector<int>> st; vector<vector<int>> ans; for(int i=0;i<arr.size()-3;i++) { int prevtar=k-arr[i]; //find-=arr[i]; for(int j=i+1;j<arr.size()-2;j++) { int target=prevtar-arr[j]; //find-=arr[j]; int k=j+1; int l=arr.size()-1; while(k<l) { int cs=arr[k]+arr[l] ; if(arr[k]+arr[l] == target) { vector<int> v; v.push_back(arr[i]); v.push_back(arr[j]); v.push_back(arr[k]); v.push_back(arr[l]); st.insert(v); break; } else if(arr[k] + arr[l] < target) { k++; } else l--; } } } for(auto it:st) { ans.push_back(it); } r 0 putyavka2 weeks ago Mapping used. class Solution{ public: vector<vector<int> > fourSum(vector<int> &arr, int k) { const int MIN = -100; const int MAX = 100; int N = arr.size(); sort(arr.begin(), arr.end()); vector<int> map(MAX - MIN + 1, -1); for (int i = 0; i < N; i++) map[arr[i] - MIN] = i; vector<vector<int>> res; for (int i = 0; i < N - 3; i++) { int arr_i = arr[i]; for (int j = i + 1; j < N - 2; j++) { int arr_j = arr[j]; for (int m = j + 1; m < N - 1; m++) { int arr_m = arr[m]; int v = k - (arr_i + arr_j + arr_m); if (v < MIN || v > MAX) continue; int n = map[v - MIN]; if (n > m) { vector<int> q = {arr_i, arr_j, arr_m, arr[n]}; if (!res.size() || res[res.size() - 1] < q) res.push_back(q); } } } } return res; }}; +2 sachinupreti1902 weeks ago Happy to share this, As i made this correct in first attempt, Instead of I am beginner in Competitive programming. class Solution{ public: // arr[] : int input array of integers // k : the quadruple sum required vector<vector<int> > fourSum(vector<int> &arr, int k) { // Your code goes here vector<vector<int>>vec; vector<int>v; int i,b,s,j,l; unordered_map<int,int>m1; // for(i=0;i<arr.size();i++) // m1[arr[i]]++; for(i=0;i<arr.size();i++) { for(j=i+1;j<arr.size();j++) { for(l=j+1;l<arr.size();l++) { b=k-(arr[i]+arr[j]+arr[l]); if(m1[b]) { v.push_back(arr[i]); v.push_back(arr[j]); v.push_back(arr[l]); v.push_back(b); // v.push_back($); sort(v.begin(),v.end()); vec.push_back(v); v.clear(); } } } m1[arr[i]]++; } vector<vector<int>>fin; set<vector<int>>se; for(i=0;i<vec.size();i++) { se.insert(vec[i]); } set<vector<int>>::iterator it; for(it=se.begin();it!=se.end();++it) { fin.push_back(*it); } return fin; } }; 0 divyagupta92 weeks ago Simple Java Solution with time complexity : O(n3) public ArrayList<ArrayList<Integer>> fourSum(int[] arr, int k) { int l, r; int n = arr.length; Arrays.sort(arr); ArrayList<ArrayList<Integer>> ans = new ArrayList<>(); HashSet<ArrayList<Integer>> set = new HashSet<>(); if(n<4){ return ans; } for(int i=0;i<n-3;i++){ for(int j=i+1;j<n-2;j++){ l = j+1; r = n-1; while(l<r){ if(arr[i]+arr[j]+arr[l]+arr[r]==k){ ArrayList<Integer> list = new ArrayList<>(); list.add(arr[i]); list.add(arr[j]); list.add(arr[l]); list.add(arr[r]); if(!set.contains(list)){ ans.add(list); set.add(list); } l++; r--; }else if(arr[i]+arr[j]+arr[l]+arr[r]<k){ l++; }else{ r--; } } } } return ans; } 0 joyrockok3 weeks ago class Solution { public ArrayList<ArrayList<Integer>> fourSum(int[] arr, int k) { // code here int N = arr.length; Arrays.sort(arr); ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>(); HashSet<ArrayList<Integer>> subResult = new HashSet<ArrayList<Integer>>(); ArrayList<Integer> sortList; for(int i=0; i<N-3; i++) { for(int j=i+1; j<N-2; j++) { for(int p=j+1; p<N-1; p++) { for(int r=p+1; r<N; r++) { if(arr[i] + arr[j] + arr[p] + arr[r] == k) { sortList = new ArrayList<Integer>(); sortList.add(arr[i]); sortList.add(arr[j]); sortList.add(arr[p]); sortList.add(arr[r]); // Collections.sort(sortList); int size = subResult.size(); subResult.add(sortList); if(size != subResult.size()) { resultList.add(sortList); } } } } } } return resultList; }} 0 chintankothari20003 weeks ago vector<vector<int> > fourSum(vector<int> &arr, int k) { // Your code goes here vector<vector<int> > ans; int n=arr.size(); sort(begin(arr),end(arr)); for(int i=0;(i+3)<n;i++){ for(int j=i+1;(j+2)<n;j++){ int target=k-arr[i]-arr[j]; int k=j+1,l=n-1; while(k<l){ int sum=arr[k]+arr[l]; if(target==sum){ ans.push_back({arr[i],arr[j],arr[k],arr[l]}); k++,l--; while(arr[k]==arr[k-1] and arr[l+1]==arr[l]) k++,l--; } else if(sum>target) l--; else k++; } while(j+1<n and arr[j]==arr[j+1]) j++; } while(i+1<n and arr[i]==arr[i+1]) i++; } return ans; } 0 jayesh293 weeks ago Easy Java solution public ArrayList<ArrayList<Integer>> fourSum(int[] arr, int key) { ArrayList<ArrayList<Integer>> al = new ArrayList<>(); int n=arr.length; if(arr==null || n==0) return al; Arrays.sort(arr); for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ int sum_i_j = key-arr[j]-arr[i]; int lo = j+1, hi= n-1; while(lo<hi){ int temp_sum = arr[lo]+arr[hi]; if(temp_sum<sum_i_j) lo++; else if(temp_sum>sum_i_j) hi--; else{ ArrayList<Integer> sub = new ArrayList<>(); sub.add(arr[i]); sub.add(arr[j]); sub.add(arr[lo]); sub.add(arr[hi]); al.add(sub); while(lo<hi && arr[lo]==sub.get(2)) ++lo; while(lo<hi && arr[hi]==sub.get(3)) --hi; } } while(j+1<n && arr[j+1]==arr[j]) ++j; } while(i+1<n && arr[i+1]==arr[i]) ++i; } return al; } 0 rohitsingh0000653 weeks ago GENERIC SOLUTION FOR ALL USING KSUM class Solution { public ArrayList<ArrayList<Integer>> fourSum(int[] arr, int k) { Arrays.sort(arr); return solve(arr, k, 0, 4); } private ArrayList<ArrayList<Integer>> solve(int[] arr, int target, int start, int k){ ArrayList<ArrayList<Integer>> ans = new ArrayList<>(); int n = arr.length; int avg = target/k; if(k <= 0 || start >= n || arr[start] > avg || avg > arr[n-1]) return ans; if(k == 2){ return twoSum(arr, target, start); } for(int i = start; i < n; i++){ if(i == start || arr[i] != arr[i-1]){ ArrayList<ArrayList<Integer>> subList = solve(arr, target-arr[i], i+1, k-1); for(ArrayList<Integer> list : subList){ list.add(0, arr[i]); ans.add(list); } } } return ans; } private ArrayList<ArrayList<Integer>> twoSum(int[] nums, int target, int start){ ArrayList<ArrayList<Integer>> results = new ArrayList<>(); int n = nums.length; int lo = start, hi = n - 1; while (lo < hi) { int currSum = nums[lo] + nums[hi]; if (currSum < target || (lo > start && nums[lo] == nums[lo - 1])) { lo++; } else if (currSum > target || (hi < n - 1 && nums[hi] == nums[hi + 1])) { hi--; } else { results.add(new ArrayList<>(Arrays.asList(nums[lo ++], nums[hi --]))); } } return results; } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 370, "s": 238, "text": "Given an array of integers and another number. Find all the unique quadruple from the given array that sums up to the given number." }, { "code": null, "e": 381, "s": 370, "text": "Example 1:" }, { "code": null, "e": 484, "s": 381, "text": "Input:\nN = 5, K = 3\nA[] = {0,0,2,1,1}\nOutput: 0 0 1 2 $\nExplanation: Sum of 0, 0, 1, 2 is equal\nto K.\n" }, { "code": null, "e": 495, "s": 484, "text": "Example 2:" }, { "code": null, "e": 667, "s": 495, "text": "Input:\nN = 7, K = 23\nA[] = {10,2,3,4,5,7,8}\nOutput: 2 3 8 10 $2 4 7 10 $3 5 7 8 $\nExplanation: Sum of 2, 3, 8, 10 = 23,\nsum of 2, 4, 7, 10 = 23 and sum of 3,\n5, 7, 8 = 23." }, { "code": null, "e": 1157, "s": 667, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function fourSum() which takes the array arr[] and the integer k as its input and returns an array containing all the quadruples in a lexicographical manner. Also note that all the quadruples should be internally sorted, ie for any quadruple [q1, q2, q3, q4] the following should follow: q1 <= q2 <= q3 <= q4. (In the output each quadruple is separate by $. The printing is done by the driver's code)" }, { "code": null, "e": 1223, "s": 1157, "text": "Expected Time Complexity: O(N3).\nExpected Auxiliary Space: O(N2)." }, { "code": null, "e": 1290, "s": 1223, "text": "Constraints:\n1 <= N <= 100\n-1000 <= K <= 1000\n-100 <= A[] <= 100\n " }, { "code": null, "e": 1292, "s": 1290, "text": "0" }, { "code": null, "e": 1317, "s": 1292, "text": "ashwini12920034 days ago" }, { "code": null, "e": 1335, "s": 1317, "text": "#include<stdio.h>" }, { "code": null, "e": 1347, "s": 1335, "text": "void main()" }, { "code": null, "e": 1364, "s": 1347, "text": "{ int a,b,c,d;" }, { "code": null, "e": 1412, "s": 1364, "text": " printf(\"enter the four values to be added\");" }, { "code": null, "e": 1437, "s": 1412, "text": "scanf(\"%d\",&a,&b,&c,&d);" }, { "code": null, "e": 1450, "s": 1437, "text": "sum=a+b+c+d;" }, { "code": null, "e": 1492, "s": 1450, "text": "printf(\"the sum of four numbers are\",sum)" }, { "code": null, "e": 1494, "s": 1492, "text": "}" }, { "code": null, "e": 1496, "s": 1494, "text": "0" }, { "code": null, "e": 1516, "s": 1496, "text": "sahum67031 week ago" }, { "code": null, "e": 2401, "s": 1516, "text": "vector<vector<int> > fourSum(vector<int> &arr, int k) {\n sort(arr.begin(),arr.end());\n vector<vector<int>> ans;\n unordered_map<int,int> mp;\n \n set<vector<int>> st;\n int n=arr.size();\n for(int i=0;i+3<n;i++){\n for(int j=i+1;j+2<n;j++){\n for(int k=j+1;k+1<n;k++){\n int b=k-arr[i]+arr[j]+arr[k];\n if(mp[b]){\n vector<int> v;\n v.push_back(arr[i]);\n v.push_back(arr[j]);\n v.push_back(arr[k]);\n v.push_back(b);\n st.insert(v);\n }\n }\n }\n mp[arr[i]]++;\n }\n for(auto it: st)\n ans.push_back(it);\n \n return ans;\n }\n```\nwhy is this giving seg fault?" }, { "code": null, "e": 2403, "s": 2401, "text": "0" }, { "code": null, "e": 2426, "s": 2403, "text": "peehugandhi2 weeks ago" }, { "code": null, "e": 2452, "s": 2426, "text": "it is giving wrong output" }, { "code": null, "e": 3638, "s": 2452, "text": " vector<vector<int> > fourSum(vector<int> &arr, int k) \n{\n sort(arr.begin(),arr.end());\n set<vector<int>> st;\n vector<vector<int>> ans;\n for(int i=0;i<arr.size()-3;i++)\n {\n int prevtar=k-arr[i];\n //find-=arr[i];\n for(int j=i+1;j<arr.size()-2;j++)\n {\n int target=prevtar-arr[j];\n //find-=arr[j];\n int k=j+1;\n \n int l=arr.size()-1;\n while(k<l)\n {\n int cs=arr[k]+arr[l] ;\n if(arr[k]+arr[l] == target)\n {\n vector<int> v;\n v.push_back(arr[i]);\n v.push_back(arr[j]);\n v.push_back(arr[k]);\n v.push_back(arr[l]);\n st.insert(v);\n break;\n }\n else if(arr[k] + arr[l] < target)\n {\n k++;\n }\n else l--;\n }\n }\n }\n for(auto it:st)\n {\n ans.push_back(it);\n }\n r" }, { "code": null, "e": 3640, "s": 3638, "text": "0" }, { "code": null, "e": 3660, "s": 3640, "text": "putyavka2 weeks ago" }, { "code": null, "e": 3674, "s": 3660, "text": "Mapping used." }, { "code": null, "e": 4694, "s": 3674, "text": "class Solution{ public: vector<vector<int> > fourSum(vector<int> &arr, int k) { const int MIN = -100; const int MAX = 100; int N = arr.size(); sort(arr.begin(), arr.end()); vector<int> map(MAX - MIN + 1, -1); for (int i = 0; i < N; i++) map[arr[i] - MIN] = i; vector<vector<int>> res; for (int i = 0; i < N - 3; i++) { int arr_i = arr[i]; for (int j = i + 1; j < N - 2; j++) { int arr_j = arr[j]; for (int m = j + 1; m < N - 1; m++) { int arr_m = arr[m]; int v = k - (arr_i + arr_j + arr_m); if (v < MIN || v > MAX) continue; int n = map[v - MIN]; if (n > m) { vector<int> q = {arr_i, arr_j, arr_m, arr[n]}; if (!res.size() || res[res.size() - 1] < q) res.push_back(q); } } } } return res; }};" }, { "code": null, "e": 4697, "s": 4694, "text": "+2" }, { "code": null, "e": 4724, "s": 4697, "text": "sachinupreti1902 weeks ago" }, { "code": null, "e": 4839, "s": 4724, "text": "Happy to share this, As i made this correct in first attempt, Instead of I am beginner in Competitive programming." }, { "code": null, "e": 6182, "s": 4843, "text": "class Solution{ public: // arr[] : int input array of integers // k : the quadruple sum required vector<vector<int> > fourSum(vector<int> &arr, int k) { // Your code goes here vector<vector<int>>vec; vector<int>v; int i,b,s,j,l; unordered_map<int,int>m1; // for(i=0;i<arr.size();i++) // m1[arr[i]]++; for(i=0;i<arr.size();i++) { for(j=i+1;j<arr.size();j++) { for(l=j+1;l<arr.size();l++) { b=k-(arr[i]+arr[j]+arr[l]); if(m1[b]) { v.push_back(arr[i]); v.push_back(arr[j]); v.push_back(arr[l]); v.push_back(b); // v.push_back($); sort(v.begin(),v.end()); vec.push_back(v); v.clear(); } } } m1[arr[i]]++; } vector<vector<int>>fin; set<vector<int>>se; for(i=0;i<vec.size();i++) { se.insert(vec[i]); } set<vector<int>>::iterator it; for(it=se.begin();it!=se.end();++it) { fin.push_back(*it); } return fin; } };" }, { "code": null, "e": 6186, "s": 6184, "text": "0" }, { "code": null, "e": 6209, "s": 6186, "text": "divyagupta92 weeks ago" }, { "code": null, "e": 6260, "s": 6209, "text": "Simple Java Solution with time complexity : O(n3) " }, { "code": null, "e": 7403, "s": 6260, "text": "public ArrayList<ArrayList<Integer>> fourSum(int[] arr, int k) { int l, r; int n = arr.length; Arrays.sort(arr); ArrayList<ArrayList<Integer>> ans = new ArrayList<>(); HashSet<ArrayList<Integer>> set = new HashSet<>(); if(n<4){ return ans; } for(int i=0;i<n-3;i++){ for(int j=i+1;j<n-2;j++){ l = j+1; r = n-1; while(l<r){ if(arr[i]+arr[j]+arr[l]+arr[r]==k){ ArrayList<Integer> list = new ArrayList<>(); list.add(arr[i]); list.add(arr[j]); list.add(arr[l]); list.add(arr[r]); if(!set.contains(list)){ ans.add(list); set.add(list); } l++; r--; }else if(arr[i]+arr[j]+arr[l]+arr[r]<k){ l++; }else{ r--; } } } } return ans; }" }, { "code": null, "e": 7405, "s": 7403, "text": "0" }, { "code": null, "e": 7426, "s": 7405, "text": "joyrockok3 weeks ago" }, { "code": null, "e": 8351, "s": 7426, "text": "class Solution { public ArrayList<ArrayList<Integer>> fourSum(int[] arr, int k) { // code here int N = arr.length; Arrays.sort(arr); ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>(); HashSet<ArrayList<Integer>> subResult = new HashSet<ArrayList<Integer>>(); ArrayList<Integer> sortList; for(int i=0; i<N-3; i++) { for(int j=i+1; j<N-2; j++) { for(int p=j+1; p<N-1; p++) { for(int r=p+1; r<N; r++) { if(arr[i] + arr[j] + arr[p] + arr[r] == k) { sortList = new ArrayList<Integer>(); sortList.add(arr[i]); sortList.add(arr[j]); sortList.add(arr[p]); sortList.add(arr[r]); // Collections.sort(sortList); int size = subResult.size(); subResult.add(sortList); if(size != subResult.size()) { resultList.add(sortList); } } } } } } return resultList; }}" }, { "code": null, "e": 8353, "s": 8351, "text": "0" }, { "code": null, "e": 8383, "s": 8353, "text": "chintankothari20003 weeks ago" }, { "code": null, "e": 9389, "s": 8383, "text": " vector<vector<int> > fourSum(vector<int> &arr, int k) {\n // Your code goes here\n vector<vector<int> > ans;\n int n=arr.size();\n sort(begin(arr),end(arr));\n for(int i=0;(i+3)<n;i++){\n for(int j=i+1;(j+2)<n;j++){\n int target=k-arr[i]-arr[j];\n int k=j+1,l=n-1;\n while(k<l){\n int sum=arr[k]+arr[l];\n if(target==sum){\n ans.push_back({arr[i],arr[j],arr[k],arr[l]});\n k++,l--;\n while(arr[k]==arr[k-1] and arr[l+1]==arr[l])\n k++,l--;\n }\n else if(sum>target)\n l--;\n else\n k++;\n }\n while(j+1<n and arr[j]==arr[j+1])\n j++;\n }\n while(i+1<n and arr[i]==arr[i+1])\n i++;\n }\n return ans;\n }" }, { "code": null, "e": 9391, "s": 9389, "text": "0" }, { "code": null, "e": 9411, "s": 9391, "text": "jayesh293 weeks ago" }, { "code": null, "e": 9430, "s": 9411, "text": "Easy Java solution" }, { "code": null, "e": 10641, "s": 9430, "text": " public ArrayList<ArrayList<Integer>> fourSum(int[] arr, int key) {\n ArrayList<ArrayList<Integer>> al = new ArrayList<>();\n int n=arr.length;\n if(arr==null || n==0) return al;\n Arrays.sort(arr);\n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n int sum_i_j = key-arr[j]-arr[i];\n int lo = j+1, hi= n-1;\n while(lo<hi){\n int temp_sum = arr[lo]+arr[hi];\n if(temp_sum<sum_i_j) lo++;\n else if(temp_sum>sum_i_j) hi--;\n else{\n ArrayList<Integer> sub = new ArrayList<>();\n sub.add(arr[i]);\n sub.add(arr[j]);\n sub.add(arr[lo]);\n sub.add(arr[hi]);\n al.add(sub);\n \n while(lo<hi && arr[lo]==sub.get(2)) ++lo;\n while(lo<hi && arr[hi]==sub.get(3)) --hi;\n }\n }\n while(j+1<n && arr[j+1]==arr[j]) ++j;\n }\n while(i+1<n && arr[i+1]==arr[i]) ++i;\n }\n return al;\n }" }, { "code": null, "e": 10643, "s": 10641, "text": "0" }, { "code": null, "e": 10671, "s": 10643, "text": "rohitsingh0000653 weeks ago" }, { "code": null, "e": 12328, "s": 10671, "text": "GENERIC SOLUTION FOR ALL USING KSUM\n\nclass Solution {\n public ArrayList<ArrayList<Integer>> fourSum(int[] arr, int k) {\n Arrays.sort(arr);\n return solve(arr, k, 0, 4);\n }\n \n private ArrayList<ArrayList<Integer>> solve(int[] arr, int target, int start, int k){\n ArrayList<ArrayList<Integer>> ans = new ArrayList<>();\n int n = arr.length;\n int avg = target/k;\n \n if(k <= 0 || start >= n || arr[start] > avg || avg > arr[n-1])\n return ans;\n if(k == 2){\n return twoSum(arr, target, start);\n }\n \n for(int i = start; i < n; i++){\n if(i == start || arr[i] != arr[i-1]){\n ArrayList<ArrayList<Integer>> subList = solve(arr, target-arr[i], i+1, k-1);\n for(ArrayList<Integer> list : subList){\n list.add(0, arr[i]);\n ans.add(list);\n }\n }\n }\n return ans;\n }\n \n private ArrayList<ArrayList<Integer>> twoSum(int[] nums, int target, int start){\n ArrayList<ArrayList<Integer>> results = new ArrayList<>();\n int n = nums.length;\n int lo = start, hi = n - 1;\n \n while (lo < hi) {\n int currSum = nums[lo] + nums[hi];\n if (currSum < target || (lo > start && nums[lo] == nums[lo - 1])) {\n lo++;\n } else if (currSum > target || (hi < n - 1 && nums[hi] == nums[hi + 1])) {\n hi--;\n } else {\n results.add(new ArrayList<>(Arrays.asList(nums[lo ++], nums[hi --])));\n }\n }\n return results;\n }\n}" }, { "code": null, "e": 12474, "s": 12328, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 12510, "s": 12474, "text": " Login to access your submissions. " }, { "code": null, "e": 12520, "s": 12510, "text": "\nProblem\n" }, { "code": null, "e": 12530, "s": 12520, "text": "\nContest\n" }, { "code": null, "e": 12593, "s": 12530, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 12741, "s": 12593, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 12949, "s": 12741, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 13055, "s": 12949, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to extract the residuals and predicted values from linear model in R?
The residuals are the difference between actual values and the predicted values and the predicted values are the values predicted for the actual values by the linear model. To extract the residuals and predicted values from linear model, we need to use resid and predict function with the model object. Consider the below data frame − Live Demo x1<-rnorm(20,14,3.25) y1<-rnorm(20,6,0.35) df1<-data.frame(x1,y1) df1 x1 y1 1 14.565652 6.506233 2 13.350634 6.481486 3 8.636661 5.806754 4 11.495087 6.164963 5 12.159347 6.749101 6 16.642371 6.061237 7 9.137345 6.121711 8 12.616223 5.911341 9 10.109950 5.819494 10 15.953629 6.067601 11 13.579602 6.438686 12 14.708544 5.175576 13 19.234206 6.926994 14 13.539790 5.669169 15 15.101462 6.253202 16 13.812982 6.042699 17 12.680245 6.019822 18 15.292250 6.174533 19 12.759720 5.648624 20 11.371360 5.879896 Creating linear model between x1 and y1 − Model1<-lm(y1~x1,data=df1) Finding the residuals and predicted values from Model1 − resid(Model1) 1 2 3 4 5 6 0.34576809 0.38483276 -0.04232628 0.16576122 0.71501218 -0.20829562 7 8 9 10 11 12 0.24633525 -0.14674241 -0.10696233 -0.16575896 0.33000726 -0.99239332 13 14 15 16 17 18 0.52134132 -0.43741908 0.06459654 -0.07823690 -0.04162379 -0.02409178 19 20 -0.41699579 -0.11280836 > predict(Model1) 1 2 3 4 5 6 7 8 6.160465 6.096654 5.849080 5.999202 6.034088 6.269532 5.875376 6.058083 9 10 11 12 13 14 15 16 5.926456 6.233360 6.108679 6.167970 6.405653 6.106588 6.188605 6.120936 17 18 19 20 6.061445 6.198625 6.065619 5.992704 Live Demo x2<-rpois(20,5) y2<-rpois(20,2) df2<-data.frame(x2,y2) df2 x2 y2 1 7 0 2 5 1 3 3 1 4 3 2 5 6 3 6 2 8 7 4 2 8 6 0 9 9 1 10 3 0 11 4 3 12 7 1 13 6 2 14 6 0 15 5 2 16 9 1 17 5 3 18 5 2 19 6 5 20 7 0 Creating linear model between x2 and y2 − Model2<-lm(y2~x2,data=df2) Finding the residuals and predicted values from Model2 − resid(Model2) 1 2 3 4 5 6 -1.15697674 -1.02325581 -1.88953488 -0.88953488 1.40988372 4.67732558 7 8 9 10 11 12 -0.45639535 -1.59011628 0.70930233 -2.88953488 0.54360465 -0.15697674 13 14 15 16 17 18 0.40988372 -1.59011628 -0.02325581 0.70930233 0.97674419 -0.02325581 19 20 3.40988372 -1.15697674 predict(Model2) 1 2 3 4 5 6 7 8 1.1569767 2.0232558 2.8895349 2.8895349 1.5901163 3.3226744 2.4563953 1.5901163 9 10 11 12 13 14 15 16 0.2906977 2.8895349 2.4563953 1.1569767 1.5901163 1.5901163 2.0232558 0.2906977 17 18 19 20 2.0232558 2.0232558 1.5901163 1.1569767
[ { "code": null, "e": 1365, "s": 1062, "text": "The residuals are the difference between actual values and the predicted values and the predicted values are the values predicted for the actual values by the linear model. To extract the residuals and predicted values from linear model, we need to use resid and predict function with the model object." }, { "code": null, "e": 1397, "s": 1365, "text": "Consider the below data frame −" }, { "code": null, "e": 1408, "s": 1397, "text": " Live Demo" }, { "code": null, "e": 1478, "s": 1408, "text": "x1<-rnorm(20,14,3.25)\ny1<-rnorm(20,6,0.35)\ndf1<-data.frame(x1,y1)\ndf1" }, { "code": null, "e": 1957, "s": 1478, "text": " x1 y1\n1 14.565652 6.506233\n2 13.350634 6.481486\n3 8.636661 5.806754\n4 11.495087 6.164963\n5 12.159347 6.749101\n6 16.642371 6.061237\n7 9.137345 6.121711\n8 12.616223 5.911341\n9 10.109950 5.819494\n10 15.953629 6.067601\n11 13.579602 6.438686\n12 14.708544 5.175576\n13 19.234206 6.926994\n14 13.539790 5.669169\n15 15.101462 6.253202\n16 13.812982 6.042699\n17 12.680245 6.019822\n18 15.292250 6.174533\n19 12.759720 5.648624\n20 11.371360 5.879896" }, { "code": null, "e": 1999, "s": 1957, "text": "Creating linear model between x1 and y1 −" }, { "code": null, "e": 2026, "s": 1999, "text": "Model1<-lm(y1~x1,data=df1)" }, { "code": null, "e": 2083, "s": 2026, "text": "Finding the residuals and predicted values from Model1 −" }, { "code": null, "e": 2097, "s": 2083, "text": "resid(Model1)" }, { "code": null, "e": 2909, "s": 2097, "text": " 1 2 3 4 5 6\n0.34576809 0.38483276 -0.04232628 0.16576122 0.71501218 -0.20829562\n 7 8 9 10 11 12\n0.24633525 -0.14674241 -0.10696233 -0.16575896 0.33000726 -0.99239332\n 13 14 15 16 17 18\n0.52134132 -0.43741908 0.06459654 -0.07823690 -0.04162379 -0.02409178\n 19 20\n-0.41699579 -0.11280836\n> predict(Model1)\n 1 2 3 4 5 6 7 8\n6.160465 6.096654 5.849080 5.999202 6.034088 6.269532 5.875376 6.058083\n 9 10 11 12 13 14 15 16\n5.926456 6.233360 6.108679 6.167970 6.405653 6.106588 6.188605 6.120936\n 17 18 19 20\n6.061445 6.198625 6.065619 5.992704" }, { "code": null, "e": 2920, "s": 2909, "text": " Live Demo" }, { "code": null, "e": 2979, "s": 2920, "text": "x2<-rpois(20,5)\ny2<-rpois(20,2)\ndf2<-data.frame(x2,y2)\ndf2" }, { "code": null, "e": 3127, "s": 2979, "text": " x2 y2\n1 7 0\n2 5 1\n3 3 1\n4 3 2\n5 6 3\n6 2 8\n7 4 2\n8 6 0\n9 9 1\n10 3 0\n11 4 3\n12 7 1\n13 6 2\n14 6 0\n15 5 2\n16 9 1\n17 5 3\n18 5 2\n19 6 5\n20 7 0" }, { "code": null, "e": 3169, "s": 3127, "text": "Creating linear model between x2 and y2 −" }, { "code": null, "e": 3196, "s": 3169, "text": "Model2<-lm(y2~x2,data=df2)" }, { "code": null, "e": 3253, "s": 3196, "text": "Finding the residuals and predicted values from Model2 −" }, { "code": null, "e": 3267, "s": 3253, "text": "resid(Model2)" }, { "code": null, "e": 3711, "s": 3267, "text": " 1 2 3 4 5 6\n-1.15697674 -1.02325581 -1.88953488 -0.88953488 1.40988372 4.67732558\n 7 8 9 10 11 12\n-0.45639535 -1.59011628 0.70930233 -2.88953488 0.54360465 -0.15697674\n 13 14 15 16 17 18\n0.40988372 -1.59011628 -0.02325581 0.70930233 0.97674419 -0.02325581\n 19 20\n3.40988372 -1.15697674" }, { "code": null, "e": 3727, "s": 3711, "text": "predict(Model2)" }, { "code": null, "e": 4114, "s": 3727, "text": " 1 2 3 4 5 6 7 8\n1.1569767 2.0232558 2.8895349 2.8895349 1.5901163 3.3226744 2.4563953 1.5901163\n 9 10 11 12 13 14 15 16\n0.2906977 2.8895349 2.4563953 1.1569767 1.5901163 1.5901163 2.0232558 0.2906977\n 17 18 19 20\n2.0232558 2.0232558 1.5901163 1.1569767" } ]
Activity Selection | Practice | GeeksforGeeks
Given N activities with their start and finish day given in array start[ ] and end[ ]. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a given day. Note : Duration of the activity includes both starting and ending day. Example 1: Input: N = 2 start[] = {2, 1} end[] = {2, 2} Output: 1 Explanation: A person can perform only one of the given activities. Example 2: Input: N = 4 start[] = {1, 3, 2, 5} end[] = {2, 4, 3, 6} Output: 3 Explanation: A person can perform activities 1, 2 and 4. Your Task : You don't need to read input or print anything. Your task is to complete the function activityselection() which takes array start[ ], array end[ ] and integer N as input parameters and returns the maximum number of activities that can be done. Expected Time Complexity : O(N * Log(N)) Expected Auxilliary Space : O(N) Constraints: 1 ≤ N ≤ 2*105 1 ≤ start[i] ≤ end[i] ≤ 109 0 19003001002371 day ago class Solution{ public: static bool mycomp(vector<int>& a, vector<int>& b) { return a[1] < b[1]; } //Function to find the maximum number of activities that can //be performed by a single person. int activitySelection(vector<int> start, vector<int> end, int n) { // Your code here vector<vector<int>> act; for(int i=0;i<n;i++) act.push_back({start[i] , end[i]}); sort(act.begin(),act.end(), mycomp); int ans = 1,i=0; for(int j=1;j<n;j++) { if(act[j][0] > act[i][1]) { ans++; i=j; } } return ans; }}; 0 ravi1010prakash2 days ago class Solution{ public: static bool mycamp(vector<int>&a,vector<int>&b) { return a[1]<b[1]; } //Function to find the maximum number of activities that can //be performed by a single person. int activitySelection(vector<int> start, vector<int> end, int n) { vector<vector<int>>act; for(int i=0;i<n;i++) act.push_back({start[i],end[i]}); sort(act.begin(),act.end(), mycamp); int count=1; int i=0; for(int j=1;j<n;j++) { if(act[i][1]<act[j][0]){ count++; i=j;} } return count; }}; // { Driver Code Starts.int main(){ int t; //testcases cin >> t; while(t--) { //size of array int n; cin >> n; vector<int> start(n), end(n); //adding elements to arrays start and end for(int i=0;i<n;i++) cin>>start[i]; for(int i=0;i<n;i++) cin>>end[i]; Solution ob; //function call cout << ob.activitySelection(start, end, n) << endl; } return 0;} // } Driver Code Ends 0 pruthvibelgaonkar4692 weeks ago TIME TAKEN 0.5 SECONDS bool static comp(pair<int,int>a,pair<int,int>b) { if(a.second==b.second) return a.first<b.first; return a.second<b.second; } int activitySelection(vector<int> start, vector<int> end, int n) { vector<pair<int,int>>v(n); for(int i=0;i<n;i++) { v[i]={start[i],end[i]}; } sort(v.begin(),v.end(),comp); int i=0; int j=1; int c=1; while(j<n) { if(v[i].second<v[j].first) { i=j; j++; c++; } else { j++; } } return c; } 0 dha72 This comment was deleted. 0 shalini21sirothiya3 weeks ago //c++ int activitySelection(vector<int> start, vector<int> end, int n) { // Your code here vector<vector<int>>ans; for(int i=0;i<n;i++){ ans.push_back({start[i],end[i]}); } sort(ans.begin(),ans.end(),[&](vector<int>&a,vector<int>&b){return a[1]<b[1];}); int take=1,prev=ans[0][1]; for(int i=1;i<n;i++){ if(ans[i][0]>prev){ take++; prev=ans[i][1]; } } return take; } 0 manishvaishnav911 month ago Other Java solutions I found may not be easy for beginners to read and understand so here is one. class Solution { static class Meeting implements Comparable<Meeting> { private int start,end; Meeting(int start,int end) { this.start = start; this.end = end; } public int getStart() { return this.start; } public int getEnd() { return this.end; } public int compareTo(Meeting other) { return this.end - other.end; } } public static int activitySelection(int start[], int end[], int n) { // add your code here List<Meeting> list = new ArrayList<>(); for (int i = 0; i < end.length; i++) { list.add(new Meeting(start[i],end[i])); } Collections.sort(list); int count = 0; int prevStart = -1; int prevEnd = -1; for (Meeting m : list) { int e = m.getEnd(); int s = m.getStart(); if (prevStart < 0 && prevEnd < 0) { count++; prevStart = s; prevEnd = e; } else if (s > prevEnd) { count++; prevStart = s; prevEnd = e; } } return count; } } 0 harrypotter01 month ago #Function to find the maximum number of activities that can #be performed by a single person. def activitySelection(self,n,start,end): res = [] for i in range(n): res.append([start[i], end[i]]) res.sort(key = lambda x:(x[1],x[0])) temp,ans,j,i =1,1,1,0 while i<n and j<n: if res[i][1]<res[j][0]: temp+=1 # print(res[j][0], res[j][1]) i = j j+=1 else: j+=1 return temp 0 naveenapatnaik1 month ago JAVA SOLUTION!!! public static int activitySelection(int start[], int end[], int n) { List<List<Integer>> activity = new ArrayList<>(); for(int i = 0 ; i < n; i++){ List<Integer> act = new ArrayList<>(); act.add(start[i]); act.add(end[i]); activity.add(act); } activity.sort(new Comparator<List<Integer>>() { @Override public int compare(List<Integer> o1, List<Integer> o2) { if (o1.get(1) > o2.get(1)) { return 1; } else if(o1.get(1) < o2.get(1)) { return -1; } else if (o1.get(1).equals(o2.get(1)) && o1.get(0) > o2.get(0)) { return 1; } else if(o1.get(1).equals(o2.get(1)) && o1.get(0) < o2.get(0)){ return -1; } return 0; }}); int i = 0, res = 1; for(int j = 1 ; j < n ; j++){ if(activity.get(j).get(0) > activity.get(i).get(1)){ i = j; res++; } } return res; } +1 patildhiren441 month ago // Approach:// 1. Add details of meeting like start end and position with 1 based index to list// 2. sort the list acc to end time of list (if two meetings has same time then sort acc to their min pos)// 3. take max limit as first end of meeting and add the position to list// 4. if next meeting start time is greater than limit (which is prev meeting end time) then add to another final list// 5. print final list as attend meeting position or how many meeting acc to que // Java - 1.4 !! Spoiler Alert Code Ahead !! Spoiler Alert Code Ahead !! Spoiler Alert Code Ahead !! Spoiler Alert Code Ahead !! Spoiler Alert Code Ahead !! Spoiler Alert Code Ahead !! Spoiler Alert Code Ahead !! Spoiler Alert Code Ahead !! Spoiler Alert Code Ahead !! Spoiler Alert Code Ahead !! Spoiler Alert Code Ahead static class Meeting{ int st; int end; int pos; Meeting(int st, int end, int pos){ this.st = st; this.end = end; this.pos = pos; } } static class meetCompare implements Comparator<Meeting>{ public int compare(Meeting m1, Meeting m2){ if(m1.end < m2.end){ return -1; }else if(m1.end > m2.end){ return 1; }else if(m1.pos < m2.pos){ return -1; }else{ return 1; } } } public static int activitySelection(int start[], int end[], int n) { // add your code here ArrayList<Meeting> meet = new ArrayList<>(); for(int i=0; i<n; i++){ meet.add(new Meeting(start[i], end[i], i+1)); } Collections.sort(meet, new meetCompare()); ArrayList<Integer> res = new ArrayList<>(); res.add(meet.get(0).pos); int limit = meet.get(0).end; for(int i=1; i<n; i++){ if(meet.get(i).st > limit){ limit = meet.get(i).end; res.add(meet.get(i).pos); } } // for(int i=0; i<res.size(); i++){ // System.out.println(res.get(i)); // } return res.size(); } 0 harinigurram2001 This comment was deleted. We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 552, "s": 238, "text": "Given N activities with their start and finish day given in array start[ ] and end[ ]. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a given day.\nNote : Duration of the activity includes both starting and ending day." }, { "code": null, "e": 564, "s": 552, "text": "\nExample 1:" }, { "code": null, "e": 689, "s": 564, "text": "Input:\nN = 2\nstart[] = {2, 1}\nend[] = {2, 2}\nOutput: \n1\nExplanation:\nA person can perform only one of the\ngiven activities.\n" }, { "code": null, "e": 700, "s": 689, "text": "Example 2:" }, { "code": null, "e": 826, "s": 700, "text": "Input:\nN = 4\nstart[] = {1, 3, 2, 5}\nend[] = {2, 4, 3, 6}\nOutput: \n3\nExplanation:\nA person can perform activities 1, 2\nand 4.\n" }, { "code": null, "e": 1083, "s": 826, "text": "\nYour Task :\nYou don't need to read input or print anything. Your task is to complete the function activityselection() which takes array start[ ], array end[ ] and integer N as input parameters and returns the maximum number of activities that can be done." }, { "code": null, "e": 1214, "s": 1083, "text": "\nExpected Time Complexity : O(N * Log(N))\nExpected Auxilliary Space : O(N)\n\nConstraints:\n1 ≤ N ≤ 2*105\n1 ≤ start[i] ≤ end[i] ≤ 109" }, { "code": null, "e": 1216, "s": 1214, "text": "0" }, { "code": null, "e": 1239, "s": 1216, "text": "19003001002371 day ago" }, { "code": null, "e": 1874, "s": 1239, "text": "class Solution{ public: static bool mycomp(vector<int>& a, vector<int>& b) { return a[1] < b[1]; } //Function to find the maximum number of activities that can //be performed by a single person. int activitySelection(vector<int> start, vector<int> end, int n) { // Your code here vector<vector<int>> act; for(int i=0;i<n;i++) act.push_back({start[i] , end[i]}); sort(act.begin(),act.end(), mycomp); int ans = 1,i=0; for(int j=1;j<n;j++) { if(act[j][0] > act[i][1]) { ans++; i=j; } } return ans; }};" }, { "code": null, "e": 1876, "s": 1874, "text": "0" }, { "code": null, "e": 1902, "s": 1876, "text": "ravi1010prakash2 days ago" }, { "code": null, "e": 2494, "s": 1902, "text": "class Solution{ public: static bool mycamp(vector<int>&a,vector<int>&b) { return a[1]<b[1]; } //Function to find the maximum number of activities that can //be performed by a single person. int activitySelection(vector<int> start, vector<int> end, int n) { vector<vector<int>>act; for(int i=0;i<n;i++) act.push_back({start[i],end[i]}); sort(act.begin(),act.end(), mycamp); int count=1; int i=0; for(int j=1;j<n;j++) { if(act[i][1]<act[j][0]){ count++; i=j;} } return count; }};" }, { "code": null, "e": 2968, "s": 2494, "text": "// { Driver Code Starts.int main(){ int t; //testcases cin >> t; while(t--) { //size of array int n; cin >> n; vector<int> start(n), end(n); //adding elements to arrays start and end for(int i=0;i<n;i++) cin>>start[i]; for(int i=0;i<n;i++) cin>>end[i]; Solution ob; //function call cout << ob.activitySelection(start, end, n) << endl; } return 0;} // } Driver Code Ends" }, { "code": null, "e": 2970, "s": 2968, "text": "0" }, { "code": null, "e": 3002, "s": 2970, "text": "pruthvibelgaonkar4692 weeks ago" }, { "code": null, "e": 3025, "s": 3002, "text": "TIME TAKEN 0.5 SECONDS" }, { "code": null, "e": 3662, "s": 3027, "text": "bool static comp(pair<int,int>a,pair<int,int>b) { if(a.second==b.second) return a.first<b.first; return a.second<b.second; } int activitySelection(vector<int> start, vector<int> end, int n) { vector<pair<int,int>>v(n); for(int i=0;i<n;i++) { v[i]={start[i],end[i]}; } sort(v.begin(),v.end(),comp); int i=0; int j=1; int c=1; while(j<n) { if(v[i].second<v[j].first) { i=j; j++; c++; } else { j++; } } return c; }" }, { "code": null, "e": 3664, "s": 3662, "text": "0" }, { "code": null, "e": 3670, "s": 3664, "text": "dha72" }, { "code": null, "e": 3696, "s": 3670, "text": "This comment was deleted." }, { "code": null, "e": 3698, "s": 3696, "text": "0" }, { "code": null, "e": 3728, "s": 3698, "text": "shalini21sirothiya3 weeks ago" }, { "code": null, "e": 3734, "s": 3728, "text": "//c++" }, { "code": null, "e": 4198, "s": 3734, "text": "int activitySelection(vector<int> start, vector<int> end, int n) { // Your code here vector<vector<int>>ans; for(int i=0;i<n;i++){ ans.push_back({start[i],end[i]}); } sort(ans.begin(),ans.end(),[&](vector<int>&a,vector<int>&b){return a[1]<b[1];}); int take=1,prev=ans[0][1]; for(int i=1;i<n;i++){ if(ans[i][0]>prev){ take++; prev=ans[i][1]; } } return take; }" }, { "code": null, "e": 4200, "s": 4198, "text": "0" }, { "code": null, "e": 4228, "s": 4200, "text": "manishvaishnav911 month ago" }, { "code": null, "e": 4327, "s": 4228, "text": "Other Java solutions I found may not be easy for beginners to read and understand so here is one. " }, { "code": null, "e": 5590, "s": 4329, "text": "class Solution\n{\n static class Meeting implements Comparable<Meeting> {\n private int start,end;\n \n Meeting(int start,int end) {\n this.start = start;\n this.end = end;\n }\n \n public int getStart() {\n return this.start;\n }\n \n public int getEnd() {\n return this.end;\n }\n \n public int compareTo(Meeting other) {\n return this.end - other.end;\n }\n }\n \n public static int activitySelection(int start[], int end[], int n)\n {\n // add your code here\n List<Meeting> list = new ArrayList<>();\n for (int i = 0; i < end.length; i++) {\n list.add(new Meeting(start[i],end[i]));\n }\n Collections.sort(list);\n \n int count = 0;\n int prevStart = -1;\n int prevEnd = -1;\n \n for (Meeting m : list) {\n int e = m.getEnd();\n int s = m.getStart();\n if (prevStart < 0 && prevEnd < 0) {\n count++;\n prevStart = s;\n prevEnd = e;\n }\n else if (s > prevEnd) {\n count++;\n prevStart = s;\n prevEnd = e;\n }\n }\n return count;\n }\n}" }, { "code": null, "e": 5592, "s": 5590, "text": "0" }, { "code": null, "e": 5616, "s": 5592, "text": "harrypotter01 month ago" }, { "code": null, "e": 6129, "s": 5616, "text": " #Function to find the maximum number of activities that can #be performed by a single person. def activitySelection(self,n,start,end): res = [] for i in range(n): res.append([start[i], end[i]]) res.sort(key = lambda x:(x[1],x[0])) temp,ans,j,i =1,1,1,0 while i<n and j<n: if res[i][1]<res[j][0]: temp+=1 # print(res[j][0], res[j][1]) i = j j+=1 else: j+=1 return temp " }, { "code": null, "e": 6131, "s": 6129, "text": "0" }, { "code": null, "e": 6157, "s": 6131, "text": "naveenapatnaik1 month ago" }, { "code": null, "e": 6175, "s": 6157, "text": "JAVA SOLUTION!!! " }, { "code": null, "e": 7255, "s": 6175, "text": " public static int activitySelection(int start[], int end[], int n) { List<List<Integer>> activity = new ArrayList<>(); for(int i = 0 ; i < n; i++){ List<Integer> act = new ArrayList<>(); act.add(start[i]); act.add(end[i]); activity.add(act); } activity.sort(new Comparator<List<Integer>>() { @Override public int compare(List<Integer> o1, List<Integer> o2) { if (o1.get(1) > o2.get(1)) { return 1; } else if(o1.get(1) < o2.get(1)) { return -1; } else if (o1.get(1).equals(o2.get(1)) && o1.get(0) > o2.get(0)) { return 1; } else if(o1.get(1).equals(o2.get(1)) && o1.get(0) < o2.get(0)){ return -1; } return 0; }}); int i = 0, res = 1; for(int j = 1 ; j < n ; j++){ if(activity.get(j).get(0) > activity.get(i).get(1)){ i = j; res++; } } return res; }" }, { "code": null, "e": 7258, "s": 7255, "text": "+1" }, { "code": null, "e": 7283, "s": 7258, "text": "patildhiren441 month ago" }, { "code": null, "e": 7758, "s": 7283, "text": "// Approach:// 1. Add details of meeting like start end and position with 1 based index to list// 2. sort the list acc to end time of list (if two meetings has same time then sort acc to their min pos)// 3. take max limit as first end of meeting and add the position to list// 4. if next meeting start time is greater than limit (which is prev meeting end time) then add to another final list// 5. print final list as attend meeting position or how many meeting acc to que " }, { "code": null, "e": 7772, "s": 7758, "text": "// Java - 1.4" }, { "code": null, "e": 7802, "s": 7774, "text": "!! Spoiler Alert Code Ahead" }, { "code": null, "e": 7831, "s": 7802, "text": "!! Spoiler Alert Code Ahead" }, { "code": null, "e": 7860, "s": 7831, "text": "!! Spoiler Alert Code Ahead" }, { "code": null, "e": 7889, "s": 7860, "text": "!! Spoiler Alert Code Ahead" }, { "code": null, "e": 7918, "s": 7889, "text": "!! Spoiler Alert Code Ahead" }, { "code": null, "e": 7947, "s": 7918, "text": "!! Spoiler Alert Code Ahead" }, { "code": null, "e": 7976, "s": 7947, "text": "!! Spoiler Alert Code Ahead" }, { "code": null, "e": 8005, "s": 7976, "text": "!! Spoiler Alert Code Ahead" }, { "code": null, "e": 8034, "s": 8005, "text": "!! Spoiler Alert Code Ahead" }, { "code": null, "e": 8063, "s": 8034, "text": "!! Spoiler Alert Code Ahead" }, { "code": null, "e": 8092, "s": 8063, "text": "!! Spoiler Alert Code Ahead" }, { "code": null, "e": 9515, "s": 8100, "text": "static class Meeting{\n int st;\n int end;\n int pos;\n Meeting(int st, int end, int pos){\n this.st = st;\n this.end = end;\n this.pos = pos;\n }\n }\n \n static class meetCompare implements Comparator<Meeting>{\n public int compare(Meeting m1, Meeting m2){\n if(m1.end < m2.end){\n return -1;\n }else if(m1.end > m2.end){\n return 1;\n }else if(m1.pos < m2.pos){\n return -1;\n }else{\n return 1;\n }\n }\n }\n \n public static int activitySelection(int start[], int end[], int n)\n {\n // add your code here\n ArrayList<Meeting> meet = new ArrayList<>();\n \n for(int i=0; i<n; i++){\n meet.add(new Meeting(start[i], end[i], i+1));\n }\n \n Collections.sort(meet, new meetCompare());\n \n ArrayList<Integer> res = new ArrayList<>();\n \n res.add(meet.get(0).pos);\n int limit = meet.get(0).end;\n \n for(int i=1; i<n; i++){\n if(meet.get(i).st > limit){\n limit = meet.get(i).end;\n res.add(meet.get(i).pos);\n }\n }\n \n // for(int i=0; i<res.size(); i++){\n // System.out.println(res.get(i));\n // }\n \n return res.size();\n }" }, { "code": null, "e": 9517, "s": 9515, "text": "0" }, { "code": null, "e": 9534, "s": 9517, "text": "harinigurram2001" }, { "code": null, "e": 9560, "s": 9534, "text": "This comment was deleted." }, { "code": null, "e": 9706, "s": 9560, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 9742, "s": 9706, "text": " Login to access your submissions. " }, { "code": null, "e": 9752, "s": 9742, "text": "\nProblem\n" }, { "code": null, "e": 9762, "s": 9752, "text": "\nContest\n" }, { "code": null, "e": 9825, "s": 9762, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9973, "s": 9825, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 10181, "s": 9973, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 10287, "s": 10181, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to install PowerShell Module?
There are two methods to install PowerShell modules. Online and Offline. This method is just like downloading the online package through Yum in the Unix system. We first need to search the package available on the internet using the Find-Module command. You can use the wildcard character if you don’t know the full module name. All the packages are downloaded from PowerShell Gallery (https://www.powershellgallery.com/). For example, if you want a Vmware PowerCLI module and you don’t know the full module name then just use the part of the name inside the Wildcard character(*). Find-Module *vmware* | Select Name, Version, Repository Name Version Repository ---- ------- ---------- VMware.VimAutomation.Sdk 12.0.0.15939651 PSGallery VMware.VimAutomation.Core 12.0.0.15939655 PSGallery VMware.VimAutomation.Common 12.0.0.15939652 PSGallery VMware.VimAutomation.Cis.Core 12.0.0.15939657 PSGallery VMware.Vim 7.0.0.15939650 PSGallery VMware.VimAutomation.Vds 12.0.0.15940185 PSGallery VMware.VimAutomation.Srm 11.5.0.14899557 PSGallery VMware.VimAutomation.License 12.0.0.15939670 PSGallery VMware.VimAutomation.vROps 12.0.0.15940184 PSGallery VMware.VimAutomation.Cloud 12.0.0.15940183 PSGallery VMware.ImageBuilder 7.0.0.15902843 PSGallery VMware.VimAutomation.Nsxt 12.0.0.15939671 PSGallery VMware.PowerCLI 12.0.0.15947286 PSGallery VMware.VimAutomation.Horiz... 7.12.0.15718406 PSGallery VMware.VimAutomation.Storage 12.0.0.15939648 PSGallery VMware.DeployAutomation 7.0.0.15902843 PSGallery VMware.VimAutomation.Vmc 12.0.0.15947287 PSGallery VMware.VumAutomation 6.5.1.7862888 PSGallery VMware.VimAutomation.Stora... 1.3.0.0 PSGallery VMware.VimAutomation.Security 12.0.0.15939672 PSGallery VMware.VimAutomation.Hcx 12.0.0.15939647 PSGallery VMware.VimAutomation.HA 6.5.4.7567193 PSGallery VMware.VimAutomation.PCloud 10.0.0.7893924 PSGallery VMware.CloudServices 12.0.0.15947289 PSGallery VMware.VimAutomation.Workl... 12.0.0.15947288 PSGallery Now we have a list of VMware modules available and we need Vmware.PowerCLI module among them. To install the module we will use Install-Module cmdlet. Find-Module Vmware.PowerCLI | Install-Module Untrusted repository You are installing the modules from an untrusted repository. If you trust this repository, change its InstallationPolicy value by running the SetPSRepository cmdlet. Are you sure you want to install the modules from 'https://www.powershellgalle ry.com/api/v2/'? [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): You can check if the module is installed or not using the Get-Module command. PS C:\WINDOWS\system32> Get-Module -Name *vmware* -ListAvailable | Select Name, Version Name Version ---- ------- VMware.CloudServices 12.0.0.15947289 VMware.DeployAutomation 7.0.0.15902843 VMware.DeployAutomation 6.5.1.5299608 VMware.ImageBuilder 7.0.0.15902843 VMware.ImageBuilder 6.5.1.5299608 vmware.powercli 12.0.0.15947286 VMware.Vim 7.0.0.15939650 VMware.VimAutomation.Cis.Core 6.5.1.5374323 VMware.VimAutomation.Cloud 12.0.0.15940183 VMware.VimAutomation.Cloud 6.5.1.5375799 VMware.VimAutomation.Common 6.5.1.5335010 The beauty of this method is, it will install dependent modules as well. In the situation, when you don’t have an internet connection on the server, you need to download the package offline from the server or desktop having an active internet connection from PowerShell Gallery and copy the package to the offline server. You can download the package from PowerShell gallery https://www.powershellgallery.com/ and for this example search for the package “Vmware.PowerCLI” and if the package exists, you will get the package name. When you click on this package, you will get the Manual download tab as below. The package you download will be in the Nupkg format (Nuget Package). This package is ZIP format file and some browsers like Internet Explorer convert it to ZIP automatically but you can rename its extension to ZIP as well. You can directly extract the Nupkg content into the folder with the 7-Zip as well. The content of the folder will be as below. Description of the above files/folders content. _rels Folder − Contains the .rels file that lists the dependencies. _rels Folder − Contains the .rels file that lists the dependencies. Package folder − Contains the NuGet- Specific data. Package folder − Contains the NuGet- Specific data. [Content_Types] − Describes how NuGet Extension files work with PowerShellGet. [Content_Types] − Describes how NuGet Extension files work with PowerShellGet. <name>.nuspec − Contains the bulk of metadata <name>.nuspec − Contains the bulk of metadata For more details follow the article from Microsoft regarding the offline installation method. https://docs.microsoft.com/en-us/powershell/scripting/gallery/how-to/working-withpackages/manual-download?view=powershell-7 Once you have unzipped the folder name would be like <Modulename.Version>, remove the version from that folder name, and the folder name would be now the module name. According to the article above, we need to delete the Nuget-Specific elements from the folder but we can directly copy/paste the entire unzipped folder to the Powershell module path. Below is the module path for the Powershell. PS C:\WINDOWS\system32> $env:PSModulePath -split ';' C:\Users\admin\Documents\WindowsPowerShell\Modules C:\Program Files\WindowsPowerShell\Modules C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\ C:\Program Files\PoSHServer\modules\ C:\Windows\System32\WindowsPowerShell\v1.0\Modules We will choose here “C:\Program Files\WindowsPowerShell\Modules” module folder and copy the unzipped folder there. Now reopen or open a new PowerShell session and check if the copied new module loaded properly and you can see that the vmware.powercli module is there. PS C:\WINDOWS\system32> Get-Module -Name *vmware* -ListAvailable | Select Name,Version Name Version ---- ------- VMware.CloudServices 12.0.0.15947289 VMware.DeployAutomation 7.0.0.15902843 VMware.DeployAutomation 6.5.1.5299608 VMware.ImageBuilder 7.0.0.15902843 VMware.ImageBuilder 6.5.1.5299608 vmware.powercli 12.0.0.15947286 VMware.Vim 7.0.0.15939650 VMware.VimAutomation.Cis.Core 6.5.1.5374323 VMware.VimAutomation.Cloud 12.0.0.15940183 VMware.VimAutomation.Cloud 6.5.1.5375799 VMware.VimAutomation.Common 6.5.1.5335010 VMware.VimAutomation.Core 6.5.1.5374329 VMware.VimAutomation.HA 6.0.0.5314477 VMware.VimAutomation.Hcx 12.0.0.15939647 VMware.VimAutomation.HorizonView 7.12.0.15718406 VMware.VimAutomation.HorizonView 7.1.0.5307191 This method doesn’t install the dependent module. You need to download the dependent modules and install them separately if needed.
[ { "code": null, "e": 1135, "s": 1062, "text": "There are two methods to install PowerShell modules. Online and Offline." }, { "code": null, "e": 1223, "s": 1135, "text": "This method is just like downloading the online package through Yum in the Unix system." }, { "code": null, "e": 1485, "s": 1223, "text": "We first need to search the package available on the internet using the Find-Module command. You can use the wildcard character if you don’t know the full module name. All the packages are downloaded from PowerShell Gallery (https://www.powershellgallery.com/)." }, { "code": null, "e": 1644, "s": 1485, "text": "For example, if you want a Vmware PowerCLI module and you don’t know the full module name then just use the part of the name inside the Wildcard character(*)." }, { "code": null, "e": 1700, "s": 1644, "text": "Find-Module *vmware* | Select Name, Version, Repository" }, { "code": null, "e": 3320, "s": 1700, "text": "Name Version Repository\n---- ------- ----------\nVMware.VimAutomation.Sdk 12.0.0.15939651 PSGallery\nVMware.VimAutomation.Core 12.0.0.15939655 PSGallery\nVMware.VimAutomation.Common 12.0.0.15939652 PSGallery\nVMware.VimAutomation.Cis.Core 12.0.0.15939657 PSGallery\nVMware.Vim 7.0.0.15939650 PSGallery\nVMware.VimAutomation.Vds 12.0.0.15940185 PSGallery\nVMware.VimAutomation.Srm 11.5.0.14899557 PSGallery\nVMware.VimAutomation.License 12.0.0.15939670 PSGallery\nVMware.VimAutomation.vROps 12.0.0.15940184 PSGallery\nVMware.VimAutomation.Cloud 12.0.0.15940183 PSGallery\nVMware.ImageBuilder 7.0.0.15902843 PSGallery\nVMware.VimAutomation.Nsxt 12.0.0.15939671 PSGallery\nVMware.PowerCLI 12.0.0.15947286 PSGallery\nVMware.VimAutomation.Horiz... 7.12.0.15718406 PSGallery\nVMware.VimAutomation.Storage 12.0.0.15939648 PSGallery\nVMware.DeployAutomation 7.0.0.15902843 PSGallery\nVMware.VimAutomation.Vmc 12.0.0.15947287 PSGallery\nVMware.VumAutomation 6.5.1.7862888 PSGallery\nVMware.VimAutomation.Stora... 1.3.0.0 PSGallery\nVMware.VimAutomation.Security 12.0.0.15939672 PSGallery\nVMware.VimAutomation.Hcx 12.0.0.15939647 PSGallery\nVMware.VimAutomation.HA 6.5.4.7567193 PSGallery\nVMware.VimAutomation.PCloud 10.0.0.7893924 PSGallery\nVMware.CloudServices 12.0.0.15947289 PSGallery\nVMware.VimAutomation.Workl... 12.0.0.15947288 PSGallery" }, { "code": null, "e": 3471, "s": 3320, "text": "Now we have a list of VMware modules available and we need Vmware.PowerCLI module among them. To install the module we will use Install-Module cmdlet." }, { "code": null, "e": 3516, "s": 3471, "text": "Find-Module Vmware.PowerCLI | Install-Module" }, { "code": null, "e": 3882, "s": 3516, "text": "Untrusted repository\nYou are installing the modules from an untrusted repository. If you trust this repository, change its InstallationPolicy value by running the SetPSRepository cmdlet.\nAre you sure you want to install the modules from 'https://www.powershellgalle ry.com/api/v2/'?\n[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is \"N\"):" }, { "code": null, "e": 3960, "s": 3882, "text": "You can check if the module is installed or not using the Get-Module command." }, { "code": null, "e": 4616, "s": 3960, "text": "PS C:\\WINDOWS\\system32> Get-Module -Name *vmware* -ListAvailable |\nSelect Name, Version\n\nName Version\n---- -------\nVMware.CloudServices 12.0.0.15947289\nVMware.DeployAutomation 7.0.0.15902843\nVMware.DeployAutomation 6.5.1.5299608\nVMware.ImageBuilder 7.0.0.15902843\nVMware.ImageBuilder 6.5.1.5299608\nvmware.powercli 12.0.0.15947286\nVMware.Vim 7.0.0.15939650\nVMware.VimAutomation.Cis.Core 6.5.1.5374323\nVMware.VimAutomation.Cloud 12.0.0.15940183\nVMware.VimAutomation.Cloud 6.5.1.5375799\nVMware.VimAutomation.Common 6.5.1.5335010" }, { "code": null, "e": 4689, "s": 4616, "text": "The beauty of this method is, it will install dependent modules as well." }, { "code": null, "e": 4938, "s": 4689, "text": "In the situation, when you don’t have an internet connection on the server, you need to download the package offline from the server or desktop having an active internet connection from PowerShell Gallery and copy the package to the offline server." }, { "code": null, "e": 5146, "s": 4938, "text": "You can download the package from PowerShell gallery https://www.powershellgallery.com/ and for this example search for the package “Vmware.PowerCLI” and if the package exists, you will get the package name." }, { "code": null, "e": 5225, "s": 5146, "text": "When you click on this package, you will get the Manual download tab as below." }, { "code": null, "e": 5576, "s": 5225, "text": "The package you download will be in the Nupkg format (Nuget Package). This package is ZIP format file and some browsers like Internet Explorer convert it to ZIP automatically but you can rename its extension to ZIP as well. You can directly extract the Nupkg content into the folder with the 7-Zip as well. The content of the folder will be as below." }, { "code": null, "e": 5624, "s": 5576, "text": "Description of the above files/folders content." }, { "code": null, "e": 5692, "s": 5624, "text": "_rels Folder − Contains the .rels file that lists the dependencies." }, { "code": null, "e": 5760, "s": 5692, "text": "_rels Folder − Contains the .rels file that lists the dependencies." }, { "code": null, "e": 5812, "s": 5760, "text": "Package folder − Contains the NuGet- Specific data." }, { "code": null, "e": 5864, "s": 5812, "text": "Package folder − Contains the NuGet- Specific data." }, { "code": null, "e": 5943, "s": 5864, "text": "[Content_Types] − Describes how NuGet Extension files work with PowerShellGet." }, { "code": null, "e": 6022, "s": 5943, "text": "[Content_Types] − Describes how NuGet Extension files work with PowerShellGet." }, { "code": null, "e": 6068, "s": 6022, "text": "<name>.nuspec − Contains the bulk of metadata" }, { "code": null, "e": 6114, "s": 6068, "text": "<name>.nuspec − Contains the bulk of metadata" }, { "code": null, "e": 6208, "s": 6114, "text": "For more details follow the article from Microsoft regarding the offline installation method." }, { "code": null, "e": 6332, "s": 6208, "text": "https://docs.microsoft.com/en-us/powershell/scripting/gallery/how-to/working-withpackages/manual-download?view=powershell-7" }, { "code": null, "e": 6499, "s": 6332, "text": "Once you have unzipped the folder name would be like <Modulename.Version>, remove the version from that folder name, and the folder name would be now the module name." }, { "code": null, "e": 6727, "s": 6499, "text": "According to the article above, we need to delete the Nuget-Specific elements from the folder but we can directly copy/paste the entire unzipped folder to the Powershell module path. Below is the module path for the Powershell." }, { "code": null, "e": 7014, "s": 6727, "text": "PS C:\\WINDOWS\\system32> $env:PSModulePath -split ';'\nC:\\Users\\admin\\Documents\\WindowsPowerShell\\Modules\nC:\\Program Files\\WindowsPowerShell\\Modules\nC:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\Modules\\\nC:\\Program Files\\PoSHServer\\modules\\\nC:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Modules" }, { "code": null, "e": 7282, "s": 7014, "text": "We will choose here “C:\\Program Files\\WindowsPowerShell\\Modules” module folder and copy the unzipped folder there. Now reopen or open a new PowerShell session and check if the copied new module loaded properly and you can see that the vmware.powercli module is there." }, { "code": null, "e": 8214, "s": 7282, "text": "PS C:\\WINDOWS\\system32> Get-Module -Name *vmware* -ListAvailable | Select\nName,Version\nName Version\n---- -------\nVMware.CloudServices 12.0.0.15947289\nVMware.DeployAutomation 7.0.0.15902843\nVMware.DeployAutomation 6.5.1.5299608\nVMware.ImageBuilder 7.0.0.15902843\nVMware.ImageBuilder 6.5.1.5299608\nvmware.powercli 12.0.0.15947286\nVMware.Vim 7.0.0.15939650\nVMware.VimAutomation.Cis.Core 6.5.1.5374323\nVMware.VimAutomation.Cloud 12.0.0.15940183\nVMware.VimAutomation.Cloud 6.5.1.5375799\nVMware.VimAutomation.Common 6.5.1.5335010\nVMware.VimAutomation.Core 6.5.1.5374329\nVMware.VimAutomation.HA 6.0.0.5314477\nVMware.VimAutomation.Hcx 12.0.0.15939647\nVMware.VimAutomation.HorizonView 7.12.0.15718406\nVMware.VimAutomation.HorizonView 7.1.0.5307191" }, { "code": null, "e": 8346, "s": 8214, "text": "This method doesn’t install the dependent module. You need to download the dependent modules and install them separately if needed." } ]
Python - Queue
We are familiar with queue in our day to day life as we wait for a service. The queue data structure aslo means the same where the data elements are arranged in a queue. The uniqueness of queue lies in the way items are added and removed. The items are allowed at on end but removed form the other end. So it is a First-in-First out method. A queue can be implemented using python list where we can use the insert() and pop() methods to add and remove elements. Their is no insertion as data elements are always added at the end of the queue. In the below example we create a queue class where we implement the First-in-First-Out method. We use the in-built insert method for adding data elements. class Queue: def __init__(self): self.queue = list() def addtoq(self,dataval): # Insert method to add element if dataval not in self.queue: self.queue.insert(0,dataval) return True return False def size(self): return len(self.queue) TheQueue = Queue() TheQueue.addtoq("Mon") TheQueue.addtoq("Tue") TheQueue.addtoq("Wed") print(TheQueue.size()) When the above code is executed, it produces the following result − 3 In the below example we create a queue class where we insert the data and then remove the data using the in-built pop method. class Queue: def __init__(self): self.queue = list() def addtoq(self,dataval): # Insert method to add element if dataval not in self.queue: self.queue.insert(0,dataval) return True return False # Pop method to remove element def removefromq(self): if len(self.queue)>0: return self.queue.pop() return ("No elements in Queue!") TheQueue = Queue() TheQueue.addtoq("Mon") TheQueue.addtoq("Tue") TheQueue.addtoq("Wed") print(TheQueue.removefromq()) print(TheQueue.removefromq()) When the above code is executed, it produces the following result − Mon Tue 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": 2668, "s": 2327, "text": "We are familiar with queue in our day to day life as we wait for a service. The queue data structure aslo means the same where the data elements are arranged in a queue. The uniqueness of queue lies in the way items are added and removed. The items are allowed at on end but removed form the other end. So it is a First-in-First out method." }, { "code": null, "e": 2870, "s": 2668, "text": "A queue can be implemented using python list where we can use the insert() and pop() methods to add and remove elements. Their is no insertion as data elements are always added at the end of the queue." }, { "code": null, "e": 3025, "s": 2870, "text": "In the below example we create a queue class where we implement the First-in-First-Out method. We use the in-built insert method for adding data elements." }, { "code": null, "e": 3411, "s": 3025, "text": "class Queue:\n def __init__(self):\n self.queue = list()\n\n def addtoq(self,dataval):\n# Insert method to add element\n if dataval not in self.queue:\n self.queue.insert(0,dataval)\n return True\n return False\n\n def size(self):\n return len(self.queue)\n\nTheQueue = Queue()\nTheQueue.addtoq(\"Mon\")\nTheQueue.addtoq(\"Tue\")\nTheQueue.addtoq(\"Wed\")\nprint(TheQueue.size())" }, { "code": null, "e": 3479, "s": 3411, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3482, "s": 3479, "text": "3\n" }, { "code": null, "e": 3608, "s": 3482, "text": "In the below example we create a queue class where we insert the data and then remove the data using the in-built pop method." }, { "code": null, "e": 4139, "s": 3608, "text": "class Queue:\n def __init__(self):\n self.queue = list()\n\n def addtoq(self,dataval):\n# Insert method to add element\n if dataval not in self.queue:\n self.queue.insert(0,dataval)\n return True\n return False\n# Pop method to remove element\n def removefromq(self):\n if len(self.queue)>0:\n return self.queue.pop()\n return (\"No elements in Queue!\")\n\nTheQueue = Queue()\nTheQueue.addtoq(\"Mon\")\nTheQueue.addtoq(\"Tue\")\nTheQueue.addtoq(\"Wed\")\nprint(TheQueue.removefromq())\nprint(TheQueue.removefromq())" }, { "code": null, "e": 4207, "s": 4139, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 4216, "s": 4207, "text": "Mon\nTue\n" }, { "code": null, "e": 4253, "s": 4216, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4269, "s": 4253, "text": " Malhar Lathkar" }, { "code": null, "e": 4302, "s": 4269, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4321, "s": 4302, "text": " Arnab Chakraborty" }, { "code": null, "e": 4356, "s": 4321, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4378, "s": 4356, "text": " In28Minutes Official" }, { "code": null, "e": 4412, "s": 4378, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4440, "s": 4412, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4475, "s": 4440, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4489, "s": 4475, "text": " Lets Kode It" }, { "code": null, "e": 4522, "s": 4489, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4539, "s": 4522, "text": " Abhilash Nelson" }, { "code": null, "e": 4546, "s": 4539, "text": " Print" }, { "code": null, "e": 4557, "s": 4546, "text": " Add Notes" } ]
Replace values in Pandas dataframe using regex - GeeksforGeeks
29 Dec, 2020 While working with large sets of data, it often contains text data and in many cases, those texts are not pretty at all. The is often in very messier form and we need to clean those data before we can do anything meaningful with that text data. Mostly the text corpus is so large that we cannot manually list out all the texts that we want to replace. So in those cases, we use regular expressions to deal with such data having some pattern in it. We have already discussed in previous article how to replace some known string values in dataframe. In this post, we will use regular expressions to replace strings which have some pattern to it. Problem #1 : You are given a dataframe which contains the details about various events in different cities. For those cities which starts with the keyword ‘New’ or ‘new’, change it to ‘New_’. Solution : We are going to use regular expression to detect such names and then we will use Dataframe.replace() function to replace those names. # importing pandas as pdimport pandas as pd # Let's create a Dataframedf = pd.DataFrame({'City':['New York', 'Parague', 'New Delhi', 'Venice', 'new Orleans'], 'Event':['Music', 'Poetry', 'Theatre', 'Comedy', 'Tech_Summit'], 'Cost':[10000, 5000, 15000, 2000, 12000]}) # Let's create the indexindex_ = [pd.Period('02-2018'), pd.Period('04-2018'), pd.Period('06-2018'), pd.Period('10-2018'), pd.Period('12-2018')] # Set the indexdf.index = index_ # Let's print the dataframeprint(df) Output : Now we will write the regular expression to match the string and then we will use Dataframe.replace() function to replace those names. # replace the matching stringsdf_updated = df.replace(to_replace ='[nN]ew', value = 'New_', regex = True) # Print the updated dataframeprint(df_updated) Output :As we can see in the output, the old strings have been replaced with the new ones successfully. Problem #2 : You are given a dataframe which contains the details about various events in different cities. The names of certain cities contain some additional details enclosed in a bracket. Search for such names and remove the additional details. Solution : For this task, we will write our own customized function using regular expression to identify and update the names of those cities. Additionally, We will use Dataframe.apply() function to apply our customized function on each values the column. # importing pandas as pdimport pandas as pd # Let's create a Dataframedf = pd.DataFrame({'City':['New York (City)', 'Parague', 'New Delhi (Delhi)', 'Venice', 'new Orleans'], 'Event':['Music', 'Poetry', 'Theatre', 'Comedy', 'Tech_Summit'], 'Cost':[10000, 5000, 15000, 2000, 12000]}) # Let's create the indexindex_ = [pd.Period('02-2018'), pd.Period('04-2018'), pd.Period('06-2018'), pd.Period('10-2018'), pd.Period('12-2018')] # Set the indexdf.index = index_ # Let's print the dataframeprint(df) Output : Now we will write our own customized function to match the description in the names of the cities. # Importing re package for using regular expressionsimport re # Function to clean the namesdef Clean_names(City_name): # Search for opening bracket in the name followed by # any characters repeated any number of times if re.search('\(.*', City_name): # Extract the position of beginning of pattern pos = re.search('\(.*', City_name).start() # return the cleaned name return City_name[:pos] else: # if clean up needed return the same name return City_name # Updated the city columnsdf['City'] = df['City'].apply(Clean_names) # Print the updated dataframeprint(df) Output : pandas-dataframe-program Python pandas-dataFrame Python Regex-programs Python-pandas python-regex Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python
[ { "code": null, "e": 24567, "s": 24539, "text": "\n29 Dec, 2020" }, { "code": null, "e": 25015, "s": 24567, "text": "While working with large sets of data, it often contains text data and in many cases, those texts are not pretty at all. The is often in very messier form and we need to clean those data before we can do anything meaningful with that text data. Mostly the text corpus is so large that we cannot manually list out all the texts that we want to replace. So in those cases, we use regular expressions to deal with such data having some pattern in it." }, { "code": null, "e": 25211, "s": 25015, "text": "We have already discussed in previous article how to replace some known string values in dataframe. In this post, we will use regular expressions to replace strings which have some pattern to it." }, { "code": null, "e": 25403, "s": 25211, "text": "Problem #1 : You are given a dataframe which contains the details about various events in different cities. For those cities which starts with the keyword ‘New’ or ‘new’, change it to ‘New_’." }, { "code": null, "e": 25548, "s": 25403, "text": "Solution : We are going to use regular expression to detect such names and then we will use Dataframe.replace() function to replace those names." }, { "code": "# importing pandas as pdimport pandas as pd # Let's create a Dataframedf = pd.DataFrame({'City':['New York', 'Parague', 'New Delhi', 'Venice', 'new Orleans'], 'Event':['Music', 'Poetry', 'Theatre', 'Comedy', 'Tech_Summit'], 'Cost':[10000, 5000, 15000, 2000, 12000]}) # Let's create the indexindex_ = [pd.Period('02-2018'), pd.Period('04-2018'), pd.Period('06-2018'), pd.Period('10-2018'), pd.Period('12-2018')] # Set the indexdf.index = index_ # Let's print the dataframeprint(df)", "e": 26080, "s": 25548, "text": null }, { "code": null, "e": 26089, "s": 26080, "text": "Output :" }, { "code": null, "e": 26224, "s": 26089, "text": "Now we will write the regular expression to match the string and then we will use Dataframe.replace() function to replace those names." }, { "code": "# replace the matching stringsdf_updated = df.replace(to_replace ='[nN]ew', value = 'New_', regex = True) # Print the updated dataframeprint(df_updated)", "e": 26378, "s": 26224, "text": null }, { "code": null, "e": 26730, "s": 26378, "text": "Output :As we can see in the output, the old strings have been replaced with the new ones successfully. Problem #2 : You are given a dataframe which contains the details about various events in different cities. The names of certain cities contain some additional details enclosed in a bracket. Search for such names and remove the additional details." }, { "code": null, "e": 26986, "s": 26730, "text": "Solution : For this task, we will write our own customized function using regular expression to identify and update the names of those cities. Additionally, We will use Dataframe.apply() function to apply our customized function on each values the column." }, { "code": "# importing pandas as pdimport pandas as pd # Let's create a Dataframedf = pd.DataFrame({'City':['New York (City)', 'Parague', 'New Delhi (Delhi)', 'Venice', 'new Orleans'], 'Event':['Music', 'Poetry', 'Theatre', 'Comedy', 'Tech_Summit'], 'Cost':[10000, 5000, 15000, 2000, 12000]}) # Let's create the indexindex_ = [pd.Period('02-2018'), pd.Period('04-2018'), pd.Period('06-2018'), pd.Period('10-2018'), pd.Period('12-2018')] # Set the indexdf.index = index_ # Let's print the dataframeprint(df)", "e": 27535, "s": 26986, "text": null }, { "code": null, "e": 27544, "s": 27535, "text": "Output :" }, { "code": null, "e": 27643, "s": 27544, "text": "Now we will write our own customized function to match the description in the names of the cities." }, { "code": "# Importing re package for using regular expressionsimport re # Function to clean the namesdef Clean_names(City_name): # Search for opening bracket in the name followed by # any characters repeated any number of times if re.search('\\(.*', City_name): # Extract the position of beginning of pattern pos = re.search('\\(.*', City_name).start() # return the cleaned name return City_name[:pos] else: # if clean up needed return the same name return City_name # Updated the city columnsdf['City'] = df['City'].apply(Clean_names) # Print the updated dataframeprint(df)", "e": 28277, "s": 27643, "text": null }, { "code": null, "e": 28286, "s": 28277, "text": "Output :" }, { "code": null, "e": 28311, "s": 28286, "text": "pandas-dataframe-program" }, { "code": null, "e": 28335, "s": 28311, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28357, "s": 28335, "text": "Python Regex-programs" }, { "code": null, "e": 28371, "s": 28357, "text": "Python-pandas" }, { "code": null, "e": 28384, "s": 28371, "text": "python-regex" }, { "code": null, "e": 28391, "s": 28384, "text": "Python" }, { "code": null, "e": 28489, "s": 28391, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28498, "s": 28489, "text": "Comments" }, { "code": null, "e": 28511, "s": 28498, "text": "Old Comments" }, { "code": null, "e": 28529, "s": 28511, "text": "Python Dictionary" }, { "code": null, "e": 28564, "s": 28529, "text": "Read a file line by line in Python" }, { "code": null, "e": 28586, "s": 28564, "text": "Enumerate() in Python" }, { "code": null, "e": 28618, "s": 28586, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28660, "s": 28618, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28704, "s": 28660, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28729, "s": 28704, "text": "sum() function in Python" }, { "code": null, "e": 28766, "s": 28729, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28822, "s": 28766, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
How to create a border pane using JavaFX?
Once you create all the required nodes for your application you can arrange them using a layout. Where a layout is a process of calculating the position of objects in the given space. JavaFX provides various layouts in the javafx.scene.layout package. In this layout, the nodes are arranged in the top, center, bottom, left, and, right positions. You can create a border pane in your application by instantiating the javafx.scene.layout.BorderPane class. There are five properties of this class (Node type) specifying the positions in the pane, namely, top, bottom, right, left, center. You can set nodes as values to these properties using the setTop(), setBottom(), setRight(), setleft() and, setCenter(). You can set the size of the border pane using the setPrefSize() method. To add nodes to this pane you can either pass them as arguments of the constructor or, add them to the observable list of the pane as − getChildren().addAll(); import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class BorderPaneExample extends Application { public void start(Stage stage) { //Creating buttons Button left = new Button("Left"); left.setPrefSize(200, 100); Button right = new Button("Right"); right.setPrefSize(200, 100); Button top = new Button("Top"); top.setPrefSize(595, 100); Button bottom = new Button("Buttom"); bottom.setPrefSize(595, 100); Button center = new Button("Center"); center.setPrefSize(200, 100); //Creating the border pane BorderPane pane = new BorderPane(); //Setting the top, bottom, center, right and left nodes to the pane pane.setTop(top); pane.setBottom(bottom); pane.setLeft(left); pane.setRight(right); pane.setCenter(center); //Setting the Scene Scene scene = new Scene(pane, 595, 300); stage.setTitle("Border Pane"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1314, "s": 1062, "text": "Once you create all the required nodes for your application you can arrange them using a layout. Where a layout is a process of calculating the position of objects in the given space. JavaFX provides various layouts in the javafx.scene.layout package." }, { "code": null, "e": 1517, "s": 1314, "text": "In this layout, the nodes are arranged in the top, center, bottom, left, and, right positions. You can create a border pane in your application by instantiating the javafx.scene.layout.BorderPane class." }, { "code": null, "e": 1770, "s": 1517, "text": "There are five properties of this class (Node type) specifying the positions in the pane, namely, top, bottom, right, left, center. You can set nodes as values to these properties using the setTop(), setBottom(), setRight(), setleft() and, setCenter()." }, { "code": null, "e": 1978, "s": 1770, "text": "You can set the size of the border pane using the setPrefSize() method. To add nodes to this pane you can either pass them as arguments of the constructor or, add them to the observable list of the pane as −" }, { "code": null, "e": 2002, "s": 1978, "text": "getChildren().addAll();" }, { "code": null, "e": 3187, "s": 2002, "text": "import javafx.application.Application;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Button;\nimport javafx.scene.layout.BorderPane;\nimport javafx.stage.Stage;\npublic class BorderPaneExample extends Application {\n public void start(Stage stage) {\n //Creating buttons\n Button left = new Button(\"Left\");\n left.setPrefSize(200, 100);\n Button right = new Button(\"Right\");\n right.setPrefSize(200, 100);\n Button top = new Button(\"Top\");\n top.setPrefSize(595, 100);\n Button bottom = new Button(\"Buttom\");\n bottom.setPrefSize(595, 100);\n Button center = new Button(\"Center\");\n center.setPrefSize(200, 100);\n //Creating the border pane\n BorderPane pane = new BorderPane();\n //Setting the top, bottom, center, right and left nodes to the pane\n pane.setTop(top);\n pane.setBottom(bottom);\n pane.setLeft(left);\n pane.setRight(right);\n pane.setCenter(center);\n //Setting the Scene\n Scene scene = new Scene(pane, 595, 300);\n stage.setTitle(\"Border Pane\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
Android | Alert Dialog Box and How to create it - GeeksforGeeks
01 Feb, 2019 Alert Dialog shows the Alert message and gives the answer in the form of yes or no. Alert Dialog displays the message to warn you and then according to your response the next step is processed. Android Alert Dialog is built with the use of three fields: Title, Message area, Action Button.Alert Dialog code has three methods: setTitle() method for displaying the Alert Dialog box Title setMessage() method for displaying the message setIcon() method is use to set the icon on Alert dialog box. Then we add the two Button, setPositiveButton and setNegativeButton to our Alert Dialog Box as shown below. Example: Below are the steps for Creating the Alert Dialog Android Application: Step 1: Create a new project. After that, you have java and XML file. Step 2: Open your XML file and then add TextView for message as shown below (you can change it accordingly). Step 3: Now, open up the activity java file. After, on create method declaration, the onbackpressed method is called when you click the back button of your device. Step 4: Create the object of Builder class Using AlertDialog.Builder. Now, set the Title, message. Step 5: In a builder object set the positive Button now gives the button name and add the OnClickListener of DialogInterface. Same as with the negative Button, at last, create the Alert dialog Box with builder object and then show the Alert Dialog. Step 6: Now if positive button press finish the app goto outside from the app if negative then finish the dialog box Step 7: Now run it and then press the back button. After that click Yes or No Button.The complete code of MainActivity.java or activity_main.xml of Alert Dialog is given below:activity_main.xmlMainActivity.javaactivity_main.xml<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Press The Back Button of Your Phone." android:textStyle="bold" android:textSize="30dp" android:gravity="center_horizontal" android:layout_marginTop="180dp" /> </RelativeLayout>MainActivity.javapackage org.geeksforgeeks.navedmalik.alertdialog; import android.content.DialogInterface;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // Declare the onBackPressed method // when the back button is pressed // this method will call @Override public void onBackPressed() { // Create the object of // AlertDialog Builder class AlertDialog.Builder builder = new AlertDialog .Builder(MainActivity.this); // Set the message show for the Alert time builder.setMessage("Do you want to exit ?"); // Set Alert Title builder.setTitle("Alert !"); // Set Cancelable false // for when the user clicks on the outside // the Dialog Box then it will remain show builder.setCancelable(false); // Set the positive button with yes name // OnClickListener method is use of // DialogInterface interface. builder .setPositiveButton( "Yes", new DialogInterface .OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // When the user click yes button // then app will close finish(); } }); // Set the Negative button with No name // OnClickListener method is use // of DialogInterface interface. builder .setNegativeButton( "No", new DialogInterface .OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // If user click no // then dialog box is canceled. dialog.cancel(); } }); // Create the Alert dialog AlertDialog alertDialog = builder.create(); // Show the Alert Dialog box alertDialog.show(); }}Output:Want a more fast-paced & competitive environment to learn the fundamentals of Android? Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!My Personal Notes arrow_drop_upSave The complete code of MainActivity.java or activity_main.xml of Alert Dialog is given below: activity_main.xml MainActivity.java <?xml version="1.0" encoding="utf-8"?><RelativeLayout 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"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Press The Back Button of Your Phone." android:textStyle="bold" android:textSize="30dp" android:gravity="center_horizontal" android:layout_marginTop="180dp" /> </RelativeLayout> package org.geeksforgeeks.navedmalik.alertdialog; import android.content.DialogInterface;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // Declare the onBackPressed method // when the back button is pressed // this method will call @Override public void onBackPressed() { // Create the object of // AlertDialog Builder class AlertDialog.Builder builder = new AlertDialog .Builder(MainActivity.this); // Set the message show for the Alert time builder.setMessage("Do you want to exit ?"); // Set Alert Title builder.setTitle("Alert !"); // Set Cancelable false // for when the user clicks on the outside // the Dialog Box then it will remain show builder.setCancelable(false); // Set the positive button with yes name // OnClickListener method is use of // DialogInterface interface. builder .setPositiveButton( "Yes", new DialogInterface .OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // When the user click yes button // then app will close finish(); } }); // Set the Negative button with No name // OnClickListener method is use // of DialogInterface interface. builder .setNegativeButton( "No", new DialogInterface .OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // If user click no // then dialog box is canceled. dialog.cancel(); } }); // Create the Alert dialog AlertDialog alertDialog = builder.create(); // Show the Alert Dialog box alertDialog.show(); }} vartika02 android Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Collections in Java Set in Java Overriding in Java
[ { "code": null, "e": 24091, "s": 24063, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24285, "s": 24091, "text": "Alert Dialog shows the Alert message and gives the answer in the form of yes or no. Alert Dialog displays the message to warn you and then according to your response the next step is processed." }, { "code": null, "e": 24417, "s": 24285, "text": "Android Alert Dialog is built with the use of three fields: Title, Message area, Action Button.Alert Dialog code has three methods:" }, { "code": null, "e": 24477, "s": 24417, "text": "setTitle() method for displaying the Alert Dialog box Title" }, { "code": null, "e": 24524, "s": 24477, "text": "setMessage() method for displaying the message" }, { "code": null, "e": 24585, "s": 24524, "text": "setIcon() method is use to set the icon on Alert dialog box." }, { "code": null, "e": 24693, "s": 24585, "text": "Then we add the two Button, setPositiveButton and setNegativeButton to our Alert Dialog Box as shown below." }, { "code": null, "e": 24702, "s": 24693, "text": "Example:" }, { "code": null, "e": 24773, "s": 24702, "text": "Below are the steps for Creating the Alert Dialog Android Application:" }, { "code": null, "e": 24843, "s": 24773, "text": "Step 1: Create a new project. After that, you have java and XML file." }, { "code": null, "e": 24952, "s": 24843, "text": "Step 2: Open your XML file and then add TextView for message as shown below (you can change it accordingly)." }, { "code": null, "e": 25116, "s": 24952, "text": "Step 3: Now, open up the activity java file. After, on create method declaration, the onbackpressed method is called when you click the back button of your device." }, { "code": null, "e": 25215, "s": 25116, "text": "Step 4: Create the object of Builder class Using AlertDialog.Builder. Now, set the Title, message." }, { "code": null, "e": 25464, "s": 25215, "text": "Step 5: In a builder object set the positive Button now gives the button name and add the OnClickListener of DialogInterface. Same as with the negative Button, at last, create the Alert dialog Box with builder object and then show the Alert Dialog." }, { "code": null, "e": 25581, "s": 25464, "text": "Step 6: Now if positive button press finish the app goto outside from the app if negative then finish the dialog box" }, { "code": null, "e": 29268, "s": 25581, "text": "Step 7: Now run it and then press the back button. After that click Yes or No Button.The complete code of MainActivity.java or activity_main.xml of Alert Dialog is given below:activity_main.xmlMainActivity.javaactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout 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\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Press The Back Button of Your Phone.\" android:textStyle=\"bold\" android:textSize=\"30dp\" android:gravity=\"center_horizontal\" android:layout_marginTop=\"180dp\" /> </RelativeLayout>MainActivity.javapackage org.geeksforgeeks.navedmalik.alertdialog; import android.content.DialogInterface;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // Declare the onBackPressed method // when the back button is pressed // this method will call @Override public void onBackPressed() { // Create the object of // AlertDialog Builder class AlertDialog.Builder builder = new AlertDialog .Builder(MainActivity.this); // Set the message show for the Alert time builder.setMessage(\"Do you want to exit ?\"); // Set Alert Title builder.setTitle(\"Alert !\"); // Set Cancelable false // for when the user clicks on the outside // the Dialog Box then it will remain show builder.setCancelable(false); // Set the positive button with yes name // OnClickListener method is use of // DialogInterface interface. builder .setPositiveButton( \"Yes\", new DialogInterface .OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // When the user click yes button // then app will close finish(); } }); // Set the Negative button with No name // OnClickListener method is use // of DialogInterface interface. builder .setNegativeButton( \"No\", new DialogInterface .OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // If user click no // then dialog box is canceled. dialog.cancel(); } }); // Create the Alert dialog AlertDialog alertDialog = builder.create(); // Show the Alert Dialog box alertDialog.show(); }}Output:Want a more fast-paced & competitive environment to learn the fundamentals of Android?\nClick here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29360, "s": 29268, "text": "The complete code of MainActivity.java or activity_main.xml of Alert Dialog is given below:" }, { "code": null, "e": 29378, "s": 29360, "text": "activity_main.xml" }, { "code": null, "e": 29396, "s": 29378, "text": "MainActivity.java" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout 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\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Press The Back Button of Your Phone.\" android:textStyle=\"bold\" android:textSize=\"30dp\" android:gravity=\"center_horizontal\" android:layout_marginTop=\"180dp\" /> </RelativeLayout>", "e": 30031, "s": 29396, "text": null }, { "code": "package org.geeksforgeeks.navedmalik.alertdialog; import android.content.DialogInterface;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // Declare the onBackPressed method // when the back button is pressed // this method will call @Override public void onBackPressed() { // Create the object of // AlertDialog Builder class AlertDialog.Builder builder = new AlertDialog .Builder(MainActivity.this); // Set the message show for the Alert time builder.setMessage(\"Do you want to exit ?\"); // Set Alert Title builder.setTitle(\"Alert !\"); // Set Cancelable false // for when the user clicks on the outside // the Dialog Box then it will remain show builder.setCancelable(false); // Set the positive button with yes name // OnClickListener method is use of // DialogInterface interface. builder .setPositiveButton( \"Yes\", new DialogInterface .OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // When the user click yes button // then app will close finish(); } }); // Set the Negative button with No name // OnClickListener method is use // of DialogInterface interface. builder .setNegativeButton( \"No\", new DialogInterface .OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // If user click no // then dialog box is canceled. dialog.cancel(); } }); // Create the Alert dialog AlertDialog alertDialog = builder.create(); // Show the Alert Dialog box alertDialog.show(); }}", "e": 32598, "s": 30031, "text": null }, { "code": null, "e": 32608, "s": 32598, "text": "vartika02" }, { "code": null, "e": 32616, "s": 32608, "text": "android" }, { "code": null, "e": 32621, "s": 32616, "text": "Java" }, { "code": null, "e": 32626, "s": 32621, "text": "Java" }, { "code": null, "e": 32724, "s": 32626, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32733, "s": 32724, "text": "Comments" }, { "code": null, "e": 32746, "s": 32733, "text": "Old Comments" }, { "code": null, "e": 32776, "s": 32746, "text": "HashMap in Java with Examples" }, { "code": null, "e": 32807, "s": 32776, "text": "How to iterate any Map in Java" }, { "code": null, "e": 32826, "s": 32807, "text": "Interfaces in Java" }, { "code": null, "e": 32858, "s": 32826, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 32878, "s": 32858, "text": "Stack Class in Java" }, { "code": null, "e": 32910, "s": 32878, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32934, "s": 32910, "text": "Singleton Class in Java" }, { "code": null, "e": 32954, "s": 32934, "text": "Collections in Java" }, { "code": null, "e": 32966, "s": 32954, "text": "Set in Java" } ]
My 10 recommendations after getting the Databricks Certification for Apache Spark | by Antonio Cachuan | Towards Data Science
Since some months ago I started to prepare myself to achieve the Databricks Certifications for Apache Spark. It was not easy because there is no much information about it so to promote self-preparation I’m going to share ten useful recommendations. This is the only non-technical recommendation but is also useful of all 9 remainings. When you have a deadline for taking an exam, you have more reasons and pressure to study. In this case for the exam, a 5–7 weeks preparation would make you ready for a successful result especially if you have work experience with Apache Spark. Register on the web page It will cost you $300 and you get 1 additional chance if you fail the first attempt (my advice is rescheduling the second attempt maximum between the next 2 weeks). You need a score minimum of 65% answering 40 questions of multiple alternatives in 3 hours and you can take the exam in Python or Scala. If you find your self in a disjunctive about wich Spark language API use Python or Scala my advice is that not worry so much because the question doesn’t need a deep knowledge of those programming languages. For example, you can find this type of questions where you are provided by a snippet of code (Python or Scala) and you need to identify which of then is incorrect. //Scalaval df = spark.read.format("parquet").load("/data/sales/june")df.createOrReplaceTempView("table")#Pythondf = spark.read.orc().load("/data/bikes/june")df.createGlobalTempView("table")#Pythonfrom pyspark.sql import RowmyRow = Row(3.14156, "Chicago", 7)import org.apache.spark.sql.functions.litdf.select(lit("7.5"), lit("11.47")).show(2) Could you find the incorrect code? So to face this kind of question remember the structures and the main options in Spark Dataframe (20%-25% of the questions), RDDs, SQL, Streaming and Graphframes. For example, these are the Write and Read core structures in Spark Dataframe. #ReadDataFrameReader.format(...).option("key","value").schema(...).load()#Read modes: permissive (default), dropMalformed and failFast.#WriteDataFrameWriter.format(...).option(...).partitionBy(...).bucketBy(...).sortBy(...).save()#Save modes: append, overwrite, errorIfExists (default) and ignore. If you used your mind to get the output of the code above well you are doing fine because during the test you are not allowed to check any documentation or even have a paper to take notes so you will find another kind of question where you need to identify the correct alternative (could be more than one) that produces the output showed based in one o more tables. #Table+---------+---------+| Name| Age| +---------+---------+| David| 71|| Angelica| 22|| Martin| 7|| Sol| 12|+---------+---------+#Output needed# Quantity of people greater than 21df = spark.read.format("csv")\ .option("header", "true")\ .option("inferSchema", "true")\ .load("/names/*.csv")df.where(col("Age")>21).count()df = spark.read.parquet("/names/*.parquet")\ .option("inferSchema", "true")\df.where("Age > 21").count()logic = "Age > 21"df = spark.read.("/names/*.parquet")\ .option("inferSchema", "true")\df.where(logic).count()df =spark.read.format("json").option("mode", "FAILFAST")\ .option("inferSchema", "true")\ .load("names.json")df.where("Age > 21").count() Could you find the correct code? Hint: exists more than one. Not only this kind of question is about Dataframes also is used in RDD question so study carefully some functions like map, reduce, flatmap, groupby, etc. My recommendation is to check the book Learning Spark especially chapters 3 and 4. Understand the Spark Architecture (15% of the exam) means have to read not only the official documentation and know the modules but also discover: How a simple or a complex query in Spark is executed? Spark’s different cluster managers What means ‘Lazy evaluation’, ‘Actions’, ‘Transformations’? Hierarchy of a Spark application Cluster deployment choices Basic knowledge of the Spark’s toolset The kind of question for Spark Architecture trying that you check if a concept or definition is correct or not. What means RDDs? What part of Spark are?Resilent Distributed Dataframes. Streaming APIResilent Distributed Datasets. Structured APIsResilent Distributed Datasets. Low lever APIs To go further in Architecture I recommend checking chapters 2, 3, 15 and 16 of the book Spark: The Definitive Guide. Around 10% of the questions are about Spark Structured Streaming* mainly trying that you recognize the correct code that will not produce errors to achieve that you need to have clear the basic components and definitions in this module. In this case, this code was obtained from the official Spark Documentation Repo on Github and shows a basic word count that get the data from a Socket, apply some basic logic and write the result in console with the outputMode complete. # Start running the query that prints the running counts to the consolefrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import explodefrom pyspark.sql.functions import splitspark = SparkSession \ .builder \ .appName("StructuredNetworkWordCount") \ .getOrCreate()lines = spark \ .readStream \ .format("socket") \ .option("host", "localhost") \ .option("port", 9999) \ .load()# Split the lines into wordswords = lines.select( explode( split(lines.value, " ") ).alias("word"))# Generate running word countwordCounts = words.groupBy("word").count()query = wordCounts \ .writeStream \ .outputMode("complete") \ .format("console") \ .start()query.awaitTermination() The questions for this module will require that you identify the correct or incorrect code. It will combine the different input sources (Apache Kafka, files, sockets, etc) and/or sinks (output) e.g. Apache Kafka, any file format, console, memory, etc. and also output modes: append, update and complete. To practice for this question read chapter 21 of the book Spark: The Definitive Guide. *I know that exists DStreams but it is low-level APIs and is unlikely to come in the exam. Like recommendation 5 exists few Graph Algorithms that you need to identify so my advice is to check first the concept of Graphs and Graphframes* (5%–10% of the questions) and then practice these algorithms: PageRank In-Degree and Out-Degree Metrics Breadth-First Search Connected Components Here, for example, we are creating a GraphFrame based on two Dataframes, if you want to practice more, you can find this code and a complete notebook in the GraphFrame user guide on Databricks from functools import reducefrom pyspark.sql.functions import col, lit, whenfrom graphframes import *vertices = sqlContext.createDataFrame([ ("a", "Alice", 34), ("b", "Bob", 36), ("c", "Charlie", 30), ("d", "David", 29), ("e", "Esther", 32), ("f", "Fanny", 36), ("g", "Gabby", 60)], ["id", "name", "age"])edges = sqlContext.createDataFrame([ ("a", "b", "friend"), ("b", "c", "follow"), ("c", "b", "follow"), ("f", "c", "follow"), ("e", "f", "follow"), ("e", "d", "friend"), ("d", "a", "friend"), ("a", "e", "friend")], ["src", "dst", "relationship"])g = GraphFrame(vertices, edges)print(g) *Also before Graphframes existed GraphX (still exists now) but for the first one is more utilized nowadays. Spark ML* (10% of the exam) is the module that is bundled with many machine learning algorithms for Classification, Regression, Clustering or for basic statistics, tunning, model selection and pipelines. Here you need to focus on understanding some must-know concepts like steps to build, train and apply a trained model. For example, is mandatory to have only number variables for all the algorithms so if you have a String column you need to use a StringIndexermethod a OneHotEncoderan encoder and all the variables are needed to be in one vector so we need to use the class VectorAssemblerto finally group all the transformation in a Pipeline from pyspark.ml.feature import StringIndexerindexer = StringIndexer()\ .setInputCol("month")\ .setOutputCol("month_index")from pyspark.ml.feature import OneHotEncoderencoder = OneHotEncoder()\ .setInputCol("month_index")\ .setOutputCol("month_encoded")from pyspark.ml.feature import VectorAssemblervectorAssembler = VectorAssembler()\ .setInputCols(["Sales", "month_encoded"])\ .setOutputCol("features")from pyspark.ml import PipelinetransfPipeline = Pipeline()\ .setStages([indexer, encoder, vectorAssembler])fitPipeline = transfPipeline.fit(trainDataFrame) *Spark MLlib is an RDD-based API that since Spark 2.0 have entered in maintenance mode so Spark ML is the primary ML API and is DataFrame-based. Going back to Spark RDDs (15% of questions) a question could be like ‘Select the alternative with all the Transformation (wide/narrow) or Actions’ so you need to make sure you recognize the majority of them. You have a good explanation in the Spark Documentation. Another important topic is to understand well these topics: Broadcast variables broadcastVar = sc.broadcast([1, 2, 3])broadcastVar.value Accumulators RDD Persistence Passing functions to Spark Coalesce, repartition What is the method of persistence cache()?MEMORY_ONLYMEMORY_AND_DISKDISK_ONLYOFF_HEAP Yes! I know you want to follow many fantastic tutorials that exist on Medium but to prepare for this exam I strongly recommend to choose one of these options that will let you focus in the content and not in configurations. I prefer Databricks because you get a small Spark cluster configured ready to start practicing for free. community.cloud.databricks.com colab.research.google.com notebooks.azure.com www.kaggle.com If you need some data to practice I recommend this Github repository where you can have CSVs, JSONs, Parquet, ORC files. Your friends on this road to learn more about Apache Spark are: Spark: The Definitive Guide Learning Spark Spark Documentation 5 Tips for Cracking Databricks Apache Spark Certification. Now you’re ready to become a certified Apache Spark Developer :) PS if you have any questions, or would like something clarified, you can find me on Twitter and LinkedIn. Also If you want to explore cloud certifications, I recently published an article about the Google Cloud Certification Challenge. towardsdatascience.com Update: This certification will be available until October 19 and now is available the Databricks Certified Associate Developer for Apache Spark 2.4 with the same topics (focus on Spark Architecture, SQL and Dataframes) Update 2 (early 2021): Databricks now also offers the Databricks Certified Associate Developer for Apache Spark 3.0 exam. In comparison to the Spark 2.4 exam, the Spark 3.0 exam also asks about new features in Spark 3.0, like Adaptive Query Execution. I highly recommend these great Databricks Certified Developer for Spark 3.0 Practice Exams[link: https://bit.ly/sparkpracticeexams] to prepare. The practice exams include explanations and a static PDF of the documentation, similar to what you would get in the real exam.
[ { "code": null, "e": 420, "s": 171, "text": "Since some months ago I started to prepare myself to achieve the Databricks Certifications for Apache Spark. It was not easy because there is no much information about it so to promote self-preparation I’m going to share ten useful recommendations." }, { "code": null, "e": 1077, "s": 420, "text": "This is the only non-technical recommendation but is also useful of all 9 remainings. When you have a deadline for taking an exam, you have more reasons and pressure to study. In this case for the exam, a 5–7 weeks preparation would make you ready for a successful result especially if you have work experience with Apache Spark. Register on the web page It will cost you $300 and you get 1 additional chance if you fail the first attempt (my advice is rescheduling the second attempt maximum between the next 2 weeks). You need a score minimum of 65% answering 40 questions of multiple alternatives in 3 hours and you can take the exam in Python or Scala." }, { "code": null, "e": 1449, "s": 1077, "text": "If you find your self in a disjunctive about wich Spark language API use Python or Scala my advice is that not worry so much because the question doesn’t need a deep knowledge of those programming languages. For example, you can find this type of questions where you are provided by a snippet of code (Python or Scala) and you need to identify which of then is incorrect." }, { "code": null, "e": 1791, "s": 1449, "text": "//Scalaval df = spark.read.format(\"parquet\").load(\"/data/sales/june\")df.createOrReplaceTempView(\"table\")#Pythondf = spark.read.orc().load(\"/data/bikes/june\")df.createGlobalTempView(\"table\")#Pythonfrom pyspark.sql import RowmyRow = Row(3.14156, \"Chicago\", 7)import org.apache.spark.sql.functions.litdf.select(lit(\"7.5\"), lit(\"11.47\")).show(2)" }, { "code": null, "e": 1826, "s": 1791, "text": "Could you find the incorrect code?" }, { "code": null, "e": 2067, "s": 1826, "text": "So to face this kind of question remember the structures and the main options in Spark Dataframe (20%-25% of the questions), RDDs, SQL, Streaming and Graphframes. For example, these are the Write and Read core structures in Spark Dataframe." }, { "code": null, "e": 2365, "s": 2067, "text": "#ReadDataFrameReader.format(...).option(\"key\",\"value\").schema(...).load()#Read modes: permissive (default), dropMalformed and failFast.#WriteDataFrameWriter.format(...).option(...).partitionBy(...).bucketBy(...).sortBy(...).save()#Save modes: append, overwrite, errorIfExists (default) and ignore." }, { "code": null, "e": 2731, "s": 2365, "text": "If you used your mind to get the output of the code above well you are doing fine because during the test you are not allowed to check any documentation or even have a paper to take notes so you will find another kind of question where you need to identify the correct alternative (could be more than one) that produces the output showed based in one o more tables." }, { "code": null, "e": 3457, "s": 2731, "text": "#Table+---------+---------+| Name| Age| +---------+---------+| David| 71|| Angelica| 22|| Martin| 7|| Sol| 12|+---------+---------+#Output needed# Quantity of people greater than 21df = spark.read.format(\"csv\")\\ .option(\"header\", \"true\")\\ .option(\"inferSchema\", \"true\")\\ .load(\"/names/*.csv\")df.where(col(\"Age\")>21).count()df = spark.read.parquet(\"/names/*.parquet\")\\ .option(\"inferSchema\", \"true\")\\df.where(\"Age > 21\").count()logic = \"Age > 21\"df = spark.read.(\"/names/*.parquet\")\\ .option(\"inferSchema\", \"true\")\\df.where(logic).count()df =spark.read.format(\"json\").option(\"mode\", \"FAILFAST\")\\ .option(\"inferSchema\", \"true\")\\ .load(\"names.json\")df.where(\"Age > 21\").count()" }, { "code": null, "e": 3518, "s": 3457, "text": "Could you find the correct code? Hint: exists more than one." }, { "code": null, "e": 3756, "s": 3518, "text": "Not only this kind of question is about Dataframes also is used in RDD question so study carefully some functions like map, reduce, flatmap, groupby, etc. My recommendation is to check the book Learning Spark especially chapters 3 and 4." }, { "code": null, "e": 3903, "s": 3756, "text": "Understand the Spark Architecture (15% of the exam) means have to read not only the official documentation and know the modules but also discover:" }, { "code": null, "e": 3957, "s": 3903, "text": "How a simple or a complex query in Spark is executed?" }, { "code": null, "e": 3992, "s": 3957, "text": "Spark’s different cluster managers" }, { "code": null, "e": 4052, "s": 3992, "text": "What means ‘Lazy evaluation’, ‘Actions’, ‘Transformations’?" }, { "code": null, "e": 4085, "s": 4052, "text": "Hierarchy of a Spark application" }, { "code": null, "e": 4112, "s": 4085, "text": "Cluster deployment choices" }, { "code": null, "e": 4151, "s": 4112, "text": "Basic knowledge of the Spark’s toolset" }, { "code": null, "e": 4263, "s": 4151, "text": "The kind of question for Spark Architecture trying that you check if a concept or definition is correct or not." }, { "code": null, "e": 4441, "s": 4263, "text": "What means RDDs? What part of Spark are?Resilent Distributed Dataframes. Streaming APIResilent Distributed Datasets. Structured APIsResilent Distributed Datasets. Low lever APIs" }, { "code": null, "e": 4558, "s": 4441, "text": "To go further in Architecture I recommend checking chapters 2, 3, 15 and 16 of the book Spark: The Definitive Guide." }, { "code": null, "e": 4795, "s": 4558, "text": "Around 10% of the questions are about Spark Structured Streaming* mainly trying that you recognize the correct code that will not produce errors to achieve that you need to have clear the basic components and definitions in this module." }, { "code": null, "e": 5032, "s": 4795, "text": "In this case, this code was obtained from the official Spark Documentation Repo on Github and shows a basic word count that get the data from a Socket, apply some basic logic and write the result in console with the outputMode complete." }, { "code": null, "e": 5752, "s": 5032, "text": "# Start running the query that prints the running counts to the consolefrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import explodefrom pyspark.sql.functions import splitspark = SparkSession \\ .builder \\ .appName(\"StructuredNetworkWordCount\") \\ .getOrCreate()lines = spark \\ .readStream \\ .format(\"socket\") \\ .option(\"host\", \"localhost\") \\ .option(\"port\", 9999) \\ .load()# Split the lines into wordswords = lines.select( explode( split(lines.value, \" \") ).alias(\"word\"))# Generate running word countwordCounts = words.groupBy(\"word\").count()query = wordCounts \\ .writeStream \\ .outputMode(\"complete\") \\ .format(\"console\") \\ .start()query.awaitTermination()" }, { "code": null, "e": 6143, "s": 5752, "text": "The questions for this module will require that you identify the correct or incorrect code. It will combine the different input sources (Apache Kafka, files, sockets, etc) and/or sinks (output) e.g. Apache Kafka, any file format, console, memory, etc. and also output modes: append, update and complete. To practice for this question read chapter 21 of the book Spark: The Definitive Guide." }, { "code": null, "e": 6234, "s": 6143, "text": "*I know that exists DStreams but it is low-level APIs and is unlikely to come in the exam." }, { "code": null, "e": 6442, "s": 6234, "text": "Like recommendation 5 exists few Graph Algorithms that you need to identify so my advice is to check first the concept of Graphs and Graphframes* (5%–10% of the questions) and then practice these algorithms:" }, { "code": null, "e": 6451, "s": 6442, "text": "PageRank" }, { "code": null, "e": 6484, "s": 6451, "text": "In-Degree and Out-Degree Metrics" }, { "code": null, "e": 6505, "s": 6484, "text": "Breadth-First Search" }, { "code": null, "e": 6526, "s": 6505, "text": "Connected Components" }, { "code": null, "e": 6719, "s": 6526, "text": "Here, for example, we are creating a GraphFrame based on two Dataframes, if you want to practice more, you can find this code and a complete notebook in the GraphFrame user guide on Databricks" }, { "code": null, "e": 7324, "s": 6719, "text": "from functools import reducefrom pyspark.sql.functions import col, lit, whenfrom graphframes import *vertices = sqlContext.createDataFrame([ (\"a\", \"Alice\", 34), (\"b\", \"Bob\", 36), (\"c\", \"Charlie\", 30), (\"d\", \"David\", 29), (\"e\", \"Esther\", 32), (\"f\", \"Fanny\", 36), (\"g\", \"Gabby\", 60)], [\"id\", \"name\", \"age\"])edges = sqlContext.createDataFrame([ (\"a\", \"b\", \"friend\"), (\"b\", \"c\", \"follow\"), (\"c\", \"b\", \"follow\"), (\"f\", \"c\", \"follow\"), (\"e\", \"f\", \"follow\"), (\"e\", \"d\", \"friend\"), (\"d\", \"a\", \"friend\"), (\"a\", \"e\", \"friend\")], [\"src\", \"dst\", \"relationship\"])g = GraphFrame(vertices, edges)print(g)" }, { "code": null, "e": 7432, "s": 7324, "text": "*Also before Graphframes existed GraphX (still exists now) but for the first one is more utilized nowadays." }, { "code": null, "e": 7636, "s": 7432, "text": "Spark ML* (10% of the exam) is the module that is bundled with many machine learning algorithms for Classification, Regression, Clustering or for basic statistics, tunning, model selection and pipelines." }, { "code": null, "e": 8078, "s": 7636, "text": "Here you need to focus on understanding some must-know concepts like steps to build, train and apply a trained model. For example, is mandatory to have only number variables for all the algorithms so if you have a String column you need to use a StringIndexermethod a OneHotEncoderan encoder and all the variables are needed to be in one vector so we need to use the class VectorAssemblerto finally group all the transformation in a Pipeline" }, { "code": null, "e": 8644, "s": 8078, "text": "from pyspark.ml.feature import StringIndexerindexer = StringIndexer()\\ .setInputCol(\"month\")\\ .setOutputCol(\"month_index\")from pyspark.ml.feature import OneHotEncoderencoder = OneHotEncoder()\\ .setInputCol(\"month_index\")\\ .setOutputCol(\"month_encoded\")from pyspark.ml.feature import VectorAssemblervectorAssembler = VectorAssembler()\\ .setInputCols([\"Sales\", \"month_encoded\"])\\ .setOutputCol(\"features\")from pyspark.ml import PipelinetransfPipeline = Pipeline()\\ .setStages([indexer, encoder, vectorAssembler])fitPipeline = transfPipeline.fit(trainDataFrame)" }, { "code": null, "e": 8789, "s": 8644, "text": "*Spark MLlib is an RDD-based API that since Spark 2.0 have entered in maintenance mode so Spark ML is the primary ML API and is DataFrame-based." }, { "code": null, "e": 9053, "s": 8789, "text": "Going back to Spark RDDs (15% of questions) a question could be like ‘Select the alternative with all the Transformation (wide/narrow) or Actions’ so you need to make sure you recognize the majority of them. You have a good explanation in the Spark Documentation." }, { "code": null, "e": 9113, "s": 9053, "text": "Another important topic is to understand well these topics:" }, { "code": null, "e": 9133, "s": 9113, "text": "Broadcast variables" }, { "code": null, "e": 9190, "s": 9133, "text": "broadcastVar = sc.broadcast([1, 2, 3])broadcastVar.value" }, { "code": null, "e": 9203, "s": 9190, "text": "Accumulators" }, { "code": null, "e": 9219, "s": 9203, "text": "RDD Persistence" }, { "code": null, "e": 9246, "s": 9219, "text": "Passing functions to Spark" }, { "code": null, "e": 9268, "s": 9246, "text": "Coalesce, repartition" }, { "code": null, "e": 9354, "s": 9268, "text": "What is the method of persistence cache()?MEMORY_ONLYMEMORY_AND_DISKDISK_ONLYOFF_HEAP" }, { "code": null, "e": 9683, "s": 9354, "text": "Yes! I know you want to follow many fantastic tutorials that exist on Medium but to prepare for this exam I strongly recommend to choose one of these options that will let you focus in the content and not in configurations. I prefer Databricks because you get a small Spark cluster configured ready to start practicing for free." }, { "code": null, "e": 9714, "s": 9683, "text": "community.cloud.databricks.com" }, { "code": null, "e": 9740, "s": 9714, "text": "colab.research.google.com" }, { "code": null, "e": 9760, "s": 9740, "text": "notebooks.azure.com" }, { "code": null, "e": 9775, "s": 9760, "text": "www.kaggle.com" }, { "code": null, "e": 9896, "s": 9775, "text": "If you need some data to practice I recommend this Github repository where you can have CSVs, JSONs, Parquet, ORC files." }, { "code": null, "e": 9960, "s": 9896, "text": "Your friends on this road to learn more about Apache Spark are:" }, { "code": null, "e": 9988, "s": 9960, "text": "Spark: The Definitive Guide" }, { "code": null, "e": 10003, "s": 9988, "text": "Learning Spark" }, { "code": null, "e": 10023, "s": 10003, "text": "Spark Documentation" }, { "code": null, "e": 10082, "s": 10023, "text": "5 Tips for Cracking Databricks Apache Spark Certification." }, { "code": null, "e": 10147, "s": 10082, "text": "Now you’re ready to become a certified Apache Spark Developer :)" }, { "code": null, "e": 10383, "s": 10147, "text": "PS if you have any questions, or would like something clarified, you can find me on Twitter and LinkedIn. Also If you want to explore cloud certifications, I recently published an article about the Google Cloud Certification Challenge." }, { "code": null, "e": 10406, "s": 10383, "text": "towardsdatascience.com" }, { "code": null, "e": 10626, "s": 10406, "text": "Update: This certification will be available until October 19 and now is available the Databricks Certified Associate Developer for Apache Spark 2.4 with the same topics (focus on Spark Architecture, SQL and Dataframes)" } ]
10 Tricks for Data Scientists using Jupyter Notebooks | by Benedikt Droste | Towards Data Science
When I started to use Python for data analysis, I found out very fast that Jupyter notebooks are a great tool to give my code a better structure. However, some things were still annoying. If I use headlines for better readability, larger notebooks get quickly confusing. If I calculate more than one value in a cell, I receive just an output for the last variable and so on and so on...But hey, we are using Python and other people had the same problems and found great solutions for it. I want to share some of them. Table of contents: 1. Two datasets side by side2. Print every output from a specific cell3. Change screen width4. Jupyter extensions4.1 Code folding4.2 Collapsible heading4.3 Execution time4.4 Scratchpad4.5 Kernle idle4.6 Zenmode4.7 Table beautifier Sometimes I want to compare two smaller dataframes side by side. With the following css-snippet you can adjust the output: CSS = """.output {flex-direction: row;}"""HTML('<style>{}</style>'.format(CSS)) Now you can use display(df) with multiple dataframes in one single Jupyter cell: Imagine you calculate two variables in one cell (even if it is not best practice 😉). Usually just the last result appears: Just add this syntax and every result will be printed: from IPython.core.interactiveshell import InteractiveShellInteractiveShell.ast_node_interactivity = "all" With the standard configuration the Jupyter notebook covers 60% of your screen. With a short css command you can adjust the width (here 80%): from IPython.core.display import display, HTMLdisplay(HTML("<style>.container { width:80% !important; }</style>")) In the following screenshot you see the result: Now we come to a very interesting topic: Jupyter extensions. As I already mentioned, a lot of people wrote extensions to optimize notebooks. I will show you some really useful extensions for data science. If you are using conda, just type: conda install -c conda-forge jupyter_contrib_nbextensions After you will have access to the Jupyter extensions. In the menu you usually start notebooks, you can also choose the extensions now (red-marked area). I will show you 7useful extensions (green-marked area). You can activate them by clicking the checkboxes: If you write a lot of code, it can be confusing to read it after a while. With Codefolding you can hide indented code If you activate the extensions Codefolding , a little triangle will appear in the upper left corner of each cell. You can click on it and indented code will be minimized. Collapsible heading will make every project better readable. The extensions before helped you to structure the content of cells. With this extension you can give the whole notebook a better structure: In the screenshot, you see the first part of the notebook I created for this article. The first headline is created with # and the second with ## . Similar to the Codefolding extension, you can use Collapsible heading with the little triangles in the upper left corner. You can click on it and all the content after a headline will be hidden: It is a hierarchical system, h2 headlines will also be hidden if you click on the triangle of an h1 headline: As soon as you are familiar with Python packages for data analysis, you want to improve the performance of your code. The Jupyter magic command %% timeit is great for getting the execution time of a cell because it will be executed 100 or 1000 times for example to get a valid mean of the execution time. For faster checks, the extension Execution time is great because it will always show the needed time in each output cell: Sometimes I want to try something in a notebook. Usually, I create a cell and afterwards I am deleting it. But in larger projects, I sometimes forget to delete some junk and I got unnecessary commands in my notebook. A better practice is to use Scratchpad . This extension allows to create “throw-away” snippets: As soon as you activate the extension you can open your Scratchpad with the little triangle in the right bottom corner. Larger scripts take sometimes minutes or even hours to execute. With the extension Kernle idle you will receive a notification from your browser when the execution is finished: You can disable the notification or change the timing in the top of your notebook. If you change the timing to 30, you will just receive notifications for scripts which need more than 30 seconds to execute. In the screenshot below you can see a clean notebook without unnecessary menus. I like this look very much and you can get it by activating the zenmode mode: I think it is important to learn the Python code and I think it ́s always better to document everything you do with the syntax. With the Table beautifier you can sort columns or the index by clicking on it. For fast checks this can be really useful: Jupyter notebooks are great for analysis but there is still some potential to make them even better. As data scientist, there are some really useful css snippets and extensions to make your work more comfortable. I hope you enjoyed this article. If you know about any other useful extensions, feel free to post a comment. If you enjoy Medium and Towards Data Science and didn’t sign up yet, feel free to use my referral link to join the community.
[ { "code": null, "e": 690, "s": 172, "text": "When I started to use Python for data analysis, I found out very fast that Jupyter notebooks are a great tool to give my code a better structure. However, some things were still annoying. If I use headlines for better readability, larger notebooks get quickly confusing. If I calculate more than one value in a cell, I receive just an output for the last variable and so on and so on...But hey, we are using Python and other people had the same problems and found great solutions for it. I want to share some of them." }, { "code": null, "e": 709, "s": 690, "text": "Table of contents:" }, { "code": null, "e": 940, "s": 709, "text": "1. Two datasets side by side2. Print every output from a specific cell3. Change screen width4. Jupyter extensions4.1 Code folding4.2 Collapsible heading4.3 Execution time4.4 Scratchpad4.5 Kernle idle4.6 Zenmode4.7 Table beautifier" }, { "code": null, "e": 1063, "s": 940, "text": "Sometimes I want to compare two smaller dataframes side by side. With the following css-snippet you can adjust the output:" }, { "code": null, "e": 1143, "s": 1063, "text": "CSS = \"\"\".output {flex-direction: row;}\"\"\"HTML('<style>{}</style>'.format(CSS))" }, { "code": null, "e": 1224, "s": 1143, "text": "Now you can use display(df) with multiple dataframes in one single Jupyter cell:" }, { "code": null, "e": 1347, "s": 1224, "text": "Imagine you calculate two variables in one cell (even if it is not best practice 😉). Usually just the last result appears:" }, { "code": null, "e": 1402, "s": 1347, "text": "Just add this syntax and every result will be printed:" }, { "code": null, "e": 1508, "s": 1402, "text": "from IPython.core.interactiveshell import InteractiveShellInteractiveShell.ast_node_interactivity = \"all\"" }, { "code": null, "e": 1650, "s": 1508, "text": "With the standard configuration the Jupyter notebook covers 60% of your screen. With a short css command you can adjust the width (here 80%):" }, { "code": null, "e": 1765, "s": 1650, "text": "from IPython.core.display import display, HTMLdisplay(HTML(\"<style>.container { width:80% !important; }</style>\"))" }, { "code": null, "e": 1813, "s": 1765, "text": "In the following screenshot you see the result:" }, { "code": null, "e": 2053, "s": 1813, "text": "Now we come to a very interesting topic: Jupyter extensions. As I already mentioned, a lot of people wrote extensions to optimize notebooks. I will show you some really useful extensions for data science. If you are using conda, just type:" }, { "code": null, "e": 2111, "s": 2053, "text": "conda install -c conda-forge jupyter_contrib_nbextensions" }, { "code": null, "e": 2370, "s": 2111, "text": "After you will have access to the Jupyter extensions. In the menu you usually start notebooks, you can also choose the extensions now (red-marked area). I will show you 7useful extensions (green-marked area). You can activate them by clicking the checkboxes:" }, { "code": null, "e": 2488, "s": 2370, "text": "If you write a lot of code, it can be confusing to read it after a while. With Codefolding you can hide indented code" }, { "code": null, "e": 2659, "s": 2488, "text": "If you activate the extensions Codefolding , a little triangle will appear in the upper left corner of each cell. You can click on it and indented code will be minimized." }, { "code": null, "e": 2860, "s": 2659, "text": "Collapsible heading will make every project better readable. The extensions before helped you to structure the content of cells. With this extension you can give the whole notebook a better structure:" }, { "code": null, "e": 3203, "s": 2860, "text": "In the screenshot, you see the first part of the notebook I created for this article. The first headline is created with # and the second with ## . Similar to the Codefolding extension, you can use Collapsible heading with the little triangles in the upper left corner. You can click on it and all the content after a headline will be hidden:" }, { "code": null, "e": 3313, "s": 3203, "text": "It is a hierarchical system, h2 headlines will also be hidden if you click on the triangle of an h1 headline:" }, { "code": null, "e": 3740, "s": 3313, "text": "As soon as you are familiar with Python packages for data analysis, you want to improve the performance of your code. The Jupyter magic command %% timeit is great for getting the execution time of a cell because it will be executed 100 or 1000 times for example to get a valid mean of the execution time. For faster checks, the extension Execution time is great because it will always show the needed time in each output cell:" }, { "code": null, "e": 4053, "s": 3740, "text": "Sometimes I want to try something in a notebook. Usually, I create a cell and afterwards I am deleting it. But in larger projects, I sometimes forget to delete some junk and I got unnecessary commands in my notebook. A better practice is to use Scratchpad . This extension allows to create “throw-away” snippets:" }, { "code": null, "e": 4173, "s": 4053, "text": "As soon as you activate the extension you can open your Scratchpad with the little triangle in the right bottom corner." }, { "code": null, "e": 4350, "s": 4173, "text": "Larger scripts take sometimes minutes or even hours to execute. With the extension Kernle idle you will receive a notification from your browser when the execution is finished:" }, { "code": null, "e": 4557, "s": 4350, "text": "You can disable the notification or change the timing in the top of your notebook. If you change the timing to 30, you will just receive notifications for scripts which need more than 30 seconds to execute." }, { "code": null, "e": 4715, "s": 4557, "text": "In the screenshot below you can see a clean notebook without unnecessary menus. I like this look very much and you can get it by activating the zenmode mode:" }, { "code": null, "e": 4965, "s": 4715, "text": "I think it is important to learn the Python code and I think it ́s always better to document everything you do with the syntax. With the Table beautifier you can sort columns or the index by clicking on it. For fast checks this can be really useful:" }, { "code": null, "e": 5287, "s": 4965, "text": "Jupyter notebooks are great for analysis but there is still some potential to make them even better. As data scientist, there are some really useful css snippets and extensions to make your work more comfortable. I hope you enjoyed this article. If you know about any other useful extensions, feel free to post a comment." } ]
7 Points to Create Better Histograms with Seaborn | by Soner Yıldırım | Towards Data Science
Data visualization is of crucial importance in data science. It helps us explore the underlying structure within a dataset as well as the relationships between variables. We can also use data visualization techniques to report our findings more effectively. How we deliver a message through data visualization is also important. We can make the plots more informative or appealing by small adjustments. Data visualization libraries provide several parameters to customize the generated plots. In this article, we will go over 7 points to customize a histogram in Seaborn library. Histograms are mainly used to check the distribution of a continuous variable. It divides the value range into discrete bins and shows the number of data points (i.e. rows) in each bin. We will create a sample dataframe with two columns, one continuous and one categorical. We first import the libraries. import numpy as npimport pandas as pdimport seaborn as snssns.set(style='darkgrid') We can now create the sample dataframe with NumPy and Pandas. df1 = pd.DataFrame({'col1':'A', 'col2':np.random.randn(100) * 10 + 50})df2 = pd.DataFrame({'col1':'B', 'col2':np.random.randn(100) * 10 + 60})df3 = pd.DataFrame({'col1':'C', 'col2':np.random.randn(100) * 10 + 70})df = pd.concat([df1, df2, df3]) The “col1” includes three distinct categories and the “col2” includes normally distributed numerical values. Let’s start by creating a simple histogram with default settings. We will then try to improve it throughout the article. The displot function of Seaborn is used for creating distribution plots. The kind parameter is set as ‘hist’ to generate a histogram. sns.displot(data=df, x='col2', kind='hist') The first and foremost adjustment is the size. The height seems to be fine but a wider plot might look better. The two parameters to customize the size are the height and aspect which is the ratio of the width and height. sns.displot(data=df, x='col2', kind='hist', height=6, aspect=1.4) Increasing the number of bins is like increasing the resolution of an image. We get a more detailed overview of the distribution by dividing the value range into more bins. The number of desired bins is passed to the bins parameter. sns.displot(data=df, x='col2', kind='hist', height=6, aspect=1.4, bins=18) The “col1” column has three distinct categories. We may want to see the distribution for each category separately. One way to put apart the categories is the hue parameter. We just pass the name of the column to be used as separator. sns.displot(data=df, x='col2', kind='hist', height=6, aspect=1.4, bins=18, hue='col1') Each category is displayed with a different color. Bars representing the bins are placed on top of each other. If you prefer to display them side-by-side, you can use the multiple parameter as follows. sns.displot(data=df, x='col2', kind='hist', height=6, aspect=1.4, bins=18, hue='col1', multiple='dodge') Another way to generate separate distributions for different categories is to create a grid of plots. The col parameter is used to represent each category as a new column. Similarly, the row parameter does the same using rows. sns.displot(data=df, x='col2', kind='hist', bins=18, col='col1') In some cases, we may need to check the distribution of a specific range. For instance, if a variable contains extreme outliers, a histogram that contains all the values will not tell us much. We can use the “binrange” parameter to determine the upper and lower limit of the range to be plotted. Before implementing this feature, let’s add a few outliers to our dataframe. df4 = pd.DataFrame({'col1':'D', 'col2':np.random.randn(10) * 10 + 1000})df_new = pd.concat([df, df4]) The histogram for the entire value range looks as below. sns.displot(data=df_new, x='col2', kind='hist', height=6, aspect=1.4) We can narrow the range down to the interval between 20 and 100. sns.displot(data=df_new, x='col2', kind='hist', height=6, aspect=1.4, binrange=(20,100)) Another method to visualize the distribution of a variable with outliers is to transform the value with scaling. For instance, we can use log scaling on the dataframe in previous example. sns.displot(data=df_new, x='col2', kind='hist', height=6, aspect=1.4, log_scale=True) The effect of outliers is eliminated to a certain extent. Color is an important part of visualizations. We have lots of options for the color of bars. If we use the hue parameter to distinguish between categories, we can change the colors using the palette parameter. sns.displot(data=df, x='col2', bins=18, height=6, aspect=1.4, hue='col1', palette='GnBu') If you want to quickly see the available options for the palette value, just input a random value and the error message will display all the possible choices. If we are not using the hue parameter, we can change the color simply by using the color parameter. sns.displot(data=df, x='col2', bins=18, height=6, aspect=1.4, color='lightblue') We have covered 7 tips for making the histograms more informative and appealing. There are other techniques to further customize these visualizations but the 7 tips in this article will be enough in most cases. Data visualizations are highly important in data science. They are not only helpful for reporting and delivering results but also a powerful tool for data analysis. In order to make most out of data visualization, we need to go beyond the default settings of a function or library in some cases. Therefore, we should learn how to customize or adjust them. Thank you reading. Please let me know if you have any feedback.
[ { "code": null, "e": 430, "s": 172, "text": "Data visualization is of crucial importance in data science. It helps us explore the underlying structure within a dataset as well as the relationships between variables. We can also use data visualization techniques to report our findings more effectively." }, { "code": null, "e": 665, "s": 430, "text": "How we deliver a message through data visualization is also important. We can make the plots more informative or appealing by small adjustments. Data visualization libraries provide several parameters to customize the generated plots." }, { "code": null, "e": 938, "s": 665, "text": "In this article, we will go over 7 points to customize a histogram in Seaborn library. Histograms are mainly used to check the distribution of a continuous variable. It divides the value range into discrete bins and shows the number of data points (i.e. rows) in each bin." }, { "code": null, "e": 1057, "s": 938, "text": "We will create a sample dataframe with two columns, one continuous and one categorical. We first import the libraries." }, { "code": null, "e": 1141, "s": 1057, "text": "import numpy as npimport pandas as pdimport seaborn as snssns.set(style='darkgrid')" }, { "code": null, "e": 1203, "s": 1141, "text": "We can now create the sample dataframe with NumPy and Pandas." }, { "code": null, "e": 1508, "s": 1203, "text": "df1 = pd.DataFrame({'col1':'A', 'col2':np.random.randn(100) * 10 + 50})df2 = pd.DataFrame({'col1':'B', 'col2':np.random.randn(100) * 10 + 60})df3 = pd.DataFrame({'col1':'C', 'col2':np.random.randn(100) * 10 + 70})df = pd.concat([df1, df2, df3])" }, { "code": null, "e": 1617, "s": 1508, "text": "The “col1” includes three distinct categories and the “col2” includes normally distributed numerical values." }, { "code": null, "e": 1872, "s": 1617, "text": "Let’s start by creating a simple histogram with default settings. We will then try to improve it throughout the article. The displot function of Seaborn is used for creating distribution plots. The kind parameter is set as ‘hist’ to generate a histogram." }, { "code": null, "e": 1916, "s": 1872, "text": "sns.displot(data=df, x='col2', kind='hist')" }, { "code": null, "e": 2138, "s": 1916, "text": "The first and foremost adjustment is the size. The height seems to be fine but a wider plot might look better. The two parameters to customize the size are the height and aspect which is the ratio of the width and height." }, { "code": null, "e": 2215, "s": 2138, "text": "sns.displot(data=df, x='col2', kind='hist', height=6, aspect=1.4)" }, { "code": null, "e": 2388, "s": 2215, "text": "Increasing the number of bins is like increasing the resolution of an image. We get a more detailed overview of the distribution by dividing the value range into more bins." }, { "code": null, "e": 2448, "s": 2388, "text": "The number of desired bins is passed to the bins parameter." }, { "code": null, "e": 2534, "s": 2448, "text": "sns.displot(data=df, x='col2', kind='hist', height=6, aspect=1.4, bins=18)" }, { "code": null, "e": 2707, "s": 2534, "text": "The “col1” column has three distinct categories. We may want to see the distribution for each category separately. One way to put apart the categories is the hue parameter." }, { "code": null, "e": 2768, "s": 2707, "text": "We just pass the name of the column to be used as separator." }, { "code": null, "e": 2877, "s": 2768, "text": "sns.displot(data=df, x='col2', kind='hist', height=6, aspect=1.4, bins=18, hue='col1')" }, { "code": null, "e": 3079, "s": 2877, "text": "Each category is displayed with a different color. Bars representing the bins are placed on top of each other. If you prefer to display them side-by-side, you can use the multiple parameter as follows." }, { "code": null, "e": 3206, "s": 3079, "text": "sns.displot(data=df, x='col2', kind='hist', height=6, aspect=1.4, bins=18, hue='col1', multiple='dodge')" }, { "code": null, "e": 3433, "s": 3206, "text": "Another way to generate separate distributions for different categories is to create a grid of plots. The col parameter is used to represent each category as a new column. Similarly, the row parameter does the same using rows." }, { "code": null, "e": 3510, "s": 3433, "text": "sns.displot(data=df, x='col2', kind='hist', bins=18, col='col1')" }, { "code": null, "e": 3703, "s": 3510, "text": "In some cases, we may need to check the distribution of a specific range. For instance, if a variable contains extreme outliers, a histogram that contains all the values will not tell us much." }, { "code": null, "e": 3806, "s": 3703, "text": "We can use the “binrange” parameter to determine the upper and lower limit of the range to be plotted." }, { "code": null, "e": 3883, "s": 3806, "text": "Before implementing this feature, let’s add a few outliers to our dataframe." }, { "code": null, "e": 4005, "s": 3883, "text": "df4 = pd.DataFrame({'col1':'D', 'col2':np.random.randn(10) * 10 + 1000})df_new = pd.concat([df, df4])" }, { "code": null, "e": 4062, "s": 4005, "text": "The histogram for the entire value range looks as below." }, { "code": null, "e": 4143, "s": 4062, "text": "sns.displot(data=df_new, x='col2', kind='hist', height=6, aspect=1.4)" }, { "code": null, "e": 4208, "s": 4143, "text": "We can narrow the range down to the interval between 20 and 100." }, { "code": null, "e": 4319, "s": 4208, "text": "sns.displot(data=df_new, x='col2', kind='hist', height=6, aspect=1.4, binrange=(20,100))" }, { "code": null, "e": 4507, "s": 4319, "text": "Another method to visualize the distribution of a variable with outliers is to transform the value with scaling. For instance, we can use log scaling on the dataframe in previous example." }, { "code": null, "e": 4615, "s": 4507, "text": "sns.displot(data=df_new, x='col2', kind='hist', height=6, aspect=1.4, log_scale=True)" }, { "code": null, "e": 4673, "s": 4615, "text": "The effect of outliers is eliminated to a certain extent." }, { "code": null, "e": 4883, "s": 4673, "text": "Color is an important part of visualizations. We have lots of options for the color of bars. If we use the hue parameter to distinguish between categories, we can change the colors using the palette parameter." }, { "code": null, "e": 4995, "s": 4883, "text": "sns.displot(data=df, x='col2', bins=18, height=6, aspect=1.4, hue='col1', palette='GnBu')" }, { "code": null, "e": 5154, "s": 4995, "text": "If you want to quickly see the available options for the palette value, just input a random value and the error message will display all the possible choices." }, { "code": null, "e": 5254, "s": 5154, "text": "If we are not using the hue parameter, we can change the color simply by using the color parameter." }, { "code": null, "e": 5357, "s": 5254, "text": "sns.displot(data=df, x='col2', bins=18, height=6, aspect=1.4, color='lightblue')" }, { "code": null, "e": 5568, "s": 5357, "text": "We have covered 7 tips for making the histograms more informative and appealing. There are other techniques to further customize these visualizations but the 7 tips in this article will be enough in most cases." }, { "code": null, "e": 5733, "s": 5568, "text": "Data visualizations are highly important in data science. They are not only helpful for reporting and delivering results but also a powerful tool for data analysis." }, { "code": null, "e": 5924, "s": 5733, "text": "In order to make most out of data visualization, we need to go beyond the default settings of a function or library in some cases. Therefore, we should learn how to customize or adjust them." } ]
How to create a stacked bar chart for my DataFrame using Seaborn in Matplotlib?
To create a stacked bar chart, we can use Seaborn's barplot() method, i.e., show point estimates and confidence intervals with bars. Create df using Pandas Data Frame. Create df using Pandas Data Frame. Using barplot() method, create bar_plot1 and bar_plot2 with color as red and green, and label as count and select. Using barplot() method, create bar_plot1 and bar_plot2 with color as red and green, and label as count and select. To enable legend, use legend() method, at the upper-right location. To enable legend, use legend() method, at the upper-right location. To display the figuree, use show() method. To display the figuree, use show() method. import pandas import matplotlib.pylab as plt import seaborn as sns plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True df = pandas.DataFrame(dict( number=[2, 5, 1, 6, 3], count=[56, 21, 34, 36, 12], select=[29, 13, 17, 21, 8] )) bar_plot1 = sns.barplot(x='number', y='count', data=df, label="count", color="red") bar_plot2 = sns.barplot(x='number', y='select', data=df, label="select", color="green") plt.legend(ncol=2, loc="upper right", frameon=True) plt.show()
[ { "code": null, "e": 1195, "s": 1062, "text": "To create a stacked bar chart, we can use Seaborn's barplot() method, i.e., show point estimates and confidence intervals with bars." }, { "code": null, "e": 1230, "s": 1195, "text": "Create df using Pandas Data Frame." }, { "code": null, "e": 1265, "s": 1230, "text": "Create df using Pandas Data Frame." }, { "code": null, "e": 1380, "s": 1265, "text": "Using barplot() method, create bar_plot1 and bar_plot2 with color as red and green, and label as count and select." }, { "code": null, "e": 1495, "s": 1380, "text": "Using barplot() method, create bar_plot1 and bar_plot2 with color as red and green, and label as count and select." }, { "code": null, "e": 1563, "s": 1495, "text": "To enable legend, use legend() method, at the upper-right location." }, { "code": null, "e": 1631, "s": 1563, "text": "To enable legend, use legend() method, at the upper-right location." }, { "code": null, "e": 1674, "s": 1631, "text": "To display the figuree, use show() method." }, { "code": null, "e": 1717, "s": 1674, "text": "To display the figuree, use show() method." }, { "code": null, "e": 2225, "s": 1717, "text": "import pandas\nimport matplotlib.pylab as plt\nimport seaborn as sns\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndf = pandas.DataFrame(dict(\n number=[2, 5, 1, 6, 3],\n count=[56, 21, 34, 36, 12],\n select=[29, 13, 17, 21, 8]\n))\nbar_plot1 = sns.barplot(x='number', y='count', data=df, label=\"count\", color=\"red\")\nbar_plot2 = sns.barplot(x='number', y='select', data=df, label=\"select\", color=\"green\")\nplt.legend(ncol=2, loc=\"upper right\", frameon=True)\nplt.show()" } ]
Convert a binary number to octal - GeeksforGeeks
17 Dec, 2021 The problem is to convert the given binary number (represented as string) to its equivalent octal number. The input could be very large and may not fit even into unsigned long long int. Examples: Input : 110001110 Output : 616 Input : 1111001010010100001.010110110011011 Output : 1712241.26633 The idea is to consider the binary input as a string of characters and then follow the steps: Get length of substring to the left and right of the decimal point(‘.’) as left_len and right_len.If left_len is not a multiple of 3 add min number of 0’s in the beginning to make length of left substring a multiple of 3.If right_len is not a multiple of 3 add min number of 0’s in the end to make length of right substring a multiple of 3.Now, from the left extract one by one substrings of length 3 and add its corresponding octal code to the result.If in between a decimal(‘.’) is encountered then add it to the result. Get length of substring to the left and right of the decimal point(‘.’) as left_len and right_len. If left_len is not a multiple of 3 add min number of 0’s in the beginning to make length of left substring a multiple of 3. If right_len is not a multiple of 3 add min number of 0’s in the end to make length of right substring a multiple of 3. Now, from the left extract one by one substrings of length 3 and add its corresponding octal code to the result. If in between a decimal(‘.’) is encountered then add it to the result. C++ Java Python3 C# Javascript // C++ implementation to convert a binary number// to octal number#include <bits/stdc++.h>using namespace std; // function to create map between binary// number and its equivalent octalvoid createMap(unordered_map<string, char> *um){ (*um)["000"] = '0'; (*um)["001"] = '1'; (*um)["010"] = '2'; (*um)["011"] = '3'; (*um)["100"] = '4'; (*um)["101"] = '5'; (*um)["110"] = '6'; (*um)["111"] = '7'; } // Function to find octal equivalent of binarystring convertBinToOct(string bin){ int l = bin.size(); int t = bin.find_first_of('.'); // length of string before '.' int len_left = t != -1 ? t : l; // add min 0's in the beginning to make // left substring length divisible by 3 for (int i = 1; i <= (3 - len_left % 3) % 3; i++) bin = '0' + bin; // if decimal point exists if (t != -1) { // length of string after '.' int len_right = l - len_left - 1; // add min 0's in the end to make right // substring length divisible by 3 for (int i = 1; i <= (3 - len_right % 3) % 3; i++) bin = bin + '0'; } // create map between binary and its // equivalent octal code unordered_map<string, char> bin_oct_map; createMap(&bin_oct_map); int i = 0; string octal = ""; while (1) { // one by one extract from left, substring // of size 3 and add its octal code octal += bin_oct_map[bin.substr(i, 3)]; i += 3; if (i == bin.size()) break; // if '.' is encountered add it to result if (bin.at(i) == '.') { octal += '.'; i++; } } // required octal number return octal; } // Driver program to test aboveint main(){ string bin = "1111001010010100001.010110110011011"; cout << "Octal number = " << convertBinToOct(bin); return 0; } // Java implementation to convert a// binary number to octal numberimport java.io.*;import java.util.*; class GFG{ // Function to create map between binary// number and its equivalent hexadecimalstatic void createMap(Map<String, Character> um){ um.put("000", '0'); um.put("001", '1'); um.put("010", '2'); um.put("011", '3'); um.put("100", '4'); um.put("101", '5'); um.put("110", '6'); um.put("111", '7');} // Function to find octal equivalent of binarystatic String convertBinToOct(String bin){ int l = bin.length(); int t = bin.indexOf('.'); // Length of string before '.' int len_left = t != -1 ? t : l; // Add min 0's in the beginning to make // left substring length divisible by 3 for(int i = 1; i <= (3 - len_left % 3) % 3; i++) bin = '0' + bin; // If decimal point exists if (t != -1) { // Length of string after '.' int len_right = l - len_left - 1; // add min 0's in the end to make right // substring length divisible by 3 for(int i = 1; i <= (3 - len_right % 3) % 3; i++) bin = bin + '0'; } // Create map between binary and its // equivalent octal code Map<String, Character> bin_oct_map = new HashMap<String, Character>(); createMap(bin_oct_map); int i = 0; String octal = ""; while (true) { // One by one extract from left, substring // of size 3 and add its octal code octal += bin_oct_map.get( bin.substring(i, i + 3)); i += 3; if (i == bin.length()) break; // If '.' is encountered add it to result if (bin.charAt(i) == '.') { octal += '.'; i++; } } // Required octal number return octal;} // Driver codepublic static void main(String[] args){ String bin = "1111001010010100001.010110110011011"; System.out.println("Octal number = " + convertBinToOct(bin));}} // This code is contributed by jithin # Python3 implementation to convert a binary number# to octal number # function to create map between binary# number and its equivalent octaldef createMap(bin_oct_map): bin_oct_map["000"] = '0' bin_oct_map["001"] = '1' bin_oct_map["010"] = '2' bin_oct_map["011"] = '3' bin_oct_map["100"] = '4' bin_oct_map["101"] = '5' bin_oct_map["110"] = '6' bin_oct_map["111"] = '7' # Function to find octal equivalent of binarydef convertBinToOct(bin): l = len(bin) # length of string before '.' t = -1 if '.' in bin: t = bin.index('.') len_left = t else: len_left = l # add min 0's in the beginning to make # left substring length divisible by 3 for i in range(1, (3 - len_left % 3) % 3 + 1): bin = '0' + bin # if decimal point exists if (t != -1): # length of string after '.' len_right = l - len_left - 1 # add min 0's in the end to make right # substring length divisible by 3 for i in range(1, (3 - len_right % 3) % 3 + 1): bin = bin + '0' # create dictionary between binary and its # equivalent octal code bin_oct_map = {} createMap(bin_oct_map) i = 0 octal = "" while (True) : # one by one extract from left, substring # of size 3 and add its octal code octal += bin_oct_map[bin[i:i + 3]] i += 3 if (i == len(bin)): break # if '.' is encountered add it to result if (bin[i] == '.'): octal += '.' i += 1 # required octal number return octal # Driver Codebin = "1111001010010100001.010110110011011"print("Octal number = ", convertBinToOct(bin)) # This code is contributed# by Atul_kumar_Shrivastava // C# implementation to convert a// binary number to octal number using System;using System.Collections.Generic; public class GFG{ // Function to create map between binary// number and its equivalent hexadecimalstatic void createMap(Dictionary<String, char> um){ um.Add("000", '0'); um.Add("001", '1'); um.Add("010", '2'); um.Add("011", '3'); um.Add("100", '4'); um.Add("101", '5'); um.Add("110", '6'); um.Add("111", '7');} // Function to find octal equivalent of binarystatic String convertBinToOct(String bin){ int l = bin.Length; int t = bin.IndexOf('.'); int i = 0; // Length of string before '.' int len_left = t != -1 ? t : l; // Add min 0's in the beginning to make // left substring length divisible by 3 for(i = 1; i <= (3 - len_left % 3) % 3; i++) bin = '0' + bin; // If decimal point exists if (t != -1) { // Length of string after '.' int len_right = l - len_left - 1; // add min 0's in the end to make right // substring length divisible by 3 for(i = 1; i <= (3 - len_right % 3) % 3; i++) bin = bin + '0'; } // Create map between binary and its // equivalent octal code Dictionary<String, char> bin_oct_map = new Dictionary<String, char>(); createMap(bin_oct_map); i = 0; String octal = ""; while (true) { // One by one extract from left, substring // of size 3 and add its octal code octal += bin_oct_map[ bin.Substring(i, 3)]; i += 3; if (i == bin.Length) break; // If '.' is encountered add it to result if (bin[i] == '.') { octal += '.'; i++; } } // Required octal number return octal;} // Driver codepublic static void Main(String[] args){ String bin = "1111001010010100001.010110110011011"; Console.WriteLine("Octal number = " + convertBinToOct(bin));}} // This code is contributed by 29AjayKumar <script> // Javascript implementation to convert a// binary number to octal number // Function to create map between binary// number and its equivalent hexadecimalfunction createMap(um){ um.set("000", '0'); um.set("001", '1'); um.set("010", '2'); um.set("011", '3'); um.set("100", '4'); um.set("101", '5'); um.set("110", '6'); um.set("111", '7');} // Function to find octal equivalent of binaryfunction convertBinToOct(bin){ let l = bin.length; let t = bin.indexOf('.'); // Length of string before '.' let len_left = t != -1 ? t : l; // Add min 0's in the beginning to make // left substring length divisible by 3 for(let i = 1; i <= (3 - len_left % 3) % 3; i++) bin = '0' + bin; // If decimal point exists if (t != -1) { // Length of string after '.' let len_right = l - len_left - 1; // add min 0's in the end to make right // substring length divisible by 3 for(let i = 1; i <= (3 - len_right % 3) % 3; i++) bin = bin + '0'; } // Create map between binary and its // equivalent octal code let bin_oct_map = new Map(); createMap(bin_oct_map); let i = 0; let octal = ""; while (true) { // One by one extract from left, substring // of size 3 and add its octal code octal += bin_oct_map.get(bin.substr(i, 3)); i += 3; if (i == bin.length) break; // If '.' is encountered add it to result if (bin.charAt(i) == '.') { octal += '.'; i++; } } // Required octal number return octal;} // Driver codelet bin = "1111001010010100001.010110110011011";document.write("Octal number = " + convertBinToOct(bin)); // This code is contributed by gfgking </script> Output: Octal number = 1712241.26633 Time Complexity: O(n), where n is the length of string. This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Atul_kumar_Shrivastava jithin gfgking 29AjayKumar base-conversion binary-representation Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Cyclic Redundancy Check and Modulo-2 Division Little and Big Endian Mystery Bits manipulation (Important tactics) Bit Fields in C Find the element that appears once Add two numbers without using arithmetic operators Set, Clear and Toggle a given bit of a number in C Josephus problem | Set 1 (A O(n) Solution) C++ bitset and its application 1's and 2's complement of a Binary Number
[ { "code": null, "e": 25040, "s": 25012, "text": "\n17 Dec, 2021" }, { "code": null, "e": 25226, "s": 25040, "text": "The problem is to convert the given binary number (represented as string) to its equivalent octal number. The input could be very large and may not fit even into unsigned long long int." }, { "code": null, "e": 25238, "s": 25226, "text": "Examples: " }, { "code": null, "e": 25339, "s": 25238, "text": "Input : 110001110\nOutput : 616\n\nInput : 1111001010010100001.010110110011011\nOutput : 1712241.26633 " }, { "code": null, "e": 25434, "s": 25339, "text": "The idea is to consider the binary input as a string of characters and then follow the steps: " }, { "code": null, "e": 25957, "s": 25434, "text": "Get length of substring to the left and right of the decimal point(‘.’) as left_len and right_len.If left_len is not a multiple of 3 add min number of 0’s in the beginning to make length of left substring a multiple of 3.If right_len is not a multiple of 3 add min number of 0’s in the end to make length of right substring a multiple of 3.Now, from the left extract one by one substrings of length 3 and add its corresponding octal code to the result.If in between a decimal(‘.’) is encountered then add it to the result." }, { "code": null, "e": 26056, "s": 25957, "text": "Get length of substring to the left and right of the decimal point(‘.’) as left_len and right_len." }, { "code": null, "e": 26180, "s": 26056, "text": "If left_len is not a multiple of 3 add min number of 0’s in the beginning to make length of left substring a multiple of 3." }, { "code": null, "e": 26300, "s": 26180, "text": "If right_len is not a multiple of 3 add min number of 0’s in the end to make length of right substring a multiple of 3." }, { "code": null, "e": 26413, "s": 26300, "text": "Now, from the left extract one by one substrings of length 3 and add its corresponding octal code to the result." }, { "code": null, "e": 26484, "s": 26413, "text": "If in between a decimal(‘.’) is encountered then add it to the result." }, { "code": null, "e": 26488, "s": 26484, "text": "C++" }, { "code": null, "e": 26493, "s": 26488, "text": "Java" }, { "code": null, "e": 26501, "s": 26493, "text": "Python3" }, { "code": null, "e": 26504, "s": 26501, "text": "C#" }, { "code": null, "e": 26515, "s": 26504, "text": "Javascript" }, { "code": "// C++ implementation to convert a binary number// to octal number#include <bits/stdc++.h>using namespace std; // function to create map between binary// number and its equivalent octalvoid createMap(unordered_map<string, char> *um){ (*um)[\"000\"] = '0'; (*um)[\"001\"] = '1'; (*um)[\"010\"] = '2'; (*um)[\"011\"] = '3'; (*um)[\"100\"] = '4'; (*um)[\"101\"] = '5'; (*um)[\"110\"] = '6'; (*um)[\"111\"] = '7'; } // Function to find octal equivalent of binarystring convertBinToOct(string bin){ int l = bin.size(); int t = bin.find_first_of('.'); // length of string before '.' int len_left = t != -1 ? t : l; // add min 0's in the beginning to make // left substring length divisible by 3 for (int i = 1; i <= (3 - len_left % 3) % 3; i++) bin = '0' + bin; // if decimal point exists if (t != -1) { // length of string after '.' int len_right = l - len_left - 1; // add min 0's in the end to make right // substring length divisible by 3 for (int i = 1; i <= (3 - len_right % 3) % 3; i++) bin = bin + '0'; } // create map between binary and its // equivalent octal code unordered_map<string, char> bin_oct_map; createMap(&bin_oct_map); int i = 0; string octal = \"\"; while (1) { // one by one extract from left, substring // of size 3 and add its octal code octal += bin_oct_map[bin.substr(i, 3)]; i += 3; if (i == bin.size()) break; // if '.' is encountered add it to result if (bin.at(i) == '.') { octal += '.'; i++; } } // required octal number return octal; } // Driver program to test aboveint main(){ string bin = \"1111001010010100001.010110110011011\"; cout << \"Octal number = \" << convertBinToOct(bin); return 0; } ", "e": 28461, "s": 26515, "text": null }, { "code": "// Java implementation to convert a// binary number to octal numberimport java.io.*;import java.util.*; class GFG{ // Function to create map between binary// number and its equivalent hexadecimalstatic void createMap(Map<String, Character> um){ um.put(\"000\", '0'); um.put(\"001\", '1'); um.put(\"010\", '2'); um.put(\"011\", '3'); um.put(\"100\", '4'); um.put(\"101\", '5'); um.put(\"110\", '6'); um.put(\"111\", '7');} // Function to find octal equivalent of binarystatic String convertBinToOct(String bin){ int l = bin.length(); int t = bin.indexOf('.'); // Length of string before '.' int len_left = t != -1 ? t : l; // Add min 0's in the beginning to make // left substring length divisible by 3 for(int i = 1; i <= (3 - len_left % 3) % 3; i++) bin = '0' + bin; // If decimal point exists if (t != -1) { // Length of string after '.' int len_right = l - len_left - 1; // add min 0's in the end to make right // substring length divisible by 3 for(int i = 1; i <= (3 - len_right % 3) % 3; i++) bin = bin + '0'; } // Create map between binary and its // equivalent octal code Map<String, Character> bin_oct_map = new HashMap<String, Character>(); createMap(bin_oct_map); int i = 0; String octal = \"\"; while (true) { // One by one extract from left, substring // of size 3 and add its octal code octal += bin_oct_map.get( bin.substring(i, i + 3)); i += 3; if (i == bin.length()) break; // If '.' is encountered add it to result if (bin.charAt(i) == '.') { octal += '.'; i++; } } // Required octal number return octal;} // Driver codepublic static void main(String[] args){ String bin = \"1111001010010100001.010110110011011\"; System.out.println(\"Octal number = \" + convertBinToOct(bin));}} // This code is contributed by jithin", "e": 30593, "s": 28461, "text": null }, { "code": "# Python3 implementation to convert a binary number# to octal number # function to create map between binary# number and its equivalent octaldef createMap(bin_oct_map): bin_oct_map[\"000\"] = '0' bin_oct_map[\"001\"] = '1' bin_oct_map[\"010\"] = '2' bin_oct_map[\"011\"] = '3' bin_oct_map[\"100\"] = '4' bin_oct_map[\"101\"] = '5' bin_oct_map[\"110\"] = '6' bin_oct_map[\"111\"] = '7' # Function to find octal equivalent of binarydef convertBinToOct(bin): l = len(bin) # length of string before '.' t = -1 if '.' in bin: t = bin.index('.') len_left = t else: len_left = l # add min 0's in the beginning to make # left substring length divisible by 3 for i in range(1, (3 - len_left % 3) % 3 + 1): bin = '0' + bin # if decimal point exists if (t != -1): # length of string after '.' len_right = l - len_left - 1 # add min 0's in the end to make right # substring length divisible by 3 for i in range(1, (3 - len_right % 3) % 3 + 1): bin = bin + '0' # create dictionary between binary and its # equivalent octal code bin_oct_map = {} createMap(bin_oct_map) i = 0 octal = \"\" while (True) : # one by one extract from left, substring # of size 3 and add its octal code octal += bin_oct_map[bin[i:i + 3]] i += 3 if (i == len(bin)): break # if '.' is encountered add it to result if (bin[i] == '.'): octal += '.' i += 1 # required octal number return octal # Driver Codebin = \"1111001010010100001.010110110011011\"print(\"Octal number = \", convertBinToOct(bin)) # This code is contributed# by Atul_kumar_Shrivastava", "e": 32405, "s": 30593, "text": null }, { "code": "// C# implementation to convert a// binary number to octal number using System;using System.Collections.Generic; public class GFG{ // Function to create map between binary// number and its equivalent hexadecimalstatic void createMap(Dictionary<String, char> um){ um.Add(\"000\", '0'); um.Add(\"001\", '1'); um.Add(\"010\", '2'); um.Add(\"011\", '3'); um.Add(\"100\", '4'); um.Add(\"101\", '5'); um.Add(\"110\", '6'); um.Add(\"111\", '7');} // Function to find octal equivalent of binarystatic String convertBinToOct(String bin){ int l = bin.Length; int t = bin.IndexOf('.'); int i = 0; // Length of string before '.' int len_left = t != -1 ? t : l; // Add min 0's in the beginning to make // left substring length divisible by 3 for(i = 1; i <= (3 - len_left % 3) % 3; i++) bin = '0' + bin; // If decimal point exists if (t != -1) { // Length of string after '.' int len_right = l - len_left - 1; // add min 0's in the end to make right // substring length divisible by 3 for(i = 1; i <= (3 - len_right % 3) % 3; i++) bin = bin + '0'; } // Create map between binary and its // equivalent octal code Dictionary<String, char> bin_oct_map = new Dictionary<String, char>(); createMap(bin_oct_map); i = 0; String octal = \"\"; while (true) { // One by one extract from left, substring // of size 3 and add its octal code octal += bin_oct_map[ bin.Substring(i, 3)]; i += 3; if (i == bin.Length) break; // If '.' is encountered add it to result if (bin[i] == '.') { octal += '.'; i++; } } // Required octal number return octal;} // Driver codepublic static void Main(String[] args){ String bin = \"1111001010010100001.010110110011011\"; Console.WriteLine(\"Octal number = \" + convertBinToOct(bin));}} // This code is contributed by 29AjayKumar", "e": 34542, "s": 32405, "text": null }, { "code": "<script> // Javascript implementation to convert a// binary number to octal number // Function to create map between binary// number and its equivalent hexadecimalfunction createMap(um){ um.set(\"000\", '0'); um.set(\"001\", '1'); um.set(\"010\", '2'); um.set(\"011\", '3'); um.set(\"100\", '4'); um.set(\"101\", '5'); um.set(\"110\", '6'); um.set(\"111\", '7');} // Function to find octal equivalent of binaryfunction convertBinToOct(bin){ let l = bin.length; let t = bin.indexOf('.'); // Length of string before '.' let len_left = t != -1 ? t : l; // Add min 0's in the beginning to make // left substring length divisible by 3 for(let i = 1; i <= (3 - len_left % 3) % 3; i++) bin = '0' + bin; // If decimal point exists if (t != -1) { // Length of string after '.' let len_right = l - len_left - 1; // add min 0's in the end to make right // substring length divisible by 3 for(let i = 1; i <= (3 - len_right % 3) % 3; i++) bin = bin + '0'; } // Create map between binary and its // equivalent octal code let bin_oct_map = new Map(); createMap(bin_oct_map); let i = 0; let octal = \"\"; while (true) { // One by one extract from left, substring // of size 3 and add its octal code octal += bin_oct_map.get(bin.substr(i, 3)); i += 3; if (i == bin.length) break; // If '.' is encountered add it to result if (bin.charAt(i) == '.') { octal += '.'; i++; } } // Required octal number return octal;} // Driver codelet bin = \"1111001010010100001.010110110011011\";document.write(\"Octal number = \" + convertBinToOct(bin)); // This code is contributed by gfgking </script>", "e": 36429, "s": 34542, "text": null }, { "code": null, "e": 36439, "s": 36429, "text": "Output: " }, { "code": null, "e": 36468, "s": 36439, "text": "Octal number = 1712241.26633" }, { "code": null, "e": 36524, "s": 36468, "text": "Time Complexity: O(n), where n is the length of string." }, { "code": null, "e": 36946, "s": 36524, "text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 36969, "s": 36946, "text": "Atul_kumar_Shrivastava" }, { "code": null, "e": 36976, "s": 36969, "text": "jithin" }, { "code": null, "e": 36984, "s": 36976, "text": "gfgking" }, { "code": null, "e": 36996, "s": 36984, "text": "29AjayKumar" }, { "code": null, "e": 37012, "s": 36996, "text": "base-conversion" }, { "code": null, "e": 37034, "s": 37012, "text": "binary-representation" }, { "code": null, "e": 37044, "s": 37034, "text": "Bit Magic" }, { "code": null, "e": 37054, "s": 37044, "text": "Bit Magic" }, { "code": null, "e": 37152, "s": 37054, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37198, "s": 37152, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 37228, "s": 37198, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 37266, "s": 37228, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 37282, "s": 37266, "text": "Bit Fields in C" }, { "code": null, "e": 37317, "s": 37282, "text": "Find the element that appears once" }, { "code": null, "e": 37368, "s": 37317, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 37419, "s": 37368, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 37462, "s": 37419, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 37493, "s": 37462, "text": "C++ bitset and its application" } ]
Spring Boot MVC Example | Spring Boot Login Online TutorialsPoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, I am going to show how to create a Spring Boot MVC application. Here we are going to use the below technologies: Spring.4.3.7.RELEASE SpringBoot 1.4.5.RELEASE Java 8 Project Structure : A typical Maven project directory structure. <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>org.springframework.samples.service.service</groupId> <artifactId>Spring_Boot_MVC_Example</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.5.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Spring Controller : It’s a typical spring login form controller. package com.onlinetutorialspoint.spring.boot; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.onlinetutorialspoint.bean.LoginBean; @Controller public class LoginController { @RequestMapping(value = "login", method = RequestMethod.GET) public String init(Model model) { model.addAttribute("msg", "Please Enter Your Login Details"); return "login.jsp"; } @RequestMapping(method = RequestMethod.POST) public String submit(Model model, @ModelAttribute("loginBean") LoginBean loginBean) { if (loginBean != null && loginBean.getUserName() != null & loginBean.getPassword() != null) { if (loginBean.getUserName().equals("chandra") && loginBean.getPassword().equals("chandra123")) { model.addAttribute("msg", loginBean.getUserName()); return "success.jsp"; } else { model.addAttribute("error", "Invalid Details"); return "login.jsp"; } } else { model.addAttribute("error", "Please enter Details"); return "login.jsp"; } } } Model Bean : package com.onlinetutorialspoint.bean; public class LoginBean { private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } Preparing View: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Spring Login Form</title> </head> <body> <form:form name="submitForm" method="POST"> <div align="center"> <table> <tr> <td>User Name</td> <td><input type="text" name="userName" /></td> </tr> <tr> <td>Password</td> <td><input type="password" name="password" /></td> </tr> <tr> <td></td> <td><input type="submit" value="Submit" /></td> </tr> </table> <div style="color: red">${error}</div> </div> </form:form> </body> </html> Preparing a success view : <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Success Form</title> </head> <body> <font color="green"><h2>Hello</h2></font> <h3>${msg}</h3> You have successfully logged in. <font color="green"><h3>Welcome to Spring Boot World !</h3></font> </body> </html> Spring Boot Application class : package com.onlinetutorialspoint.spring.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; @SpringBootApplication public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } } @SpringBootApplication annotation tells to Spring Boot; this is a starting point of our Spring Boot Application. SpringApplication is a class which is coming from org.springframework.boot. This class can be used to bootstrap and launch the spring application using the Java main method. SpringApplication.run(Application.class, args) is a static method in SpringApplication class, which accepts two arguments. First one is a class which is the main class of Spring boot, and another one is arguments which can be passed to the main method. When we run this class the SpringApplication class does many things for us : It sets up the default configurations for Spring application. It starts the Spring application context. Performs the Classpath scan (Loads all spring annotated classes). And finally, start the Tomcat Server. Yes, we are done with the Spring Boot MVC login example. Now time to run the application. We can run the Spring Boot application like as simple as Java standalone application (by running the main method). You can access your application by bit the below URL on your favourite browser. http://localhost:8080/login Now you can see the login page like below. Success page : Happy Learning 🙂 spring_boot_mvc_example Spring Boot MVC Login Example File size: 8 MB Downloads: 4859 Spring MVC Login Form Example Tutorials Spring Boot Validation Login Form Example How to set Spring Boot SetTimeZone Spring Web MVC Framework Flow How to change Spring Boot Tomcat Port Number How To Change Spring Boot Context Path Simple Spring Boot Example Spring Boot FileUpload Ajax Example Spring MVC Form Validation Example Spring Boot H2 Database + JDBC Template Example Spring Boot Actuator Database Health Check Spring Boot RabbitMQ Message Publishing Example How to use Spring Boot Random Port Spring Boot How to change the Tomcat to Jetty Server Spring Boot MockMvc JUnit Test Example Spring MVC Login Form Example Tutorials Spring Boot Validation Login Form Example How to set Spring Boot SetTimeZone Spring Web MVC Framework Flow How to change Spring Boot Tomcat Port Number How To Change Spring Boot Context Path Simple Spring Boot Example Spring Boot FileUpload Ajax Example Spring MVC Form Validation Example Spring Boot H2 Database + JDBC Template Example Spring Boot Actuator Database Health Check Spring Boot RabbitMQ Message Publishing Example How to use Spring Boot Random Port Spring Boot How to change the Tomcat to Jetty Server Spring Boot MockMvc JUnit Test Example Δ Spring Boot – Hello World Spring Boot – MVC Example Spring Boot- Change Context Path Spring Boot – Change Tomcat Port Number Spring Boot – Change Tomcat to Jetty Server Spring Boot – Tomcat session timeout Spring Boot – Enable Random Port Spring Boot – Properties File Spring Boot – Beans Lazy Loading Spring Boot – Set Favicon image Spring Boot – Set Custom Banner Spring Boot – Set Application TimeZone Spring Boot – Send Mail Spring Boot – FileUpload Ajax Spring Boot – Actuator Spring Boot – Actuator Database Health Check Spring Boot – Swagger Spring Boot – Enable CORS Spring Boot – External Apache ActiveMQ Setup Spring Boot – Inmemory Apache ActiveMq Spring Boot – Scheduler Job Spring Boot – Exception Handling Spring Boot – Hibernate CRUD Spring Boot – JPA Integration CRUD Spring Boot – JPA DataRest CRUD Spring Boot – JdbcTemplate CRUD Spring Boot – Multiple Data Sources Config Spring Boot – JNDI Configuration Spring Boot – H2 Database CRUD Spring Boot – MongoDB CRUD Spring Boot – Redis Data CRUD Spring Boot – MVC Login Form Validation Spring Boot – Custom Error Pages Spring Boot – iText PDF Spring Boot – Enable SSL (HTTPs) Spring Boot – Basic Authentication Spring Boot – In Memory Basic Authentication Spring Boot – Security MySQL Database Integration Spring Boot – Redis Cache – Redis Server Spring Boot – Hazelcast Cache Spring Boot – EhCache Spring Boot – Kafka Producer Spring Boot – Kafka Consumer Spring Boot – Kafka JSON Message to Kafka Topic Spring Boot – RabbitMQ Publisher Spring Boot – RabbitMQ Consumer Spring Boot – SOAP Consumer Spring Boot – Soap WebServices Spring Boot – Batch Csv to Database Spring Boot – Eureka Server Spring Boot – MockMvc JUnit Spring Boot – Docker Deployment
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 480, "s": 398, "text": "In this tutorial, I am going to show how to create a Spring Boot MVC application." }, { "code": null, "e": 529, "s": 480, "text": "Here we are going to use the below technologies:" }, { "code": null, "e": 550, "s": 529, "text": "Spring.4.3.7.RELEASE" }, { "code": null, "e": 575, "s": 550, "text": "SpringBoot 1.4.5.RELEASE" }, { "code": null, "e": 582, "s": 575, "text": "Java 8" }, { "code": null, "e": 602, "s": 582, "text": "Project Structure :" }, { "code": null, "e": 647, "s": 602, "text": "A typical Maven project directory structure." }, { "code": null, "e": 1869, "s": 647, "text": "\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n<modelVersion>4.0.0</modelVersion>\n<groupId>org.springframework.samples.service.service</groupId>\n<artifactId>Spring_Boot_MVC_Example</artifactId>\n<version>0.0.1-SNAPSHOT</version>\n<packaging>war</packaging>\n<parent>\n<groupId>org.springframework.boot</groupId>\n<artifactId>spring-boot-starter-parent</artifactId>\n<version>1.4.5.RELEASE</version>\n</parent>\n<properties>\n<java.version>1.8</java.version>\n</properties>\n<dependencies>\n<dependency>\n<groupId>org.springframework.boot</groupId>\n<artifactId>spring-boot-starter-web</artifactId>\n</dependency>\n<dependency>\n<groupId>org.springframework.boot</groupId>\n<artifactId>spring-boot-starter-tomcat</artifactId>\n<scope>provided</scope>\n</dependency>\n<dependency>\n<groupId>org.apache.tomcat.embed</groupId>\n<artifactId>tomcat-embed-jasper</artifactId>\n<scope>provided</scope>\n</dependency>\n</dependencies>\n<build>\n<plugins>\n<plugin>\n<groupId>org.springframework.boot</groupId>\n<artifactId>spring-boot-maven-plugin</artifactId>\n</plugin>\n</plugins>\n</build>\n</project>\n" }, { "code": null, "e": 1889, "s": 1869, "text": "Spring Controller :" }, { "code": null, "e": 1934, "s": 1889, "text": "It’s a typical spring login form controller." }, { "code": null, "e": 3328, "s": 1934, "text": "package com.onlinetutorialspoint.spring.boot;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.ModelAttribute;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\nimport com.onlinetutorialspoint.bean.LoginBean;\n\n@Controller\npublic class LoginController {\n @RequestMapping(value = \"login\", method = RequestMethod.GET)\n public String init(Model model) {\n model.addAttribute(\"msg\", \"Please Enter Your Login Details\");\n return \"login.jsp\";\n }\n\n @RequestMapping(method = RequestMethod.POST)\n public String submit(Model model,\n @ModelAttribute(\"loginBean\") LoginBean loginBean) {\n if (loginBean != null && loginBean.getUserName() != null\n & loginBean.getPassword() != null) {\n if (loginBean.getUserName().equals(\"chandra\")\n && loginBean.getPassword().equals(\"chandra123\")) {\n model.addAttribute(\"msg\", loginBean.getUserName());\n return \"success.jsp\";\n } else {\n model.addAttribute(\"error\", \"Invalid Details\");\n return \"login.jsp\";\n }\n } else {\n model.addAttribute(\"error\", \"Please enter Details\");\n return \"login.jsp\";\n }\n }\n}" }, { "code": null, "e": 3341, "s": 3328, "text": "Model Bean :" }, { "code": null, "e": 3777, "s": 3341, "text": "package com.onlinetutorialspoint.bean;\n\npublic class LoginBean {\n\n private String userName;\n private String password;\n\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userName) {\n this.userName = userName;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n}\n" }, { "code": null, "e": 3793, "s": 3777, "text": "Preparing View:" }, { "code": null, "e": 4573, "s": 3793, "text": "\n<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\"\npageEncoding=\"UTF-8\"%>\n<%@taglib uri=\"http://www.springframework.org/tags/form\" prefix=\"form\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<title>Spring Login Form</title>\n</head>\n<body>\n<form:form name=\"submitForm\" method=\"POST\">\n\n<div align=\"center\">\n<table>\n<tr>\n<td>User Name</td>\n<td><input type=\"text\" name=\"userName\" /></td>\n</tr>\n<tr>\n<td>Password</td>\n<td><input type=\"password\" name=\"password\" /></td>\n</tr>\n<tr>\n<td></td>\n<td><input type=\"submit\" value=\"Submit\" /></td>\n</tr>\n</table>\n<div style=\"color: red\">${error}</div>\n\n</div>\n</form:form>\n</body>\n</html>\n" }, { "code": null, "e": 4600, "s": 4573, "text": "Preparing a success view :" }, { "code": null, "e": 5103, "s": 4600, "text": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\"\n\npageEncoding=\"UTF-8\"%>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n\n<html>\n\n<head>\n\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n\n<title>Success Form</title>\n\n</head>\n\n<body>\n\n<font color=\"green\"><h2>Hello</h2></font>\n\n<h3>${msg}</h3> You have successfully logged in.\n\n<font color=\"green\"><h3>Welcome to Spring Boot World !</h3></font>\n\n</body>\n\n</html>\n" }, { "code": null, "e": 5135, "s": 5103, "text": "Spring Boot Application class :" }, { "code": null, "e": 5620, "s": 5135, "text": "package com.onlinetutorialspoint.spring.boot;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.boot.builder.SpringApplicationBuilder;\nimport org.springframework.boot.context.web.SpringBootServletInitializer;\n\n@SpringBootApplication\npublic class Application {\n public static void main(String[] args) throws Exception {\n SpringApplication.run(Application.class, args);\n }\n}\n" }, { "code": null, "e": 5733, "s": 5620, "text": "@SpringBootApplication annotation tells to Spring Boot; this is a starting point of our Spring Boot Application." }, { "code": null, "e": 5907, "s": 5733, "text": "SpringApplication is a class which is coming from org.springframework.boot. This class can be used to bootstrap and launch the spring application using the Java main method." }, { "code": null, "e": 6237, "s": 5907, "text": "SpringApplication.run(Application.class, args) is a static method in SpringApplication class, which accepts two arguments. First one is a class which is the main class of Spring boot, and another one is arguments which can be passed to the main method. When we run this class the SpringApplication class does many things for us :" }, { "code": null, "e": 6299, "s": 6237, "text": "It sets up the default configurations for Spring application." }, { "code": null, "e": 6341, "s": 6299, "text": "It starts the Spring application context." }, { "code": null, "e": 6407, "s": 6341, "text": "Performs the Classpath scan (Loads all spring annotated classes)." }, { "code": null, "e": 6445, "s": 6407, "text": "And finally, start the Tomcat Server." }, { "code": null, "e": 6650, "s": 6445, "text": "Yes, we are done with the Spring Boot MVC login example. Now time to run the application. We can run the Spring Boot application like as simple as Java standalone application (by running the main method)." }, { "code": null, "e": 6730, "s": 6650, "text": "You can access your application by bit the below URL on your favourite browser." }, { "code": null, "e": 6758, "s": 6730, "text": "http://localhost:8080/login" }, { "code": null, "e": 6801, "s": 6758, "text": "Now you can see the login page like below." }, { "code": null, "e": 6816, "s": 6801, "text": "Success page :" }, { "code": null, "e": 6833, "s": 6816, "text": "Happy Learning 🙂" }, { "code": null, "e": 6923, "s": 6833, "text": "\n\nspring_boot_mvc_example\n\nSpring Boot MVC Login Example\nFile size: 8 MB\nDownloads: 4859\n" }, { "code": null, "e": 7520, "s": 6923, "text": "\nSpring MVC Login Form Example Tutorials\nSpring Boot Validation Login Form Example\nHow to set Spring Boot SetTimeZone\nSpring Web MVC Framework Flow\nHow to change Spring Boot Tomcat Port Number\nHow To Change Spring Boot Context Path\nSimple Spring Boot Example\nSpring Boot FileUpload Ajax Example\nSpring MVC Form Validation Example\nSpring Boot H2 Database + JDBC Template Example\nSpring Boot Actuator Database Health Check\nSpring Boot RabbitMQ Message Publishing Example\nHow to use Spring Boot Random Port\nSpring Boot How to change the Tomcat to Jetty Server\nSpring Boot MockMvc JUnit Test Example\n" }, { "code": null, "e": 7560, "s": 7520, "text": "Spring MVC Login Form Example Tutorials" }, { "code": null, "e": 7602, "s": 7560, "text": "Spring Boot Validation Login Form Example" }, { "code": null, "e": 7637, "s": 7602, "text": "How to set Spring Boot SetTimeZone" }, { "code": null, "e": 7667, "s": 7637, "text": "Spring Web MVC Framework Flow" }, { "code": null, "e": 7712, "s": 7667, "text": "How to change Spring Boot Tomcat Port Number" }, { "code": null, "e": 7751, "s": 7712, "text": "How To Change Spring Boot Context Path" }, { "code": null, "e": 7778, "s": 7751, "text": "Simple Spring Boot Example" }, { "code": null, "e": 7814, "s": 7778, "text": "Spring Boot FileUpload Ajax Example" }, { "code": null, "e": 7849, "s": 7814, "text": "Spring MVC Form Validation Example" }, { "code": null, "e": 7897, "s": 7849, "text": "Spring Boot H2 Database + JDBC Template Example" }, { "code": null, "e": 7940, "s": 7897, "text": "Spring Boot Actuator Database Health Check" }, { "code": null, "e": 7988, "s": 7940, "text": "Spring Boot RabbitMQ Message Publishing Example" }, { "code": null, "e": 8023, "s": 7988, "text": "How to use Spring Boot Random Port" }, { "code": null, "e": 8076, "s": 8023, "text": "Spring Boot How to change the Tomcat to Jetty Server" }, { "code": null, "e": 8115, "s": 8076, "text": "Spring Boot MockMvc JUnit Test Example" }, { "code": null, "e": 8121, "s": 8119, "text": "Δ" }, { "code": null, "e": 8148, "s": 8121, "text": " Spring Boot – Hello World" }, { "code": null, "e": 8175, "s": 8148, "text": " Spring Boot – MVC Example" }, { "code": null, "e": 8209, "s": 8175, "text": " Spring Boot- Change Context Path" }, { "code": null, "e": 8250, "s": 8209, "text": " Spring Boot – Change Tomcat Port Number" }, { "code": null, "e": 8295, "s": 8250, "text": " Spring Boot – Change Tomcat to Jetty Server" }, { "code": null, "e": 8333, "s": 8295, "text": " Spring Boot – Tomcat session timeout" }, { "code": null, "e": 8367, "s": 8333, "text": " Spring Boot – Enable Random Port" }, { "code": null, "e": 8398, "s": 8367, "text": " Spring Boot – Properties File" }, { "code": null, "e": 8432, "s": 8398, "text": " Spring Boot – Beans Lazy Loading" }, { "code": null, "e": 8465, "s": 8432, "text": " Spring Boot – Set Favicon image" }, { "code": null, "e": 8498, "s": 8465, "text": " Spring Boot – Set Custom Banner" }, { "code": null, "e": 8538, "s": 8498, "text": " Spring Boot – Set Application TimeZone" }, { "code": null, "e": 8563, "s": 8538, "text": " Spring Boot – Send Mail" }, { "code": null, "e": 8594, "s": 8563, "text": " Spring Boot – FileUpload Ajax" }, { "code": null, "e": 8618, "s": 8594, "text": " Spring Boot – Actuator" }, { "code": null, "e": 8664, "s": 8618, "text": " Spring Boot – Actuator Database Health Check" }, { "code": null, "e": 8687, "s": 8664, "text": " Spring Boot – Swagger" }, { "code": null, "e": 8714, "s": 8687, "text": " Spring Boot – Enable CORS" }, { "code": null, "e": 8760, "s": 8714, "text": " Spring Boot – External Apache ActiveMQ Setup" }, { "code": null, "e": 8800, "s": 8760, "text": " Spring Boot – Inmemory Apache ActiveMq" }, { "code": null, "e": 8829, "s": 8800, "text": " Spring Boot – Scheduler Job" }, { "code": null, "e": 8863, "s": 8829, "text": " Spring Boot – Exception Handling" }, { "code": null, "e": 8893, "s": 8863, "text": " Spring Boot – Hibernate CRUD" }, { "code": null, "e": 8929, "s": 8893, "text": " Spring Boot – JPA Integration CRUD" }, { "code": null, "e": 8962, "s": 8929, "text": " Spring Boot – JPA DataRest CRUD" }, { "code": null, "e": 8995, "s": 8962, "text": " Spring Boot – JdbcTemplate CRUD" }, { "code": null, "e": 9039, "s": 8995, "text": " Spring Boot – Multiple Data Sources Config" }, { "code": null, "e": 9073, "s": 9039, "text": " Spring Boot – JNDI Configuration" }, { "code": null, "e": 9105, "s": 9073, "text": " Spring Boot – H2 Database CRUD" }, { "code": null, "e": 9133, "s": 9105, "text": " Spring Boot – MongoDB CRUD" }, { "code": null, "e": 9164, "s": 9133, "text": " Spring Boot – Redis Data CRUD" }, { "code": null, "e": 9205, "s": 9164, "text": " Spring Boot – MVC Login Form Validation" }, { "code": null, "e": 9239, "s": 9205, "text": " Spring Boot – Custom Error Pages" }, { "code": null, "e": 9264, "s": 9239, "text": " Spring Boot – iText PDF" }, { "code": null, "e": 9298, "s": 9264, "text": " Spring Boot – Enable SSL (HTTPs)" }, { "code": null, "e": 9334, "s": 9298, "text": " Spring Boot – Basic Authentication" }, { "code": null, "e": 9380, "s": 9334, "text": " Spring Boot – In Memory Basic Authentication" }, { "code": null, "e": 9431, "s": 9380, "text": " Spring Boot – Security MySQL Database Integration" }, { "code": null, "e": 9473, "s": 9431, "text": " Spring Boot – Redis Cache – Redis Server" }, { "code": null, "e": 9504, "s": 9473, "text": " Spring Boot – Hazelcast Cache" }, { "code": null, "e": 9527, "s": 9504, "text": " Spring Boot – EhCache" }, { "code": null, "e": 9557, "s": 9527, "text": " Spring Boot – Kafka Producer" }, { "code": null, "e": 9587, "s": 9557, "text": " Spring Boot – Kafka Consumer" }, { "code": null, "e": 9636, "s": 9587, "text": " Spring Boot – Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 9670, "s": 9636, "text": " Spring Boot – RabbitMQ Publisher" }, { "code": null, "e": 9703, "s": 9670, "text": " Spring Boot – RabbitMQ Consumer" }, { "code": null, "e": 9732, "s": 9703, "text": " Spring Boot – SOAP Consumer" }, { "code": null, "e": 9764, "s": 9732, "text": " Spring Boot – Soap WebServices" }, { "code": null, "e": 9801, "s": 9764, "text": " Spring Boot – Batch Csv to Database" }, { "code": null, "e": 9830, "s": 9801, "text": " Spring Boot – Eureka Server" }, { "code": null, "e": 9859, "s": 9830, "text": " Spring Boot – MockMvc JUnit" } ]
C# - Arithmatic Operators
Following table shows all the arithmetic operators supported by C#. Assume variable A holds 10 and variable B holds 20, then − The following example demonstrates all the arithmetic operators available in C# − using System; namespace OperatorsAppl { class Program { static void Main(string[] args) { int a = 21; int b = 10; int c; c = a + b; Console.WriteLine("Line 1 - Value of c is {0}", c); c = a - b; Console.WriteLine("Line 2 - Value of c is {0}", c); c = a * b; Console.WriteLine("Line 3 - Value of c is {0}", c); c = a / b; Console.WriteLine("Line 4 - Value of c is {0}", c); c = a % b; Console.WriteLine("Line 5 - Value of c is {0}", c); c = a++; Console.WriteLine("Line 6 - Value of c is {0}", c); c = a--; Console.WriteLine("Line 7 - Value of c is {0}", c); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − Line 1 - Value of c is 31 Line 2 - Value of c is 11 Line 3 - Value of c is 210 Line 4 - Value of c is 2 Line 5 - Value of c is 1 Line 6 - Value of c is 21 Line 7 - Value of c is 22 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2397, "s": 2270, "text": "Following table shows all the arithmetic operators supported by C#. Assume variable A holds 10 and variable B holds 20, then −" }, { "code": null, "e": 2479, "s": 2397, "text": "The following example demonstrates all the arithmetic operators available in C# −" }, { "code": null, "e": 3307, "s": 2479, "text": "using System;\n\nnamespace OperatorsAppl {\n class Program { \n static void Main(string[] args) { \n int a = 21;\n int b = 10;\n int c;\n\n c = a + b;\n Console.WriteLine(\"Line 1 - Value of c is {0}\", c);\n \n c = a - b;\n Console.WriteLine(\"Line 2 - Value of c is {0}\", c);\n \n c = a * b;\n Console.WriteLine(\"Line 3 - Value of c is {0}\", c);\n \n c = a / b;\n Console.WriteLine(\"Line 4 - Value of c is {0}\", c);\n \n c = a % b;\n Console.WriteLine(\"Line 5 - Value of c is {0}\", c);\n \n c = a++;\n Console.WriteLine(\"Line 6 - Value of c is {0}\", c);\n \n c = a--;\n Console.WriteLine(\"Line 7 - Value of c is {0}\", c);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 3388, "s": 3307, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3570, "s": 3388, "text": "Line 1 - Value of c is 31\nLine 2 - Value of c is 11\nLine 3 - Value of c is 210\nLine 4 - Value of c is 2\nLine 5 - Value of c is 1\nLine 6 - Value of c is 21\nLine 7 - Value of c is 22\n" }, { "code": null, "e": 3607, "s": 3570, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 3620, "s": 3607, "text": " Raja Biswas" }, { "code": null, "e": 3654, "s": 3620, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 3672, "s": 3654, "text": " Trevoir Williams" }, { "code": null, "e": 3705, "s": 3672, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 3719, "s": 3705, "text": " Peter Jepson" }, { "code": null, "e": 3756, "s": 3719, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 3771, "s": 3756, "text": " Ebenezer Ogbu" }, { "code": null, "e": 3806, "s": 3771, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 3821, "s": 3806, "text": " Arnold Higuit" }, { "code": null, "e": 3856, "s": 3821, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3868, "s": 3856, "text": " Eric Frick" }, { "code": null, "e": 3875, "s": 3868, "text": " Print" }, { "code": null, "e": 3886, "s": 3875, "text": " Add Notes" } ]
Count Primes in Ranges in C++
We are given range variables START and END. The goal is to find the count of prime numbers in the range [START,END]. We will check if number i in range is prime by checking if any number other than 1 fully divides it and is between 1 and i/2. If it is prime. Increment count. Let’s understand with examples. Input Start=1 End=20 Output Primes in Ranges : 8 Explanation Primes between 1 and 20 are: 2,3,5,7,11,13,17,19. Input Start=100 End=200 Output Primes in Ranges : 21 Explanation Primes between 100 and 200 are: 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 We take range variables as START and END. We take range variables as START and END. Function countPrimes(int strt,int end) returns the count of primes in range. Function countPrimes(int strt,int end) returns the count of primes in range. Take the initial variable count as 0. Take the initial variable count as 0. Traverse using for loop from i=strt to i <=end Traverse using for loop from i=strt to i <=end Take each number i and check if it is prime using isprime(i). Take each number i and check if it is prime using isprime(i). Function isprime(int num) returns 0 if the number is non prime and 1 if it is prime. Function isprime(int num) returns 0 if the number is non prime and 1 if it is prime. After the end of loop, return count as result. After the end of loop, return count as result. Live Demo #include <bits/stdc++.h> using namespace std; int isprime(int num){ if (num <= 1) return 0; for (int i = 2; i <= num/2; i++){ if (num % i == 0) { return 0; } } return 1; //if both failed then num is prime } int countPrimes(int strt,int end){ int count=0; for(int i=strt;i<=end;i++){ if(isprime(i)==1) { count++; } } return count; } int main(){ int START=10, END=20; cout <<endl<<"Primes in Ranges : "<<countPrimes(START,END); return 0; } If we run the above code it will generate the following output − Primes in Ranges : 4
[ { "code": null, "e": 1179, "s": 1062, "text": "We are given range variables START and END. The goal is to find the count of prime numbers in the range [START,END]." }, { "code": null, "e": 1338, "s": 1179, "text": "We will check if number i in range is prime by checking if any number other than 1 fully divides it and is between 1 and i/2. If it is prime. Increment count." }, { "code": null, "e": 1370, "s": 1338, "text": "Let’s understand with examples." }, { "code": null, "e": 1377, "s": 1370, "text": "Input " }, { "code": null, "e": 1392, "s": 1377, "text": "Start=1 End=20" }, { "code": null, "e": 1400, "s": 1392, "text": "Output " }, { "code": null, "e": 1421, "s": 1400, "text": "Primes in Ranges : 8" }, { "code": null, "e": 1434, "s": 1421, "text": "Explanation " }, { "code": null, "e": 1484, "s": 1434, "text": "Primes between 1 and 20 are: 2,3,5,7,11,13,17,19." }, { "code": null, "e": 1491, "s": 1484, "text": "Input " }, { "code": null, "e": 1509, "s": 1491, "text": "Start=100 End=200" }, { "code": null, "e": 1517, "s": 1509, "text": "Output " }, { "code": null, "e": 1539, "s": 1517, "text": "Primes in Ranges : 21" }, { "code": null, "e": 1552, "s": 1539, "text": "Explanation " }, { "code": null, "e": 1668, "s": 1552, "text": "Primes between 100 and 200 are: 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199" }, { "code": null, "e": 1710, "s": 1668, "text": "We take range variables as START and END." }, { "code": null, "e": 1752, "s": 1710, "text": "We take range variables as START and END." }, { "code": null, "e": 1829, "s": 1752, "text": "Function countPrimes(int strt,int end) returns the count of primes in range." }, { "code": null, "e": 1906, "s": 1829, "text": "Function countPrimes(int strt,int end) returns the count of primes in range." }, { "code": null, "e": 1944, "s": 1906, "text": "Take the initial variable count as 0." }, { "code": null, "e": 1982, "s": 1944, "text": "Take the initial variable count as 0." }, { "code": null, "e": 2029, "s": 1982, "text": "Traverse using for loop from i=strt to i <=end" }, { "code": null, "e": 2076, "s": 2029, "text": "Traverse using for loop from i=strt to i <=end" }, { "code": null, "e": 2138, "s": 2076, "text": "Take each number i and check if it is prime using isprime(i)." }, { "code": null, "e": 2200, "s": 2138, "text": "Take each number i and check if it is prime using isprime(i)." }, { "code": null, "e": 2285, "s": 2200, "text": "Function isprime(int num) returns 0 if the number is non prime and 1 if it is prime." }, { "code": null, "e": 2370, "s": 2285, "text": "Function isprime(int num) returns 0 if the number is non prime and 1 if it is prime." }, { "code": null, "e": 2417, "s": 2370, "text": "After the end of loop, return count as result." }, { "code": null, "e": 2464, "s": 2417, "text": "After the end of loop, return count as result." }, { "code": null, "e": 2475, "s": 2464, "text": " Live Demo" }, { "code": null, "e": 2982, "s": 2475, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint isprime(int num){\n if (num <= 1)\n return 0;\n for (int i = 2; i <= num/2; i++){\n if (num % i == 0)\n { return 0; }\n }\n return 1; //if both failed then num is prime\n}\nint countPrimes(int strt,int end){\n int count=0;\n for(int i=strt;i<=end;i++){\n if(isprime(i)==1)\n { count++; }\n }\n return count;\n}\nint main(){\n int START=10, END=20;\n cout <<endl<<\"Primes in Ranges : \"<<countPrimes(START,END);\n return 0;\n}" }, { "code": null, "e": 3047, "s": 2982, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 3068, "s": 3047, "text": "Primes in Ranges : 4" } ]
Python Altair Combines Filtering, Grouping, and Merging into a Single Data Visualization | by Soner Yıldırım | Towards Data Science
Altair is a statistical data visualization library for Python. It provides a simple and easy-to-understand syntax for creating both static and interactive visualizations. What I think separates Altair from other common data visualization libraries is that it integrates data analysis components into the visualizations seamlessly. Thus, it serves as a highly practical tool for data exploration. In this article, we will see, step-by-step, how to create a visualization that includes filtering, grouping, and merging operations. Eventually, we will create an informative plot that can be used as part of an exploratory data analysis process. We first generate mock data which consists of two data frames. The first one contains restaurant orders and the other one contains the prices of the items placed in the orders. # import librariesimport numpy as npimport pandas as pdimport altair as altimport random# mock dataorders = pd.DataFrame({ "order_id": np.arange(1,101), "item": np.random.randint(1, 50, size=100), "qty": np.random.randint(1, 10, size=100), "tip": (np.random.random(100) * 10).round(2)})prices = pd.DataFrame({ "item": np.arange(1,51), "price": (np.random.random(50) * 50).round(2)})order_type = ["lunch", "dinner"] * 50random.shuffle(order_type)orders["order_type"] = order_type The values are generated using numpy functions. Then, we add order type using a list of 100 items. The shuffle function under the random module of Python is used for randomizing the list. Let’s take a look at the data frames we have just created. You may argue that we can have the item prices in the orders table. We designed the data frames this way to be able to use the merging operation. Besides, it slightly demonstrates the idea of relational databases. Let’s first create a simple plot to introduce the structure of Altair syntax. alt.Chart(orders).mark_circle(size=50).encode( x="qty", y="tip", color="order_type").properties( title = "Tip vs Quantity") We start by passing the data to a top-level Chart object. The data can be in the form of a Pandas data frame or a URL string pointing to a json or csv file. Then, the type of visualization (e.g. mark_circle, mark_line, and so on) is selected. The encode function specifies what to plot in the given data frame. Thus, anything we write in the encode function must be linked to the data frame. Finally, we specify certain properties of the plot using the properties function. Consider a case where we need to create a scatter plot of the price and tip values. They are in different data frames. One option is to merge two data frames and use these two columns in a scatter plot. Altair offers a more practical way. It allows for looking up a column in a different data frame. The intuition is the same as the merge function of Pandas. alt.Chart(orders).mark_circle(size=50).encode( x="tip", y="price:Q", color="order_type").transform_lookup( lookup="item", from_=alt.LookupData(data=prices, key="item", fields=["price"])).properties( title = "Price vs Tip") The transform_lookup function is similar to the merge function of Pandas. The column used for matching the observations (i.e. rows) is passed to the lookup parameter. The fields parameter is used for selecting the desired columns from the other data frame. We can also integrate a filtering component to our plot. Let’s plot the data points with a price of more than 10 dollars. alt.Chart(orders).mark_circle(size=50).encode( x="tip", y="price:Q", color="order_type").transform_lookup( lookup="item", from_=alt.LookupData(data=prices, key="item", fields=["price"])).transform_filter( alt.FieldGTPredicate(field='price', gt=10)).properties( title = "Price vs Tip") The transform_filter function is used for filtering. The FieldGTPredicate handles “greater than” conditions. Altair also provides predicates for other conditions such as “equal”, “less than”, “range”, and so on. In addition to filtering and merging, Altair allows for grouping the data points before plotting. For instance, we can create a bar plot that shows the average price of items for each order type. Furthermore, we can perform this operation for items that cost less than 20 dollars. alt.Chart(orders).mark_bar().encode( y="order_type", x="avg_price:Q").transform_lookup( lookup="item", from_=alt.LookupData(data=prices, key="item", fields=["price"])).transform_filter( alt.FieldLTPredicate(field='price', lt=20)).transform_aggregate( avg_price = "mean(price)", groupby = ["order_type"]).properties( height=200, width=300) Let’s elaborate on each step: transform_lookup: Looks up the price from the prices data frame. transform_filter: Filter the prices that are less than 20 dollars. transform_aggregate: Groups the prices by order type and calculates the mean. Make sure you pass the name of the aggregated column to the encode function. Filtering, merging, and grouping are essential to an exploratory data analysis process. Altair allows for performing all of these operations while creating data visualizations. In that sense, Altair can also be considered as a data analysis tool. The examples we have done in the article may not seem so useful but they clearly explain how these components are used in the visualizations. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 342, "s": 171, "text": "Altair is a statistical data visualization library for Python. It provides a simple and easy-to-understand syntax for creating both static and interactive visualizations." }, { "code": null, "e": 567, "s": 342, "text": "What I think separates Altair from other common data visualization libraries is that it integrates data analysis components into the visualizations seamlessly. Thus, it serves as a highly practical tool for data exploration." }, { "code": null, "e": 813, "s": 567, "text": "In this article, we will see, step-by-step, how to create a visualization that includes filtering, grouping, and merging operations. Eventually, we will create an informative plot that can be used as part of an exploratory data analysis process." }, { "code": null, "e": 990, "s": 813, "text": "We first generate mock data which consists of two data frames. The first one contains restaurant orders and the other one contains the prices of the items placed in the orders." }, { "code": null, "e": 1481, "s": 990, "text": "# import librariesimport numpy as npimport pandas as pdimport altair as altimport random# mock dataorders = pd.DataFrame({ \"order_id\": np.arange(1,101), \"item\": np.random.randint(1, 50, size=100), \"qty\": np.random.randint(1, 10, size=100), \"tip\": (np.random.random(100) * 10).round(2)})prices = pd.DataFrame({ \"item\": np.arange(1,51), \"price\": (np.random.random(50) * 50).round(2)})order_type = [\"lunch\", \"dinner\"] * 50random.shuffle(order_type)orders[\"order_type\"] = order_type" }, { "code": null, "e": 1669, "s": 1481, "text": "The values are generated using numpy functions. Then, we add order type using a list of 100 items. The shuffle function under the random module of Python is used for randomizing the list." }, { "code": null, "e": 1728, "s": 1669, "text": "Let’s take a look at the data frames we have just created." }, { "code": null, "e": 1942, "s": 1728, "text": "You may argue that we can have the item prices in the orders table. We designed the data frames this way to be able to use the merging operation. Besides, it slightly demonstrates the idea of relational databases." }, { "code": null, "e": 2020, "s": 1942, "text": "Let’s first create a simple plot to introduce the structure of Altair syntax." }, { "code": null, "e": 2148, "s": 2020, "text": "alt.Chart(orders).mark_circle(size=50).encode( x=\"qty\", y=\"tip\", color=\"order_type\").properties( title = \"Tip vs Quantity\")" }, { "code": null, "e": 2391, "s": 2148, "text": "We start by passing the data to a top-level Chart object. The data can be in the form of a Pandas data frame or a URL string pointing to a json or csv file. Then, the type of visualization (e.g. mark_circle, mark_line, and so on) is selected." }, { "code": null, "e": 2622, "s": 2391, "text": "The encode function specifies what to plot in the given data frame. Thus, anything we write in the encode function must be linked to the data frame. Finally, we specify certain properties of the plot using the properties function." }, { "code": null, "e": 2825, "s": 2622, "text": "Consider a case where we need to create a scatter plot of the price and tip values. They are in different data frames. One option is to merge two data frames and use these two columns in a scatter plot." }, { "code": null, "e": 2981, "s": 2825, "text": "Altair offers a more practical way. It allows for looking up a column in a different data frame. The intuition is the same as the merge function of Pandas." }, { "code": null, "e": 3212, "s": 2981, "text": "alt.Chart(orders).mark_circle(size=50).encode( x=\"tip\", y=\"price:Q\", color=\"order_type\").transform_lookup( lookup=\"item\", from_=alt.LookupData(data=prices, key=\"item\", fields=[\"price\"])).properties( title = \"Price vs Tip\")" }, { "code": null, "e": 3469, "s": 3212, "text": "The transform_lookup function is similar to the merge function of Pandas. The column used for matching the observations (i.e. rows) is passed to the lookup parameter. The fields parameter is used for selecting the desired columns from the other data frame." }, { "code": null, "e": 3591, "s": 3469, "text": "We can also integrate a filtering component to our plot. Let’s plot the data points with a price of more than 10 dollars." }, { "code": null, "e": 3886, "s": 3591, "text": "alt.Chart(orders).mark_circle(size=50).encode( x=\"tip\", y=\"price:Q\", color=\"order_type\").transform_lookup( lookup=\"item\", from_=alt.LookupData(data=prices, key=\"item\", fields=[\"price\"])).transform_filter( alt.FieldGTPredicate(field='price', gt=10)).properties( title = \"Price vs Tip\")" }, { "code": null, "e": 4098, "s": 3886, "text": "The transform_filter function is used for filtering. The FieldGTPredicate handles “greater than” conditions. Altair also provides predicates for other conditions such as “equal”, “less than”, “range”, and so on." }, { "code": null, "e": 4379, "s": 4098, "text": "In addition to filtering and merging, Altair allows for grouping the data points before plotting. For instance, we can create a bar plot that shows the average price of items for each order type. Furthermore, we can perform this operation for items that cost less than 20 dollars." }, { "code": null, "e": 4730, "s": 4379, "text": "alt.Chart(orders).mark_bar().encode( y=\"order_type\", x=\"avg_price:Q\").transform_lookup( lookup=\"item\", from_=alt.LookupData(data=prices, key=\"item\", fields=[\"price\"])).transform_filter( alt.FieldLTPredicate(field='price', lt=20)).transform_aggregate( avg_price = \"mean(price)\", groupby = [\"order_type\"]).properties( height=200, width=300)" }, { "code": null, "e": 4760, "s": 4730, "text": "Let’s elaborate on each step:" }, { "code": null, "e": 4825, "s": 4760, "text": "transform_lookup: Looks up the price from the prices data frame." }, { "code": null, "e": 4892, "s": 4825, "text": "transform_filter: Filter the prices that are less than 20 dollars." }, { "code": null, "e": 4970, "s": 4892, "text": "transform_aggregate: Groups the prices by order type and calculates the mean." }, { "code": null, "e": 5047, "s": 4970, "text": "Make sure you pass the name of the aggregated column to the encode function." }, { "code": null, "e": 5294, "s": 5047, "text": "Filtering, merging, and grouping are essential to an exploratory data analysis process. Altair allows for performing all of these operations while creating data visualizations. In that sense, Altair can also be considered as a data analysis tool." }, { "code": null, "e": 5436, "s": 5294, "text": "The examples we have done in the article may not seem so useful but they clearly explain how these components are used in the visualizations." } ]
MySQL - Transactions
A transaction is a sequential group of database manipulation operations, which is performed as if it were one single work unit. In other words, a transaction will never be complete unless each individual operation within the group is successful. If any operation within the transaction fails, the entire transaction will fail. Practically, you will club many SQL queries into a group and you will execute all of them together as a part of a transaction. Transactions have the following four standard properties, usually referred to by the acronym ACID − Atomicity − This ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state. Atomicity − This ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state. Consistency − This ensures that the database properly changes states upon a successfully committed transaction. Consistency − This ensures that the database properly changes states upon a successfully committed transaction. Isolation − This enables transactions to operate independently on and transparent to each other. Isolation − This enables transactions to operate independently on and transparent to each other. Durability − This ensures that the result or effect of a committed transaction persists in case of a system failure. Durability − This ensures that the result or effect of a committed transaction persists in case of a system failure. In MySQL, the transactions begin with the statement BEGIN WORK and end with either a COMMIT or a ROLLBACK statement. The SQL commands between the beginning and ending statements form the bulk of the transaction. These two keywords Commit and Rollback are mainly used for MySQL Transactions. When a successful transaction is completed, the COMMIT command should be issued so that the changes to all involved tables will take effect. When a successful transaction is completed, the COMMIT command should be issued so that the changes to all involved tables will take effect. If a failure occurs, a ROLLBACK command should be issued to return every table referenced in the transaction to its previous state. If a failure occurs, a ROLLBACK command should be issued to return every table referenced in the transaction to its previous state. You can control the behavior of a transaction by setting session variable called AUTOCOMMIT. If AUTOCOMMIT is set to 1 (the default), then each SQL statement (within a transaction or not) is considered a complete transaction and committed by default when it finishes. When AUTOCOMMIT is set to 0, by issuing the SET AUTOCOMMIT = 0 command, the subsequent series of statements acts like a transaction and no activities are committed until an explicit COMMIT statement is issued. You can execute these SQL commands in PHP by using the mysql_query() function. This sequence of events is independent of the programming language used. The logical path can be created in whichever language you use to create your application. You can execute these SQL commands in PHP by using the mysql_query() function. Begin transaction by issuing the SQL command BEGIN WORK. Begin transaction by issuing the SQL command BEGIN WORK. Issue one or more SQL commands like SELECT, INSERT, UPDATE or DELETE. Issue one or more SQL commands like SELECT, INSERT, UPDATE or DELETE. Check if there is no error and everything is according to your requirement. Check if there is no error and everything is according to your requirement. If there is any error, then issue a ROLLBACK command, otherwise issue a COMMIT command. If there is any error, then issue a ROLLBACK command, otherwise issue a COMMIT command. You cannot use transactions directly, but for certain exceptions you can. However, they are not safe and guaranteed. If you plan to use transactions in your MySQL programming, then you need to create your tables in a special way. There are many types of tables, which support transactions, but the most popular one is InnoDB. Support for InnoDB tables requires a specific compilation parameter when compiling MySQL from the source. If your MySQL version does not have InnoDB support, ask your Internet Service Provider to build a version of MySQL with support for InnoDB table types or download and install the MySQL-Max Binary Distribution for Windows or Linux/UNIX and work with the table type in a development environment. If your MySQL installation supports InnoDB tables, simply add a TYPE = InnoDB definition to the table creation statement. For example, the following code creates an InnoDB table called tcount_tbl − root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> create table tcount_tbl -> ( -> tutorial_author varchar(40) NOT NULL, -> tutorial_count INT -> ) TYPE = InnoDB; Query OK, 0 rows affected (0.05 sec) For more details on InnoDB, you can click on the following link −InnoDB You can use other table types like GEMINI or BDB, but it depends on your installation, whether it supports these two table types or not. 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2660, "s": 2333, "text": "A transaction is a sequential group of database manipulation operations, which is performed as if it were one single work unit. In other words, a transaction will never be complete unless each individual operation within the group is successful. If any operation within the transaction fails, the entire transaction will fail." }, { "code": null, "e": 2787, "s": 2660, "text": "Practically, you will club many SQL queries into a group and you will execute all of them together as a part of a transaction." }, { "code": null, "e": 2887, "s": 2787, "text": "Transactions have the following four standard properties, usually referred to by the acronym ACID −" }, { "code": null, "e": 3106, "s": 2887, "text": "Atomicity − This ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state." }, { "code": null, "e": 3325, "s": 3106, "text": "Atomicity − This ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state." }, { "code": null, "e": 3437, "s": 3325, "text": "Consistency − This ensures that the database properly changes states upon a successfully committed transaction." }, { "code": null, "e": 3549, "s": 3437, "text": "Consistency − This ensures that the database properly changes states upon a successfully committed transaction." }, { "code": null, "e": 3646, "s": 3549, "text": "Isolation − This enables transactions to operate independently on and transparent to each other." }, { "code": null, "e": 3743, "s": 3646, "text": "Isolation − This enables transactions to operate independently on and transparent to each other." }, { "code": null, "e": 3860, "s": 3743, "text": "Durability − This ensures that the result or effect of a committed transaction persists in case of a system failure." }, { "code": null, "e": 3977, "s": 3860, "text": "Durability − This ensures that the result or effect of a committed transaction persists in case of a system failure." }, { "code": null, "e": 4189, "s": 3977, "text": "In MySQL, the transactions begin with the statement BEGIN WORK and end with either a COMMIT or a ROLLBACK statement. The SQL commands between the beginning and ending statements form the bulk of the transaction." }, { "code": null, "e": 4268, "s": 4189, "text": "These two keywords Commit and Rollback are mainly used for MySQL Transactions." }, { "code": null, "e": 4409, "s": 4268, "text": "When a successful transaction is completed, the COMMIT command should be issued so that the changes to all involved tables will take effect." }, { "code": null, "e": 4550, "s": 4409, "text": "When a successful transaction is completed, the COMMIT command should be issued so that the changes to all involved tables will take effect." }, { "code": null, "e": 4682, "s": 4550, "text": "If a failure occurs, a ROLLBACK command should be issued to return every table referenced in the transaction to its previous state." }, { "code": null, "e": 4814, "s": 4682, "text": "If a failure occurs, a ROLLBACK command should be issued to return every table referenced in the transaction to its previous state." }, { "code": null, "e": 5082, "s": 4814, "text": "You can control the behavior of a transaction by setting session variable called AUTOCOMMIT. If AUTOCOMMIT is set to 1 (the default), then each SQL statement (within a transaction or not) is considered a complete transaction and committed by default when it finishes." }, { "code": null, "e": 5292, "s": 5082, "text": "When AUTOCOMMIT is set to 0, by issuing the SET AUTOCOMMIT = 0 command, the subsequent series of statements acts like a transaction and no activities are committed until an explicit COMMIT statement is issued." }, { "code": null, "e": 5371, "s": 5292, "text": "You can execute these SQL commands in PHP by using the mysql_query() function." }, { "code": null, "e": 5534, "s": 5371, "text": "This sequence of events is independent of the programming language used. The logical path can be created in whichever language you use to create your application." }, { "code": null, "e": 5613, "s": 5534, "text": "You can execute these SQL commands in PHP by using the mysql_query() function." }, { "code": null, "e": 5670, "s": 5613, "text": "Begin transaction by issuing the SQL command BEGIN WORK." }, { "code": null, "e": 5727, "s": 5670, "text": "Begin transaction by issuing the SQL command BEGIN WORK." }, { "code": null, "e": 5797, "s": 5727, "text": "Issue one or more SQL commands like SELECT, INSERT, UPDATE or DELETE." }, { "code": null, "e": 5867, "s": 5797, "text": "Issue one or more SQL commands like SELECT, INSERT, UPDATE or DELETE." }, { "code": null, "e": 5943, "s": 5867, "text": "Check if there is no error and everything is according to your requirement." }, { "code": null, "e": 6019, "s": 5943, "text": "Check if there is no error and everything is according to your requirement." }, { "code": null, "e": 6107, "s": 6019, "text": "If there is any error, then issue a ROLLBACK command, otherwise issue a COMMIT command." }, { "code": null, "e": 6195, "s": 6107, "text": "If there is any error, then issue a ROLLBACK command, otherwise issue a COMMIT command." }, { "code": null, "e": 6521, "s": 6195, "text": "You cannot use transactions directly, but for certain exceptions you can. However, they are not safe and guaranteed. If you plan to use transactions in your MySQL programming, then you need to create your tables in a special way. There are many types of tables, which support transactions, but the most popular one is InnoDB." }, { "code": null, "e": 6921, "s": 6521, "text": "Support for InnoDB tables requires a specific compilation parameter when compiling MySQL from the source. If your MySQL version does not have InnoDB support, ask your Internet Service Provider to build a version of MySQL with support for InnoDB table types or download and install the MySQL-Max Binary Distribution for Windows or Linux/UNIX and work with the table type in a development environment." }, { "code": null, "e": 7043, "s": 6921, "text": "If your MySQL installation supports InnoDB tables, simply add a TYPE = InnoDB definition to the table creation statement." }, { "code": null, "e": 7119, "s": 7043, "text": "For example, the following code creates an InnoDB table called tcount_tbl −" }, { "code": null, "e": 7390, "s": 7119, "text": "root@host# mysql -u root -p password;\nEnter password:*******\n\nmysql> use TUTORIALS;\nDatabase changed\n\nmysql> create table tcount_tbl\n -> (\n -> tutorial_author varchar(40) NOT NULL,\n -> tutorial_count INT\n -> ) TYPE = InnoDB;\nQuery OK, 0 rows affected (0.05 sec)" }, { "code": null, "e": 7462, "s": 7390, "text": "For more details on InnoDB, you can click on the following link −InnoDB" }, { "code": null, "e": 7599, "s": 7462, "text": "You can use other table types like GEMINI or BDB, but it depends on your installation, whether it supports these two table types or not." }, { "code": null, "e": 7632, "s": 7599, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 7660, "s": 7632, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7695, "s": 7660, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7712, "s": 7695, "text": " Frahaan Hussain" }, { "code": null, "e": 7746, "s": 7712, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7781, "s": 7746, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 7815, "s": 7781, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 7843, "s": 7815, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 7876, "s": 7843, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 7896, "s": 7876, "text": " Harshit Srivastava" }, { "code": null, "e": 7929, "s": 7896, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 7947, "s": 7929, "text": " Trevoir Williams" }, { "code": null, "e": 7954, "s": 7947, "text": " Print" }, { "code": null, "e": 7965, "s": 7954, "text": " Add Notes" } ]
Prolog - Linked Lists
Following chapters describe how to generate/create linked lists using recursive structures. Linked list has two components, the integer part and the link part. The link part will hold another node. End of list will have nil into the link part. In prolog, we can express this using node(2, node(5, node(6, nil))). Note − The smallest possible list is nil, and every other list will contain nil as the "next" of the end node. In list terminology, the first element is usually called the head of the list, and the rest of the list is called the tail part. Thus the head of the above list is 2, and its tail is the list node(5, node(6, nil)). We can also insert elements into front and back side − add_front(L,E,NList) :- NList = node(E,L). add_back(nil, E, NList) :- NList = node(E,nil). add_back(node(Head,Tail), E, NList) :- add_back(Tail, E, NewTail), NList = node(Head,NewTail). | ?- [linked_list]. compiling D:/TP Prolog/Sample_Codes/linked_list.pl for byte code... D:/TP Prolog/Sample_Codes/linked_list.pl compiled, 7 lines read - 966 bytes written, 14 ms (15 ms) yes | ?- add_front(nil, 6, L1), add_front(L1, 5, L2), add_front(L2, 2, L3). L1 = node(6,nil) L2 = node(5,node(6,nil)) L3 = node(2,node(5,node(6,nil))) yes | ?- add_back(nil, 6, L1), add_back(L1, 5, L2), add_back(L2, 2, L3). L1 = node(6,nil) L2 = node(6,node(5,nil)) L3 = node(6,node(5,node(2,nil))) yes | ?- add_front(nil, 6, L1), add_front(L1, 5, L2), add_back(L2, 2, L3). L1 = node(6,nil) L2 = node(5,node(6,nil)) L3 = node(5,node(6,node(2,nil))) yes | ?- 65 Lectures 5 hours Arnab Chakraborty 78 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2184, "s": 2092, "text": "Following chapters describe how to generate/create linked lists using recursive structures." }, { "code": null, "e": 2336, "s": 2184, "text": "Linked list has two components, the integer part and the link part. The link part will hold another node. End of list will have nil into the link part." }, { "code": null, "e": 2405, "s": 2336, "text": "In prolog, we can express this using node(2, node(5, node(6, nil)))." }, { "code": null, "e": 2731, "s": 2405, "text": "Note − The smallest possible list is nil, and every other list will contain nil as the \"next\" of the end node. In list terminology, the first element is usually called the head of the list, and the rest of the list is called the tail part. Thus the head of the above list is 2, and its tail is the list node(5, node(6, nil))." }, { "code": null, "e": 2786, "s": 2731, "text": "We can also insert elements into front and back side −" }, { "code": null, "e": 2986, "s": 2786, "text": "add_front(L,E,NList) :- NList = node(E,L).\n\nadd_back(nil, E, NList) :-\n NList = node(E,nil).\n \nadd_back(node(Head,Tail), E, NList) :-\n add_back(Tail, E, NewTail),\n NList = node(Head,NewTail)." }, { "code": null, "e": 3639, "s": 2986, "text": "| ?- [linked_list].\ncompiling D:/TP Prolog/Sample_Codes/linked_list.pl for byte code...\nD:/TP Prolog/Sample_Codes/linked_list.pl compiled, 7 lines read - 966 bytes written, 14 ms\n\n(15 ms) yes\n| ?- add_front(nil, 6, L1), add_front(L1, 5, L2), add_front(L2, 2, L3).\n\nL1 = node(6,nil)\nL2 = node(5,node(6,nil))\nL3 = node(2,node(5,node(6,nil)))\n\nyes\n| ?- add_back(nil, 6, L1), add_back(L1, 5, L2), add_back(L2, 2, L3).\n\nL1 = node(6,nil)\nL2 = node(6,node(5,nil))\nL3 = node(6,node(5,node(2,nil)))\n\nyes\n| ?- add_front(nil, 6, L1), add_front(L1, 5, L2), add_back(L2, 2, L3).\n\nL1 = node(6,nil)\nL2 = node(5,node(6,nil))\nL3 = node(5,node(6,node(2,nil)))\n\nyes\n| ?-\n" }, { "code": null, "e": 3672, "s": 3639, "text": "\n 65 Lectures \n 5 hours \n" }, { "code": null, "e": 3691, "s": 3672, "text": " Arnab Chakraborty" }, { "code": null, "e": 3724, "s": 3691, "text": "\n 78 Lectures \n 7 hours \n" }, { "code": null, "e": 3743, "s": 3724, "text": " Arnab Chakraborty" }, { "code": null, "e": 3750, "s": 3743, "text": " Print" }, { "code": null, "e": 3761, "s": 3750, "text": " Add Notes" } ]
Caesar Cipher in Cryptography - GeeksforGeeks
22 Jan, 2022 The Caesar Cipher technique is one of the earliest and simplest method of encryption technique. It’s simply a type of substitution cipher, i.e., each letter of a given text is replaced by a letter some fixed number of positions down the alphabet. For example with a shift of 1, A would be replaced by B, B would become C, and so on. The method is apparently named after Julius Caesar, who apparently used it to communicate with his officials. Thus to cipher a given text we need an integer value, known as shift which indicates the number of position each letter of the text has been moved down. The encryption can be represented using modular arithmetic by first transforming the letters into numbers, according to the scheme, A = 0, B = 1,..., Z = 25. Encryption of a letter by a shift n can be described mathematically as. (Encryption Phase with shift n) (Decryption Phase with shift n) Examples : Text : ABCDEFGHIJKLMNOPQRSTUVWXYZ Shift: 23 Cipher: XYZABCDEFGHIJKLMNOPQRSTUVW Text : ATTACKATONCE Shift: 4 Cipher: EXXEGOEXSRGI Algorithm for Caesar Cipher: Input: A String of lower case letters, called Text.An Integer between 0-25 denoting the required shift. A String of lower case letters, called Text. An Integer between 0-25 denoting the required shift. Procedure: Traverse the given text one character at a time . For each character, transform the given character as per the rule, depending on whether we’re encrypting or decrypting the text. Return the new string generated. Program that receives a Text (string) and Shift value( integer) and returns the encrypted text. C++ Java Python3 C# PHP Javascript // A C++ program to illustrate Caesar Cipher Technique#include <iostream>using namespace std; // This function receives text and shift and// returns the encrypted textstring encrypt(string text, int s){ string result = ""; // traverse text for (int i=0;i<text.length();i++) { // apply transformation to each character // Encrypt Uppercase letters if (isupper(text[i])) result += char(int(text[i]+s-65)%26 +65); // Encrypt Lowercase letters else result += char(int(text[i]+s-97)%26 +97); } // Return the resulting string return result;} // Driver program to test the above functionint main(){ string text="ATTACKATONCE"; int s = 4; cout << "Text : " << text; cout << "\nShift: " << s; cout << "\nCipher: " << encrypt(text, s); return 0;} //A Java Program to illustrate Caesar Cipher Techniqueclass CaesarCipher{ // Encrypts text using a shift od s public static StringBuffer encrypt(String text, int s) { StringBuffer result= new StringBuffer(); for (int i=0; i<text.length(); i++) { if (Character.isUpperCase(text.charAt(i))) { char ch = (char)(((int)text.charAt(i) + s - 65) % 26 + 65); result.append(ch); } else { char ch = (char)(((int)text.charAt(i) + s - 97) % 26 + 97); result.append(ch); } } return result; } // Driver code public static void main(String[] args) { String text = "ATTACKATONCE"; int s = 4; System.out.println("Text : " + text); System.out.println("Shift : " + s); System.out.println("Cipher: " + encrypt(text, s)); }} #A python program to illustrate Caesar Cipher Techniquedef encrypt(text,s): result = "" # traverse text for i in range(len(text)): char = text[i] # Encrypt uppercase characters if (char.isupper()): result += chr((ord(char) + s-65) % 26 + 65) # Encrypt lowercase characters else: result += chr((ord(char) + s - 97) % 26 + 97) return result #check the above functiontext = "ATTACKATONCE"s = 4print ("Text : " + text)print ("Shift : " + str(s))print ("Cipher: " + encrypt(text,s)) // A C# Program to illustrate Caesar Cipher Techniqueusing System;using System.Text; public class CaesarCipher{ // Encrypts text using a shift od s public static StringBuilder encrypt(String text, int s) { StringBuilder result= new StringBuilder(); for (int i=0; i<text.Length; i++) { if (char.IsUpper(text[i])) { char ch = (char)(((int)text[i] + s - 65) % 26 + 65); result.Append(ch); } else { char ch = (char)(((int)text[i] + s - 97) % 26 + 97); result.Append(ch); } } return result; } // Driver code public static void Main(String[] args) { String text = "ATTACKATONCE"; int s = 4; Console.WriteLine("Text : " + text); Console.WriteLine("Shift : " + s); Console.WriteLine("Cipher: " + encrypt(text, s)); }} /* This code contributed by PrinciRaj1992 */ <?php// A PHP program to illustrate Caesar// Cipher Technique // This function receives text and shift// and returns the encrypted textfunction encrypt($text, $s){ $result = ""; // traverse text for ($i = 0; $i < strlen($text); $i++) { // apply transformation to each // character Encrypt Uppercase letters if (ctype_upper($text[$i])) $result = $result.chr((ord($text[$i]) + $s - 65) % 26 + 65); // Encrypt Lowercase letters else $result = $result.chr((ord($text[$i]) + $s - 97) % 26 + 97); } // Return the resulting string return $result;} // Driver Code$text = "ATTACKATONCE";$s = 4;echo "Text : " . $text;echo "\nShift: " . $s;echo "\nCipher: " . encrypt($text, $s); // This code is contributed by ita_c?> <script>//A Javascript Program to illustrate Caesar Cipher Technique // Encrypts text using a shift od s function encrypt(text, s) { let result="" for (let i = 0; i < text.length; i++) { let char = text[i]; if (char.toUpperCase(text[i])) { let ch = String.fromCharCode((char.charCodeAt(0) + s-65) % 26 + 65); result += ch; } else { let ch = String.fromCharCode((char.charCodeAt(0) + s-97) % 26 + 97); result += ch; } } return result; } // Driver code let text = "ATTACKATONCE"; let s = 4; document.write("Text : " + text + "<br>"); document.write("Shift : " + s + "<br>"); document.write("Cipher: " + encrypt(text, s) + "<br>"); // This code is contributed by avanitrachhadiya2155</script> Output: Text : ATTACKATONCE Shift: 4 Cipher: EXXEGOEXSRGI How to decrypt? We can either write another function decrypt similar to encrypt, that’ll apply the given shift in the opposite direction to decrypt the original text. However we can use the cyclic property of the cipher under modulo , hence we can simply observe Cipher(n) = De-cipher(26-n) Hence, we can use the same function to decrypt, instead we’ll modify the shift value such that shift = 26-shift (Refer this for a sample run in C++). https://www.youtube.com/watch?v=S472gPqwF -o This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above SOURABH MANGAL ukasp princiraj1992 avanitrachhadiya2155 amartyaniel20 cryptography Computer Networks GATE CS Strings Strings cryptography Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between IPv4 and IPv6 Types of Network Topology TCP 3-Way Handshake Process UDP Server-Client implementation in C User Datagram Protocol (UDP) ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Cache Memory in Computer Organization
[ { "code": null, "e": 25659, "s": 25631, "text": "\n22 Jan, 2022" }, { "code": null, "e": 26487, "s": 25659, "text": "The Caesar Cipher technique is one of the earliest and simplest method of encryption technique. It’s simply a type of substitution cipher, i.e., each letter of a given text is replaced by a letter some fixed number of positions down the alphabet. For example with a shift of 1, A would be replaced by B, B would become C, and so on. The method is apparently named after Julius Caesar, who apparently used it to communicate with his officials. Thus to cipher a given text we need an integer value, known as shift which indicates the number of position each letter of the text has been moved down. The encryption can be represented using modular arithmetic by first transforming the letters into numbers, according to the scheme, A = 0, B = 1,..., Z = 25. Encryption of a letter by a shift n can be described mathematically as. " }, { "code": null, "e": 26519, "s": 26487, "text": "(Encryption Phase with shift n)" }, { "code": null, "e": 26551, "s": 26519, "text": "(Decryption Phase with shift n)" }, { "code": null, "e": 26564, "s": 26551, "text": "Examples : " }, { "code": null, "e": 26694, "s": 26564, "text": "Text : ABCDEFGHIJKLMNOPQRSTUVWXYZ\nShift: 23\nCipher: XYZABCDEFGHIJKLMNOPQRSTUVW\n\nText : ATTACKATONCE\nShift: 4\nCipher: EXXEGOEXSRGI" }, { "code": null, "e": 26732, "s": 26694, "text": "Algorithm for Caesar Cipher: Input: " }, { "code": null, "e": 26829, "s": 26732, "text": "A String of lower case letters, called Text.An Integer between 0-25 denoting the required shift." }, { "code": null, "e": 26874, "s": 26829, "text": "A String of lower case letters, called Text." }, { "code": null, "e": 26927, "s": 26874, "text": "An Integer between 0-25 denoting the required shift." }, { "code": null, "e": 26940, "s": 26927, "text": "Procedure: " }, { "code": null, "e": 26990, "s": 26940, "text": "Traverse the given text one character at a time ." }, { "code": null, "e": 27119, "s": 26990, "text": "For each character, transform the given character as per the rule, depending on whether we’re encrypting or decrypting the text." }, { "code": null, "e": 27152, "s": 27119, "text": "Return the new string generated." }, { "code": null, "e": 27250, "s": 27152, "text": "Program that receives a Text (string) and Shift value( integer) and returns the encrypted text. " }, { "code": null, "e": 27254, "s": 27250, "text": "C++" }, { "code": null, "e": 27259, "s": 27254, "text": "Java" }, { "code": null, "e": 27267, "s": 27259, "text": "Python3" }, { "code": null, "e": 27270, "s": 27267, "text": "C#" }, { "code": null, "e": 27274, "s": 27270, "text": "PHP" }, { "code": null, "e": 27285, "s": 27274, "text": "Javascript" }, { "code": "// A C++ program to illustrate Caesar Cipher Technique#include <iostream>using namespace std; // This function receives text and shift and// returns the encrypted textstring encrypt(string text, int s){ string result = \"\"; // traverse text for (int i=0;i<text.length();i++) { // apply transformation to each character // Encrypt Uppercase letters if (isupper(text[i])) result += char(int(text[i]+s-65)%26 +65); // Encrypt Lowercase letters else result += char(int(text[i]+s-97)%26 +97); } // Return the resulting string return result;} // Driver program to test the above functionint main(){ string text=\"ATTACKATONCE\"; int s = 4; cout << \"Text : \" << text; cout << \"\\nShift: \" << s; cout << \"\\nCipher: \" << encrypt(text, s); return 0;}", "e": 28109, "s": 27285, "text": null }, { "code": "//A Java Program to illustrate Caesar Cipher Techniqueclass CaesarCipher{ // Encrypts text using a shift od s public static StringBuffer encrypt(String text, int s) { StringBuffer result= new StringBuffer(); for (int i=0; i<text.length(); i++) { if (Character.isUpperCase(text.charAt(i))) { char ch = (char)(((int)text.charAt(i) + s - 65) % 26 + 65); result.append(ch); } else { char ch = (char)(((int)text.charAt(i) + s - 97) % 26 + 97); result.append(ch); } } return result; } // Driver code public static void main(String[] args) { String text = \"ATTACKATONCE\"; int s = 4; System.out.println(\"Text : \" + text); System.out.println(\"Shift : \" + s); System.out.println(\"Cipher: \" + encrypt(text, s)); }}", "e": 29102, "s": 28109, "text": null }, { "code": "#A python program to illustrate Caesar Cipher Techniquedef encrypt(text,s): result = \"\" # traverse text for i in range(len(text)): char = text[i] # Encrypt uppercase characters if (char.isupper()): result += chr((ord(char) + s-65) % 26 + 65) # Encrypt lowercase characters else: result += chr((ord(char) + s - 97) % 26 + 97) return result #check the above functiontext = \"ATTACKATONCE\"s = 4print (\"Text : \" + text)print (\"Shift : \" + str(s))print (\"Cipher: \" + encrypt(text,s))", "e": 29654, "s": 29102, "text": null }, { "code": "// A C# Program to illustrate Caesar Cipher Techniqueusing System;using System.Text; public class CaesarCipher{ // Encrypts text using a shift od s public static StringBuilder encrypt(String text, int s) { StringBuilder result= new StringBuilder(); for (int i=0; i<text.Length; i++) { if (char.IsUpper(text[i])) { char ch = (char)(((int)text[i] + s - 65) % 26 + 65); result.Append(ch); } else { char ch = (char)(((int)text[i] + s - 97) % 26 + 97); result.Append(ch); } } return result; } // Driver code public static void Main(String[] args) { String text = \"ATTACKATONCE\"; int s = 4; Console.WriteLine(\"Text : \" + text); Console.WriteLine(\"Shift : \" + s); Console.WriteLine(\"Cipher: \" + encrypt(text, s)); }} /* This code contributed by PrinciRaj1992 */", "e": 30693, "s": 29654, "text": null }, { "code": "<?php// A PHP program to illustrate Caesar// Cipher Technique // This function receives text and shift// and returns the encrypted textfunction encrypt($text, $s){ $result = \"\"; // traverse text for ($i = 0; $i < strlen($text); $i++) { // apply transformation to each // character Encrypt Uppercase letters if (ctype_upper($text[$i])) $result = $result.chr((ord($text[$i]) + $s - 65) % 26 + 65); // Encrypt Lowercase letters else $result = $result.chr((ord($text[$i]) + $s - 97) % 26 + 97); } // Return the resulting string return $result;} // Driver Code$text = \"ATTACKATONCE\";$s = 4;echo \"Text : \" . $text;echo \"\\nShift: \" . $s;echo \"\\nCipher: \" . encrypt($text, $s); // This code is contributed by ita_c?>", "e": 31527, "s": 30693, "text": null }, { "code": "<script>//A Javascript Program to illustrate Caesar Cipher Technique // Encrypts text using a shift od s function encrypt(text, s) { let result=\"\" for (let i = 0; i < text.length; i++) { let char = text[i]; if (char.toUpperCase(text[i])) { let ch = String.fromCharCode((char.charCodeAt(0) + s-65) % 26 + 65); result += ch; } else { let ch = String.fromCharCode((char.charCodeAt(0) + s-97) % 26 + 97); result += ch; } } return result; } // Driver code let text = \"ATTACKATONCE\"; let s = 4; document.write(\"Text : \" + text + \"<br>\"); document.write(\"Shift : \" + s + \"<br>\"); document.write(\"Cipher: \" + encrypt(text, s) + \"<br>\"); // This code is contributed by avanitrachhadiya2155</script>", "e": 32440, "s": 31527, "text": null }, { "code": null, "e": 32450, "s": 32440, "text": "Output: " }, { "code": null, "e": 32500, "s": 32450, "text": "Text : ATTACKATONCE\nShift: 4\nCipher: EXXEGOEXSRGI" }, { "code": null, "e": 32765, "s": 32500, "text": "How to decrypt? We can either write another function decrypt similar to encrypt, that’ll apply the given shift in the opposite direction to decrypt the original text. However we can use the cyclic property of the cipher under modulo , hence we can simply observe " }, { "code": null, "e": 32793, "s": 32765, "text": "Cipher(n) = De-cipher(26-n)" }, { "code": null, "e": 32944, "s": 32793, "text": "Hence, we can use the same function to decrypt, instead we’ll modify the shift value such that shift = 26-shift (Refer this for a sample run in C++). " }, { "code": null, "e": 32986, "s": 32944, "text": "https://www.youtube.com/watch?v=S472gPqwF" }, { "code": null, "e": 32990, "s": 32986, "text": "-o " }, { "code": null, "e": 33263, "s": 32994, "text": "This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 33390, "s": 33265, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 33407, "s": 33392, "text": "SOURABH MANGAL" }, { "code": null, "e": 33413, "s": 33407, "text": "ukasp" }, { "code": null, "e": 33427, "s": 33413, "text": "princiraj1992" }, { "code": null, "e": 33448, "s": 33427, "text": "avanitrachhadiya2155" }, { "code": null, "e": 33462, "s": 33448, "text": "amartyaniel20" }, { "code": null, "e": 33475, "s": 33462, "text": "cryptography" }, { "code": null, "e": 33493, "s": 33475, "text": "Computer Networks" }, { "code": null, "e": 33501, "s": 33493, "text": "GATE CS" }, { "code": null, "e": 33509, "s": 33501, "text": "Strings" }, { "code": null, "e": 33517, "s": 33509, "text": "Strings" }, { "code": null, "e": 33530, "s": 33517, "text": "cryptography" }, { "code": null, "e": 33548, "s": 33530, "text": "Computer Networks" }, { "code": null, "e": 33646, "s": 33548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33680, "s": 33646, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 33706, "s": 33680, "text": "Types of Network Topology" }, { "code": null, "e": 33734, "s": 33706, "text": "TCP 3-Way Handshake Process" }, { "code": null, "e": 33772, "s": 33734, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 33801, "s": 33772, "text": "User Datagram Protocol (UDP)" }, { "code": null, "e": 33825, "s": 33801, "text": "ACID Properties in DBMS" }, { "code": null, "e": 33852, "s": 33825, "text": "Types of Operating Systems" }, { "code": null, "e": 33873, "s": 33852, "text": "Normal Forms in DBMS" }, { "code": null, "e": 33922, "s": 33873, "text": "Page Replacement Algorithms in Operating Systems" } ]
Seven Must-Know Statistical Distributions and Their Simulations for Data Science | by Zijing Zhu | Towards Data Science
A statistical distribution is a parameterized mathematical function that gives the probabilities of different outcomes for a random variable. There are discrete and continuous distributions depending on the random value it models. This article will introduce the seven most important statistical distributions, show their Python simulations with either the Numpy library embedded functions or with a random variable generator, discuss the relationships among different distributions and their applications in data science. Bernoulli distribution is a discrete distribution. The assumptions of Bernoulli distribution include: 1, only two outcomes; 2, only one trial. Bernoulli distribution describes a random variable that only contains two outcomes. For example, when tossing a coin one time, you can only get “Head” or “Tail.” We can also generalize it by defining the outcomes as “success” and “failure.” If I assume that when I toss a die, I only care if I get six, I can define the outcome of a die showing six as “success” and all other outcomes as “failure.” Even though tossing a die has six outcomes, in this experiment that I define, there are only two outcomes, and I can use Bernoulli distribution. The probability mass function (PMF) of a random variable x that follows the Bernoulli distribution is: p is the probability that this random variable x equals ‘success,’ which is defined based on different scenarios. Sometimes we have p = 1-p, like when tossing a fair coin. From the PMF, we can calculate the expected value and variance of random variable x depending on the numerical value of x. If x=1 when “success” and x=0 when “failure,” E (x) and Var (x) are: Simulating a Bernoulli trial is straightforward by defining a random variable that only generates two outcomes with a certain “success” probability p: import numpy as np#success probability is the same as failure probabilitynp.random.choice([‘success’,’failure’], p=(0.5, 0.5))#probabilities are differentnp.random.choice(['success','failure'], p=(0.9, 0.1)) Binomial distribution is also a discrete distribution, and it describes the random variable x as the number of success in n Bernoulli trials. You can think of the binomial distribution as the outcome distribution of n identical Bernoulli distributed random variables. The assumptions of the Binomial distribution are: 1, each trial only has two outcomes (like tossing a coin); 2, there are n identical trials in total (tossing the same coin for n times); 3, each trial is independent of other trials (getting “Head” at the first trial wouldn’t affect the chance of getting “Head” at the second trial); 4, p, and 1-p are the same for all trials (the chance of getting “Head” is the same across all trials); There are two parameters in the distribution, the success probability p and the number of trials n. The PMF is defined using the combination formula: The probability that we have x number of success out of n trials is like choosing x out of n when order doesn’t matter. Thinking about Binomial distribution as n identical Bernoulli distributions helps understand the calculation of its expected value and variance: If you are interested in getting these two equations above, you can watch these wonderful videos from Khan Academy. Python’s Numpy library has a built-in Binomial distribution function. To simulate it, define n and p, and set to simulate 1000 times: n = 100p = 0.5size = 1000binomial = np.random.binomial(n,p,size)plt.hist(binomial) We can get the histogram: When setting n equals to 1, we can simulate the Bernoulli distribution: n = 1p = 0.5size = 10000bernoulli = np.random.binomial(n,p,size)plt.hist(bernoulli) Geometric distribution is a discrete distribution that models the number of failures (x failures) before the first success in repeated, independent Bernoulli trials. For example, the random variable can be how many “Tails” would you get before you get your first “Head.” It can also model the number of trials to get the first success (x-1 failures), like how many times you have to toss until you get the first “Head.” The only difference between these two random variables is the number of failures. The Geometric distribution assumptions are the same as the Binomial distribution because they both derive from some identical independent Bernoulli trails. When the random variable x is the number of failures before the first success, the PMF is: the expected value and variance are: When the random variable x is the number of trials to get the first success, the PMF is: the expected value and variance are: We need to use the geometric series to derive the expected value and variance for Geometric distribution. There is a great tutorial at Khan Academy that explains the details. To simulate Geometric distribution, we can use the Bernoulli trials and count for the number of failures before the first success, and then plot the number of failures (Many thanks to Tiffany Sung who caught the typo in this code snippet): geometric = []failure = 0n=0p=0.5while n<10000: result = np.random.choice(['success','failure'],p=(p,1-p)) if result == 'failure': failure+=1 else: geometric.append(failure) failure = 0 n+=1plt.hist(geometric)plt.axvline(np.mean(geometric),color='red') Uniform distribution models a random variable whose outcomes are equally likely to happen. The outcomes can be discrete, like the outcomes getting form tossing a die, or continuous, like the waiting time for a bus to arrive. Thus Uniform distribution can be a discrete or continuous distribution depending on the random variable. The assumptions are: 1, there are n outcomes (discrete), or a range for the outcomes to be at (continuous); 2, All values in the outcome set or the range are equally likely to occur. The discrete uniform distribution is straightforward, and it is easy to calculate the expected values and variance. For a continuous Uniform distribution that is uniformly distributed at [a, b], the probability density function (PDF) is: Using integrals, the expected value and variance are: To simulate Uniform distribution, we can use the Numpy’s embedded function and specifying the range of the distribution. Based on a Uniform distribution at [0,1], we can generate the Uniform distribution at [a, b]: #generate a random variable follows U(0,1)np.random.uniform(0,1,size=10000)#use U(0,1) to generate U(a,b)def uniform(a,b): return a + (b-a) * np.random.uniform(0,1,size=10000) Normal (Gaussian) distribution is the most widely used continuous distribution because it represents the most universe situations. Many random variables are normally distributed because of the Central Limit Theory, or they are assumed to be normally distributed before fitting them into a statistical model. Normal distribution has some unique characteristics: 1, mean=mode=median=μ ; 2, the PDF is bell-shaped and symmetric at x=μ; 3, the values between [μ-σ, μ+σ] takes roughly 68% of the data, where σ is the standard deviation, and: the PDF for Normal distribution is: When μ=0 and σ=1, we have a Standard Normal distribution, where the PDF is simplified as: The expected value and variance are embedded in the PDF of Normal distribution. The expected value is the mean, which is μ, and the variance is the square of standard deviation, σ2. To simulate the Normal distribution, we can use the Numpy function: np.random.normal(mu, sigma, 1000) Or we can also use Central Limit Theory to simulate Normal distribution: def clm(N,n):#generate a sample from any random population N lis = np.random.random(size=N) means = []#take a random sub sample with size n from N for i in range(n): lis_index = np.random.randint(0,N,n) means.append(lis[lis_index].mean()) i+=1#plot means return plt.hist(means)clm(10000,1000) Poisson distribution is a discrete distribution that models the probability of a number of events occurring in a fixed interval of time or space. Poisson distribution can be used to present the number of customers arriving in a store in an hour, or the number of phone calls a company receives one day, etc. Poisson distribution is closely related to binomial distribution if you measure the number of event occurrences as the number of success. For example, when measuring how many cars will pass a particular street in an hour, the number of cars passing is a random variable that follows Poisson distribution. To understand the car passing event, you can break down one hour into 60 minutes, and see how many cars will pass in a minute, then generalize it into an hour. For a minute, maybe more than one cars pass the street, thus it is not a binary random variable. However, if we break down one minute into 60 seconds, it is likely that only one car passes or no car pass in a single second. We can keep breaking down a second to make a more confident claim. We can then consider car passing as a successful event and no car passing as a failure event, and model how many success events (how many cars passing) in 3600 trials (3600 seconds in an hour), which is a Binomial distribution with success probability p, and the number of trials equals to 3600. Connecting Poisson distribution with binomial distribution helps us understand the assumptions and PMF of Poisson distribution. The assumptions Poisson distribution are: 1, any successful event should not influence the outcome of other successful events (observing one car at the first second doesn’t affect the chance of observing another car the next second); 2, the probability of success p, is the same across all intervals (there is no difference between this hour with other hours to observe cars passing by); 3, the probability of success p in an interval goes to zero as the interval gets smaller (if we are discussing how many cars will pass in a millisecond, the probability is close to zero because the time is too short); The PMF of Poisson distribution can be derived from the PMF of binomial distribution: We know x is the number of success in n Bernoulli trials, and E(x)=np. If we define λ =E(x) =np as the average number of success in n Bernoulli trials, the success probability p can be estimated by λ/n. As n goes to infinity, the PMF becomes: After some calculation, we can get a new PMF, which is the PMF for Poisson distribution: The Poisson distribution gives the probability of observing a certain number of events in an interval, given the average number of events in the interval. The expected value and variance of a random variable that follows Poisson distribution are both λ: To simulate Poisson distribution, we can use the Numpy function: lam = 1poi = np.random.poisson(lam=lam,size=1000)plt.hist(poi)plt.axvline(x=lam,c='red') The Exponential distribution is a continuous distribution that is closely related to the Poisson distribution. It is the probability distribution of the time intervals between Poisson events. If the number of calls a company receives in an hour follows Poisson distribution, then the time interval between calls follows Exponential distribution. Since exponential distribution is closely related to Poisson distribution, its assumptions follow the Poisson distribution’s assumptions. We can derive the PDF of exponential distribution by first deriving its Cumulative Distribution Function (CDF) and then take the derivative of the CDF. We are using this trick because we can get the CDF using Poisson distribution. Suppose we are still observing how many cars are passing in the same street, and now we care about the random variable ω, which is defined as when we see one car passing, it takes at least ω minutes to observe another car passing. Let’s start from the beginning — how long it takes to observe the first car? Assume it takes ω minutes to observe the first car in ω minutes, there is zero car passing. We know that the number of cars passing in the street in a minute follows Poisson distribution: For ω minutes, the number of cars passing in the street follows: the probability that we observe zero cars in ω minutes is: From exponential distribution’s perspective, we now already know the probability of taking at least ω minutes to observe the first car, then the probability of taking less than ω minutes is: This is the CDF of the random variable ω, taking the derivative with respect to ω, we have the PDF: If we know in a minute, on average, we are likely to observe three cars (λ=3) passing by the street, then it is expected that every 1/3 minutes, we will observe one car passing by. Thus, the expected value and variance of exponential distribution are: To simulate the Exponential distribution, we can use the Numpy random function: lam = 2exp = np.random.exponential(lam, 10000) plt.hist(exp)plt.axvline(x=lam, c=’red’) Or we can use the CDF and Uniform distribution from (0,1) to simulate it. The following equations show the process: Following the code: rate = 1/20inverse_cdf=np.random.uniform(0,1,size=1000)interval = [-np.log(1-u)/rate for u in inverse_cdf]plt.hist(interval) As discussed partially above, these distributions are closely related to each other in different ways: 1, Bernoulli distribution is a special case of Binomial distribution when n equals one; 2, As n goes to infinity, and p goes to zero, np = λ, a finite number, binomial distribution approaches to Poisson distribution; 3, As n goes to infinity, and p are not indefinitely small, λ goes to infinity as well, binomial distribution approaches normal distribution; 4, If the total number of events in a time interval of length t follows the Poisson distribution with parameter λ, the times between random events follow an Exponential distribution with rate λ/t. 5, Geometric distribution is the only discrete distribution that has the memoryless property, and exponential distribution is the only continuous distribution with the memoryless property. The mathematical definition of memoryless property is: P( X > a + b | X> a ) = P ( X> b ) You can read more details about this property here. One of the implications you can think of is that if the lifetime of batteries has an Exponential distribution, then a used battery is as good as a new one, as long as it’s not dead. Understanding the assumptions, properties of different statistical distributions definitely helps data scientists with their daily tasks: 1, Monte Carlo simulations start with generating random variables from a Uniform distribution; 2, Binomial distribution sets the foundation of any binary classification model; 3, All regression models that use the least-squares cost function assume the residuals to follow a Normal distribution with mean equals to zero; 4, The transformed distributions from the Normal distribution, like the Student t distribution, Standard Normal distribution are the distributions used for conducting hypothesis testing, computing p values, and getting confidence interval; Log-normal distribution describes all samples of data when the data is right-skewed; 5, Poisson and Exponential distributions are greater for modeling events with a fixed time rate (λ). For example, we can use Poisson distribution to model how many customers will show up in a shop in a day, and use Exponential distribution to model how many time it takes between two consecutive customers to enter the shop. Statistical distributions are everywhere in daily life. Understanding statistical distributions play a very important role for data scientists to know the data more thoroughly, conduct better data analysis, choosing the more suitable model, etc. Help this article helps. Thank you for reading. Here is the list of all my blog posts. Check them out if you are interested!
[ { "code": null, "e": 695, "s": 172, "text": "A statistical distribution is a parameterized mathematical function that gives the probabilities of different outcomes for a random variable. There are discrete and continuous distributions depending on the random value it models. This article will introduce the seven most important statistical distributions, show their Python simulations with either the Numpy library embedded functions or with a random variable generator, discuss the relationships among different distributions and their applications in data science." }, { "code": null, "e": 797, "s": 695, "text": "Bernoulli distribution is a discrete distribution. The assumptions of Bernoulli distribution include:" }, { "code": null, "e": 819, "s": 797, "text": "1, only two outcomes;" }, { "code": null, "e": 838, "s": 819, "text": "2, only one trial." }, { "code": null, "e": 1382, "s": 838, "text": "Bernoulli distribution describes a random variable that only contains two outcomes. For example, when tossing a coin one time, you can only get “Head” or “Tail.” We can also generalize it by defining the outcomes as “success” and “failure.” If I assume that when I toss a die, I only care if I get six, I can define the outcome of a die showing six as “success” and all other outcomes as “failure.” Even though tossing a die has six outcomes, in this experiment that I define, there are only two outcomes, and I can use Bernoulli distribution." }, { "code": null, "e": 1485, "s": 1382, "text": "The probability mass function (PMF) of a random variable x that follows the Bernoulli distribution is:" }, { "code": null, "e": 1657, "s": 1485, "text": "p is the probability that this random variable x equals ‘success,’ which is defined based on different scenarios. Sometimes we have p = 1-p, like when tossing a fair coin." }, { "code": null, "e": 1849, "s": 1657, "text": "From the PMF, we can calculate the expected value and variance of random variable x depending on the numerical value of x. If x=1 when “success” and x=0 when “failure,” E (x) and Var (x) are:" }, { "code": null, "e": 2000, "s": 1849, "text": "Simulating a Bernoulli trial is straightforward by defining a random variable that only generates two outcomes with a certain “success” probability p:" }, { "code": null, "e": 2208, "s": 2000, "text": "import numpy as np#success probability is the same as failure probabilitynp.random.choice([‘success’,’failure’], p=(0.5, 0.5))#probabilities are differentnp.random.choice(['success','failure'], p=(0.9, 0.1))" }, { "code": null, "e": 2526, "s": 2208, "text": "Binomial distribution is also a discrete distribution, and it describes the random variable x as the number of success in n Bernoulli trials. You can think of the binomial distribution as the outcome distribution of n identical Bernoulli distributed random variables. The assumptions of the Binomial distribution are:" }, { "code": null, "e": 2585, "s": 2526, "text": "1, each trial only has two outcomes (like tossing a coin);" }, { "code": null, "e": 2663, "s": 2585, "text": "2, there are n identical trials in total (tossing the same coin for n times);" }, { "code": null, "e": 2810, "s": 2663, "text": "3, each trial is independent of other trials (getting “Head” at the first trial wouldn’t affect the chance of getting “Head” at the second trial);" }, { "code": null, "e": 2914, "s": 2810, "text": "4, p, and 1-p are the same for all trials (the chance of getting “Head” is the same across all trials);" }, { "code": null, "e": 3064, "s": 2914, "text": "There are two parameters in the distribution, the success probability p and the number of trials n. The PMF is defined using the combination formula:" }, { "code": null, "e": 3184, "s": 3064, "text": "The probability that we have x number of success out of n trials is like choosing x out of n when order doesn’t matter." }, { "code": null, "e": 3329, "s": 3184, "text": "Thinking about Binomial distribution as n identical Bernoulli distributions helps understand the calculation of its expected value and variance:" }, { "code": null, "e": 3445, "s": 3329, "text": "If you are interested in getting these two equations above, you can watch these wonderful videos from Khan Academy." }, { "code": null, "e": 3579, "s": 3445, "text": "Python’s Numpy library has a built-in Binomial distribution function. To simulate it, define n and p, and set to simulate 1000 times:" }, { "code": null, "e": 3662, "s": 3579, "text": "n = 100p = 0.5size = 1000binomial = np.random.binomial(n,p,size)plt.hist(binomial)" }, { "code": null, "e": 3688, "s": 3662, "text": "We can get the histogram:" }, { "code": null, "e": 3760, "s": 3688, "text": "When setting n equals to 1, we can simulate the Bernoulli distribution:" }, { "code": null, "e": 3844, "s": 3760, "text": "n = 1p = 0.5size = 10000bernoulli = np.random.binomial(n,p,size)plt.hist(bernoulli)" }, { "code": null, "e": 4502, "s": 3844, "text": "Geometric distribution is a discrete distribution that models the number of failures (x failures) before the first success in repeated, independent Bernoulli trials. For example, the random variable can be how many “Tails” would you get before you get your first “Head.” It can also model the number of trials to get the first success (x-1 failures), like how many times you have to toss until you get the first “Head.” The only difference between these two random variables is the number of failures. The Geometric distribution assumptions are the same as the Binomial distribution because they both derive from some identical independent Bernoulli trails." }, { "code": null, "e": 4593, "s": 4502, "text": "When the random variable x is the number of failures before the first success, the PMF is:" }, { "code": null, "e": 4630, "s": 4593, "text": "the expected value and variance are:" }, { "code": null, "e": 4719, "s": 4630, "text": "When the random variable x is the number of trials to get the first success, the PMF is:" }, { "code": null, "e": 4756, "s": 4719, "text": "the expected value and variance are:" }, { "code": null, "e": 4931, "s": 4756, "text": "We need to use the geometric series to derive the expected value and variance for Geometric distribution. There is a great tutorial at Khan Academy that explains the details." }, { "code": null, "e": 5171, "s": 4931, "text": "To simulate Geometric distribution, we can use the Bernoulli trials and count for the number of failures before the first success, and then plot the number of failures (Many thanks to Tiffany Sung who caught the typo in this code snippet):" }, { "code": null, "e": 5461, "s": 5171, "text": "geometric = []failure = 0n=0p=0.5while n<10000: result = np.random.choice(['success','failure'],p=(p,1-p)) if result == 'failure': failure+=1 else: geometric.append(failure) failure = 0 n+=1plt.hist(geometric)plt.axvline(np.mean(geometric),color='red')" }, { "code": null, "e": 5812, "s": 5461, "text": "Uniform distribution models a random variable whose outcomes are equally likely to happen. The outcomes can be discrete, like the outcomes getting form tossing a die, or continuous, like the waiting time for a bus to arrive. Thus Uniform distribution can be a discrete or continuous distribution depending on the random variable. The assumptions are:" }, { "code": null, "e": 5899, "s": 5812, "text": "1, there are n outcomes (discrete), or a range for the outcomes to be at (continuous);" }, { "code": null, "e": 5974, "s": 5899, "text": "2, All values in the outcome set or the range are equally likely to occur." }, { "code": null, "e": 6212, "s": 5974, "text": "The discrete uniform distribution is straightforward, and it is easy to calculate the expected values and variance. For a continuous Uniform distribution that is uniformly distributed at [a, b], the probability density function (PDF) is:" }, { "code": null, "e": 6266, "s": 6212, "text": "Using integrals, the expected value and variance are:" }, { "code": null, "e": 6481, "s": 6266, "text": "To simulate Uniform distribution, we can use the Numpy’s embedded function and specifying the range of the distribution. Based on a Uniform distribution at [0,1], we can generate the Uniform distribution at [a, b]:" }, { "code": null, "e": 6660, "s": 6481, "text": "#generate a random variable follows U(0,1)np.random.uniform(0,1,size=10000)#use U(0,1) to generate U(a,b)def uniform(a,b): return a + (b-a) * np.random.uniform(0,1,size=10000)" }, { "code": null, "e": 7021, "s": 6660, "text": "Normal (Gaussian) distribution is the most widely used continuous distribution because it represents the most universe situations. Many random variables are normally distributed because of the Central Limit Theory, or they are assumed to be normally distributed before fitting them into a statistical model. Normal distribution has some unique characteristics:" }, { "code": null, "e": 7045, "s": 7021, "text": "1, mean=mode=median=μ ;" }, { "code": null, "e": 7093, "s": 7045, "text": "2, the PDF is bell-shaped and symmetric at x=μ;" }, { "code": null, "e": 7197, "s": 7093, "text": "3, the values between [μ-σ, μ+σ] takes roughly 68% of the data, where σ is the standard deviation, and:" }, { "code": null, "e": 7233, "s": 7197, "text": "the PDF for Normal distribution is:" }, { "code": null, "e": 7323, "s": 7233, "text": "When μ=0 and σ=1, we have a Standard Normal distribution, where the PDF is simplified as:" }, { "code": null, "e": 7505, "s": 7323, "text": "The expected value and variance are embedded in the PDF of Normal distribution. The expected value is the mean, which is μ, and the variance is the square of standard deviation, σ2." }, { "code": null, "e": 7573, "s": 7505, "text": "To simulate the Normal distribution, we can use the Numpy function:" }, { "code": null, "e": 7607, "s": 7573, "text": "np.random.normal(mu, sigma, 1000)" }, { "code": null, "e": 7680, "s": 7607, "text": "Or we can also use Central Limit Theory to simulate Normal distribution:" }, { "code": null, "e": 8006, "s": 7680, "text": "def clm(N,n):#generate a sample from any random population N lis = np.random.random(size=N) means = []#take a random sub sample with size n from N for i in range(n): lis_index = np.random.randint(0,N,n) means.append(lis[lis_index].mean()) i+=1#plot means return plt.hist(means)clm(10000,1000)" }, { "code": null, "e": 9366, "s": 8006, "text": "Poisson distribution is a discrete distribution that models the probability of a number of events occurring in a fixed interval of time or space. Poisson distribution can be used to present the number of customers arriving in a store in an hour, or the number of phone calls a company receives one day, etc. Poisson distribution is closely related to binomial distribution if you measure the number of event occurrences as the number of success. For example, when measuring how many cars will pass a particular street in an hour, the number of cars passing is a random variable that follows Poisson distribution. To understand the car passing event, you can break down one hour into 60 minutes, and see how many cars will pass in a minute, then generalize it into an hour. For a minute, maybe more than one cars pass the street, thus it is not a binary random variable. However, if we break down one minute into 60 seconds, it is likely that only one car passes or no car pass in a single second. We can keep breaking down a second to make a more confident claim. We can then consider car passing as a successful event and no car passing as a failure event, and model how many success events (how many cars passing) in 3600 trials (3600 seconds in an hour), which is a Binomial distribution with success probability p, and the number of trials equals to 3600." }, { "code": null, "e": 9536, "s": 9366, "text": "Connecting Poisson distribution with binomial distribution helps us understand the assumptions and PMF of Poisson distribution. The assumptions Poisson distribution are:" }, { "code": null, "e": 9728, "s": 9536, "text": "1, any successful event should not influence the outcome of other successful events (observing one car at the first second doesn’t affect the chance of observing another car the next second);" }, { "code": null, "e": 9882, "s": 9728, "text": "2, the probability of success p, is the same across all intervals (there is no difference between this hour with other hours to observe cars passing by);" }, { "code": null, "e": 10100, "s": 9882, "text": "3, the probability of success p in an interval goes to zero as the interval gets smaller (if we are discussing how many cars will pass in a millisecond, the probability is close to zero because the time is too short);" }, { "code": null, "e": 10186, "s": 10100, "text": "The PMF of Poisson distribution can be derived from the PMF of binomial distribution:" }, { "code": null, "e": 10429, "s": 10186, "text": "We know x is the number of success in n Bernoulli trials, and E(x)=np. If we define λ =E(x) =np as the average number of success in n Bernoulli trials, the success probability p can be estimated by λ/n. As n goes to infinity, the PMF becomes:" }, { "code": null, "e": 10518, "s": 10429, "text": "After some calculation, we can get a new PMF, which is the PMF for Poisson distribution:" }, { "code": null, "e": 10772, "s": 10518, "text": "The Poisson distribution gives the probability of observing a certain number of events in an interval, given the average number of events in the interval. The expected value and variance of a random variable that follows Poisson distribution are both λ:" }, { "code": null, "e": 10837, "s": 10772, "text": "To simulate Poisson distribution, we can use the Numpy function:" }, { "code": null, "e": 10926, "s": 10837, "text": "lam = 1poi = np.random.poisson(lam=lam,size=1000)plt.hist(poi)plt.axvline(x=lam,c='red')" }, { "code": null, "e": 11410, "s": 10926, "text": "The Exponential distribution is a continuous distribution that is closely related to the Poisson distribution. It is the probability distribution of the time intervals between Poisson events. If the number of calls a company receives in an hour follows Poisson distribution, then the time interval between calls follows Exponential distribution. Since exponential distribution is closely related to Poisson distribution, its assumptions follow the Poisson distribution’s assumptions." }, { "code": null, "e": 12137, "s": 11410, "text": "We can derive the PDF of exponential distribution by first deriving its Cumulative Distribution Function (CDF) and then take the derivative of the CDF. We are using this trick because we can get the CDF using Poisson distribution. Suppose we are still observing how many cars are passing in the same street, and now we care about the random variable ω, which is defined as when we see one car passing, it takes at least ω minutes to observe another car passing. Let’s start from the beginning — how long it takes to observe the first car? Assume it takes ω minutes to observe the first car in ω minutes, there is zero car passing. We know that the number of cars passing in the street in a minute follows Poisson distribution:" }, { "code": null, "e": 12202, "s": 12137, "text": "For ω minutes, the number of cars passing in the street follows:" }, { "code": null, "e": 12261, "s": 12202, "text": "the probability that we observe zero cars in ω minutes is:" }, { "code": null, "e": 12452, "s": 12261, "text": "From exponential distribution’s perspective, we now already know the probability of taking at least ω minutes to observe the first car, then the probability of taking less than ω minutes is:" }, { "code": null, "e": 12552, "s": 12452, "text": "This is the CDF of the random variable ω, taking the derivative with respect to ω, we have the PDF:" }, { "code": null, "e": 12804, "s": 12552, "text": "If we know in a minute, on average, we are likely to observe three cars (λ=3) passing by the street, then it is expected that every 1/3 minutes, we will observe one car passing by. Thus, the expected value and variance of exponential distribution are:" }, { "code": null, "e": 12884, "s": 12804, "text": "To simulate the Exponential distribution, we can use the Numpy random function:" }, { "code": null, "e": 12972, "s": 12884, "text": "lam = 2exp = np.random.exponential(lam, 10000) plt.hist(exp)plt.axvline(x=lam, c=’red’)" }, { "code": null, "e": 13088, "s": 12972, "text": "Or we can use the CDF and Uniform distribution from (0,1) to simulate it. The following equations show the process:" }, { "code": null, "e": 13108, "s": 13088, "text": "Following the code:" }, { "code": null, "e": 13233, "s": 13108, "text": "rate = 1/20inverse_cdf=np.random.uniform(0,1,size=1000)interval = [-np.log(1-u)/rate for u in inverse_cdf]plt.hist(interval)" }, { "code": null, "e": 13336, "s": 13233, "text": "As discussed partially above, these distributions are closely related to each other in different ways:" }, { "code": null, "e": 13424, "s": 13336, "text": "1, Bernoulli distribution is a special case of Binomial distribution when n equals one;" }, { "code": null, "e": 13553, "s": 13424, "text": "2, As n goes to infinity, and p goes to zero, np = λ, a finite number, binomial distribution approaches to Poisson distribution;" }, { "code": null, "e": 13695, "s": 13553, "text": "3, As n goes to infinity, and p are not indefinitely small, λ goes to infinity as well, binomial distribution approaches normal distribution;" }, { "code": null, "e": 13892, "s": 13695, "text": "4, If the total number of events in a time interval of length t follows the Poisson distribution with parameter λ, the times between random events follow an Exponential distribution with rate λ/t." }, { "code": null, "e": 14136, "s": 13892, "text": "5, Geometric distribution is the only discrete distribution that has the memoryless property, and exponential distribution is the only continuous distribution with the memoryless property. The mathematical definition of memoryless property is:" }, { "code": null, "e": 14171, "s": 14136, "text": "P( X > a + b | X> a ) = P ( X> b )" }, { "code": null, "e": 14405, "s": 14171, "text": "You can read more details about this property here. One of the implications you can think of is that if the lifetime of batteries has an Exponential distribution, then a used battery is as good as a new one, as long as it’s not dead." }, { "code": null, "e": 14543, "s": 14405, "text": "Understanding the assumptions, properties of different statistical distributions definitely helps data scientists with their daily tasks:" }, { "code": null, "e": 14638, "s": 14543, "text": "1, Monte Carlo simulations start with generating random variables from a Uniform distribution;" }, { "code": null, "e": 14719, "s": 14638, "text": "2, Binomial distribution sets the foundation of any binary classification model;" }, { "code": null, "e": 14864, "s": 14719, "text": "3, All regression models that use the least-squares cost function assume the residuals to follow a Normal distribution with mean equals to zero;" }, { "code": null, "e": 15189, "s": 14864, "text": "4, The transformed distributions from the Normal distribution, like the Student t distribution, Standard Normal distribution are the distributions used for conducting hypothesis testing, computing p values, and getting confidence interval; Log-normal distribution describes all samples of data when the data is right-skewed;" }, { "code": null, "e": 15514, "s": 15189, "text": "5, Poisson and Exponential distributions are greater for modeling events with a fixed time rate (λ). For example, we can use Poisson distribution to model how many customers will show up in a shop in a day, and use Exponential distribution to model how many time it takes between two consecutive customers to enter the shop." }, { "code": null, "e": 15808, "s": 15514, "text": "Statistical distributions are everywhere in daily life. Understanding statistical distributions play a very important role for data scientists to know the data more thoroughly, conduct better data analysis, choosing the more suitable model, etc. Help this article helps. Thank you for reading." } ]
How can we create a MySQL temporary table by using PHP script?
As we know that PHP provides us the function named mysql_query() to create a MySQL table. Similarly, we can use mysql_query() function to create MySQL temporary table. To illustrate this, we are using the following example − In this example, we are creating a temporary table named ‘SalesSummary’ with the help of PHP script in the following example − <html> <head> <title>Creating MySQL Temporary Tables</title> </head> <body> <?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully<br />'; $sql = "CREATE TEMPORARY TABLE SalesSummary( ". "Product_Name VARCHAR(50) NOT NULL, ". "total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00, ". "avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00, ". "total_units_sold INT UNSIGNED NOT NULL DEFAULT 0, ".); "; mysql_select_db( 'TUTORIALS' ); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not create table: ' . mysql_error()); } echo "Table created successfully\n"; mysql_close($conn); ?> </body> </html>
[ { "code": null, "e": 1287, "s": 1062, "text": "As we know that PHP provides us the function named mysql_query() to create a MySQL table. Similarly, we can use mysql_query() function to create MySQL temporary table. To illustrate this, we are using the following example −" }, { "code": null, "e": 1414, "s": 1287, "text": "In this example, we are creating a temporary table named ‘SalesSummary’ with the help of PHP script in the following example −" }, { "code": null, "e": 2424, "s": 1414, "text": "<html>\n <head>\n <title>Creating MySQL Temporary Tables</title>\n </head>\n <body>\n <?php\n $dbhost = 'localhost:3036';\n $dbuser = 'root';\n $dbpass = 'rootpassword';\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n\n if(! $conn ) {\n die('Could not connect: ' . mysql_error());\n }\n echo 'Connected successfully<br />';\n $sql = \"CREATE TEMPORARY TABLE SalesSummary( \".\n \"Product_Name VARCHAR(50) NOT NULL, \".\n \"total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00, \".\n \"avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00, \".\n \"total_units_sold INT UNSIGNED NOT NULL DEFAULT 0, \".); \";\n \n mysql_select_db( 'TUTORIALS' );\n $retval = mysql_query( $sql, $conn );\n\n if(! $retval ) {\n die('Could not create table: ' . mysql_error());\n }\n echo \"Table created successfully\\n\";\n mysql_close($conn);\n ?>\n </body>\n</html>" } ]
Convert varchar to date in MySQL?
You can use date_format() to convert varchar to date. The syntax is as follows − SELECT DATE_FORMAT(STR_TO_DATE(yourColumnName, 'yourFormatSpecifier'), 'yourDateFormatSpecifier') as anyVariableName from yourTableName; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table VarcharToDate -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Created_Time varchar(100), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (1.10 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into VarcharToDate(Created_Time) values('12/1/2016'); Query OK, 1 row affected (0.14 sec) mysql> insert into VarcharToDate(Created_Time) values('14/3/2017'); Query OK, 1 row affected (0.18 sec) mysql> insert into VarcharToDate(Created_Time) values('15/3/2018'); Query OK, 1 row affected (0.21 sec) mysql> insert into VarcharToDate(Created_Time) values('19/5/2011'); Query OK, 1 row affected (0.18 sec) mysql> insert into VarcharToDate(Created_Time) values('19/8/2019'); Query OK, 1 row affected (0.15 sec) mysql> insert into VarcharToDate(Created_Time) values('21/11/2020'); Query OK, 1 row affected (0.23 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from VarcharToDate; +----+--------------+ | Id | Created_Time | +----+--------------+ | 1 | 12/1/2016 | | 2 | 14/3/2017 | | 3 | 15/3/2018 | | 4 | 19/5/2011 | | 5 | 19/8/2019 | | 6 | 21/11/2020 | +----+--------------+ 6 rows in set (0.00 sec) Here is the query to convert varchar to date. First, you need to use str_to_date() function to convert into date. After that use date_format() to give the actual date − mysql> select date_format(str_to_date(Created_Time, '%d/%m/%Y'), '%Y-%m-%d') as Date from VarcharToDate; The following is the output − +------------+ | Date | +------------+ | 2016-01-12 | | 2017-03-14 | | 2018-03-15 | | 2011-05-19 | | 2019-08-19 | | 2020-11-21 | +------------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1143, "s": 1062, "text": "You can use date_format() to convert varchar to date. The syntax is as follows −" }, { "code": null, "e": 1280, "s": 1143, "text": "SELECT DATE_FORMAT(STR_TO_DATE(yourColumnName, 'yourFormatSpecifier'), 'yourDateFormatSpecifier') as anyVariableName from yourTableName;" }, { "code": null, "e": 1379, "s": 1280, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1560, "s": 1379, "text": "mysql> create table VarcharToDate\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> Created_Time varchar(100),\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (1.10 sec)" }, { "code": null, "e": 1641, "s": 1560, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2271, "s": 1641, "text": "mysql> insert into VarcharToDate(Created_Time) values('12/1/2016');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into VarcharToDate(Created_Time) values('14/3/2017');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into VarcharToDate(Created_Time) values('15/3/2018');\nQuery OK, 1 row affected (0.21 sec)\n\nmysql> insert into VarcharToDate(Created_Time) values('19/5/2011');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into\nVarcharToDate(Created_Time) values('19/8/2019');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into VarcharToDate(Created_Time) values('21/11/2020');\nQuery OK, 1 row affected (0.23 sec)" }, { "code": null, "e": 2356, "s": 2271, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2636, "s": 2356, "text": "mysql> select *from VarcharToDate;\n+----+--------------+\n| Id | Created_Time |\n+----+--------------+\n| 1 | 12/1/2016 |\n| 2 | 14/3/2017 |\n| 3 | 15/3/2018 |\n| 4 | 19/5/2011 |\n| 5 | 19/8/2019 |\n| 6 | 21/11/2020 |\n+----+--------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2805, "s": 2636, "text": "Here is the query to convert varchar to date. First, you need to use str_to_date() function to convert into date. After that use date_format() to give the actual date −" }, { "code": null, "e": 2910, "s": 2805, "text": "mysql> select date_format(str_to_date(Created_Time, '%d/%m/%Y'), '%Y-%m-%d') as Date from VarcharToDate;" }, { "code": null, "e": 2940, "s": 2910, "text": "The following is the output −" }, { "code": null, "e": 3115, "s": 2940, "text": "+------------+\n| Date |\n+------------+\n| 2016-01-12 |\n| 2017-03-14 |\n| 2018-03-15 |\n| 2011-05-19 |\n| 2019-08-19 |\n| 2020-11-21 |\n+------------+\n6 rows in set (0.00 sec)" } ]
OpenCV - Scaling
You can perform scaling on an image using the resize() method of the imgproc class. Following is the syntax of this method. resize(Mat src, Mat dst, Size dsize, double fx, double fy, int interpolation) This method accepts the following parameters − src − A Mat object representing the source (input image) for this operation. src − A Mat object representing the source (input image) for this operation. dst − A Mat object representing the destination (output image) for this operation. dst − A Mat object representing the destination (output image) for this operation. dsize − A Size object representing the size of the output image. dsize − A Size object representing the size of the output image. fx − A variable of the type double representing the scale factor along the horizontal axis. fx − A variable of the type double representing the scale factor along the horizontal axis. fy − A variable of the type double representing the scale factor along the vertical axis. fy − A variable of the type double representing the scale factor along the vertical axis. Interpolation − An integer variable representing interpolation method. Interpolation − An integer variable representing interpolation method. The following program demonstrates how to apply scale transformation to an image. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Size; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class Scaling { public static void main(String args[]) { // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Reading the Image from the file and storing it in to a Matrix object String file ="E:/OpenCV/chap24/transform_input.jpg"; Mat src = Imgcodecs.imread(file); // Creating an empty matrix to store the result Mat dst = new Mat(); // Creating the Size object Size size = new Size(src.rows()*2, src.rows()*2); // Scaling the Image Imgproc.resize(src, dst, size, 0, 0, Imgproc.INTER_AREA); // Writing the image Imgcodecs.imwrite("E:/OpenCV/chap24/scale_output.jpg", dst); System.out.println("Image Processed"); } } Assume that following is the input image transform_input.jpg specified in the above program (size − Width:300px and height:300px). On executing the program, you will get the following output − Image Processed If you open the specified path, you can observe the output image as follows (size − Width:600px and height:600px) − 70 Lectures 9 hours Abhilash Nelson 41 Lectures 4 hours Abhilash Nelson 20 Lectures 2 hours Spotle Learn 12 Lectures 46 mins Srikanth Guskra 19 Lectures 2 hours Haithem Gasmi 67 Lectures 6.5 hours Gianluca Mottola Print Add Notes Bookmark this page
[ { "code": null, "e": 3128, "s": 3004, "text": "You can perform scaling on an image using the resize() method of the imgproc class. Following is the syntax of this method." }, { "code": null, "e": 3207, "s": 3128, "text": "resize(Mat src, Mat dst, Size dsize, double fx, double fy, int interpolation)\n" }, { "code": null, "e": 3254, "s": 3207, "text": "This method accepts the following parameters −" }, { "code": null, "e": 3331, "s": 3254, "text": "src − A Mat object representing the source (input image) for this operation." }, { "code": null, "e": 3408, "s": 3331, "text": "src − A Mat object representing the source (input image) for this operation." }, { "code": null, "e": 3491, "s": 3408, "text": "dst − A Mat object representing the destination (output image) for this operation." }, { "code": null, "e": 3574, "s": 3491, "text": "dst − A Mat object representing the destination (output image) for this operation." }, { "code": null, "e": 3639, "s": 3574, "text": "dsize − A Size object representing the size of the output image." }, { "code": null, "e": 3704, "s": 3639, "text": "dsize − A Size object representing the size of the output image." }, { "code": null, "e": 3796, "s": 3704, "text": "fx − A variable of the type double representing the scale factor along the horizontal axis." }, { "code": null, "e": 3888, "s": 3796, "text": "fx − A variable of the type double representing the scale factor along the horizontal axis." }, { "code": null, "e": 3978, "s": 3888, "text": "fy − A variable of the type double representing the scale factor along the vertical axis." }, { "code": null, "e": 4068, "s": 3978, "text": "fy − A variable of the type double representing the scale factor along the vertical axis." }, { "code": null, "e": 4139, "s": 4068, "text": "Interpolation − An integer variable representing interpolation method." }, { "code": null, "e": 4210, "s": 4139, "text": "Interpolation − An integer variable representing interpolation method." }, { "code": null, "e": 4292, "s": 4210, "text": "The following program demonstrates how to apply scale transformation to an image." }, { "code": null, "e": 5207, "s": 4292, "text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.Size;\n\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class Scaling {\n public static void main(String args[]) {\n // Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n\n // Reading the Image from the file and storing it in to a Matrix object\n String file =\"E:/OpenCV/chap24/transform_input.jpg\";\n Mat src = Imgcodecs.imread(file);\n\n // Creating an empty matrix to store the result\n Mat dst = new Mat();\n\n // Creating the Size object\n Size size = new Size(src.rows()*2, src.rows()*2);\n\n // Scaling the Image\n Imgproc.resize(src, dst, size, 0, 0, Imgproc.INTER_AREA);\n\n // Writing the image\n Imgcodecs.imwrite(\"E:/OpenCV/chap24/scale_output.jpg\", dst);\n\n System.out.println(\"Image Processed\");\n }\n}" }, { "code": null, "e": 5338, "s": 5207, "text": "Assume that following is the input image transform_input.jpg specified in the above program (size − Width:300px and height:300px)." }, { "code": null, "e": 5400, "s": 5338, "text": "On executing the program, you will get the following output −" }, { "code": null, "e": 5417, "s": 5400, "text": "Image Processed\n" }, { "code": null, "e": 5533, "s": 5417, "text": "If you open the specified path, you can observe the output image as follows (size − Width:600px and height:600px) −" }, { "code": null, "e": 5566, "s": 5533, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 5583, "s": 5566, "text": " Abhilash Nelson" }, { "code": null, "e": 5616, "s": 5583, "text": "\n 41 Lectures \n 4 hours \n" }, { "code": null, "e": 5633, "s": 5616, "text": " Abhilash Nelson" }, { "code": null, "e": 5666, "s": 5633, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 5680, "s": 5666, "text": " Spotle Learn" }, { "code": null, "e": 5712, "s": 5680, "text": "\n 12 Lectures \n 46 mins\n" }, { "code": null, "e": 5729, "s": 5712, "text": " Srikanth Guskra" }, { "code": null, "e": 5762, "s": 5729, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 5777, "s": 5762, "text": " Haithem Gasmi" }, { "code": null, "e": 5812, "s": 5777, "text": "\n 67 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5830, "s": 5812, "text": " Gianluca Mottola" }, { "code": null, "e": 5837, "s": 5830, "text": " Print" }, { "code": null, "e": 5848, "s": 5837, "text": " Add Notes" } ]
Online Election in C++
Suppose in an election, the i-th vote was cast for persons[i] at time times[i]. Now, we have to implement the following query function: TopVotedCandidate.q(int t) this will find the number of the person that was leading the election at time t. Votes cast at time t will count towards our query. If there is a tie, the most recent vote (among tied candidates) wins. So if we initialize this with TopVotedCandidate([0,1,1,0,0,1,0], [0,5,10,15,20,25,30]), then call q() like: q(3), q(12), q(25), q(15), q(24), q(8), then the result will be [0, 1, 1, 0, 0, 1] for each call of q(). This is because at time 3, the votes are [0], and 0 is leading. At time 12, the votes are [0,1,1], and here 1 is leading. At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.). This continues for 3 more queries at time 15, 24, and finally 8. To solve this, we will follow these steps − Create two maps m and count Create two maps m and count In the initializer, do the following tasks In the initializer, do the following tasks lead := -1 lead := -1 for i in range 0 to size of times arrayx := times[i]increase the value of count[persons[i]] by 1if count[lead] <= count[persons[i]], then lead := persons[i] and m[x] := lead otherwise m[x] := lead for i in range 0 to size of times array x := times[i] x := times[i] increase the value of count[persons[i]] by 1 increase the value of count[persons[i]] by 1 if count[lead] <= count[persons[i]], then lead := persons[i] and m[x] := lead otherwise m[x] := lead if count[lead] <= count[persons[i]], then lead := persons[i] and m[x] := lead otherwise m[x] := lead the q() method will be likedecrease the upper bound of t in m, and return the corresponding value the q() method will be like decrease the upper bound of t in m, and return the corresponding value decrease the upper bound of t in m, and return the corresponding value Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class TopVotedCandidate { public: map <int, int> m; map <int, int> count; TopVotedCandidate(vector<int>& persons, vector<int>& times) { int lead = -1; for(int i = 0; i < times.size(); i++){ int x = times[i]; count[persons[i]]++; if(count[lead] <= count[persons[i]]){ lead = persons[i]; m[x] = lead; }else{ m[x] = lead; } } } int q(int t) { return ((--m.upper_bound(t)) -> second); } }; main(){ vector<int> v1 = {0,1,1,0,0,1,0}, v2 = {0,5,10,15,20,25,30}; TopVotedCandidate ob(v1, v2); cout << (ob.q(3)) << endl; cout << (ob.q(12)) << endl; cout << (ob.q(25)) << endl; cout << (ob.q(15)) << endl; cout << (ob.q(24)) << endl; cout << (ob.q(8)) << endl; } Initialize the class using [0,1,1,0,0,1,0] and [0,5,10,15,20,25,30]. Call q() method like below: q(3) q(12) q(25) q(15) q(24) q(8) 0 1 1 0 0 1
[ { "code": null, "e": 1427, "s": 1062, "text": "Suppose in an election, the i-th vote was cast for persons[i] at time times[i]. Now, we have to implement the following query function: TopVotedCandidate.q(int t) this will find the number of the person that was leading the election at time t. Votes cast at time t will count towards our query. If there is a tie, the most recent vote (among tied candidates) wins." }, { "code": null, "e": 1924, "s": 1427, "text": "So if we initialize this with TopVotedCandidate([0,1,1,0,0,1,0], [0,5,10,15,20,25,30]), then call q() like: q(3), q(12), q(25), q(15), q(24), q(8), then the result will be [0, 1, 1, 0, 0, 1] for each call of q(). This is because at time 3, the votes are [0], and 0 is leading. At time 12, the votes are [0,1,1], and here 1 is leading. At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.). This continues for 3 more queries at time 15, 24, and finally 8." }, { "code": null, "e": 1968, "s": 1924, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1996, "s": 1968, "text": "Create two maps m and count" }, { "code": null, "e": 2024, "s": 1996, "text": "Create two maps m and count" }, { "code": null, "e": 2067, "s": 2024, "text": "In the initializer, do the following tasks" }, { "code": null, "e": 2110, "s": 2067, "text": "In the initializer, do the following tasks" }, { "code": null, "e": 2121, "s": 2110, "text": "lead := -1" }, { "code": null, "e": 2132, "s": 2121, "text": "lead := -1" }, { "code": null, "e": 2329, "s": 2132, "text": "for i in range 0 to size of times arrayx := times[i]increase the value of count[persons[i]] by 1if count[lead] <= count[persons[i]], then lead := persons[i] and m[x] := lead otherwise m[x] := lead" }, { "code": null, "e": 2369, "s": 2329, "text": "for i in range 0 to size of times array" }, { "code": null, "e": 2383, "s": 2369, "text": "x := times[i]" }, { "code": null, "e": 2397, "s": 2383, "text": "x := times[i]" }, { "code": null, "e": 2442, "s": 2397, "text": "increase the value of count[persons[i]] by 1" }, { "code": null, "e": 2487, "s": 2442, "text": "increase the value of count[persons[i]] by 1" }, { "code": null, "e": 2588, "s": 2487, "text": "if count[lead] <= count[persons[i]], then lead := persons[i] and m[x] := lead otherwise m[x] := lead" }, { "code": null, "e": 2689, "s": 2588, "text": "if count[lead] <= count[persons[i]], then lead := persons[i] and m[x] := lead otherwise m[x] := lead" }, { "code": null, "e": 2787, "s": 2689, "text": "the q() method will be likedecrease the upper bound of t in m, and return the corresponding value" }, { "code": null, "e": 2815, "s": 2787, "text": "the q() method will be like" }, { "code": null, "e": 2886, "s": 2815, "text": "decrease the upper bound of t in m, and return the corresponding value" }, { "code": null, "e": 2957, "s": 2886, "text": "decrease the upper bound of t in m, and return the corresponding value" }, { "code": null, "e": 3027, "s": 2957, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3038, "s": 3027, "text": " Live Demo" }, { "code": null, "e": 3887, "s": 3038, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass TopVotedCandidate {\n public:\n map <int, int> m;\n map <int, int> count;\n TopVotedCandidate(vector<int>& persons, vector<int>& times) {\n int lead = -1;\n for(int i = 0; i < times.size(); i++){\n int x = times[i];\n count[persons[i]]++;\n if(count[lead] <= count[persons[i]]){\n lead = persons[i];\n m[x] = lead;\n }else{\n m[x] = lead;\n }\n }\n }\n int q(int t) {\n return ((--m.upper_bound(t)) -> second);\n }\n};\nmain(){\n vector<int> v1 = {0,1,1,0,0,1,0}, v2 = {0,5,10,15,20,25,30};\n TopVotedCandidate ob(v1, v2);\n cout << (ob.q(3)) << endl;\n cout << (ob.q(12)) << endl;\n cout << (ob.q(25)) << endl;\n cout << (ob.q(15)) << endl;\n cout << (ob.q(24)) << endl;\n cout << (ob.q(8)) << endl;\n}" }, { "code": null, "e": 4018, "s": 3887, "text": "Initialize the class using [0,1,1,0,0,1,0] and [0,5,10,15,20,25,30]. Call q()\nmethod like below:\nq(3)\nq(12)\nq(25)\nq(15)\nq(24)\nq(8)" }, { "code": null, "e": 4030, "s": 4018, "text": "0\n1\n1\n0\n0\n1" } ]
Python Environment Management with Conda (Python 2 + 3, Using Multiple Versions of Python) | by Michael Galarnyk | Towards Data Science
Coming across an ImportError similar to the one in the image below can be annoying. Luckily, Anaconda makes it easy to install packages with the package manager functionality of conda. In case you need a refresher, a package manager is a tool which automates the process of installing, updating, and removing packages. While Conda is a package and environment manager, let’s first review the package manager functionality of conda and then focus on the environment manager functionality. Open a command prompt/anaconda prompt (windows) or a terminal (mac/linux) and run the command below. You can be substitute numpy for whatever package you want to install. conda install numpy Run the command below to uninstall a package. You can be substitute numpy for whatever package you want to uninstall. conda uninstall numpy Run the command below to update a package. You can be substitute scikit-learn for whatever package you want to update. conda update scikit-learn Pip is a Python package manager which stands for “Pip Installs Packages” that is usually coupled with virtualenv (a tool for creating isolated environments). Most of the time (with some exceptions) there isn’t much of a difference between installing packages through conda or through pip. This is because pip packages are also installable into Conda environments. conda install numpypip install numpy This isn’t a discussion on conda vs pip as Jake VanderPlas covered it pretty extensively, but why you can mostly install packages through either pip or conda. Say you have multiple projects and they all rely on a library (Pandas, Numpy etc). If you upgrade one package it could break your other projects relying on old versions of the package as the old project’s syntax could become deprecated or obsolete. What should you do? Set up a virtual environment. It allows you to separate out packages, dependencies and versions you are going to use from project to project. A common use of virtual environments for python users is having separate Python 2 and 3 environments. For example, a couple of my classmates at UC San Diego recently started a machine learning class where one professor sets assignments in Python 3. However, another class has a professor who sets assignments in Python 2. Consequently, they have to frequently switch between python 2 and 3 in their different class projects. With that, let’s get into conda environment commands. I recommend you open the video in a separate tab to watch the commands in action. Create a New Environment The command below creates a conda environment named subscribe in python version 3.6. You can be substitute subscribe for whatever you want to name your environment. conda create --name subscribe python=3.6 Keep in mind that you will need to install additional packages inside that environment once you activate (enter) that environment. The packages you have in your root environment are not necessarily the ones you will have in your new environment unless you install them. You can also create an environment with multiple packages in it. This also gives you the option to install additional packages later if you need them. conda create --name chooseAnotherName python=3.6 numpy pandas scipy Enter an Environment If the name of your environment is not subscribe, you will need to substitute subscribe for the name of your environment. Windows: activate subscribe Mac: source activate subscribe Leave an Environment If the name of your environment is not subscribe, you will need to substitute subscribe for the name of your environment. Windows: deactivate subscribe Mac: source deactivate subscribe List your Environments This command shows you all the This is a really helpful command to see what environments you have, but also to see what conda environment you are in. conda env list Remove an Environment If the name of your environment you want to remove is not subscribe, you will need to substitute subscribe for the name of your environment you want to remove. conda env remove --name subscribe If you have questions on this part, please refer to the documentation, leave a comment or refer to the video above. While this section of the post was largely taken and improved from stackoverflow, I feel like it is important to go over how and go over some technical issues people run into. The main idea is to have multiple ipython kernels. The package nb_conda_kernels will automatically detect different conda environments with notebook kernels and automatically register them. Make sure you have anaconda 4.1.0 or higher. Open a new terminal and check your conda version by typing Make sure you have anaconda 4.1.0 or higher. Open a new terminal and check your conda version by typing if you are below anaconda 4.1.0, type conda update conda 2. Next we check to see if we have the library nb_conda_kernels by typing 3. If you don’t see nb_conda_kernels type 4. If you are using Python 2 and want a separate Python 3 environment please type the following If you are using Python 3 and want a separate Python 2 environment, you could type the following. 5. Close your terminal and open up a new terminal. type jupyter notebook 6. Click new and you will see your virtual environment listed. Please let me know if you have any questions either here or in the youtube video comments!
[ { "code": null, "e": 255, "s": 171, "text": "Coming across an ImportError similar to the one in the image below can be annoying." }, { "code": null, "e": 659, "s": 255, "text": "Luckily, Anaconda makes it easy to install packages with the package manager functionality of conda. In case you need a refresher, a package manager is a tool which automates the process of installing, updating, and removing packages. While Conda is a package and environment manager, let’s first review the package manager functionality of conda and then focus on the environment manager functionality." }, { "code": null, "e": 830, "s": 659, "text": "Open a command prompt/anaconda prompt (windows) or a terminal (mac/linux) and run the command below. You can be substitute numpy for whatever package you want to install." }, { "code": null, "e": 850, "s": 830, "text": "conda install numpy" }, { "code": null, "e": 968, "s": 850, "text": "Run the command below to uninstall a package. You can be substitute numpy for whatever package you want to uninstall." }, { "code": null, "e": 990, "s": 968, "text": "conda uninstall numpy" }, { "code": null, "e": 1109, "s": 990, "text": "Run the command below to update a package. You can be substitute scikit-learn for whatever package you want to update." }, { "code": null, "e": 1135, "s": 1109, "text": "conda update scikit-learn" }, { "code": null, "e": 1293, "s": 1135, "text": "Pip is a Python package manager which stands for “Pip Installs Packages” that is usually coupled with virtualenv (a tool for creating isolated environments)." }, { "code": null, "e": 1499, "s": 1293, "text": "Most of the time (with some exceptions) there isn’t much of a difference between installing packages through conda or through pip. This is because pip packages are also installable into Conda environments." }, { "code": null, "e": 1536, "s": 1499, "text": "conda install numpypip install numpy" }, { "code": null, "e": 1695, "s": 1536, "text": "This isn’t a discussion on conda vs pip as Jake VanderPlas covered it pretty extensively, but why you can mostly install packages through either pip or conda." }, { "code": null, "e": 2106, "s": 1695, "text": "Say you have multiple projects and they all rely on a library (Pandas, Numpy etc). If you upgrade one package it could break your other projects relying on old versions of the package as the old project’s syntax could become deprecated or obsolete. What should you do? Set up a virtual environment. It allows you to separate out packages, dependencies and versions you are going to use from project to project." }, { "code": null, "e": 2667, "s": 2106, "text": "A common use of virtual environments for python users is having separate Python 2 and 3 environments. For example, a couple of my classmates at UC San Diego recently started a machine learning class where one professor sets assignments in Python 3. However, another class has a professor who sets assignments in Python 2. Consequently, they have to frequently switch between python 2 and 3 in their different class projects. With that, let’s get into conda environment commands. I recommend you open the video in a separate tab to watch the commands in action." }, { "code": null, "e": 2692, "s": 2667, "text": "Create a New Environment" }, { "code": null, "e": 2857, "s": 2692, "text": "The command below creates a conda environment named subscribe in python version 3.6. You can be substitute subscribe for whatever you want to name your environment." }, { "code": null, "e": 2898, "s": 2857, "text": "conda create --name subscribe python=3.6" }, { "code": null, "e": 3168, "s": 2898, "text": "Keep in mind that you will need to install additional packages inside that environment once you activate (enter) that environment. The packages you have in your root environment are not necessarily the ones you will have in your new environment unless you install them." }, { "code": null, "e": 3319, "s": 3168, "text": "You can also create an environment with multiple packages in it. This also gives you the option to install additional packages later if you need them." }, { "code": null, "e": 3387, "s": 3319, "text": "conda create --name chooseAnotherName python=3.6 numpy pandas scipy" }, { "code": null, "e": 3408, "s": 3387, "text": "Enter an Environment" }, { "code": null, "e": 3530, "s": 3408, "text": "If the name of your environment is not subscribe, you will need to substitute subscribe for the name of your environment." }, { "code": null, "e": 3539, "s": 3530, "text": "Windows:" }, { "code": null, "e": 3558, "s": 3539, "text": "activate subscribe" }, { "code": null, "e": 3563, "s": 3558, "text": "Mac:" }, { "code": null, "e": 3589, "s": 3563, "text": "source activate subscribe" }, { "code": null, "e": 3610, "s": 3589, "text": "Leave an Environment" }, { "code": null, "e": 3732, "s": 3610, "text": "If the name of your environment is not subscribe, you will need to substitute subscribe for the name of your environment." }, { "code": null, "e": 3741, "s": 3732, "text": "Windows:" }, { "code": null, "e": 3762, "s": 3741, "text": "deactivate subscribe" }, { "code": null, "e": 3767, "s": 3762, "text": "Mac:" }, { "code": null, "e": 3795, "s": 3767, "text": "source deactivate subscribe" }, { "code": null, "e": 3818, "s": 3795, "text": "List your Environments" }, { "code": null, "e": 3968, "s": 3818, "text": "This command shows you all the This is a really helpful command to see what environments you have, but also to see what conda environment you are in." }, { "code": null, "e": 3983, "s": 3968, "text": "conda env list" }, { "code": null, "e": 4005, "s": 3983, "text": "Remove an Environment" }, { "code": null, "e": 4165, "s": 4005, "text": "If the name of your environment you want to remove is not subscribe, you will need to substitute subscribe for the name of your environment you want to remove." }, { "code": null, "e": 4199, "s": 4165, "text": "conda env remove --name subscribe" }, { "code": null, "e": 4315, "s": 4199, "text": "If you have questions on this part, please refer to the documentation, leave a comment or refer to the video above." }, { "code": null, "e": 4681, "s": 4315, "text": "While this section of the post was largely taken and improved from stackoverflow, I feel like it is important to go over how and go over some technical issues people run into. The main idea is to have multiple ipython kernels. The package nb_conda_kernels will automatically detect different conda environments with notebook kernels and automatically register them." }, { "code": null, "e": 4785, "s": 4681, "text": "Make sure you have anaconda 4.1.0 or higher. Open a new terminal and check your conda version by typing" }, { "code": null, "e": 4889, "s": 4785, "text": "Make sure you have anaconda 4.1.0 or higher. Open a new terminal and check your conda version by typing" }, { "code": null, "e": 4946, "s": 4889, "text": "if you are below anaconda 4.1.0, type conda update conda" }, { "code": null, "e": 5020, "s": 4946, "text": "2. Next we check to see if we have the library nb_conda_kernels by typing" }, { "code": null, "e": 5062, "s": 5020, "text": "3. If you don’t see nb_conda_kernels type" }, { "code": null, "e": 5158, "s": 5062, "text": "4. If you are using Python 2 and want a separate Python 3 environment please type the following" }, { "code": null, "e": 5256, "s": 5158, "text": "If you are using Python 3 and want a separate Python 2 environment, you could type the following." }, { "code": null, "e": 5329, "s": 5256, "text": "5. Close your terminal and open up a new terminal. type jupyter notebook" }, { "code": null, "e": 5392, "s": 5329, "text": "6. Click new and you will see your virtual environment listed." } ]
Compute nCr % p | Set 3 (Using Fermat Little Theorem) - GeeksforGeeks
25 Jun, 2021 Given three numbers n, r and p, compute the value of nCr mod p. Here p is a prime number greater than n. Here nCr is Binomial Coefficient.Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6. Input: n = 6, r = 2, p = 13 Output: 2 We have discussed the following methods in previous posts. Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution) Compute nCr % p | Set 2 (Lucas Theorem)In this post, Fermat Theorem-based solution is discussed.Background: Fermat’s little theorem and modular inverse Fermat’s little theorem states that if p is a prime number, then for any integer a, the number ap – a is an integer multiple of p. In the notation of modular arithmetic, this is expressed as: ap = a (mod p) For example, if a = 2 and p = 7, 27 = 128, and 128 – 2 = 7 × 18 is an integer multiple of 7.If a is not divisible by p, Fermat’s little theorem is equivalent to the statement a p – 1 – 1 is an integer multiple of p, i.e ap-1 = 1 (mod p)If we multiply both sides by a-1, we get. ap-2 = a-1 (mod p)So we can find modular inverse as p-2. Computation: We know the formula for nCr nCr = fact(n) / (fact(r) x fact(n-r)) Here fact() means factorial. nCr % p = (fac[n]* modIverse(fac[r]) % p * modIverse(fac[n-r]) % p) % p; Here modIverse() means modular inverse under modulo p. Following is the implementation of the above algorithm. In the following implementation, an array fac[] is used to store all the computed factorial values. C++ Java Python3 C# PHP Javascript // A modular inverse based solution to// compute nCr % p#include <bits/stdc++.h>using namespace std; /* Iterative Function to calculate (x^y)%pin O(log y) */unsigned long long power(unsigned long long x, int y, int p){ unsigned long long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Returns n^(-1) mod punsigned long long modInverse(unsigned long long n, int p){ return power(n, p - 2, p);} // Returns nCr % p using Fermat's little// theorem.unsigned long long nCrModPFermat(unsigned long long n, int r, int p){ // If n<r, then nCr should return 0 if (n < r) return 0; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r unsigned long long fac[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (fac[i - 1] * i) % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p;} // Driver programint main(){ // p must be a prime greater than n. int n = 10, r = 2, p = 13; cout << "Value of nCr % p is " << nCrModPFermat(n, r, p); return 0;} // A modular inverse based solution to// compute nCr %import java.io.*; class GFG { /* Iterative Function to calculate (x^y)%p in O(log y) */ static int power(int x, int y, int p) { // Initialize result int res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p static int modInverse(int n, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static int nCrModPFermat(int n, int r, int p) { if (n<r) return 0; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r int[] fac = new int[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } // Driver program public static void main(String[] args) { // p must be a prime greater than n. int n = 10, r = 2, p = 13; System.out.println("Value of nCr % p is " + nCrModPFermat(n, r, p)); }} // This code is contributed by Anuj_67. # Python3 function to# calculate nCr % pdef ncr(n, r, p): # initialize numerator # and denominator num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p # p must be a prime# greater than nn, r, p = 10, 11, 13print("Value of nCr % p is", ncr(n, r, p)) // A modular inverse based solution to// compute nCr % pusing System; class GFG { /* Iterative Function to calculate (x^y)%p in O(log y) */ static int power(int x, int y, int p) { // Initialize result int res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p static int modInverse(int n, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static int nCrModPFermat(int n, int r, int p) { if (n<r) return 0; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r int[] fac = new int[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } // Driver program static void Main() { // p must be a prime greater than n. int n = 10, r = 11, p = 13; Console.Write("Value of nCr % p is " + nCrModPFermat(n, r, p)); }} // This code is contributed by Anuj_67 <?php// A modular inverse// based solution to// compute nCr % p // Iterative Function to// calculate (x^y)%p// in O(log y)function power($x, $y, $p){ // Initialize result $res = 1; // Update x if it // is more than or // equal to p $x = $x % $p; while ($y > 0) { // If y is odd, // multiply x // with result if ($y & 1) $res = ($res * $x) % $p; // y must be // even now // y = y/2 $y = $y >> 1; $x = ($x * $x) % $p; } return $res;} // Returns n^(-1) mod pfunction modInverse($n, $p){ return power($n, $p - 2, $p);} // Returns nCr % p using// Fermat's little// theorem.function nCrModPFermat($n, $r, $p){ if ($n<$r) return 0; // Base case if ($r==0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r //$fac[$n+1]; $fac[0] = 1; for ($i = 1; $i <= $n; $i++) $fac[$i] = $fac[$i - 1] * $i % $p; return ($fac[$n] * modInverse($fac[$r], $p) % $p * modInverse($fac[$n - $r], $p) % $p) % $p;} // Driver Code // p must be a prime // greater than n. $n = 10; $r = 2; $p = 13; echo "Value of nCr % p is ", nCrModPFermat($n, $r, $p); // This code is contributed by Ajit.?> <script> // A modular inverse based solution // to compute nCr % p /* Iterative Function to calculate (x^y)%p in O(log y) */ function power(x, y, p) { // Initialize result let res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p function modInverse(n, p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. function nCrModPFermat(n, r, p) { if (n<r) { return 0; } // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r let fac = new Array(n + 1); fac[0] = 1; for (let i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } // p must be a prime greater than n. let n = 10, r = 2, p = 13; document.write("Value of nCr % p is " + nCrModPFermat(n, r, p)); </script> Value of nCr % p is 6 Improvements: In competitive programming, we can pre-compute fac[] for given upper limit so that we don’t have to compute it for every test case. We also can use unsigned long long int everywhere to avoid overflows.This article is contributed by Nikhil Papisetty. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t vt_m HemanthSai1 mohdnazarkashif mukesh07 simmytarika5 surindertarika1234 binomial coefficient factorial Modular Arithmetic number-theory Mathematical number-theory Mathematical Modular Arithmetic factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Program to find GCD or HCF of two numbers Prime Numbers Program to find sum of elements in a given array Program for Decimal to Binary Conversion Sieve of Eratosthenes Program for factorial of a number Operators in C / C++ Euclidean algorithms (Basic and Extended)
[ { "code": null, "e": 24692, "s": 24664, "text": "\n25 Jun, 2021" }, { "code": null, "e": 24840, "s": 24692, "text": "Given three numbers n, r and p, compute the value of nCr mod p. Here p is a prime number greater than n. Here nCr is Binomial Coefficient.Example: " }, { "code": null, "e": 24962, "s": 24840, "text": "Input: n = 10, r = 2, p = 13\nOutput: 6\nExplanation: 10C2 is 45 and 45 % 13 is 6.\n\nInput: n = 6, r = 2, p = 13\nOutput: 2" }, { "code": null, "e": 25801, "s": 24962, "text": "We have discussed the following methods in previous posts. Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution) Compute nCr % p | Set 2 (Lucas Theorem)In this post, Fermat Theorem-based solution is discussed.Background: Fermat’s little theorem and modular inverse Fermat’s little theorem states that if p is a prime number, then for any integer a, the number ap – a is an integer multiple of p. In the notation of modular arithmetic, this is expressed as: ap = a (mod p) For example, if a = 2 and p = 7, 27 = 128, and 128 – 2 = 7 × 18 is an integer multiple of 7.If a is not divisible by p, Fermat’s little theorem is equivalent to the statement a p – 1 – 1 is an integer multiple of p, i.e ap-1 = 1 (mod p)If we multiply both sides by a-1, we get. ap-2 = a-1 (mod p)So we can find modular inverse as p-2. Computation: " }, { "code": null, "e": 26044, "s": 25801, "text": "We know the formula for nCr \nnCr = fact(n) / (fact(r) x fact(n-r)) \nHere fact() means factorial.\n\n nCr % p = (fac[n]* modIverse(fac[r]) % p *\n modIverse(fac[n-r]) % p) % p;\nHere modIverse() means modular inverse under\nmodulo p." }, { "code": null, "e": 26201, "s": 26044, "text": "Following is the implementation of the above algorithm. In the following implementation, an array fac[] is used to store all the computed factorial values. " }, { "code": null, "e": 26205, "s": 26201, "text": "C++" }, { "code": null, "e": 26210, "s": 26205, "text": "Java" }, { "code": null, "e": 26218, "s": 26210, "text": "Python3" }, { "code": null, "e": 26221, "s": 26218, "text": "C#" }, { "code": null, "e": 26225, "s": 26221, "text": "PHP" }, { "code": null, "e": 26236, "s": 26225, "text": "Javascript" }, { "code": "// A modular inverse based solution to// compute nCr % p#include <bits/stdc++.h>using namespace std; /* Iterative Function to calculate (x^y)%pin O(log y) */unsigned long long power(unsigned long long x, int y, int p){ unsigned long long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Returns n^(-1) mod punsigned long long modInverse(unsigned long long n, int p){ return power(n, p - 2, p);} // Returns nCr % p using Fermat's little// theorem.unsigned long long nCrModPFermat(unsigned long long n, int r, int p){ // If n<r, then nCr should return 0 if (n < r) return 0; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r unsigned long long fac[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (fac[i - 1] * i) % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p;} // Driver programint main(){ // p must be a prime greater than n. int n = 10, r = 2, p = 13; cout << \"Value of nCr % p is \" << nCrModPFermat(n, r, p); return 0;}", "e": 27762, "s": 26236, "text": null }, { "code": "// A modular inverse based solution to// compute nCr %import java.io.*; class GFG { /* Iterative Function to calculate (x^y)%p in O(log y) */ static int power(int x, int y, int p) { // Initialize result int res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p static int modInverse(int n, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static int nCrModPFermat(int n, int r, int p) { if (n<r) return 0; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r int[] fac = new int[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } // Driver program public static void main(String[] args) { // p must be a prime greater than n. int n = 10, r = 2, p = 13; System.out.println(\"Value of nCr % p is \" + nCrModPFermat(n, r, p)); }} // This code is contributed by Anuj_67.", "e": 29386, "s": 27762, "text": null }, { "code": "# Python3 function to# calculate nCr % pdef ncr(n, r, p): # initialize numerator # and denominator num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p # p must be a prime# greater than nn, r, p = 10, 11, 13print(\"Value of nCr % p is\", ncr(n, r, p))", "e": 29760, "s": 29386, "text": null }, { "code": "// A modular inverse based solution to// compute nCr % pusing System; class GFG { /* Iterative Function to calculate (x^y)%p in O(log y) */ static int power(int x, int y, int p) { // Initialize result int res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p static int modInverse(int n, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static int nCrModPFermat(int n, int r, int p) { if (n<r) return 0; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r int[] fac = new int[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } // Driver program static void Main() { // p must be a prime greater than n. int n = 10, r = 11, p = 13; Console.Write(\"Value of nCr % p is \" + nCrModPFermat(n, r, p)); }} // This code is contributed by Anuj_67", "e": 31346, "s": 29760, "text": null }, { "code": "<?php// A modular inverse// based solution to// compute nCr % p // Iterative Function to// calculate (x^y)%p// in O(log y)function power($x, $y, $p){ // Initialize result $res = 1; // Update x if it // is more than or // equal to p $x = $x % $p; while ($y > 0) { // If y is odd, // multiply x // with result if ($y & 1) $res = ($res * $x) % $p; // y must be // even now // y = y/2 $y = $y >> 1; $x = ($x * $x) % $p; } return $res;} // Returns n^(-1) mod pfunction modInverse($n, $p){ return power($n, $p - 2, $p);} // Returns nCr % p using// Fermat's little// theorem.function nCrModPFermat($n, $r, $p){ if ($n<$r) return 0; // Base case if ($r==0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r //$fac[$n+1]; $fac[0] = 1; for ($i = 1; $i <= $n; $i++) $fac[$i] = $fac[$i - 1] * $i % $p; return ($fac[$n] * modInverse($fac[$r], $p) % $p * modInverse($fac[$n - $r], $p) % $p) % $p;} // Driver Code // p must be a prime // greater than n. $n = 10; $r = 2; $p = 13; echo \"Value of nCr % p is \", nCrModPFermat($n, $r, $p); // This code is contributed by Ajit.?>", "e": 32705, "s": 31346, "text": null }, { "code": "<script> // A modular inverse based solution // to compute nCr % p /* Iterative Function to calculate (x^y)%p in O(log y) */ function power(x, y, p) { // Initialize result let res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p function modInverse(n, p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. function nCrModPFermat(n, r, p) { if (n<r) { return 0; } // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r let fac = new Array(n + 1); fac[0] = 1; for (let i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } // p must be a prime greater than n. let n = 10, r = 2, p = 13; document.write(\"Value of nCr % p is \" + nCrModPFermat(n, r, p)); </script>", "e": 34105, "s": 32705, "text": null }, { "code": null, "e": 34127, "s": 34105, "text": "Value of nCr % p is 6" }, { "code": null, "e": 34768, "s": 34129, "text": "Improvements: In competitive programming, we can pre-compute fac[] for given upper limit so that we don’t have to compute it for every test case. We also can use unsigned long long int everywhere to avoid overflows.This article is contributed by Nikhil Papisetty. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 34774, "s": 34768, "text": "jit_t" }, { "code": null, "e": 34779, "s": 34774, "text": "vt_m" }, { "code": null, "e": 34791, "s": 34779, "text": "HemanthSai1" }, { "code": null, "e": 34807, "s": 34791, "text": "mohdnazarkashif" }, { "code": null, "e": 34816, "s": 34807, "text": "mukesh07" }, { "code": null, "e": 34829, "s": 34816, "text": "simmytarika5" }, { "code": null, "e": 34848, "s": 34829, "text": "surindertarika1234" }, { "code": null, "e": 34869, "s": 34848, "text": "binomial coefficient" }, { "code": null, "e": 34879, "s": 34869, "text": "factorial" }, { "code": null, "e": 34898, "s": 34879, "text": "Modular Arithmetic" }, { "code": null, "e": 34912, "s": 34898, "text": "number-theory" }, { "code": null, "e": 34925, "s": 34912, "text": "Mathematical" }, { "code": null, "e": 34939, "s": 34925, "text": "number-theory" }, { "code": null, "e": 34952, "s": 34939, "text": "Mathematical" }, { "code": null, "e": 34971, "s": 34952, "text": "Modular Arithmetic" }, { "code": null, "e": 34981, "s": 34971, "text": "factorial" }, { "code": null, "e": 35079, "s": 34981, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35103, "s": 35079, "text": "Merge two sorted arrays" }, { "code": null, "e": 35146, "s": 35103, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 35188, "s": 35146, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 35202, "s": 35188, "text": "Prime Numbers" }, { "code": null, "e": 35251, "s": 35202, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 35292, "s": 35251, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 35314, "s": 35292, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 35348, "s": 35314, "text": "Program for factorial of a number" }, { "code": null, "e": 35369, "s": 35348, "text": "Operators in C / C++" } ]
Methods to Round Values in Pandas DataFrame - GeeksforGeeks
18 Aug, 2020 There are various ways to Round Values in Pandas DataFrame so let’s see each one by one: Let’s create a Dataframe with ‘Data Entry’ Column only: Code: Python3 # import Dataframe class# from pandas libraryfrom pandas import DataFrame # import numpy libraryimport numpy as np # dictionaryMyvalue = {'DATA ENTRY': [4.834327, 5.334477, 6.89, 7.6454, 8.9659]} # create a Dataframedf = DataFrame(Myvalue, columns = ['DATA ENTRY']) # show the dataframedf Output: Method 1: Using numpy.round(). Syntax: numpy.round_(arr, decimals = 0, out = None) Return: An array with all array elements beingrounded off, having same type as input. This method can be used to round value to specific decimal places for any particular column or can also be used to round the value of the entire data frame to the specific number of decimal places. Example: Rounding off the value of the “DATA ENTRY” column up to 2 decimal places. Python3 # import Dataframe class# from pandas libraryfrom pandas import DataFrame # import numpy libraryimport numpy as np # dictionaryMyvalue = {'DATA ENTRY': [4.834327, 5.334477, 6.89, 7.6454, 8.9659]} # create a Dataframedf = DataFrame(Myvalue, columns = ['DATA ENTRY']) # Rounding value of 'DATA ENTRY' # column upto 2 decimal placesroundplaces = np.round(df['DATA ENTRY'], decimals = 2) # show the rounded valueroundplaces Output: Method 2: Using Dataframe.apply() and numpy.ceil() together. Syntax: Dataframe/Series.apply(func, convert_dtype=True, args=()) Return: Pandas Series after applied function/operation. Syntax: numpy.ceil(x[, out]) = ufunc ‘ceil’) Return: An array with the ceil of each element of float data-type. These methods are used to round values to ceiling value(smallest integer value greater than particular value). Example: Rounding off the value of a particular column. Python3 # import Dataframe from # pandas libraryfrom pandas import DataFrame # import numpyimport numpy as np # dictionaryMyvalue = {'DATA ENTRY': [4.834327, 5.334477, 6.89, 7.6454, 8.9659]} # create a Dataframedf = DataFrame(Myvalue, columns = ['DATA ENTRY']) # Here we are rounding the # value to its ceiling valuesroundUp = df['DATA ENTRY'].apply(np.ceil) # show the rounded valueroundUp Output: Method 3: Using Dataframe.apply() and numpy.floor() together. Syntax: numpy.floor(x[, out]) = ufunc ‘floor’) Return: An array with the floor of each element. These methods are used to round values to floor value(largest integer value smaller than particular value). Example: Rounding off the value of the “DATA ENTRY” column to its corresponding Floor value. Python3 # import Dataframe class # from pandas libraryfrom pandas import DataFrame # import numpy libraryimport numpy as np # dictionaryMyvalue = {'DATA ENTRY':[4.834327, 5.334477, 6.89, 7.6454, 8.9659] } # create a Dataframedf = DataFrame(Myvalue, columns = ['DATA ENTRY']) # Rounding of Value to its Floor value rounddown = df['DATA ENTRY'].apply(np.floor) # show the rounded valuerounddown Output: Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Split string into list of characters
[ { "code": null, "e": 24292, "s": 24264, "text": "\n18 Aug, 2020" }, { "code": null, "e": 24381, "s": 24292, "text": "There are various ways to Round Values in Pandas DataFrame so let’s see each one by one:" }, { "code": null, "e": 24437, "s": 24381, "text": "Let’s create a Dataframe with ‘Data Entry’ Column only:" }, { "code": null, "e": 24443, "s": 24437, "text": "Code:" }, { "code": null, "e": 24451, "s": 24443, "text": "Python3" }, { "code": "# import Dataframe class# from pandas libraryfrom pandas import DataFrame # import numpy libraryimport numpy as np # dictionaryMyvalue = {'DATA ENTRY': [4.834327, 5.334477, 6.89, 7.6454, 8.9659]} # create a Dataframedf = DataFrame(Myvalue, columns = ['DATA ENTRY']) # show the dataframedf", "e": 24784, "s": 24451, "text": null }, { "code": null, "e": 24792, "s": 24784, "text": "Output:" }, { "code": null, "e": 24824, "s": 24792, "text": "Method 1: Using numpy.round()." }, { "code": null, "e": 24876, "s": 24824, "text": "Syntax: numpy.round_(arr, decimals = 0, out = None)" }, { "code": null, "e": 24963, "s": 24876, "text": "Return: An array with all array elements beingrounded off, having same type as input. " }, { "code": null, "e": 25162, "s": 24963, "text": "This method can be used to round value to specific decimal places for any particular column or can also be used to round the value of the entire data frame to the specific number of decimal places." }, { "code": null, "e": 25246, "s": 25162, "text": "Example: Rounding off the value of the “DATA ENTRY” column up to 2 decimal places." }, { "code": null, "e": 25254, "s": 25246, "text": "Python3" }, { "code": "# import Dataframe class# from pandas libraryfrom pandas import DataFrame # import numpy libraryimport numpy as np # dictionaryMyvalue = {'DATA ENTRY': [4.834327, 5.334477, 6.89, 7.6454, 8.9659]} # create a Dataframedf = DataFrame(Myvalue, columns = ['DATA ENTRY']) # Rounding value of 'DATA ENTRY' # column upto 2 decimal placesroundplaces = np.round(df['DATA ENTRY'], decimals = 2) # show the rounded valueroundplaces", "e": 25742, "s": 25254, "text": null }, { "code": null, "e": 25750, "s": 25742, "text": "Output:" }, { "code": null, "e": 25811, "s": 25750, "text": "Method 2: Using Dataframe.apply() and numpy.ceil() together." }, { "code": null, "e": 25877, "s": 25811, "text": "Syntax: Dataframe/Series.apply(func, convert_dtype=True, args=())" }, { "code": null, "e": 25934, "s": 25877, "text": "Return: Pandas Series after applied function/operation. " }, { "code": null, "e": 25979, "s": 25934, "text": "Syntax: numpy.ceil(x[, out]) = ufunc ‘ceil’)" }, { "code": null, "e": 26046, "s": 25979, "text": "Return: An array with the ceil of each element of float data-type." }, { "code": null, "e": 26158, "s": 26046, "text": "These methods are used to round values to ceiling value(smallest integer value greater than particular value). " }, { "code": null, "e": 26215, "s": 26158, "text": "Example: Rounding off the value of a particular column. " }, { "code": null, "e": 26223, "s": 26215, "text": "Python3" }, { "code": "# import Dataframe from # pandas libraryfrom pandas import DataFrame # import numpyimport numpy as np # dictionaryMyvalue = {'DATA ENTRY': [4.834327, 5.334477, 6.89, 7.6454, 8.9659]} # create a Dataframedf = DataFrame(Myvalue, columns = ['DATA ENTRY']) # Here we are rounding the # value to its ceiling valuesroundUp = df['DATA ENTRY'].apply(np.ceil) # show the rounded valueroundUp", "e": 26653, "s": 26223, "text": null }, { "code": null, "e": 26662, "s": 26653, "text": "Output: " }, { "code": null, "e": 26724, "s": 26662, "text": "Method 3: Using Dataframe.apply() and numpy.floor() together." }, { "code": null, "e": 26771, "s": 26724, "text": "Syntax: numpy.floor(x[, out]) = ufunc ‘floor’)" }, { "code": null, "e": 26821, "s": 26771, "text": "Return: An array with the floor of each element. " }, { "code": null, "e": 26929, "s": 26821, "text": "These methods are used to round values to floor value(largest integer value smaller than particular value)." }, { "code": null, "e": 27022, "s": 26929, "text": "Example: Rounding off the value of the “DATA ENTRY” column to its corresponding Floor value." }, { "code": null, "e": 27030, "s": 27022, "text": "Python3" }, { "code": "# import Dataframe class # from pandas libraryfrom pandas import DataFrame # import numpy libraryimport numpy as np # dictionaryMyvalue = {'DATA ENTRY':[4.834327, 5.334477, 6.89, 7.6454, 8.9659] } # create a Dataframedf = DataFrame(Myvalue, columns = ['DATA ENTRY']) # Rounding of Value to its Floor value rounddown = df['DATA ENTRY'].apply(np.floor) # show the rounded valuerounddown", "e": 27462, "s": 27030, "text": null }, { "code": null, "e": 27470, "s": 27462, "text": "Output:" }, { "code": null, "e": 27494, "s": 27470, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27517, "s": 27494, "text": "Python Pandas-exercise" }, { "code": null, "e": 27531, "s": 27517, "text": "Python-pandas" }, { "code": null, "e": 27538, "s": 27531, "text": "Python" }, { "code": null, "e": 27636, "s": 27538, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27668, "s": 27636, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27724, "s": 27668, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27766, "s": 27724, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27808, "s": 27766, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27863, "s": 27808, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27885, "s": 27863, "text": "Defaultdict in Python" }, { "code": null, "e": 27924, "s": 27885, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27955, "s": 27924, "text": "Python | os.path.join() method" }, { "code": null, "e": 27984, "s": 27955, "text": "Create a directory in Python" } ]
Elm - Basic Syntax
This chapter discusses how to write a simple program in elm. Step 1 − Create a directory HelloApp in VSCode Now, create a file − Hello.elm in this directory. The above diagram shows project folder HelloApp and terminal opened in VSCode. Step 2 − Install the necessary elm packages The package manager in elm is elm-package. Install the elm-lang/html package. This package will help us display output of elm code in the browser. Traverse to the HelloApp project folder by right clicking on File → Open in command prompt in VSCode. Execute the following command in the terminal window − C:\Users\dell\Elm\HelloApp> elm-package install elm-lang/html The following files/folders are added to the project directory on installing the package. elm-package.json (file), stores project meta data elm-stuff (folder), stores external packages The following message will appear once the package is installed successfully. Step 3 − Add the following code to the Hello.elm file -- importing Html module and the function text import Html exposing (text) -- create main method main = -- invoke text function text "Hello Elm from TutorialsPoint" The above program will display a string message Hello Elm from TutorialsPoint in the browser. For this, we need to import the function text within the Html module. The text function is used to print any string value in the browser. The main method is the entry point to a program. The main method invokes the text function and passes a string value to it. Step 4 − Compile the project Execute the following command in VSCode terminal window. elm make Hello.elm The output of the above command is as shown below − //update path to the proj folder in the command elm make C:\Users\dell\elm\HelloApp>elm make Hello.elm Success! Compiled 38 modules. Successfully generated index.html The above command will generate an index.html file. The elm compiler converts .elm file to JavaScript and embeds it in the index.html file. Step 5 − Open the index.html in the browser Open the index.html file in any browser. The output will be as shown below − Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function construct, etc. Comments are ignored by the compiler. Elm supports the following types of comments − Single-line comments (--) − Any text between a -- and the end of a line is treated as a comment. Single-line comments (--) − Any text between a -- and the end of a line is treated as a comment. Multi-line comments ({- -}) − These comments may span multiple lines. Multi-line comments ({- -}) − These comments may span multiple lines. -- this is single line comment {- This is a Multi-line comment -} Elm provides no braces to indicate blocks of code for function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced. All statements within a block must be indented the same amount. For example − module ModuleIf exposing (..) x = 0 function1 = if x > 5 then "x is greater" else "x is small" However, the following block generates an error − -- Create file ModuleIf.elm module ModuleIf exposing (..) x = 0 function1 = if x > 5 then "x is greater" else --Error:else indentation not at same level of if statement "x is small" Thus, in Elm all the continuous lines indented with same number of spaces would form a block. C:\Users\admin>elm repl ---- elm-repl 0.18.0 ----------------------------------------------------------- :help for help, :exit to exit, more at <https://github.com/elm-lang/elm-repl> --------------------------------------- ----------------------------------------- > import ModuleIf exposing(..) -- importing module from ModuleIf.elm file >function1 -- executing function from module -- SYNTAX PROBLEM --------------------------------------------------- I need whitespace, but got stuck on what looks like a new declaration. You are either missing some stuff in the declaration above or just need to add some spaces here: 7| else ^ I am looking for one of the following things: whitespace 27 Lectures 2.5 hours Ahmed Elfakharany Print Add Notes Bookmark this page
[ { "code": null, "e": 1941, "s": 1880, "text": "This chapter discusses how to write a simple program in elm." }, { "code": null, "e": 1988, "s": 1941, "text": "Step 1 − Create a directory HelloApp in VSCode" }, { "code": null, "e": 2038, "s": 1988, "text": "Now, create a file − Hello.elm in this directory." }, { "code": null, "e": 2117, "s": 2038, "text": "The above diagram shows project folder HelloApp and terminal opened in VSCode." }, { "code": null, "e": 2161, "s": 2117, "text": "Step 2 − Install the necessary elm packages" }, { "code": null, "e": 2308, "s": 2161, "text": "The package manager in elm is elm-package. Install the elm-lang/html package. This package will help us display output of elm code in the browser." }, { "code": null, "e": 2410, "s": 2308, "text": "Traverse to the HelloApp project folder by right clicking on File → Open in command prompt in VSCode." }, { "code": null, "e": 2465, "s": 2410, "text": "Execute the following command in the terminal window −" }, { "code": null, "e": 2528, "s": 2465, "text": "C:\\Users\\dell\\Elm\\HelloApp> elm-package install elm-lang/html\n" }, { "code": null, "e": 2618, "s": 2528, "text": "The following files/folders are added to the project directory on installing the package." }, { "code": null, "e": 2668, "s": 2618, "text": "elm-package.json (file), stores project meta data" }, { "code": null, "e": 2713, "s": 2668, "text": "elm-stuff (folder), stores external packages" }, { "code": null, "e": 2791, "s": 2713, "text": "The following message will appear once the package is installed successfully." }, { "code": null, "e": 2845, "s": 2791, "text": "Step 3 − Add the following code to the Hello.elm file" }, { "code": null, "e": 3011, "s": 2845, "text": "-- importing Html module and the function text\nimport Html exposing (text)\n\n-- create main method\nmain =\n-- invoke text function\ntext \"Hello Elm from TutorialsPoint\"" }, { "code": null, "e": 3105, "s": 3011, "text": "The above program will display a string message Hello Elm from TutorialsPoint in the browser." }, { "code": null, "e": 3367, "s": 3105, "text": "For this, we need to import the function text within the Html module. The text function is used to print any string value in the browser. The main method is the entry point to a program. The main method invokes the text function and passes a string value to it." }, { "code": null, "e": 3396, "s": 3367, "text": "Step 4 − Compile the project" }, { "code": null, "e": 3453, "s": 3396, "text": "Execute the following command in VSCode terminal window." }, { "code": null, "e": 3473, "s": 3453, "text": "elm make Hello.elm\n" }, { "code": null, "e": 3525, "s": 3473, "text": "The output of the above command is as shown below −" }, { "code": null, "e": 3693, "s": 3525, "text": "//update path to the proj folder in the command elm make\nC:\\Users\\dell\\elm\\HelloApp>elm make Hello.elm\nSuccess! Compiled 38 modules.\nSuccessfully generated index.html\n" }, { "code": null, "e": 3833, "s": 3693, "text": "The above command will generate an index.html file. The elm compiler converts .elm file to JavaScript and embeds it in the index.html file." }, { "code": null, "e": 3877, "s": 3833, "text": "Step 5 − Open the index.html in the browser" }, { "code": null, "e": 3954, "s": 3877, "text": "Open the index.html file in any browser. The output will be as shown below −" }, { "code": null, "e": 4187, "s": 3954, "text": "Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function construct, etc. Comments are ignored by the compiler." }, { "code": null, "e": 4234, "s": 4187, "text": "Elm supports the following types of comments −" }, { "code": null, "e": 4331, "s": 4234, "text": "Single-line comments (--) − Any text between a -- and the end of a line is treated as a comment." }, { "code": null, "e": 4428, "s": 4331, "text": "Single-line comments (--) − Any text between a -- and the end of a line is treated as a comment." }, { "code": null, "e": 4498, "s": 4428, "text": "Multi-line comments ({- -}) − These comments may span multiple lines." }, { "code": null, "e": 4568, "s": 4498, "text": "Multi-line comments ({- -}) − These comments may span multiple lines." }, { "code": null, "e": 4639, "s": 4568, "text": "-- this is single line comment\n\n{- This is a\n Multi-line comment\n-}\n" }, { "code": null, "e": 4884, "s": 4639, "text": "Elm provides no braces to indicate blocks of code for function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced. All statements within a block must be indented the same amount. For example −" }, { "code": null, "e": 4998, "s": 4884, "text": "module ModuleIf exposing (..)\nx = 0\n\nfunction1 =\n if x > 5 then\n \"x is greater\"\n else\n \"x is small\"" }, { "code": null, "e": 5048, "s": 4998, "text": "However, the following block generates an error −" }, { "code": null, "e": 5255, "s": 5048, "text": "-- Create file ModuleIf.elm\nmodule ModuleIf exposing (..)\nx = 0\n\nfunction1 =\n if x > 5 then\n \"x is greater\"\n else --Error:else indentation not at same level of if statement\n \"x is small\"" }, { "code": null, "e": 5349, "s": 5255, "text": "Thus, in Elm all the continuous lines indented with same number of spaces would form a block." }, { "code": null, "e": 6061, "s": 5349, "text": "C:\\Users\\admin>elm repl\n---- elm-repl 0.18.0 -----------------------------------------------------------\n :help for help, :exit to exit, more at \n <https://github.com/elm-lang/elm-repl>\n ---------------------------------------\n -----------------------------------------\n\n> import ModuleIf exposing(..) -- importing module from ModuleIf.elm file\n>function1 -- executing function from module\n-- SYNTAX PROBLEM ---------------------------------------------------\n\nI need whitespace, but got stuck on what looks like a new declaration. \nYou are either missing some stuff in the declaration above or just need to add some spaces here:\n7| else\n ^\nI am looking for one of the following things:\n\n whitespace" }, { "code": null, "e": 6096, "s": 6061, "text": "\n 27 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6115, "s": 6096, "text": " Ahmed Elfakharany" }, { "code": null, "e": 6122, "s": 6115, "text": " Print" }, { "code": null, "e": 6133, "s": 6122, "text": " Add Notes" } ]
Find all Palindrome Strings in given Array of strings - GeeksforGeeks
08 Mar, 2022 Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to find all palindromic string in the array. Print -1 if no palindrome is present in the given array. Examples: Input: arr[] = {“abc”, “car”, “ada”, “racecar”, “cool”}Output: “ada”, “racecar”Explanation: These two are the only palindrome strings in the given array Input: arr[] = {“def”, “ab”}Output: -1Explanation: No palindrome string is present in the given array. Approach: The solution is based on greedy approach. Check every string of an array if it is palindrome or not and also keep track of the all palindrome string. Follow the steps below to solve the problem: Initialize a vector of string ans. Iterate over the range [0, N) using the variable i and If arr[i] is a palindrome, then add it to the ans. After performing the above steps, print the strings present in ans as the resultant strings. Below is the implementation of the above approach. C++ Java C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if given string// is Palindrome or notbool isPalindrome(string& s){ // Copy string s char into string a string a = s; reverse(s.begin(), s.end()); // Check if two string are equal or not return s == a;} // Function to return all Palindrome stringvector<string> PalindromicStrings(string arr[], int N){ vector<string> ans; // Loop to find palindrome string for (int i = 0; i < N; i++) { // Checking if given string is // palindrome or not if (isPalindrome(arr[i])) { // Update answer variable ans.push_back(arr[i]); } } return ans;} // Driver Codeint main(){ string arr[] = { "abc", "car", "ada", "racecar", "cool" }; int N = sizeof(arr) / sizeof(arr[0]); // Print required answer vector<string> s = PalindromicStrings(arr, N); if(s.size() == 0) cout << "-1"; for(string st: s) cout << st << " "; return 0;} // Java code to find the maximum median// of a sub array having length at least K.import java.util.*;public class GFG{ // Function to check if given string // is Palindrome or not static boolean isPalindrome(String str) { // Start from leftmost and rightmost corners of str int l = 0; int h = str.length() - 1; // Keep comparing characters while they are same while (h > l) { if (str.charAt(l++) != str.charAt(h--)) { return false; } } return true; } // Function to return all Palindrome string static ArrayList<String> PalindromicStrings(String []arr, int N) { ArrayList<String> ans = new ArrayList<String>(); // Loop to find palindrome string for (int i = 0; i < N; i++) { // Checking if given string is // palindrome or not if (isPalindrome(arr[i])) { // Update answer variable ans.add(arr[i]); } } return ans; } // Driver Code public static void main(String args[]) { String []arr = { "abc", "car", "ada", "racecar", "cool" }; int N = arr.length; // Print required answer ArrayList<String> s = PalindromicStrings(arr, N); if(s.size() == 0) System.out.print("-1"); for (String st : s) System.out.print(st + " "); }} // This code is contributed by Samim Hossain Mondal. // C# program for the above approachusing System;using System.Collections;class GFG{ // Function to check if given string // is Palindrome or not static bool isPalindrome(string str) { // Start from leftmost and rightmost corners of str int l = 0; int h = str.Length - 1; // Keep comparing characters while they are same while (h > l) { if (str[l++] != str[h--]) { return false; } } return true; } // Function to return all Palindrome string static ArrayList PalindromicStrings(string []arr, int N) { ArrayList ans = new ArrayList(); // Loop to find palindrome string for (int i = 0; i < N; i++) { // Checking if given string is // palindrome or not if (isPalindrome(arr[i])) { // Update answer variable ans.Add(arr[i]); } } return ans; } // Driver Code public static void Main() { string []arr = { "abc", "car", "ada", "racecar", "cool" }; int N = arr.Length; // Print required answer ArrayList s = PalindromicStrings(arr, N); if(s.Count == 0) Console.Write("-1"); foreach(string st in s) Console.Write(st + " "); }}// This code is contributed by Samim Hossain Mondal. <script> // JavaScript code for the above approach // Function to check if given string// is Palindrome or notfunction isPalindrome(s){ // Copy string s char into string a let a = s; s = s.split('').reverse().join(''); // Check if two string are equal or not return s == a;} // Function to return all Palindrome stringfunction PalindromicStrings(arr,N){ let ans = []; // Loop to find palindrome string for (let i = 0; i < N; i++) { // Checking if given string is // palindrome or not if (isPalindrome(arr[i])) { // Update answer variable ans.push(arr[i]); } } return ans;} // Driver Codelet arr = [ "abc", "car", "ada", "racecar", "cool" ];let N = arr.length; // Print required answerlet s = PalindromicStrings(arr, N);if(s.length == 0) document.write("-1");for(let st of s) document.write(st," "); // This code is contributed by shinjanpatra</script> ada racecar Time complexity: O(N * W) where W is the average length of the stringsAuxiliary Space: O(N * W) samim2000 varshagumber28 kk9826225 kk773572498 simranarora5sos shinjanpatra Algo-Geek 2021 palindrome Algo Geek Strings Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Count of operation required to water all the plants Lexicographically smallest string formed by concatenating any prefix and its mirrored form Divide given number into two even parts Check if the given string is valid English word or not Check if an edge is a part of any Minimum Spanning Tree Reverse a string in Java Write a program to reverse an array or string C++ Data Types Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string
[ { "code": null, "e": 26142, "s": 26114, "text": "\n08 Mar, 2022" }, { "code": null, "e": 26359, "s": 26142, "text": "Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to find all palindromic string in the array. Print -1 if no palindrome is present in the given array." }, { "code": null, "e": 26369, "s": 26359, "text": "Examples:" }, { "code": null, "e": 26522, "s": 26369, "text": "Input: arr[] = {“abc”, “car”, “ada”, “racecar”, “cool”}Output: “ada”, “racecar”Explanation: These two are the only palindrome strings in the given array" }, { "code": null, "e": 26625, "s": 26522, "text": "Input: arr[] = {“def”, “ab”}Output: -1Explanation: No palindrome string is present in the given array." }, { "code": null, "e": 26830, "s": 26625, "text": "Approach: The solution is based on greedy approach. Check every string of an array if it is palindrome or not and also keep track of the all palindrome string. Follow the steps below to solve the problem:" }, { "code": null, "e": 26865, "s": 26830, "text": "Initialize a vector of string ans." }, { "code": null, "e": 26971, "s": 26865, "text": "Iterate over the range [0, N) using the variable i and If arr[i] is a palindrome, then add it to the ans." }, { "code": null, "e": 27064, "s": 26971, "text": "After performing the above steps, print the strings present in ans as the resultant strings." }, { "code": null, "e": 27115, "s": 27064, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 27119, "s": 27115, "text": "C++" }, { "code": null, "e": 27124, "s": 27119, "text": "Java" }, { "code": null, "e": 27127, "s": 27124, "text": "C#" }, { "code": null, "e": 27138, "s": 27127, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if given string// is Palindrome or notbool isPalindrome(string& s){ // Copy string s char into string a string a = s; reverse(s.begin(), s.end()); // Check if two string are equal or not return s == a;} // Function to return all Palindrome stringvector<string> PalindromicStrings(string arr[], int N){ vector<string> ans; // Loop to find palindrome string for (int i = 0; i < N; i++) { // Checking if given string is // palindrome or not if (isPalindrome(arr[i])) { // Update answer variable ans.push_back(arr[i]); } } return ans;} // Driver Codeint main(){ string arr[] = { \"abc\", \"car\", \"ada\", \"racecar\", \"cool\" }; int N = sizeof(arr) / sizeof(arr[0]); // Print required answer vector<string> s = PalindromicStrings(arr, N); if(s.size() == 0) cout << \"-1\"; for(string st: s) cout << st << \" \"; return 0;}", "e": 28210, "s": 27138, "text": null }, { "code": "// Java code to find the maximum median// of a sub array having length at least K.import java.util.*;public class GFG{ // Function to check if given string // is Palindrome or not static boolean isPalindrome(String str) { // Start from leftmost and rightmost corners of str int l = 0; int h = str.length() - 1; // Keep comparing characters while they are same while (h > l) { if (str.charAt(l++) != str.charAt(h--)) { return false; } } return true; } // Function to return all Palindrome string static ArrayList<String> PalindromicStrings(String []arr, int N) { ArrayList<String> ans = new ArrayList<String>(); // Loop to find palindrome string for (int i = 0; i < N; i++) { // Checking if given string is // palindrome or not if (isPalindrome(arr[i])) { // Update answer variable ans.add(arr[i]); } } return ans; } // Driver Code public static void main(String args[]) { String []arr = { \"abc\", \"car\", \"ada\", \"racecar\", \"cool\" }; int N = arr.length; // Print required answer ArrayList<String> s = PalindromicStrings(arr, N); if(s.size() == 0) System.out.print(\"-1\"); for (String st : s) System.out.print(st + \" \"); }} // This code is contributed by Samim Hossain Mondal.", "e": 29579, "s": 28210, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections;class GFG{ // Function to check if given string // is Palindrome or not static bool isPalindrome(string str) { // Start from leftmost and rightmost corners of str int l = 0; int h = str.Length - 1; // Keep comparing characters while they are same while (h > l) { if (str[l++] != str[h--]) { return false; } } return true; } // Function to return all Palindrome string static ArrayList PalindromicStrings(string []arr, int N) { ArrayList ans = new ArrayList(); // Loop to find palindrome string for (int i = 0; i < N; i++) { // Checking if given string is // palindrome or not if (isPalindrome(arr[i])) { // Update answer variable ans.Add(arr[i]); } } return ans; } // Driver Code public static void Main() { string []arr = { \"abc\", \"car\", \"ada\", \"racecar\", \"cool\" }; int N = arr.Length; // Print required answer ArrayList s = PalindromicStrings(arr, N); if(s.Count == 0) Console.Write(\"-1\"); foreach(string st in s) Console.Write(st + \" \"); }}// This code is contributed by Samim Hossain Mondal.", "e": 30844, "s": 29579, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to check if given string// is Palindrome or notfunction isPalindrome(s){ // Copy string s char into string a let a = s; s = s.split('').reverse().join(''); // Check if two string are equal or not return s == a;} // Function to return all Palindrome stringfunction PalindromicStrings(arr,N){ let ans = []; // Loop to find palindrome string for (let i = 0; i < N; i++) { // Checking if given string is // palindrome or not if (isPalindrome(arr[i])) { // Update answer variable ans.push(arr[i]); } } return ans;} // Driver Codelet arr = [ \"abc\", \"car\", \"ada\", \"racecar\", \"cool\" ];let N = arr.length; // Print required answerlet s = PalindromicStrings(arr, N);if(s.length == 0) document.write(\"-1\");for(let st of s) document.write(st,\" \"); // This code is contributed by shinjanpatra</script>", "e": 31787, "s": 30844, "text": null }, { "code": null, "e": 31800, "s": 31787, "text": "ada racecar " }, { "code": null, "e": 31898, "s": 31800, "text": " Time complexity: O(N * W) where W is the average length of the stringsAuxiliary Space: O(N * W) " }, { "code": null, "e": 31908, "s": 31898, "text": "samim2000" }, { "code": null, "e": 31923, "s": 31908, "text": "varshagumber28" }, { "code": null, "e": 31933, "s": 31923, "text": "kk9826225" }, { "code": null, "e": 31945, "s": 31933, "text": "kk773572498" }, { "code": null, "e": 31961, "s": 31945, "text": "simranarora5sos" }, { "code": null, "e": 31974, "s": 31961, "text": "shinjanpatra" }, { "code": null, "e": 31989, "s": 31974, "text": "Algo-Geek 2021" }, { "code": null, "e": 32000, "s": 31989, "text": "palindrome" }, { "code": null, "e": 32010, "s": 32000, "text": "Algo Geek" }, { "code": null, "e": 32018, "s": 32010, "text": "Strings" }, { "code": null, "e": 32026, "s": 32018, "text": "Strings" }, { "code": null, "e": 32037, "s": 32026, "text": "palindrome" }, { "code": null, "e": 32135, "s": 32037, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32144, "s": 32135, "text": "Comments" }, { "code": null, "e": 32157, "s": 32144, "text": "Old Comments" }, { "code": null, "e": 32209, "s": 32157, "text": "Count of operation required to water all the plants" }, { "code": null, "e": 32300, "s": 32209, "text": "Lexicographically smallest string formed by concatenating any prefix and its mirrored form" }, { "code": null, "e": 32340, "s": 32300, "text": "Divide given number into two even parts" }, { "code": null, "e": 32395, "s": 32340, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 32451, "s": 32395, "text": "Check if an edge is a part of any Minimum Spanning Tree" }, { "code": null, "e": 32476, "s": 32451, "text": "Reverse a string in Java" }, { "code": null, "e": 32522, "s": 32476, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 32537, "s": 32522, "text": "C++ Data Types" }, { "code": null, "e": 32571, "s": 32537, "text": "Longest Common Subsequence | DP-4" } ]
Difference Between Pointer and Reference
In this post, we will understand the difference between pointer and reference. It can be initialized to any value. It can be initialized to any value. It can be initialized any time after its declaration. It can be initialized any time after its declaration. It can be assigned to point to a NULL value. It can be assigned to point to a NULL value. It can be dereferenced using the ‘*’ operator. It can be dereferenced using the ‘*’ operator. It can be changed to point to a different variable of the same type only. It can be changed to point to a different variable of the same type only. int val = 5; //code// int *p = &val; It has to be initialized when it is declared. It has to be initialized when it is declared. It can’t be a NULL value. It can’t be a NULL value. It can be used by a name. It can be used by a name. Once it has been initialized to a variable, it can’t be changed to refer to a variable object. Once it has been initialized to a variable, it can’t be changed to refer to a variable object. int val = 52; int &ref = val;
[ { "code": null, "e": 1141, "s": 1062, "text": "In this post, we will understand the difference between pointer and reference." }, { "code": null, "e": 1177, "s": 1141, "text": "It can be initialized to any value." }, { "code": null, "e": 1213, "s": 1177, "text": "It can be initialized to any value." }, { "code": null, "e": 1267, "s": 1213, "text": "It can be initialized any time after its declaration." }, { "code": null, "e": 1321, "s": 1267, "text": "It can be initialized any time after its declaration." }, { "code": null, "e": 1366, "s": 1321, "text": "It can be assigned to point to a NULL value." }, { "code": null, "e": 1411, "s": 1366, "text": "It can be assigned to point to a NULL value." }, { "code": null, "e": 1458, "s": 1411, "text": "It can be dereferenced using the ‘*’ operator." }, { "code": null, "e": 1505, "s": 1458, "text": "It can be dereferenced using the ‘*’ operator." }, { "code": null, "e": 1579, "s": 1505, "text": "It can be changed to point to a different variable of the same type only." }, { "code": null, "e": 1653, "s": 1579, "text": "It can be changed to point to a different variable of the same type only." }, { "code": null, "e": 1690, "s": 1653, "text": "int val = 5;\n//code//\nint *p = &val;" }, { "code": null, "e": 1736, "s": 1690, "text": "It has to be initialized when it is declared." }, { "code": null, "e": 1782, "s": 1736, "text": "It has to be initialized when it is declared." }, { "code": null, "e": 1808, "s": 1782, "text": "It can’t be a NULL value." }, { "code": null, "e": 1834, "s": 1808, "text": "It can’t be a NULL value." }, { "code": null, "e": 1860, "s": 1834, "text": "It can be used by a name." }, { "code": null, "e": 1886, "s": 1860, "text": "It can be used by a name." }, { "code": null, "e": 1981, "s": 1886, "text": "Once it has been initialized to a variable, it can’t be changed to refer to a variable object." }, { "code": null, "e": 2076, "s": 1981, "text": "Once it has been initialized to a variable, it can’t be changed to refer to a variable object." }, { "code": null, "e": 2106, "s": 2076, "text": "int val = 52;\nint &ref = val;" } ]
Bulma Text weight - GeeksforGeeks
08 Dec, 2021 Bulma text weight class is used to set the text into bold text. There are 5 text weights and you can transform the text weight with the use of one of 5 text weight helpers. Text weight classes: has-text-weight-light: This class is used to transform text weight to light. has-text-weight-normal: This class is used to transform text weight to normal. has-text-weight-medium: This class is used to transform text weight to medium. has-text-weight-semibold: This class is used to transform text weight to semi-bold. has-text-weight-bold: This class is used to transform text weight to bold. Example: Below example illustrate the text size class in Bulma. HTML <!DOCTYPE html><html> <head> <title>Bulma Typography</title> <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css'></head> <body class="has-text-centered"> <h1 class="is-size-2 has-text-success"> GeeksforGeeks </h1> <b>Bulma Text weight</b> <br> <div class="container"> <p class="is-size-5 has-text-weight-light">GeeksforGeeks</p> <p class="is-size-5 has-text-weight-normal">GeeksforGeeks</p> <p class="is-size-5 has-text-weight-medium">GeeksforGeeks</p> <p class="is-size-5 has-text-weight-semibold">GeeksforGeeks</p> <p class="is-size-5 has-text-weight-bold">GeeksforGeeks</p> </div></body></html> Output: Bulma Text weight Reference: https://bulma.io/documentation/helpers/typography-helpers/#text-weight Bulma CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? 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 How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 25376, "s": 25348, "text": "\n08 Dec, 2021" }, { "code": null, "e": 25549, "s": 25376, "text": "Bulma text weight class is used to set the text into bold text. There are 5 text weights and you can transform the text weight with the use of one of 5 text weight helpers." }, { "code": null, "e": 25570, "s": 25549, "text": "Text weight classes:" }, { "code": null, "e": 25647, "s": 25570, "text": "has-text-weight-light: This class is used to transform text weight to light." }, { "code": null, "e": 25726, "s": 25647, "text": "has-text-weight-normal: This class is used to transform text weight to normal." }, { "code": null, "e": 25805, "s": 25726, "text": "has-text-weight-medium: This class is used to transform text weight to medium." }, { "code": null, "e": 25889, "s": 25805, "text": "has-text-weight-semibold: This class is used to transform text weight to semi-bold." }, { "code": null, "e": 25964, "s": 25889, "text": "has-text-weight-bold: This class is used to transform text weight to bold." }, { "code": null, "e": 26028, "s": 25964, "text": "Example: Below example illustrate the text size class in Bulma." }, { "code": null, "e": 26033, "s": 26028, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Bulma Typography</title> <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css'></head> <body class=\"has-text-centered\"> <h1 class=\"is-size-2 has-text-success\"> GeeksforGeeks </h1> <b>Bulma Text weight</b> <br> <div class=\"container\"> <p class=\"is-size-5 has-text-weight-light\">GeeksforGeeks</p> <p class=\"is-size-5 has-text-weight-normal\">GeeksforGeeks</p> <p class=\"is-size-5 has-text-weight-medium\">GeeksforGeeks</p> <p class=\"is-size-5 has-text-weight-semibold\">GeeksforGeeks</p> <p class=\"is-size-5 has-text-weight-bold\">GeeksforGeeks</p> </div></body></html>", "e": 26755, "s": 26033, "text": null }, { "code": null, "e": 26764, "s": 26755, "text": "Output: " }, { "code": null, "e": 26783, "s": 26764, "text": "Bulma Text weight " }, { "code": null, "e": 26865, "s": 26783, "text": "Reference: https://bulma.io/documentation/helpers/typography-helpers/#text-weight" }, { "code": null, "e": 26871, "s": 26865, "text": "Bulma" }, { "code": null, "e": 26875, "s": 26871, "text": "CSS" }, { "code": null, "e": 26892, "s": 26875, "text": "Web Technologies" }, { "code": null, "e": 26990, "s": 26892, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26999, "s": 26990, "text": "Comments" }, { "code": null, "e": 27012, "s": 26999, "text": "Old Comments" }, { "code": null, "e": 27049, "s": 27012, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27078, "s": 27049, "text": "Form validation using jQuery" }, { "code": null, "e": 27117, "s": 27078, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 27159, "s": 27117, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 27194, "s": 27159, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 27236, "s": 27194, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27269, "s": 27236, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27312, "s": 27269, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27357, "s": 27312, "text": "Convert a string to an integer in JavaScript" } ]
Largest row-wise and column-wise sorted sub-matrix - GeeksforGeeks
27 Jan, 2022 Given an N * M matrix mat[][], the task is to find the area-wise largest rectangular sub-matrix such that each column and each row of the sub-matrix is strictly increasing. Examples: Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {1, 2, 3}} Output: 6 Largest sub-matrix will be {{1, 2, 3}, {4, 5, 6}}. Number of elements in this sub-matrix = 6. Input: mat[][] = {{1, 2, 3}, {4, 5, 3}, {1, 2, 3}} Output: 4 The largest sub-matrix will be {{1, 2}, {4, 5}} Approach: There are many approaches to solve this problem varying from O(N3 * M3) to O(N * M). In this article, an approach with O(N * M) time complexity using a stack will be discussed. Before proceeding further, its recommended to solve this. problem. Let’s try to understand the approach broadly, then the algorithm will be discussed. For every column of the matrix, try to find the largest row-wise and column-wise sorted sub-matrix having the left edge at this column. To perform the same, create a matrix pre[][] where pre[i][j] will store the length of the longest increasing sub-array starting from the index j of the array arr[i].Now using this matrix, for each column j, find the length of the longest row-wise and column-wise sorted array. To process a column, all the increasing sub-segments of the array pre[][j] will be required. The same can be found using the two-pointer technique. In each of these sub-segments, simply find the largest area under the histogram considering the row-wise increasing sub-segments as bars. Create a prefix-sum array for each row ‘i’, which stores length of the largest increasing sub-array ending at each column ‘j’ of that row. Once we have this array, for each column ‘j’. Initialize ‘i’ equals 0.Run a loop on ‘i’ while ‘i’ is less than ‘N’ Initialize ‘k’ equals i+1.while k less than N and arr[k][j] greater than arr[k-1][j], increment k.Apply histogram problem on the sub-array pre[i][j] to pre[k-1][j], to find the largest area under it. Let us call this value ‘V’. Update final answer as ans = max(ans, val).Update ‘i’ equals k-1. Initialize ‘i’ equals 0. Run a loop on ‘i’ while ‘i’ is less than ‘N’ Initialize ‘k’ equals i+1.while k less than N and arr[k][j] greater than arr[k-1][j], increment k.Apply histogram problem on the sub-array pre[i][j] to pre[k-1][j], to find the largest area under it. Let us call this value ‘V’. Update final answer as ans = max(ans, val).Update ‘i’ equals k-1. Initialize ‘k’ equals i+1. while k less than N and arr[k][j] greater than arr[k-1][j], increment k. Apply histogram problem on the sub-array pre[i][j] to pre[k-1][j], to find the largest area under it. Let us call this value ‘V’. Update final answer as ans = max(ans, val). Update ‘i’ equals k-1. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the largest// area under a histogramint histo(vector<int> q){ // Stack stack<int> q1; // Length of the vector int n = q.size(); // Function to store the next smaller // and previous smaller index int pre_smaller[q.size()]; int next_smaller[q.size()]; // Finding the next smaller for (int i = 0; i < n; i++) pre_smaller[i] = -1, next_smaller[i] = n; for (int i = 0; i < n; i++) { while (q1.size() and q[q1.top()] > q[i]) { next_smaller[q1.top()] = i; q1.pop(); } q1.push(i); } // Finding the previous smaller element while (q1.size()) q1.pop(); for (int i = n - 1; i >= 0; i--) { while (q1.size() and q[q1.top()] > q[i]) { pre_smaller[q1.top()] = i; q1.pop(); } q1.push(i); } // To store the final answer int ans = 0; // Finding the final answer for (int i = 0; i < n; i++) ans = max(ans, (next_smaller[i] - pre_smaller[i] - 1) * q[i]); // Returning the final answer return ans;} // Function to return the largest area// for the required submatrixint findLargest(vector<vector<int> > arr){ // n and m store the number of // rows and columns respectively int n = arr.size(); int m = arr[0].size(); // To store the prefix_sum int pre[n][m]; // To store the final answer int ans = 0; // Loop to create the prefix-sum // using two pointers for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { if (j == 0) { pre[i][j] = 1; continue; } if (arr[i][j] > arr[i][j - 1]) pre[i][j] = pre[i][j - 1] + 1; else pre[i][j] = 1; } // For each column run the loop for (int j = 0; j < m; j++) { // Find the largest row-wise sorted arrays for (int i = 0; i < n; i++) { int k = i + 1; vector<int> q; q.push_back(pre[i][j]); while (k < n and arr[k] > arr[k - 1]) q.push_back(pre[k][j]), k++; // Applying the largest area // under the histogram ans = max(ans, histo(q)); i = k - 1; } } // Return the final answer return ans;} // Driver codeint main(){ vector<vector<int> > arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 1, 2, 3 } }; cout << findLargest(arr); return 0;} // Java implementation of the approachimport java.io.*;import java.util.*;class GFG{ // Function to return the largest // area under a histogram static int histo(ArrayList<Integer> q) { // Stack Stack<Integer> q1 = new Stack<Integer>(); // Length of the vector int n = q.size(); // Function to store the next smaller // and previous smaller index int[] pre_smaller = new int[q.size()]; int[] next_smaller = new int[q.size()]; // Finding the next smaller for (int i = 0; i < n; i++) { pre_smaller[i] = -1; next_smaller[i] = n; } for (int i = 0; i < n; i++) { while (q1.size() > 0 && q.get(q1.peek()) > q.get(i)) { next_smaller[q1.peek()] = i; q1.pop(); } q1.push(i); } // Finding the previous smaller element while (q1.size() > 0) { q1.pop(); } for (int i = n - 1; i >= 0; i--) { while (q1.size() > 0 && q.get(q1.peek()) > q.get(i)) { pre_smaller[q1.peek()] = i; q1.pop(); } q1.push(i); } // To store the final answer int ans = 0; // Finding the final answer for (int i = 0; i < n; i++) { ans = Math.max(ans, (next_smaller[i] - pre_smaller[i] - 1) * q.get(i)); } // Returning the final answer return ans; } // Function to return the largest area // for the required submatrix static int findLargest(ArrayList<ArrayList<Integer>> arr) { // n and m store the number of // rows and columns respectively int n = arr.size(); int m = arr.get(0).size(); // To store the prefix_sum int[][] pre=new int[n][m]; // To store the final answer int ans = 0; // Loop to create the prefix-sum // using two pointers for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (j == 0) { pre[i][j] = 1; continue; } if(arr.get(i).get(j) > arr.get(i).get(j - 1)) { pre[i][j] = pre[i][j - 1] + 1; } else { pre[i][j] = 1; } } } // For each column run the loop for (int j = 0; j < m; j++) { // Find the largest row-wise sorted arrays for (int i = 0; i < n; i++) { int k = i + 1; ArrayList<Integer> q = new ArrayList<Integer>(); q.add(pre[i][j]); while (k < n && arr.get(k).get(0) > arr.get(k - 1).get(0)) { q.add(pre[k][j]); k++; } // Applying the largest area // under the histogram ans = Math.max(ans, histo(q)); i = k - 1; } } // Return the final answer return ans; } // Driver code public static void main (String[] args) { ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>(); arr.add(new ArrayList<Integer>(Arrays.asList(1, 2, 3 ))); arr.add(new ArrayList<Integer>(Arrays.asList(4, 5, 6 ))); arr.add(new ArrayList<Integer>(Arrays.asList(1, 2, 3 ))); System.out.println(findLargest(arr)); }} // This code is contributed by avanitrachhadiya2155 # Python3 implementation of the approach # Function to return the largest# area under a histogramdef histo(q): # Stack q1 = [] # Length of the vector n = len(q) # Function to store the next smaller # and previous smaller index pre_smaller = [0 for i in range(len(q))] next_smaller = [0 for i in range(len(q))] # Finding the next smaller for i in range(n): pre_smaller[i] = -1 next_smaller[i] = n for i in range(n): while (len(q1) > 0 and q[q1[-1]] > q[i]): next_smaller[q1[-1]] = i del q1[-1] q1.append(i) # Finding the previous smaller element while (len(q1) > 0): del q1[-1] for i in range(n - 1, -1, -1): while (len(q1) > 0 and q[q1[-1]] > q[i]): pre_smaller[q1[-1]] = i del q1[-1] q1.append(i) # To store the final answer ans = 0 # Finding the final answer for i in range(n): ans = max(ans, (next_smaller[i]- pre_smaller[i] - 1)* q[i]) # Returning the final answer return ans # Function to return the largest area# for the required submatrixdef findLargest(arr): # n and m store the number of # rows and columns respectively n = len(arr) m = len(arr[0]) # To store the prefix_sum pre = [[0 for i in range(m)] for i in range(n)] # To store the final answer ans = 0 # Loop to create the prefix-sum # using two pointers for i in range(n): for j in range(m): if (j == 0): pre[i][j] = 1 continue if (arr[i][j] > arr[i][j - 1]): pre[i][j] = pre[i][j - 1] + 1 else: pre[i][j] = 1 # For each column run the loop for j in range(m): # Find the largest row-wise sorted arrays for i in range(n): k = i + 1 q = [] q.append(pre[i][j]) while (k < n and arr[k] > arr[k - 1]): q.append(pre[k][j]) k += 1 # Applying the largest area # under the histogram ans = max(ans, histo(q)) i = k - 1 # Return the final answer return ans # Driver code arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 1, 2, 3 ] ] print(findLargest(arr)) # This code is contributed by mohit kumar 29 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the largest// area under a histogramstatic int histo(List<int> q){ // Stack Stack<int> q1 = new Stack<int>(); // Length of the vector int n = q.Count; // Function to store the next smaller // and previous smaller index int[] pre_smaller = new int[q.Count]; int[] next_smaller = new int[q.Count]; // Finding the next smaller for(int i = 0; i < n; i++) { pre_smaller[i] = -1; next_smaller[i] = n; } for(int i = 0; i < n; i++) { while (q1.Count > 0 && q[q1.Peek()] > q[i]) { next_smaller[q1.Peek()] = i; q1.Pop(); } q1.Push(i); } // Finding the previous smaller element while (q1.Count > 0) { q1.Pop(); } for(int i = n - 1; i >= 0; i--) { while (q1.Count > 0 && q[q1.Peek()] > q[i]) { pre_smaller[q1.Peek()] = i; q1.Pop(); } q1.Push(i); } // To store the final answer int ans = 0; // Finding the final answer for(int i = 0; i < n; i++) { ans = Math.Max(ans, (next_smaller[i] - pre_smaller[i] - 1) * q[i]); } // Returning the // final answer return ans;} // Function to return the largest area// for the required submatrixstatic int findLargest(List<List<int>> arr){ // n and m store the number of // rows and columns respectively int n = arr.Count; int m = arr[0].Count; // To store the prefix_sum int[,] pre = new int[n, m]; // To store the final answer int ans = 0; // Loop to create the prefix-sum // using two pointers for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if (j == 0) { pre[i, j] = 1; continue; } if (arr[i][j] > arr[i][j - 1]) { pre[i, j] = pre[i,j - 1] + 1; } else { pre[i, j] = 1; } } } // For each column run the loop for(int j = 0; j < m; j++) { // Find the largest row-wise sorted arrays for(int i = 0; i < n; i++) { int k = i + 1; List<int> q = new List<int>(); q.Add(pre[i, j]); while(k < n && arr[k][0] > arr[k - 1][0]) { q.Add(pre[k, j]); k++; } // Applying the largest area // under the histogram ans = Math.Max(ans, histo(q)); i = k - 1; } } // Return the final answer return ans;} // Driver codestatic public void Main(){ List<List<int>> arr = new List<List<int>>(); arr.Add(new List<int>(){1, 2, 3}); arr.Add(new List<int>(){4, 5, 6 }); arr.Add(new List<int>(){1, 2, 3}); Console.WriteLine(findLargest(arr));}} // This code is contributed by rag2127 <script>// Javascript implementation of the approach // Function to return the largest // area under a histogramfunction histo(q){ // Stack let q1 = []; // Length of the vector let n = q.length; // Function to store the next smaller // and previous smaller index let pre_smaller = new Array(q.length); let next_smaller = new Array(q.length); // Finding the next smaller for (let i = 0; i < n; i++) { pre_smaller[i] = -1; next_smaller[i] = n; } for (let i = 0; i < n; i++) { while (q1.length > 0 && q[q1[q1.length-1]] > q[i]) { next_smaller[q1[q1.length-1]] = i; q1.pop(); } q1.push(i); } // Finding the previous smaller element while (q1.length > 0) { q1.pop(); } for (let i = n - 1; i >= 0; i--) { while (q1.length > 0 && q[q1[q1.length-1]] > q[i]) { pre_smaller[q1[q1.length-1]] = i; q1.pop(); } q1.push(i); } // To store the final answer let ans = 0; // Finding the final answer for (let i = 0; i < n; i++) { ans = Math.max(ans, (next_smaller[i] - pre_smaller[i] - 1) * q[i]); } // Returning the final answer return ans;} // Function to return the largest area // for the required submatrixfunction findLargest(arr){ // n and m store the number of // rows and columns respectively let n = arr.length; let m = arr[0].length; // To store the prefix_sum let pre=new Array(n); for(let i=0;i<n;i++) { pre[i]=new Array(m); for(let j=0;j<m;j++) { pre[i][j]=0; } } // To store the final answer let ans = 0; // Loop to create the prefix-sum // using two pointers for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { if (j == 0) { pre[i][j] = 1; continue; } if(arr[i][j] > arr[i][j - 1]) { pre[i][j] = pre[i][j - 1] + 1; } else { pre[i][j] = 1; } } } // For each column run the loop for (let j = 0; j < m; j++) { // Find the largest row-wise sorted arrays for (let i = 0; i < n; i++) { let k = i + 1; let q = []; q.push(pre[i][j]); while (k < n && arr[k][0] > arr[k - 1][0]) { q.push(pre[k][j]); k++; } // Applying the largest area // under the histogram ans = Math.max(ans, histo(q)); i = k - 1; } } // Return the final answer return ans;} // Driver codelet arr=[[1, 2, 3],[4, 5, 6 ],[1, 2, 3]];document.write(findLargest(arr)); // This code is contributed by patel2127</script> 6 Time Complexity: O(N2)Auxiliary Space: O(N2). mohit kumar 29 avanitrachhadiya2155 rag2127 khushboogoyal499 patel2127 gabaa406 pankajsharmagfg surinderdawra388 media.net submatrix Data Structures Matrix Stack Data Structures Stack Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Tree Data Structure TCS NQT Coding Sheet Program to implement Singly Linked List in C++ using class Hash Functions and list/types of Hash functions Static Data Structure vs Dynamic Data Structure Matrix Chain Multiplication | DP-8 Program to find largest element in an array Print a given matrix in spiral form Sudoku | Backtracking-7 Rat in a Maze | Backtracking-2
[ { "code": null, "e": 24974, "s": 24946, "text": "\n27 Jan, 2022" }, { "code": null, "e": 25148, "s": 24974, "text": "Given an N * M matrix mat[][], the task is to find the area-wise largest rectangular sub-matrix such that each column and each row of the sub-matrix is strictly increasing. " }, { "code": null, "e": 25160, "s": 25148, "text": "Examples: " }, { "code": null, "e": 25315, "s": 25160, "text": "Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {1, 2, 3}} Output: 6 Largest sub-matrix will be {{1, 2, 3}, {4, 5, 6}}. Number of elements in this sub-matrix = 6." }, { "code": null, "e": 25425, "s": 25315, "text": "Input: mat[][] = {{1, 2, 3}, {4, 5, 3}, {1, 2, 3}} Output: 4 The largest sub-matrix will be {{1, 2}, {4, 5}} " }, { "code": null, "e": 25679, "s": 25425, "text": "Approach: There are many approaches to solve this problem varying from O(N3 * M3) to O(N * M). In this article, an approach with O(N * M) time complexity using a stack will be discussed. Before proceeding further, its recommended to solve this. problem." }, { "code": null, "e": 26463, "s": 25679, "text": "Let’s try to understand the approach broadly, then the algorithm will be discussed. For every column of the matrix, try to find the largest row-wise and column-wise sorted sub-matrix having the left edge at this column. To perform the same, create a matrix pre[][] where pre[i][j] will store the length of the longest increasing sub-array starting from the index j of the array arr[i].Now using this matrix, for each column j, find the length of the longest row-wise and column-wise sorted array. To process a column, all the increasing sub-segments of the array pre[][j] will be required. The same can be found using the two-pointer technique. In each of these sub-segments, simply find the largest area under the histogram considering the row-wise increasing sub-segments as bars. " }, { "code": null, "e": 26602, "s": 26463, "text": "Create a prefix-sum array for each row ‘i’, which stores length of the largest increasing sub-array ending at each column ‘j’ of that row." }, { "code": null, "e": 27011, "s": 26602, "text": "Once we have this array, for each column ‘j’. Initialize ‘i’ equals 0.Run a loop on ‘i’ while ‘i’ is less than ‘N’ Initialize ‘k’ equals i+1.while k less than N and arr[k][j] greater than arr[k-1][j], increment k.Apply histogram problem on the sub-array pre[i][j] to pre[k-1][j], to find the largest area under it. Let us call this value ‘V’. Update final answer as ans = max(ans, val).Update ‘i’ equals k-1." }, { "code": null, "e": 27036, "s": 27011, "text": "Initialize ‘i’ equals 0." }, { "code": null, "e": 27375, "s": 27036, "text": "Run a loop on ‘i’ while ‘i’ is less than ‘N’ Initialize ‘k’ equals i+1.while k less than N and arr[k][j] greater than arr[k-1][j], increment k.Apply histogram problem on the sub-array pre[i][j] to pre[k-1][j], to find the largest area under it. Let us call this value ‘V’. Update final answer as ans = max(ans, val).Update ‘i’ equals k-1." }, { "code": null, "e": 27402, "s": 27375, "text": "Initialize ‘k’ equals i+1." }, { "code": null, "e": 27475, "s": 27402, "text": "while k less than N and arr[k][j] greater than arr[k-1][j], increment k." }, { "code": null, "e": 27649, "s": 27475, "text": "Apply histogram problem on the sub-array pre[i][j] to pre[k-1][j], to find the largest area under it. Let us call this value ‘V’. Update final answer as ans = max(ans, val)." }, { "code": null, "e": 27672, "s": 27649, "text": "Update ‘i’ equals k-1." }, { "code": null, "e": 27725, "s": 27672, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27729, "s": 27725, "text": "C++" }, { "code": null, "e": 27734, "s": 27729, "text": "Java" }, { "code": null, "e": 27742, "s": 27734, "text": "Python3" }, { "code": null, "e": 27745, "s": 27742, "text": "C#" }, { "code": null, "e": 27756, "s": 27745, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the largest// area under a histogramint histo(vector<int> q){ // Stack stack<int> q1; // Length of the vector int n = q.size(); // Function to store the next smaller // and previous smaller index int pre_smaller[q.size()]; int next_smaller[q.size()]; // Finding the next smaller for (int i = 0; i < n; i++) pre_smaller[i] = -1, next_smaller[i] = n; for (int i = 0; i < n; i++) { while (q1.size() and q[q1.top()] > q[i]) { next_smaller[q1.top()] = i; q1.pop(); } q1.push(i); } // Finding the previous smaller element while (q1.size()) q1.pop(); for (int i = n - 1; i >= 0; i--) { while (q1.size() and q[q1.top()] > q[i]) { pre_smaller[q1.top()] = i; q1.pop(); } q1.push(i); } // To store the final answer int ans = 0; // Finding the final answer for (int i = 0; i < n; i++) ans = max(ans, (next_smaller[i] - pre_smaller[i] - 1) * q[i]); // Returning the final answer return ans;} // Function to return the largest area// for the required submatrixint findLargest(vector<vector<int> > arr){ // n and m store the number of // rows and columns respectively int n = arr.size(); int m = arr[0].size(); // To store the prefix_sum int pre[n][m]; // To store the final answer int ans = 0; // Loop to create the prefix-sum // using two pointers for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { if (j == 0) { pre[i][j] = 1; continue; } if (arr[i][j] > arr[i][j - 1]) pre[i][j] = pre[i][j - 1] + 1; else pre[i][j] = 1; } // For each column run the loop for (int j = 0; j < m; j++) { // Find the largest row-wise sorted arrays for (int i = 0; i < n; i++) { int k = i + 1; vector<int> q; q.push_back(pre[i][j]); while (k < n and arr[k] > arr[k - 1]) q.push_back(pre[k][j]), k++; // Applying the largest area // under the histogram ans = max(ans, histo(q)); i = k - 1; } } // Return the final answer return ans;} // Driver codeint main(){ vector<vector<int> > arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 1, 2, 3 } }; cout << findLargest(arr); return 0;}", "e": 30402, "s": 27756, "text": null }, { "code": "// Java implementation of the approachimport java.io.*;import java.util.*;class GFG{ // Function to return the largest // area under a histogram static int histo(ArrayList<Integer> q) { // Stack Stack<Integer> q1 = new Stack<Integer>(); // Length of the vector int n = q.size(); // Function to store the next smaller // and previous smaller index int[] pre_smaller = new int[q.size()]; int[] next_smaller = new int[q.size()]; // Finding the next smaller for (int i = 0; i < n; i++) { pre_smaller[i] = -1; next_smaller[i] = n; } for (int i = 0; i < n; i++) { while (q1.size() > 0 && q.get(q1.peek()) > q.get(i)) { next_smaller[q1.peek()] = i; q1.pop(); } q1.push(i); } // Finding the previous smaller element while (q1.size() > 0) { q1.pop(); } for (int i = n - 1; i >= 0; i--) { while (q1.size() > 0 && q.get(q1.peek()) > q.get(i)) { pre_smaller[q1.peek()] = i; q1.pop(); } q1.push(i); } // To store the final answer int ans = 0; // Finding the final answer for (int i = 0; i < n; i++) { ans = Math.max(ans, (next_smaller[i] - pre_smaller[i] - 1) * q.get(i)); } // Returning the final answer return ans; } // Function to return the largest area // for the required submatrix static int findLargest(ArrayList<ArrayList<Integer>> arr) { // n and m store the number of // rows and columns respectively int n = arr.size(); int m = arr.get(0).size(); // To store the prefix_sum int[][] pre=new int[n][m]; // To store the final answer int ans = 0; // Loop to create the prefix-sum // using two pointers for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (j == 0) { pre[i][j] = 1; continue; } if(arr.get(i).get(j) > arr.get(i).get(j - 1)) { pre[i][j] = pre[i][j - 1] + 1; } else { pre[i][j] = 1; } } } // For each column run the loop for (int j = 0; j < m; j++) { // Find the largest row-wise sorted arrays for (int i = 0; i < n; i++) { int k = i + 1; ArrayList<Integer> q = new ArrayList<Integer>(); q.add(pre[i][j]); while (k < n && arr.get(k).get(0) > arr.get(k - 1).get(0)) { q.add(pre[k][j]); k++; } // Applying the largest area // under the histogram ans = Math.max(ans, histo(q)); i = k - 1; } } // Return the final answer return ans; } // Driver code public static void main (String[] args) { ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>(); arr.add(new ArrayList<Integer>(Arrays.asList(1, 2, 3 ))); arr.add(new ArrayList<Integer>(Arrays.asList(4, 5, 6 ))); arr.add(new ArrayList<Integer>(Arrays.asList(1, 2, 3 ))); System.out.println(findLargest(arr)); }} // This code is contributed by avanitrachhadiya2155", "e": 33500, "s": 30402, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the largest# area under a histogramdef histo(q): # Stack q1 = [] # Length of the vector n = len(q) # Function to store the next smaller # and previous smaller index pre_smaller = [0 for i in range(len(q))] next_smaller = [0 for i in range(len(q))] # Finding the next smaller for i in range(n): pre_smaller[i] = -1 next_smaller[i] = n for i in range(n): while (len(q1) > 0 and q[q1[-1]] > q[i]): next_smaller[q1[-1]] = i del q1[-1] q1.append(i) # Finding the previous smaller element while (len(q1) > 0): del q1[-1] for i in range(n - 1, -1, -1): while (len(q1) > 0 and q[q1[-1]] > q[i]): pre_smaller[q1[-1]] = i del q1[-1] q1.append(i) # To store the final answer ans = 0 # Finding the final answer for i in range(n): ans = max(ans, (next_smaller[i]- pre_smaller[i] - 1)* q[i]) # Returning the final answer return ans # Function to return the largest area# for the required submatrixdef findLargest(arr): # n and m store the number of # rows and columns respectively n = len(arr) m = len(arr[0]) # To store the prefix_sum pre = [[0 for i in range(m)] for i in range(n)] # To store the final answer ans = 0 # Loop to create the prefix-sum # using two pointers for i in range(n): for j in range(m): if (j == 0): pre[i][j] = 1 continue if (arr[i][j] > arr[i][j - 1]): pre[i][j] = pre[i][j - 1] + 1 else: pre[i][j] = 1 # For each column run the loop for j in range(m): # Find the largest row-wise sorted arrays for i in range(n): k = i + 1 q = [] q.append(pre[i][j]) while (k < n and arr[k] > arr[k - 1]): q.append(pre[k][j]) k += 1 # Applying the largest area # under the histogram ans = max(ans, histo(q)) i = k - 1 # Return the final answer return ans # Driver code arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 1, 2, 3 ] ] print(findLargest(arr)) # This code is contributed by mohit kumar 29", "e": 35812, "s": 33500, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the largest// area under a histogramstatic int histo(List<int> q){ // Stack Stack<int> q1 = new Stack<int>(); // Length of the vector int n = q.Count; // Function to store the next smaller // and previous smaller index int[] pre_smaller = new int[q.Count]; int[] next_smaller = new int[q.Count]; // Finding the next smaller for(int i = 0; i < n; i++) { pre_smaller[i] = -1; next_smaller[i] = n; } for(int i = 0; i < n; i++) { while (q1.Count > 0 && q[q1.Peek()] > q[i]) { next_smaller[q1.Peek()] = i; q1.Pop(); } q1.Push(i); } // Finding the previous smaller element while (q1.Count > 0) { q1.Pop(); } for(int i = n - 1; i >= 0; i--) { while (q1.Count > 0 && q[q1.Peek()] > q[i]) { pre_smaller[q1.Peek()] = i; q1.Pop(); } q1.Push(i); } // To store the final answer int ans = 0; // Finding the final answer for(int i = 0; i < n; i++) { ans = Math.Max(ans, (next_smaller[i] - pre_smaller[i] - 1) * q[i]); } // Returning the // final answer return ans;} // Function to return the largest area// for the required submatrixstatic int findLargest(List<List<int>> arr){ // n and m store the number of // rows and columns respectively int n = arr.Count; int m = arr[0].Count; // To store the prefix_sum int[,] pre = new int[n, m]; // To store the final answer int ans = 0; // Loop to create the prefix-sum // using two pointers for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if (j == 0) { pre[i, j] = 1; continue; } if (arr[i][j] > arr[i][j - 1]) { pre[i, j] = pre[i,j - 1] + 1; } else { pre[i, j] = 1; } } } // For each column run the loop for(int j = 0; j < m; j++) { // Find the largest row-wise sorted arrays for(int i = 0; i < n; i++) { int k = i + 1; List<int> q = new List<int>(); q.Add(pre[i, j]); while(k < n && arr[k][0] > arr[k - 1][0]) { q.Add(pre[k, j]); k++; } // Applying the largest area // under the histogram ans = Math.Max(ans, histo(q)); i = k - 1; } } // Return the final answer return ans;} // Driver codestatic public void Main(){ List<List<int>> arr = new List<List<int>>(); arr.Add(new List<int>(){1, 2, 3}); arr.Add(new List<int>(){4, 5, 6 }); arr.Add(new List<int>(){1, 2, 3}); Console.WriteLine(findLargest(arr));}} // This code is contributed by rag2127", "e": 38916, "s": 35812, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the largest // area under a histogramfunction histo(q){ // Stack let q1 = []; // Length of the vector let n = q.length; // Function to store the next smaller // and previous smaller index let pre_smaller = new Array(q.length); let next_smaller = new Array(q.length); // Finding the next smaller for (let i = 0; i < n; i++) { pre_smaller[i] = -1; next_smaller[i] = n; } for (let i = 0; i < n; i++) { while (q1.length > 0 && q[q1[q1.length-1]] > q[i]) { next_smaller[q1[q1.length-1]] = i; q1.pop(); } q1.push(i); } // Finding the previous smaller element while (q1.length > 0) { q1.pop(); } for (let i = n - 1; i >= 0; i--) { while (q1.length > 0 && q[q1[q1.length-1]] > q[i]) { pre_smaller[q1[q1.length-1]] = i; q1.pop(); } q1.push(i); } // To store the final answer let ans = 0; // Finding the final answer for (let i = 0; i < n; i++) { ans = Math.max(ans, (next_smaller[i] - pre_smaller[i] - 1) * q[i]); } // Returning the final answer return ans;} // Function to return the largest area // for the required submatrixfunction findLargest(arr){ // n and m store the number of // rows and columns respectively let n = arr.length; let m = arr[0].length; // To store the prefix_sum let pre=new Array(n); for(let i=0;i<n;i++) { pre[i]=new Array(m); for(let j=0;j<m;j++) { pre[i][j]=0; } } // To store the final answer let ans = 0; // Loop to create the prefix-sum // using two pointers for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { if (j == 0) { pre[i][j] = 1; continue; } if(arr[i][j] > arr[i][j - 1]) { pre[i][j] = pre[i][j - 1] + 1; } else { pre[i][j] = 1; } } } // For each column run the loop for (let j = 0; j < m; j++) { // Find the largest row-wise sorted arrays for (let i = 0; i < n; i++) { let k = i + 1; let q = []; q.push(pre[i][j]); while (k < n && arr[k][0] > arr[k - 1][0]) { q.push(pre[k][j]); k++; } // Applying the largest area // under the histogram ans = Math.max(ans, histo(q)); i = k - 1; } } // Return the final answer return ans;} // Driver codelet arr=[[1, 2, 3],[4, 5, 6 ],[1, 2, 3]];document.write(findLargest(arr)); // This code is contributed by patel2127</script>", "e": 41683, "s": 38916, "text": null }, { "code": null, "e": 41685, "s": 41683, "text": "6" }, { "code": null, "e": 41734, "s": 41687, "text": "Time Complexity: O(N2)Auxiliary Space: O(N2). " }, { "code": null, "e": 41749, "s": 41734, "text": "mohit kumar 29" }, { "code": null, "e": 41770, "s": 41749, "text": "avanitrachhadiya2155" }, { "code": null, "e": 41778, "s": 41770, "text": "rag2127" }, { "code": null, "e": 41795, "s": 41778, "text": "khushboogoyal499" }, { "code": null, "e": 41805, "s": 41795, "text": "patel2127" }, { "code": null, "e": 41814, "s": 41805, "text": "gabaa406" }, { "code": null, "e": 41830, "s": 41814, "text": "pankajsharmagfg" }, { "code": null, "e": 41847, "s": 41830, "text": "surinderdawra388" }, { "code": null, "e": 41857, "s": 41847, "text": "media.net" }, { "code": null, "e": 41867, "s": 41857, "text": "submatrix" }, { "code": null, "e": 41883, "s": 41867, "text": "Data Structures" }, { "code": null, "e": 41890, "s": 41883, "text": "Matrix" }, { "code": null, "e": 41896, "s": 41890, "text": "Stack" }, { "code": null, "e": 41912, "s": 41896, "text": "Data Structures" }, { "code": null, "e": 41918, "s": 41912, "text": "Stack" }, { "code": null, "e": 41925, "s": 41918, "text": "Matrix" }, { "code": null, "e": 42023, "s": 41925, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42032, "s": 42023, "text": "Comments" }, { "code": null, "e": 42045, "s": 42032, "text": "Old Comments" }, { "code": null, "e": 42081, "s": 42045, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 42102, "s": 42081, "text": "TCS NQT Coding Sheet" }, { "code": null, "e": 42161, "s": 42102, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 42209, "s": 42161, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 42257, "s": 42209, "text": "Static Data Structure vs Dynamic Data Structure" }, { "code": null, "e": 42292, "s": 42257, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 42336, "s": 42292, "text": "Program to find largest element in an array" }, { "code": null, "e": 42372, "s": 42336, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 42396, "s": 42372, "text": "Sudoku | Backtracking-7" } ]
Deep dive into multi-label classification..! (With detailed Case Study) | by Kartik Nooney | Towards Data Science
With continuous increase in available data, there is a pressing need to organize it and modern classification problems often involve the prediction of multiple labels simultaneously associated with a single instance. Known as Multi-Label Classification, it is one such task which is omnipresent in many real world problems. In this project, using a Kaggle problem as example, we explore different aspects of multi-label classification. DISCLAIMER FROM THE DATA SOURCE: the dataset contains text that may be considered profane, vulgar, or offensive. Part-1: Overview of multi-label classification. Part-2: Problem definition & evaluation metrics. Part-3: Exploratory data analysis (EDA). Part-4: Data pre-processing. Part-5: Multi-label classification techniques. Multi-label classification originated from the investigation of text categorisation problem, where each document may belong to several predefined topics simultaneously. Multi-label classification of textual data is an important problem. Examples range from news articles to emails. For instance, this can be employed to find the genres that a movie belongs to, based on the summary of its plot. Or multi-label classification of genres based on movie posters. (This enters the realm of computer vision.) In multi-label classification, the training set is composed of instances each associated with a set of labels, and the task is to predict the label sets of unseen instances through analyzing training instances with known label sets. Difference between multi-class classification & multi-label classification is that in multi-class problems the classes are mutually exclusive, whereas for multi-label problems each label represents a different classification task, but the tasks are somehow related. For example, multi-class classification makes the assumption that each sample is assigned to one and only one label: a fruit can be either an apple or a pear but not both at the same time. Whereas, an instance of multi-label classification can be that a text might be about any of religion, politics, finance or education at the same time or none of these. Toxic comment classification is a multi-label text classification problem with a highly imbalanced dataset. We’re challenged to build a multi-labeld model that’s capable of detecting different types of toxicity like threats, obscenity, insults, and identity-based hate. We need to create a model which predicts a probability of each type of toxicity for each comment. Kaggle link to this problem can be found here. Note: Initially evaluation metric in the Kaggle challenge was Log-Loss, which was later changed to AUC. But in this post we throw light on other evaluation metrics as well. The evaluation measures for single-label are usually different than for multi-label. Here in single-label classfication we use simple metrics such as precision, recall, accuracy, etc,. Say, in single-label classification, accuracy is just: In multi-label classification, a misclassification is no longer a hard wrong or right. A prediction containing a subset of the actual classes should be considered better than a prediction that contains none of them, i.e., predicting two of the three labels correctly this is better than predicting no labels at all. To measure a multi-class classifier we have to average out the classes somehow. There are two different methods of doing this called micro-averaging and macro-averaging. In micro-averaging all TPs, TNs, FPs and FNs for each class are summed up and then the average is taken. In micro-averaging method, you sum up the individual true positives, false positives, and false negatives of the system for different sets and the apply them. And the micro-average F1-Score will be simply the harmonic mean of above two equations. Macro-averaging is straight forward. We just take the average of the precision and recall of the system on different sets. Macro-averaging method can be used when you want to know how the system performs overall across the sets of data. You should not come up with any specific decision with this average. On the other hand, micro-averaging can be a useful measure when your dataset varies in size. In simplest of terms, Hamming-Loss is the fraction of labels that are incorrectly predicted, i.e., the fraction of the wrong labels to the total number of labels. It is the most strict metric, indicating the percentage of samples that have all their labels classified correctly. The disadvantage of this measure is that multi-class classification problems have a chance of being partially correct, but here we ignore those partially correct matches. There is a function in scikit-learn which implements subset accuracy, called as accuracy_score. Note: We will be using accuracy_score function to evaluate all our models in this project. Exploratory Data Analysis is one of the important steps in the data analysis process. Here, the focus is on making sense of the data in hand — things like formulating the correct questions to ask to your dataset, how to manipulate the data sources to get the required answers, and others. First let us import the necessary libraries. import osimport csvimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns Next we load the data from csv files into a pandas dataframe and check its attributes. data_path = "/Users/kartik/Desktop/AAIC/Projects/jigsaw-toxic-comment-classification-challenge/data/train.csv"data_raw = pd.read_csv(data_path)print("Number of rows in data =",data_raw.shape[0])print("Number of columns in data =",data_raw.shape[1])print("\n")print("**Sample data:**")data_raw.head() Now we count the number of comments under each label. (For detailed code, please refer to the GitHub link of this project.) categories = list(data_raw.columns.values)sns.set(font_scale = 2)plt.figure(figsize=(15,8))ax= sns.barplot(categories, data_raw.iloc[:,2:].sum().values)plt.title("Comments in each category", fontsize=24)plt.ylabel('Number of comments', fontsize=18)plt.xlabel('Comment Type ', fontsize=18)#adding the text labelsrects = ax.patcheslabels = data_raw.iloc[:,2:].sum().valuesfor rect, label in zip(rects, labels): height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2, height + 5, label, ha='center', va='bottom', fontsize=18)plt.show() Counting the number of comments having multiple labels. rowSums = data_raw.iloc[:,2:].sum(axis=1)multiLabel_counts = rowSums.value_counts()multiLabel_counts = multiLabel_counts.iloc[1:]sns.set(font_scale = 2)plt.figure(figsize=(15,8))ax = sns.barplot(multiLabel_counts.index, multiLabel_counts.values)plt.title("Comments having multiple labels ")plt.ylabel('Number of comments', fontsize=18)plt.xlabel('Number of labels', fontsize=18)#adding the text labelsrects = ax.patcheslabels = multiLabel_counts.valuesfor rect, label in zip(rects, labels): height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2, height + 5, label, ha='center', va='bottom')plt.show() WordCloud representation of most used words in each category of comments. from wordcloud import WordCloud,STOPWORDSplt.figure(figsize=(40,25))# cleansubset = data_raw[data_raw.clean==True]text = subset.comment_text.valuescloud_toxic = WordCloud( stopwords=STOPWORDS, background_color='black', collocations=False, width=2500, height=1800 ).generate(" ".join(text))plt.axis('off')plt.title("Clean",fontsize=40)plt.imshow(cloud_clean)# Same code can be used to generate wordclouds of other categories. We first convert the comments to lower-case and then use custom made functions to remove html-tags, punctuation and non-alphabetic characters from the comments. import nltkfrom nltk.corpus import stopwordsfrom nltk.stem.snowball import SnowballStemmerimport reimport sysimport warningsdata = data_rawif not sys.warnoptions: warnings.simplefilter("ignore")def cleanHtml(sentence): cleanr = re.compile('<.*?>') cleantext = re.sub(cleanr, ' ', str(sentence)) return cleantextdef cleanPunc(sentence): #function to clean the word of any punctuation or special characters cleaned = re.sub(r'[?|!|\'|"|#]',r'',sentence) cleaned = re.sub(r'[.|,|)|(|\|/]',r' ',cleaned) cleaned = cleaned.strip() cleaned = cleaned.replace("\n"," ") return cleaneddef keepAlpha(sentence): alpha_sent = "" for word in sentence.split(): alpha_word = re.sub('[^a-z A-Z]+', ' ', word) alpha_sent += alpha_word alpha_sent += " " alpha_sent = alpha_sent.strip() return alpha_sentdata['comment_text'] = data['comment_text'].str.lower()data['comment_text'] = data['comment_text'].apply(cleanHtml)data['comment_text'] = data['comment_text'].apply(cleanPunc)data['comment_text'] = data['comment_text'].apply(keepAlpha) Next we remove all the stop-words present in the comments using the default set of stop-words that can be downloaded from NLTK library. We also add few stop-words to the standard list. Stop words are basically a set of commonly used words in any language, not just English. The reason why stop words are critical to many applications is that, if we remove the words that are very commonly used in a given language, we can focus on the important words instead. stop_words = set(stopwords.words('english'))stop_words.update(['zero','one','two','three','four','five','six','seven','eight','nine','ten','may','also','across','among','beside','however','yet','within'])re_stop_words = re.compile(r"\b(" + "|".join(stop_words) + ")\\W", re.I)def removeStopWords(sentence): global re_stop_words return re_stop_words.sub(" ", sentence)data['comment_text'] = data['comment_text'].apply(removeStopWords) Next we do stemming. There exist different kinds of stemming which basically transform words with roughly the same semantics to one standard form. For example, for amusing, amusement, and amused, the stem would be amus. stemmer = SnowballStemmer("english")def stemming(sentence): stemSentence = "" for word in sentence.split(): stem = stemmer.stem(word) stemSentence += stem stemSentence += " " stemSentence = stemSentence.strip() return stemSentencedata['comment_text'] = data['comment_text'].apply(stemming) After splitting the dataset into train & test sets, we want to summarize our comments and convert them into numerical vectors. One technique is to pick the most frequently occurring terms (words with high term frequency or tf). However, the most frequent word is a less useful metric since some words like ‘this’, ‘a’ occur very frequently across all documents. Hence, we also want a measure of how unique a word is i.e. how infrequently the word occurs across all documents (inverse document frequency or idf). So, the product of tf & idf (TF-IDF) of a word gives a product of how frequent this word is in the document multiplied by how unique the word is w.r.t. the entire corpus of documents. Words in the document with a high tfidf score occur frequently in the document and provide the most information about that specific document. from sklearn.model_selection import train_test_splittrain, test = train_test_split(data, random_state=42, test_size=0.30, shuffle=True)from sklearn.feature_extraction.text import TfidfVectorizervectorizer = TfidfVectorizer(strip_accents='unicode', analyzer='word', ngram_range=(1,3), norm='l2')vectorizer.fit(train_text)vectorizer.fit(test_text)x_train = vectorizer.transform(train_text)y_train = train.drop(labels = ['id','comment_text'], axis=1)x_test = vectorizer.transform(test_text)y_test = test.drop(labels = ['id','comment_text'], axis=1) TF-IDF is easy to compute but its disadvantage is that it does not capture position in text, semantics, co-occurrences in different documents, etc. Most traditional learning algorithms are developed for single-label classification problems. Therefore a lot of approaches in the literature transform the multi-label problem into multiple single-label problems, so that the existing single-label algorithms can be used. Traditional two-class and multi-class problems can both be cast into multi-label ones by restricting each instance to have only one label. On the other hand, the generality of multi-label problems inevitably makes it more difficult to learn. An intuitive approach to solving multi-label problem is to decompose it into multiple independent binary classification problems (one per category). In an “one-to-rest” strategy, one could build multiple independent classifiers and, for an unseen instance, choose the class for which the confidence is maximized. The main assumption here is that the labels are mutually exclusive. You do not consider any underlying correlation between the classes in this method. For instance, it is more like asking simple questions, say, “is the comment toxic or not”, “is the comment threatening or not?”, etc. Also there might be an extensive case of overfitting here, since most of the comments are unlabeled, i,e., most of the comments are clean comments. from sklearn.linear_model import LogisticRegressionfrom sklearn.pipeline import Pipelinefrom sklearn.metrics import accuracy_scorefrom sklearn.multiclass import OneVsRestClassifier# Using pipeline for applying logistic regression and one vs rest classifierLogReg_pipeline = Pipeline([ ('clf', OneVsRestClassifier(LogisticRegression(solver='sag'), n_jobs=-1)), ])for category in categories: print('**Processing {} comments...**'.format(category)) # Training logistic regression model on train data LogReg_pipeline.fit(x_train, train[category]) # calculating test accuracy prediction = LogReg_pipeline.predict(x_test) print('Test accuracy is {}'.format(accuracy_score(test[category], prediction))) print("\n") In this case an ensemble of single-label binary classifiers is trained, one for each class. Each classifier predicts either the membership or the non-membership of one class. The union of all classes that were predicted is taken as the multi-label output. This approach is popular because it is easy to implement, however it also ignores the possible correlations between class labels. In other words, if there’s q labels, the binary relevance method create q new data sets from the images, one for each label and train single-label classifiers on each new data set. One classifier may answer yes/no to the question “does it contain trees?”, thus the “binary” in “binary relevance”. This is a simple approach but does not work well when there’s dependencies between the labels. OneVsRest & Binary Relevance seem very much alike. If multiple classifiers in OneVsRest answer “yes” then you are back to the binary relevance scenario. # using binary relevancefrom skmultilearn.problem_transform import BinaryRelevancefrom sklearn.naive_bayes import GaussianNB# initialize binary relevance multi-label classifier# with a gaussian naive bayes base classifierclassifier = BinaryRelevance(GaussianNB())# trainclassifier.fit(x_train, y_train)# predictpredictions = classifier.predict(x_test)# accuracyprint("Accuracy = ",accuracy_score(y_test,predictions))Output:Accuracy = 0.856666666667 A chain of binary classifiers C0, C1, . . . , Cn is constructed, where a classifier Ci uses the predictions of all the classifier Cj , where j < i. This way the method, also called classifier chains (CC), can take into account label correlations. The total number of classifiers needed for this approach is equal to the number of classes, but the training of the classifiers is more involved. Following is an illustrated example with a classification problem of three categories {C1, C2, C3} chained in that order. # using classifier chainsfrom skmultilearn.problem_transform import ClassifierChainfrom sklearn.linear_model import LogisticRegression# initialize classifier chains multi-label classifierclassifier = ClassifierChain(LogisticRegression())# Training logistic regression model on train dataclassifier.fit(x_train, y_train)# predictpredictions = classifier.predict(x_test)# accuracyprint("Accuracy = ",accuracy_score(y_test,predictions))print("\n")Output:Accuracy = 0.893333333333 This approach does take possible correlations between class labels into account. More commonly this approach is called the label-powerset method, because it considers each member of the power set of labels in the training set as a single label. This method needs worst case (2^|C|) classifiers, and has a high computational complexity. However when the number of classes increases the number of distinct label combinations can grow exponentially. This easily leads to combinatorial explosion and thus computational infeasibility. Furthermore, some label combinations will have very few positive examples. # using Label Powersetfrom skmultilearn.problem_transform import LabelPowerset# initialize label powerset multi-label classifierclassifier = LabelPowerset(LogisticRegression())# trainclassifier.fit(x_train, y_train)# predictpredictions = classifier.predict(x_test)# accuracyprint("Accuracy = ",accuracy_score(y_test,predictions))print("\n")Output:Accuracy = 0.893333333333 Algorithm adaptation methods for multi-label classification concentrate on adapting single-label classification algorithms to the multi-label case usually by changes in cost/decision functions. Here we use a multi-label lazy learning approach named ML-KNN which is derived from the traditional K-nearest neighbor (KNN) algorithm. The skmultilearn.adapt module implements algorithm adaptation approaches to multi-label classification, including but not limited to ML-KNN. from skmultilearn.adapt import MLkNNfrom scipy.sparse import csr_matrix, lil_matrixclassifier_new = MLkNN(k=10)# Note that this classifier can throw up errors when handling sparse matrices.x_train = lil_matrix(x_train).toarray()y_train = lil_matrix(y_train).toarray()x_test = lil_matrix(x_test).toarray()# trainclassifier_new.fit(x_train, y_train)# predictpredictions_new = classifier_new.predict(x_test)# accuracyprint("Accuracy = ",accuracy_score(y_test,predictions_new))print("\n")Output:Accuracy = 0.88166666667 There are two main methods for tackling a multi-label classification problem: problem transformation methods and algorithm adaptation methods. Problem transformation methods transform the multi-label problem into a set of binary classification problems, which can then be handled using single-class classifiers. Whereas algorithm adaptation methods adapt the algorithms to directly perform multi-label classification. In other words, rather than trying to convert the problem to a simpler problem, they try to address the problem in its full form. In an extensive comparison with other approaches, label-powerset method scores best, followed by the one-against-all method. Both ML-KNN and label-powerset take considerable amount of time when run on this dataset, so experimentation was done on a random sample of the train data. The same problem can be solved using LSTMs in deep learning. For more speed we could use decision trees and for a reasonable trade-off between speed and accuracy we could also opt for ensemble models. Other frameworks such as MEKA can be used to deal with multi-label classification problems. Hope you enjoyed this tutorial. Thanks for reading..!
[ { "code": null, "e": 388, "s": 171, "text": "With continuous increase in available data, there is a pressing need to organize it and modern classification problems often involve the prediction of multiple labels simultaneously associated with a single instance." }, { "code": null, "e": 495, "s": 388, "text": "Known as Multi-Label Classification, it is one such task which is omnipresent in many real world problems." }, { "code": null, "e": 607, "s": 495, "text": "In this project, using a Kaggle problem as example, we explore different aspects of multi-label classification." }, { "code": null, "e": 720, "s": 607, "text": "DISCLAIMER FROM THE DATA SOURCE: the dataset contains text that may be considered profane, vulgar, or offensive." }, { "code": null, "e": 768, "s": 720, "text": "Part-1: Overview of multi-label classification." }, { "code": null, "e": 817, "s": 768, "text": "Part-2: Problem definition & evaluation metrics." }, { "code": null, "e": 858, "s": 817, "text": "Part-3: Exploratory data analysis (EDA)." }, { "code": null, "e": 887, "s": 858, "text": "Part-4: Data pre-processing." }, { "code": null, "e": 934, "s": 887, "text": "Part-5: Multi-label classification techniques." }, { "code": null, "e": 1103, "s": 934, "text": "Multi-label classification originated from the investigation of text categorisation problem, where each document may belong to several predefined topics simultaneously." }, { "code": null, "e": 1329, "s": 1103, "text": "Multi-label classification of textual data is an important problem. Examples range from news articles to emails. For instance, this can be employed to find the genres that a movie belongs to, based on the summary of its plot." }, { "code": null, "e": 1437, "s": 1329, "text": "Or multi-label classification of genres based on movie posters. (This enters the realm of computer vision.)" }, { "code": null, "e": 1670, "s": 1437, "text": "In multi-label classification, the training set is composed of instances each associated with a set of labels, and the task is to predict the label sets of unseen instances through analyzing training instances with known label sets." }, { "code": null, "e": 1936, "s": 1670, "text": "Difference between multi-class classification & multi-label classification is that in multi-class problems the classes are mutually exclusive, whereas for multi-label problems each label represents a different classification task, but the tasks are somehow related." }, { "code": null, "e": 2293, "s": 1936, "text": "For example, multi-class classification makes the assumption that each sample is assigned to one and only one label: a fruit can be either an apple or a pear but not both at the same time. Whereas, an instance of multi-label classification can be that a text might be about any of religion, politics, finance or education at the same time or none of these." }, { "code": null, "e": 2401, "s": 2293, "text": "Toxic comment classification is a multi-label text classification problem with a highly imbalanced dataset." }, { "code": null, "e": 2661, "s": 2401, "text": "We’re challenged to build a multi-labeld model that’s capable of detecting different types of toxicity like threats, obscenity, insults, and identity-based hate. We need to create a model which predicts a probability of each type of toxicity for each comment." }, { "code": null, "e": 2708, "s": 2661, "text": "Kaggle link to this problem can be found here." }, { "code": null, "e": 2881, "s": 2708, "text": "Note: Initially evaluation metric in the Kaggle challenge was Log-Loss, which was later changed to AUC. But in this post we throw light on other evaluation metrics as well." }, { "code": null, "e": 3121, "s": 2881, "text": "The evaluation measures for single-label are usually different than for multi-label. Here in single-label classfication we use simple metrics such as precision, recall, accuracy, etc,. Say, in single-label classification, accuracy is just:" }, { "code": null, "e": 3437, "s": 3121, "text": "In multi-label classification, a misclassification is no longer a hard wrong or right. A prediction containing a subset of the actual classes should be considered better than a prediction that contains none of them, i.e., predicting two of the three labels correctly this is better than predicting no labels at all." }, { "code": null, "e": 3607, "s": 3437, "text": "To measure a multi-class classifier we have to average out the classes somehow. There are two different methods of doing this called micro-averaging and macro-averaging." }, { "code": null, "e": 3712, "s": 3607, "text": "In micro-averaging all TPs, TNs, FPs and FNs for each class are summed up and then the average is taken." }, { "code": null, "e": 3959, "s": 3712, "text": "In micro-averaging method, you sum up the individual true positives, false positives, and false negatives of the system for different sets and the apply them. And the micro-average F1-Score will be simply the harmonic mean of above two equations." }, { "code": null, "e": 4082, "s": 3959, "text": "Macro-averaging is straight forward. We just take the average of the precision and recall of the system on different sets." }, { "code": null, "e": 4358, "s": 4082, "text": "Macro-averaging method can be used when you want to know how the system performs overall across the sets of data. You should not come up with any specific decision with this average. On the other hand, micro-averaging can be a useful measure when your dataset varies in size." }, { "code": null, "e": 4521, "s": 4358, "text": "In simplest of terms, Hamming-Loss is the fraction of labels that are incorrectly predicted, i.e., the fraction of the wrong labels to the total number of labels." }, { "code": null, "e": 4637, "s": 4521, "text": "It is the most strict metric, indicating the percentage of samples that have all their labels classified correctly." }, { "code": null, "e": 4808, "s": 4637, "text": "The disadvantage of this measure is that multi-class classification problems have a chance of being partially correct, but here we ignore those partially correct matches." }, { "code": null, "e": 4904, "s": 4808, "text": "There is a function in scikit-learn which implements subset accuracy, called as accuracy_score." }, { "code": null, "e": 4995, "s": 4904, "text": "Note: We will be using accuracy_score function to evaluate all our models in this project." }, { "code": null, "e": 5284, "s": 4995, "text": "Exploratory Data Analysis is one of the important steps in the data analysis process. Here, the focus is on making sense of the data in hand — things like formulating the correct questions to ask to your dataset, how to manipulate the data sources to get the required answers, and others." }, { "code": null, "e": 5329, "s": 5284, "text": "First let us import the necessary libraries." }, { "code": null, "e": 5438, "s": 5329, "text": "import osimport csvimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns" }, { "code": null, "e": 5525, "s": 5438, "text": "Next we load the data from csv files into a pandas dataframe and check its attributes." }, { "code": null, "e": 5825, "s": 5525, "text": "data_path = \"/Users/kartik/Desktop/AAIC/Projects/jigsaw-toxic-comment-classification-challenge/data/train.csv\"data_raw = pd.read_csv(data_path)print(\"Number of rows in data =\",data_raw.shape[0])print(\"Number of columns in data =\",data_raw.shape[1])print(\"\\n\")print(\"**Sample data:**\")data_raw.head()" }, { "code": null, "e": 5949, "s": 5825, "text": "Now we count the number of comments under each label. (For detailed code, please refer to the GitHub link of this project.)" }, { "code": null, "e": 6502, "s": 5949, "text": "categories = list(data_raw.columns.values)sns.set(font_scale = 2)plt.figure(figsize=(15,8))ax= sns.barplot(categories, data_raw.iloc[:,2:].sum().values)plt.title(\"Comments in each category\", fontsize=24)plt.ylabel('Number of comments', fontsize=18)plt.xlabel('Comment Type ', fontsize=18)#adding the text labelsrects = ax.patcheslabels = data_raw.iloc[:,2:].sum().valuesfor rect, label in zip(rects, labels): height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2, height + 5, label, ha='center', va='bottom', fontsize=18)plt.show()" }, { "code": null, "e": 6558, "s": 6502, "text": "Counting the number of comments having multiple labels." }, { "code": null, "e": 7180, "s": 6558, "text": "rowSums = data_raw.iloc[:,2:].sum(axis=1)multiLabel_counts = rowSums.value_counts()multiLabel_counts = multiLabel_counts.iloc[1:]sns.set(font_scale = 2)plt.figure(figsize=(15,8))ax = sns.barplot(multiLabel_counts.index, multiLabel_counts.values)plt.title(\"Comments having multiple labels \")plt.ylabel('Number of comments', fontsize=18)plt.xlabel('Number of labels', fontsize=18)#adding the text labelsrects = ax.patcheslabels = multiLabel_counts.valuesfor rect, label in zip(rects, labels): height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2, height + 5, label, ha='center', va='bottom')plt.show()" }, { "code": null, "e": 7254, "s": 7180, "text": "WordCloud representation of most used words in each category of comments." }, { "code": null, "e": 7828, "s": 7254, "text": "from wordcloud import WordCloud,STOPWORDSplt.figure(figsize=(40,25))# cleansubset = data_raw[data_raw.clean==True]text = subset.comment_text.valuescloud_toxic = WordCloud( stopwords=STOPWORDS, background_color='black', collocations=False, width=2500, height=1800 ).generate(\" \".join(text))plt.axis('off')plt.title(\"Clean\",fontsize=40)plt.imshow(cloud_clean)# Same code can be used to generate wordclouds of other categories." }, { "code": null, "e": 7989, "s": 7828, "text": "We first convert the comments to lower-case and then use custom made functions to remove html-tags, punctuation and non-alphabetic characters from the comments." }, { "code": null, "e": 9070, "s": 7989, "text": "import nltkfrom nltk.corpus import stopwordsfrom nltk.stem.snowball import SnowballStemmerimport reimport sysimport warningsdata = data_rawif not sys.warnoptions: warnings.simplefilter(\"ignore\")def cleanHtml(sentence): cleanr = re.compile('<.*?>') cleantext = re.sub(cleanr, ' ', str(sentence)) return cleantextdef cleanPunc(sentence): #function to clean the word of any punctuation or special characters cleaned = re.sub(r'[?|!|\\'|\"|#]',r'',sentence) cleaned = re.sub(r'[.|,|)|(|\\|/]',r' ',cleaned) cleaned = cleaned.strip() cleaned = cleaned.replace(\"\\n\",\" \") return cleaneddef keepAlpha(sentence): alpha_sent = \"\" for word in sentence.split(): alpha_word = re.sub('[^a-z A-Z]+', ' ', word) alpha_sent += alpha_word alpha_sent += \" \" alpha_sent = alpha_sent.strip() return alpha_sentdata['comment_text'] = data['comment_text'].str.lower()data['comment_text'] = data['comment_text'].apply(cleanHtml)data['comment_text'] = data['comment_text'].apply(cleanPunc)data['comment_text'] = data['comment_text'].apply(keepAlpha)" }, { "code": null, "e": 9255, "s": 9070, "text": "Next we remove all the stop-words present in the comments using the default set of stop-words that can be downloaded from NLTK library. We also add few stop-words to the standard list." }, { "code": null, "e": 9530, "s": 9255, "text": "Stop words are basically a set of commonly used words in any language, not just English. The reason why stop words are critical to many applications is that, if we remove the words that are very commonly used in a given language, we can focus on the important words instead." }, { "code": null, "e": 9970, "s": 9530, "text": "stop_words = set(stopwords.words('english'))stop_words.update(['zero','one','two','three','four','five','six','seven','eight','nine','ten','may','also','across','among','beside','however','yet','within'])re_stop_words = re.compile(r\"\\b(\" + \"|\".join(stop_words) + \")\\\\W\", re.I)def removeStopWords(sentence): global re_stop_words return re_stop_words.sub(\" \", sentence)data['comment_text'] = data['comment_text'].apply(removeStopWords)" }, { "code": null, "e": 10190, "s": 9970, "text": "Next we do stemming. There exist different kinds of stemming which basically transform words with roughly the same semantics to one standard form. For example, for amusing, amusement, and amused, the stem would be amus." }, { "code": null, "e": 10513, "s": 10190, "text": "stemmer = SnowballStemmer(\"english\")def stemming(sentence): stemSentence = \"\" for word in sentence.split(): stem = stemmer.stem(word) stemSentence += stem stemSentence += \" \" stemSentence = stemSentence.strip() return stemSentencedata['comment_text'] = data['comment_text'].apply(stemming)" }, { "code": null, "e": 10640, "s": 10513, "text": "After splitting the dataset into train & test sets, we want to summarize our comments and convert them into numerical vectors." }, { "code": null, "e": 10875, "s": 10640, "text": "One technique is to pick the most frequently occurring terms (words with high term frequency or tf). However, the most frequent word is a less useful metric since some words like ‘this’, ‘a’ occur very frequently across all documents." }, { "code": null, "e": 11025, "s": 10875, "text": "Hence, we also want a measure of how unique a word is i.e. how infrequently the word occurs across all documents (inverse document frequency or idf)." }, { "code": null, "e": 11209, "s": 11025, "text": "So, the product of tf & idf (TF-IDF) of a word gives a product of how frequent this word is in the document multiplied by how unique the word is w.r.t. the entire corpus of documents." }, { "code": null, "e": 11351, "s": 11209, "text": "Words in the document with a high tfidf score occur frequently in the document and provide the most information about that specific document." }, { "code": null, "e": 11897, "s": 11351, "text": "from sklearn.model_selection import train_test_splittrain, test = train_test_split(data, random_state=42, test_size=0.30, shuffle=True)from sklearn.feature_extraction.text import TfidfVectorizervectorizer = TfidfVectorizer(strip_accents='unicode', analyzer='word', ngram_range=(1,3), norm='l2')vectorizer.fit(train_text)vectorizer.fit(test_text)x_train = vectorizer.transform(train_text)y_train = train.drop(labels = ['id','comment_text'], axis=1)x_test = vectorizer.transform(test_text)y_test = test.drop(labels = ['id','comment_text'], axis=1)" }, { "code": null, "e": 12045, "s": 11897, "text": "TF-IDF is easy to compute but its disadvantage is that it does not capture position in text, semantics, co-occurrences in different documents, etc." }, { "code": null, "e": 12315, "s": 12045, "text": "Most traditional learning algorithms are developed for single-label classification problems. Therefore a lot of approaches in the literature transform the multi-label problem into multiple single-label problems, so that the existing single-label algorithms can be used." }, { "code": null, "e": 12706, "s": 12315, "text": "Traditional two-class and multi-class problems can both be cast into multi-label ones by restricting each instance to have only one label. On the other hand, the generality of multi-label problems inevitably makes it more difficult to learn. An intuitive approach to solving multi-label problem is to decompose it into multiple independent binary classification problems (one per category)." }, { "code": null, "e": 12870, "s": 12706, "text": "In an “one-to-rest” strategy, one could build multiple independent classifiers and, for an unseen instance, choose the class for which the confidence is maximized." }, { "code": null, "e": 13021, "s": 12870, "text": "The main assumption here is that the labels are mutually exclusive. You do not consider any underlying correlation between the classes in this method." }, { "code": null, "e": 13303, "s": 13021, "text": "For instance, it is more like asking simple questions, say, “is the comment toxic or not”, “is the comment threatening or not?”, etc. Also there might be an extensive case of overfitting here, since most of the comments are unlabeled, i,e., most of the comments are clean comments." }, { "code": null, "e": 14066, "s": 13303, "text": "from sklearn.linear_model import LogisticRegressionfrom sklearn.pipeline import Pipelinefrom sklearn.metrics import accuracy_scorefrom sklearn.multiclass import OneVsRestClassifier# Using pipeline for applying logistic regression and one vs rest classifierLogReg_pipeline = Pipeline([ ('clf', OneVsRestClassifier(LogisticRegression(solver='sag'), n_jobs=-1)), ])for category in categories: print('**Processing {} comments...**'.format(category)) # Training logistic regression model on train data LogReg_pipeline.fit(x_train, train[category]) # calculating test accuracy prediction = LogReg_pipeline.predict(x_test) print('Test accuracy is {}'.format(accuracy_score(test[category], prediction))) print(\"\\n\")" }, { "code": null, "e": 14452, "s": 14066, "text": "In this case an ensemble of single-label binary classifiers is trained, one for each class. Each classifier predicts either the membership or the non-membership of one class. The union of all classes that were predicted is taken as the multi-label output. This approach is popular because it is easy to implement, however it also ignores the possible correlations between class labels." }, { "code": null, "e": 14844, "s": 14452, "text": "In other words, if there’s q labels, the binary relevance method create q new data sets from the images, one for each label and train single-label classifiers on each new data set. One classifier may answer yes/no to the question “does it contain trees?”, thus the “binary” in “binary relevance”. This is a simple approach but does not work well when there’s dependencies between the labels." }, { "code": null, "e": 14997, "s": 14844, "text": "OneVsRest & Binary Relevance seem very much alike. If multiple classifiers in OneVsRest answer “yes” then you are back to the binary relevance scenario." }, { "code": null, "e": 15446, "s": 14997, "text": "# using binary relevancefrom skmultilearn.problem_transform import BinaryRelevancefrom sklearn.naive_bayes import GaussianNB# initialize binary relevance multi-label classifier# with a gaussian naive bayes base classifierclassifier = BinaryRelevance(GaussianNB())# trainclassifier.fit(x_train, y_train)# predictpredictions = classifier.predict(x_test)# accuracyprint(\"Accuracy = \",accuracy_score(y_test,predictions))Output:Accuracy = 0.856666666667" }, { "code": null, "e": 15693, "s": 15446, "text": "A chain of binary classifiers C0, C1, . . . , Cn is constructed, where a classifier Ci uses the predictions of all the classifier Cj , where j < i. This way the method, also called classifier chains (CC), can take into account label correlations." }, { "code": null, "e": 15839, "s": 15693, "text": "The total number of classifiers needed for this approach is equal to the number of classes, but the training of the classifiers is more involved." }, { "code": null, "e": 15961, "s": 15839, "text": "Following is an illustrated example with a classification problem of three categories {C1, C2, C3} chained in that order." }, { "code": null, "e": 16438, "s": 15961, "text": "# using classifier chainsfrom skmultilearn.problem_transform import ClassifierChainfrom sklearn.linear_model import LogisticRegression# initialize classifier chains multi-label classifierclassifier = ClassifierChain(LogisticRegression())# Training logistic regression model on train dataclassifier.fit(x_train, y_train)# predictpredictions = classifier.predict(x_test)# accuracyprint(\"Accuracy = \",accuracy_score(y_test,predictions))print(\"\\n\")Output:Accuracy = 0.893333333333" }, { "code": null, "e": 16683, "s": 16438, "text": "This approach does take possible correlations between class labels into account. More commonly this approach is called the label-powerset method, because it considers each member of the power set of labels in the training set as a single label." }, { "code": null, "e": 16774, "s": 16683, "text": "This method needs worst case (2^|C|) classifiers, and has a high computational complexity." }, { "code": null, "e": 17043, "s": 16774, "text": "However when the number of classes increases the number of distinct label combinations can grow exponentially. This easily leads to combinatorial explosion and thus computational infeasibility. Furthermore, some label combinations will have very few positive examples." }, { "code": null, "e": 17416, "s": 17043, "text": "# using Label Powersetfrom skmultilearn.problem_transform import LabelPowerset# initialize label powerset multi-label classifierclassifier = LabelPowerset(LogisticRegression())# trainclassifier.fit(x_train, y_train)# predictpredictions = classifier.predict(x_test)# accuracyprint(\"Accuracy = \",accuracy_score(y_test,predictions))print(\"\\n\")Output:Accuracy = 0.893333333333" }, { "code": null, "e": 17610, "s": 17416, "text": "Algorithm adaptation methods for multi-label classification concentrate on adapting single-label classification algorithms to the multi-label case usually by changes in cost/decision functions." }, { "code": null, "e": 17746, "s": 17610, "text": "Here we use a multi-label lazy learning approach named ML-KNN which is derived from the traditional K-nearest neighbor (KNN) algorithm." }, { "code": null, "e": 17887, "s": 17746, "text": "The skmultilearn.adapt module implements algorithm adaptation approaches to multi-label classification, including but not limited to ML-KNN." }, { "code": null, "e": 18403, "s": 17887, "text": "from skmultilearn.adapt import MLkNNfrom scipy.sparse import csr_matrix, lil_matrixclassifier_new = MLkNN(k=10)# Note that this classifier can throw up errors when handling sparse matrices.x_train = lil_matrix(x_train).toarray()y_train = lil_matrix(y_train).toarray()x_test = lil_matrix(x_test).toarray()# trainclassifier_new.fit(x_train, y_train)# predictpredictions_new = classifier_new.predict(x_test)# accuracyprint(\"Accuracy = \",accuracy_score(y_test,predictions_new))print(\"\\n\")Output:Accuracy = 0.88166666667" }, { "code": null, "e": 18546, "s": 18403, "text": "There are two main methods for tackling a multi-label classification problem: problem transformation methods and algorithm adaptation methods." }, { "code": null, "e": 18715, "s": 18546, "text": "Problem transformation methods transform the multi-label problem into a set of binary classification problems, which can then be handled using single-class classifiers." }, { "code": null, "e": 18951, "s": 18715, "text": "Whereas algorithm adaptation methods adapt the algorithms to directly perform multi-label classification. In other words, rather than trying to convert the problem to a simpler problem, they try to address the problem in its full form." }, { "code": null, "e": 19076, "s": 18951, "text": "In an extensive comparison with other approaches, label-powerset method scores best, followed by the one-against-all method." }, { "code": null, "e": 19232, "s": 19076, "text": "Both ML-KNN and label-powerset take considerable amount of time when run on this dataset, so experimentation was done on a random sample of the train data." }, { "code": null, "e": 19293, "s": 19232, "text": "The same problem can be solved using LSTMs in deep learning." }, { "code": null, "e": 19433, "s": 19293, "text": "For more speed we could use decision trees and for a reasonable trade-off between speed and accuracy we could also opt for ensemble models." }, { "code": null, "e": 19525, "s": 19433, "text": "Other frameworks such as MEKA can be used to deal with multi-label classification problems." } ]
Node.js crypto.privateEncrypt() Method - GeeksforGeeks
11 Oct, 2021 The crypto.privateEncrypt() method is used to encrypt the stated content of the buffer with the parameter ‘privateKey’. Syntax: crypto.privateEncrypt( privateKey, buffer ) Parameters: This method accept two parameters as mentioned above and described below: privateKey: It can hold Object, string, Buffer, or KeyObject type of data.key: It is a ‘PEM’ encoded private key. It is of type string, Buffer, and KeyObject.passphrase: It is an optional passphrase for the private key which is either string or buffer.padding It is an optional padding value which is defined in crypto.constants, which can be crypto.constants.RSA_NO_PADDING, or crypto.constants.RSA_PKCS1_PADDING. It is of type crypto.constants. key: It is a ‘PEM’ encoded private key. It is of type string, Buffer, and KeyObject.passphrase: It is an optional passphrase for the private key which is either string or buffer.padding It is an optional padding value which is defined in crypto.constants, which can be crypto.constants.RSA_NO_PADDING, or crypto.constants.RSA_PKCS1_PADDING. It is of type crypto.constants. key: It is a ‘PEM’ encoded private key. It is of type string, Buffer, and KeyObject. passphrase: It is an optional passphrase for the private key which is either string or buffer. padding It is an optional padding value which is defined in crypto.constants, which can be crypto.constants.RSA_NO_PADDING, or crypto.constants.RSA_PKCS1_PADDING. It is of type crypto.constants. buffer: It contains Buffer, TypedArray, or DataView type of data. Return Value: It returns a new Buffer with the encrypted content. Below example illustrate the use of crypto.privateEncrypt() method in Node.js: Example 1: // Node.js program to demonstrate the // crypto.privateEncrypt() method // Including crypto and fs moduleconst crypto = require('crypto');const fs = require("fs"); // Using a function generateKeyFilesfunction generateKeyFiles() { const keyPair = crypto.generateKeyPairSync('rsa', { modulusLength: 520, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: '' } }); // Creating private key file fs.writeFileSync("private_key", keyPair.privateKey);} // Generate keysgenerateKeyFiles(); // Creating a function to encrypt stringfunction encryptString (plaintext, privateKeyFile) { const privateKey = fs.readFileSync(privateKeyFile, "utf8"); // privateEncrypt() method with its parameters const encrypted = crypto.privateEncrypt( privateKey, Buffer.from(plaintext)); return encrypted.toString("base64");} // Defining a text to be encryptedconst plainText = "GfG"; // Defining encrypted textconst encrypted = encryptString(plainText, "./private_key"); // Prints plain textconsole.log("Plaintext:", plainText); // Prints encrypted textconsole.log("Encrypted: ", encrypted); Output: Plaintext: GfG Encrypted: c60eR17GTQFkTI1ipTq5qFbYS58lIQqpDiou2UlYeOUE+u7agbtHvvwKaBpzBx4SvTCh5abpaqmyXCyGcUpGc7s= Example 2: // Node.js program to demonstrate the // crypto.privateEncrypt() method // Including crypto and fs moduleconst crypto = require('crypto');const fs = require("fs"); // Using a function generateKeyFilesfunction generateKeyFiles() { const keyPair = crypto.generateKeyPairSync('rsa', { modulusLength: 520, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: '' } }); // Creating private key file fs.writeFileSync("private_key", keyPair.privateKey);} // Generate keysgenerateKeyFiles(); // Creating a function to encrypt stringfunction encryptString (plaintext, privateKeyFile) { const privateKey = fs.readFileSync(privateKeyFile, "utf8"); // privateEncrypt() method with its parameters const encrypted = crypto.privateEncrypt( privateKey, Buffer.from(plaintext)); // Returns buffer as its not encoded return encrypted;} // Defining a text to be encryptedconst plainText = "GfG"; // Defining encrypted textconst encrypted = encryptString(plainText, "./private_key"); // Prints plain textconsole.log("Plaintext:", plainText); // Prints encrypted textconsole.log("Encrypted buffer: ", encrypted); Output: Plaintext: GfG Encrypted buffer: <Buffer 14 e5 84 05 2f b5 59 64 22 d2 19 99 f9 66 e5 18 50 76 27 df 0b e6 9f 50 1d a2 51 6a 93 21 04 7b 8f 50 ba 11 82 fd 3c 6e c0 81 be 58 f9 d6 a6 c7 19 da ... > Reference: https://nodejs.org/api/crypto.html#crypto_crypto_privateencrypt_privatekey_buffer Node.js-crypto-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Node.js path.resolve() Method Node.js CRUD Operations Using Mongoose and MongoDB Atlas Node.js fs.readdir() Method Express.js res.render() Function Node.js First Application Express.js express.Router() Function Convert a string to an integer in JavaScript How to set the default value for an HTML <select> element ? Top 10 Angular Libraries For Web Developers How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 24579, "s": 24551, "text": "\n11 Oct, 2021" }, { "code": null, "e": 24699, "s": 24579, "text": "The crypto.privateEncrypt() method is used to encrypt the stated content of the buffer with the parameter ‘privateKey’." }, { "code": null, "e": 24707, "s": 24699, "text": "Syntax:" }, { "code": null, "e": 24751, "s": 24707, "text": "crypto.privateEncrypt( privateKey, buffer )" }, { "code": null, "e": 24837, "s": 24751, "text": "Parameters: This method accept two parameters as mentioned above and described below:" }, { "code": null, "e": 25284, "s": 24837, "text": "privateKey: It can hold Object, string, Buffer, or KeyObject type of data.key: It is a ‘PEM’ encoded private key. It is of type string, Buffer, and KeyObject.passphrase: It is an optional passphrase for the private key which is either string or buffer.padding It is an optional padding value which is defined in crypto.constants, which can be crypto.constants.RSA_NO_PADDING, or crypto.constants.RSA_PKCS1_PADDING. It is of type crypto.constants." }, { "code": null, "e": 25657, "s": 25284, "text": "key: It is a ‘PEM’ encoded private key. It is of type string, Buffer, and KeyObject.passphrase: It is an optional passphrase for the private key which is either string or buffer.padding It is an optional padding value which is defined in crypto.constants, which can be crypto.constants.RSA_NO_PADDING, or crypto.constants.RSA_PKCS1_PADDING. It is of type crypto.constants." }, { "code": null, "e": 25742, "s": 25657, "text": "key: It is a ‘PEM’ encoded private key. It is of type string, Buffer, and KeyObject." }, { "code": null, "e": 25837, "s": 25742, "text": "passphrase: It is an optional passphrase for the private key which is either string or buffer." }, { "code": null, "e": 26032, "s": 25837, "text": "padding It is an optional padding value which is defined in crypto.constants, which can be crypto.constants.RSA_NO_PADDING, or crypto.constants.RSA_PKCS1_PADDING. It is of type crypto.constants." }, { "code": null, "e": 26098, "s": 26032, "text": "buffer: It contains Buffer, TypedArray, or DataView type of data." }, { "code": null, "e": 26164, "s": 26098, "text": "Return Value: It returns a new Buffer with the encrypted content." }, { "code": null, "e": 26243, "s": 26164, "text": "Below example illustrate the use of crypto.privateEncrypt() method in Node.js:" }, { "code": null, "e": 26254, "s": 26243, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the // crypto.privateEncrypt() method // Including crypto and fs moduleconst crypto = require('crypto');const fs = require(\"fs\"); // Using a function generateKeyFilesfunction generateKeyFiles() { const keyPair = crypto.generateKeyPairSync('rsa', { modulusLength: 520, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: '' } }); // Creating private key file fs.writeFileSync(\"private_key\", keyPair.privateKey);} // Generate keysgenerateKeyFiles(); // Creating a function to encrypt stringfunction encryptString (plaintext, privateKeyFile) { const privateKey = fs.readFileSync(privateKeyFile, \"utf8\"); // privateEncrypt() method with its parameters const encrypted = crypto.privateEncrypt( privateKey, Buffer.from(plaintext)); return encrypted.toString(\"base64\");} // Defining a text to be encryptedconst plainText = \"GfG\"; // Defining encrypted textconst encrypted = encryptString(plainText, \"./private_key\"); // Prints plain textconsole.log(\"Plaintext:\", plainText); // Prints encrypted textconsole.log(\"Encrypted: \", encrypted);", "e": 27546, "s": 26254, "text": null }, { "code": null, "e": 27554, "s": 27546, "text": "Output:" }, { "code": null, "e": 27671, "s": 27554, "text": "Plaintext: GfG\nEncrypted: c60eR17GTQFkTI1ipTq5qFbYS58lIQqpDiou2UlYeOUE+u7agbtHvvwKaBpzBx4SvTCh5abpaqmyXCyGcUpGc7s=\n" }, { "code": null, "e": 27682, "s": 27671, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the // crypto.privateEncrypt() method // Including crypto and fs moduleconst crypto = require('crypto');const fs = require(\"fs\"); // Using a function generateKeyFilesfunction generateKeyFiles() { const keyPair = crypto.generateKeyPairSync('rsa', { modulusLength: 520, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: '' } }); // Creating private key file fs.writeFileSync(\"private_key\", keyPair.privateKey);} // Generate keysgenerateKeyFiles(); // Creating a function to encrypt stringfunction encryptString (plaintext, privateKeyFile) { const privateKey = fs.readFileSync(privateKeyFile, \"utf8\"); // privateEncrypt() method with its parameters const encrypted = crypto.privateEncrypt( privateKey, Buffer.from(plaintext)); // Returns buffer as its not encoded return encrypted;} // Defining a text to be encryptedconst plainText = \"GfG\"; // Defining encrypted textconst encrypted = encryptString(plainText, \"./private_key\"); // Prints plain textconsole.log(\"Plaintext:\", plainText); // Prints encrypted textconsole.log(\"Encrypted buffer: \", encrypted);", "e": 29001, "s": 27682, "text": null }, { "code": null, "e": 29009, "s": 29001, "text": "Output:" }, { "code": null, "e": 29208, "s": 29009, "text": "Plaintext: GfG\nEncrypted buffer: <Buffer 14 e5 84 05 2f b5 59 64\n22 d2 19 99 f9 66 e5 18 50 76 27 df 0b e6 9f 50 1d a2\n51 6a 93 21 04 7b 8f 50 ba 11 82 fd 3c 6e c0 81 be 58\nf9 d6 a6 c7 19 da ... >\n" }, { "code": null, "e": 29301, "s": 29208, "text": "Reference: https://nodejs.org/api/crypto.html#crypto_crypto_privateencrypt_privatekey_buffer" }, { "code": null, "e": 29323, "s": 29301, "text": "Node.js-crypto-module" }, { "code": null, "e": 29331, "s": 29323, "text": "Node.js" }, { "code": null, "e": 29348, "s": 29331, "text": "Web Technologies" }, { "code": null, "e": 29446, "s": 29348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29455, "s": 29446, "text": "Comments" }, { "code": null, "e": 29468, "s": 29455, "text": "Old Comments" }, { "code": null, "e": 29498, "s": 29468, "text": "Node.js path.resolve() Method" }, { "code": null, "e": 29555, "s": 29498, "text": "Node.js CRUD Operations Using Mongoose and MongoDB Atlas" }, { "code": null, "e": 29583, "s": 29555, "text": "Node.js fs.readdir() Method" }, { "code": null, "e": 29616, "s": 29583, "text": "Express.js res.render() Function" }, { "code": null, "e": 29642, "s": 29616, "text": "Node.js First Application" }, { "code": null, "e": 29679, "s": 29642, "text": "Express.js express.Router() Function" }, { "code": null, "e": 29724, "s": 29679, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29784, "s": 29724, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29828, "s": 29784, "text": "Top 10 Angular Libraries For Web Developers" } ]
Data Analysis Project — Telco Customer Churn | by John Chen (Yueh-Han) | Towards Data Science
To extract actionable insights from the dataset. I listed all the questions that came to mind below after assessing the dataset, and I tried to investigate all of them to find the insights: 1. How long did unsubscribed people who are paying for the service usually stay in the service? And what was their average LTV(Life Time Value)? 2. How many of those who unsubscribed and still subscribe used the phone service? 3. How many people use phone services with multiple lines for those who unsubscribed and still subscribe? 4. How many people used the internet service for those who unsubscribed and subscribed? 5. How many people used and using each subset of internet service for those who unsubscribed and who are paying for the service? 6. What are the differences in each service internet service for those who are still in service with LTV higher than the average LTV of leaked customers,? 7. How many subscribed to each kind of contract for those who unsubscribed and still are paying for the service,? 8. Among ‘gender’, ‘Partner’, ‘Dependents’,’PhoneService’, ‘InternetService’, ‘contract’, and ‘PaymentMethod’, which variables affected the LTV the most? This dataset is IBM Sample Data Sets that I founded at Kaggle. Each row represents a customer; each column contains the customer’s attributes described in the column Metadata. The data set includes information about: Customers who left within the last month — the column is called Churn. Services that each customer has signed up for — phone, multiple lines, internet, online security, online backup, device protection, tech support, and streaming TV and movies Customer account information — how long they’ve been a customer, contract, payment method, paperless billing, monthly charges, and total charges Demographic info about customers — gender, age range, and if they have partners and dependents Let’s start by explaining my whole data analysis steps in this project: Step 1: Gather the data Step 2: Assess and clean the data Step 3: Conduct exploratory data analysis to answer the questions & create visualizations (Final visualization code) Step 4: Understand the limilations Step 5: Summaries Step 6: Actionable insights Step 1: Gather the data For the statsmodels.api module, since I will use multiple linear regression analysis for question 8, I included here. Step 2: Assess and clean the data Here, since the purpose of this article is to show what I did and my process of conducting a data analysis project broadly, so I won’t go over every detail. Instead, I will pick the most important procedures that I did. In case you really want to check out every detail I did, see here. Usually, I would love to view all the columns all at once, so I use pandas.set_option to do this: df.describe() df.Contract.value_counts() Month-to-month: one-year: two-year is approximately 2.5: 1: 1 # show the distribution of tenure.plt.hist(data = df, x = 'tenure'); This is apparently not a normal distribution. And with two peaks, there are two extreme kinds of people among all customers, and I will investigate what services have kept those who stay more than 70 months the most. There is no tidiness issue and only 2 issues here to consider a very clean dataset. Here are the 2 Quality issues: The data type of “TotalCharges” should be the float64 type instead of the object type. Many rows of “TotalCharges” do not equal each tenue times monthly charges. First thing first, we should copy our original dataset: df_copy = df.copy() Action: Give None value to all rows, then convert it to the data type of float64. (I will recalculate it later) df_copy.TotalCharges = Nonedf_copy.TotalCharges=df_copy.TotalCharges.astype(float) Test the results: df_copy.TotalCharges.dtype Output: dtype(‘float64’) Action: recalculate it, let each tenures times monthly charges df_copy.TotalCharges = df_copy.tenure * df_copy.MonthlyCharges Test the results: df_copy[df_copy.tenure * df_copy.MonthlyCharges != df_copy.TotalCharges].shape Output: (0, 21) The final step of the cleaning process: save the data. # store the clean datadf_copy.reset_index(drop=True)df_copy.to_csv('Telco-Customer-Churn_clean.csv') Step 3: Conduct exploratory data analysis to answer the questions & create visualizations (Final visualization code) Before writing any visualization, I like to create a reusable function, so I can save lots of time without writing the same codes: Firstly, I extracted those who unsubscribed from the service and examined the distribution of tenure. Churn_df = clean_df.query('Churn=="Yes"')Churn_df.TotalCharges.describe() Let’s see its distribution: plt.hist(data = Churn_df, x = 'TotalCharges'); After viewing the distribution and the 5-number summary, I found that around 80% of the data are extremely high, so I decided to divide them to 80% and the rest 20% to see each data distribution. (Applying 80/20 rule in real life.) #find the 80th percentile of the data in total chargesChurn_df.TotalCharges.quantile(0.8) Output: 2827.5900000000006 # Divide the data by the 80th percentile of the data, and show the distribution of its TotalCharges under 80th percentile TotalCharges_under80 = Churn_df.query('TotalCharges<=2827.59')TotalCharges_above80 = Churn_df.query('TotalCharges>2827.59') Let’s visualize our unsubscribed customers divided by 80/20 group: Ok, now, let's see the graph that combines those who unsubscribed and those paying for the service. Note: 80%(low LTV) of leaked customers only stayed under 10 months. And, the average LTV of 80% of those who unsubscribed is 750 dollars. On the other hand, the average LTV of the top 20% of unsubscribed is 4750 dollars. And the ratio by the sum of total LTV by each group is 750*4: 4750 = 1: 1.6, which suggests we should focus on serving those 20% customers with high LTV, which brought 60%(1.6/2.6) of our revenue from leaked customers. Note: 100% of those who brought high LTV used and are using internet service. Note: 81% of those who bring high LTVs tend to used lines. There is no big difference between those who are still paying for the service or those who unsubscribed. Note: Those who bring high LTVs, loved to use Fiber optic(75%-90%) and DSL(10–20%), and none of them used internet service. While those who bring low LTVs, in terms of current customers, around 30% of them don’t use internet service. Now, let’s dive deeper to see the situation of each subset of internet service. Firstly, Extract 80% with low LTV who used the internet service, and save each proportion of subsets of internet service in the variable “proportion_internet_sub_service”: And then extract 20% with high LTV who used the internet service, and save each proportion of subsets of internet service in the variable “proportion_internet_sub_service_above80” Secondly, Extract 80% with low LTV who used the internet service, and save each proportion of subsets of internet service in the variable “paying_proportion_internet_sub_service_under80” And then extract 20% with high LTV who used the internet service, and save each proportion of subsets of internet service in the variable “paying_proportion_internet_sub_service_above80” Let’s visualize it: Note: Among 80%(low LTVs) of data of current customers, all the subsets of internet services are equally used by 40% of people. And among 80% (low LTVs) of current customers, streaming movies and streaming TV are two top subsets of internet service people use, and device protection and online backup are the second places, and tech support and online security are both third places, the gaps between these are near 10% of whole data. First thing first, I extracted the groups of data I want to investigate: Note: Among 80% of current customers, those whose LTV is more than the average LTV of 80% of leaked customers are 10% more likely to use multiple lines and internet service than the average 80% of current customers. Note: 89% of those who leaked used monthly contracts, while only 42% of current customers used a monthly contract. I used multiple linear regression for these questions, so first, because most of them are categorical variables, so I needed to convert them into dummy variables: Use multiple linear regression: Note: Whether people use internet service is the most important factor in creating high LTV, and the yearly contract is second. Note: Among all the subsets of internet services, online backup is the most important factor to create high LTV Step 4: Understand the limitations Before drawing any conclusion, it is always better to inform the limitations. During the process of assessing data and conducting the exploratory data analysis, I have found some limitations: Limitation 1: In this dataset, we can only see one type of each variable instead of a real-world situation of changing different options as time passes, i.e., in the real world, people might want to try streaming services, but they might change their minds to use tech supports next month. Limitation 2: We cannot consider all these variables as the exact reasons why customers left because they might leave for the better price offered by competitors or the bad economy at a certain time, etc. We cannot see the time they leaked, so it’s hard to infer those external situations. Step 5: Summaries 80%(low LTV) of leaked customers only stayed under 10 months. And, their average is 750 dollars. On the other hand, the average LTV of the top 20% of those who leaked is 4750 dollars. And the ratio by the sum of total LTV by each group is 750*4: 4750 = 1: 1.6, which suggests we should focus on serving those 20% customers with high LTV, which brought 60%(1.6/2.6) of our revenue from leaked customers81% of those who bring high LTVs tend to used lines. There is no big difference between those who are still paying for the service or those who unsubscribed.Those who bring high LTVs loved to use Fiber optic(75%-90%) and DSL(10–20%), and none of them used internet service. While those who bring low LTVs, in terms of current customers, around 30% of them don’t use internet service.Among 80%(low LTVs) of current customers, all the subsets of internet services are equally used by 40% of people. And among 80% (low LTVs) of current customers, streaming movies and streaming TV are two top subsets of internet service people use, and device protection and online backup are the second places, and tech support and online security are both third places, the gaps between these are near 10% of whole data.Among 80% of current customers, those whose LTV is more than the average LTV of 80% of leaked customers are 10% more likely to use multiple lines and internet service than the average 80% of current customers.89% of those who leaked used a monthly contract, while only 42% of current customers use a monthly contract.Whether people use internet service is the most important factor in creating high LTV, and the yearly contract is second.Among all the subsets of internet services, online backup is the most important factor in creating high LTV. 80%(low LTV) of leaked customers only stayed under 10 months. And, their average is 750 dollars. On the other hand, the average LTV of the top 20% of those who leaked is 4750 dollars. And the ratio by the sum of total LTV by each group is 750*4: 4750 = 1: 1.6, which suggests we should focus on serving those 20% customers with high LTV, which brought 60%(1.6/2.6) of our revenue from leaked customers 81% of those who bring high LTVs tend to used lines. There is no big difference between those who are still paying for the service or those who unsubscribed. Those who bring high LTVs loved to use Fiber optic(75%-90%) and DSL(10–20%), and none of them used internet service. While those who bring low LTVs, in terms of current customers, around 30% of them don’t use internet service. Among 80%(low LTVs) of current customers, all the subsets of internet services are equally used by 40% of people. And among 80% (low LTVs) of current customers, streaming movies and streaming TV are two top subsets of internet service people use, and device protection and online backup are the second places, and tech support and online security are both third places, the gaps between these are near 10% of whole data. Among 80% of current customers, those whose LTV is more than the average LTV of 80% of leaked customers are 10% more likely to use multiple lines and internet service than the average 80% of current customers. 89% of those who leaked used a monthly contract, while only 42% of current customers use a monthly contract. Whether people use internet service is the most important factor in creating high LTV, and the yearly contract is second. Among all the subsets of internet services, online backup is the most important factor in creating high LTV. Step 6: Actionable insights For retaining customers: Create marketing campaigns to upsell those currently subscribed to streaming movies and TV services on our other internet services. (Based on the graph from Q5, the more subsets of the internet service they’re paying for, the longer they tend to stay.) Create marketing campaigns to upsell those currently subscribed to streaming movies and TV services on our other internet services. (Based on the graph from Q5, the more subsets of the internet service they’re paying for, the longer they tend to stay.) For increasing customers’ lifetime values: Increase our marketing budget on our streaming movie and TV service since these two sectors have the biggest gaps between those who brought 80%(low LTV) and 20%(high LTV). (Based on the graph from Q5)Increase our marketing budget on online backup, which is the most important factor contributing to a high LTV. (Based on the graph from Q8)Increasing our marketing budget on those who want to use multiple lines. (Based on the graph from Q6) Increase our marketing budget on our streaming movie and TV service since these two sectors have the biggest gaps between those who brought 80%(low LTV) and 20%(high LTV). (Based on the graph from Q5) Increase our marketing budget on online backup, which is the most important factor contributing to a high LTV. (Based on the graph from Q8) Increasing our marketing budget on those who want to use multiple lines. (Based on the graph from Q6) Finally, data has a better idea, but you should always doubt any insight and the data to be some degree wrong or have some biases, no matter who provided them to you are experts or people with high credibility. Thanks for spending your time reading this article. If you’re an employer wanting to find a data analyst intern, here is my LinkedIn or contact me through my email([email protected]) If you’re also working in the data science/business analytics field, feel free to give me any feedback through IG(@jchen_mmm), by email, or by comment below!
[ { "code": null, "e": 362, "s": 172, "text": "To extract actionable insights from the dataset. I listed all the questions that came to mind below after assessing the dataset, and I tried to investigate all of them to find the insights:" }, { "code": null, "e": 507, "s": 362, "text": "1. How long did unsubscribed people who are paying for the service usually stay in the service? And what was their average LTV(Life Time Value)?" }, { "code": null, "e": 589, "s": 507, "text": "2. How many of those who unsubscribed and still subscribe used the phone service?" }, { "code": null, "e": 695, "s": 589, "text": "3. How many people use phone services with multiple lines for those who unsubscribed and still subscribe?" }, { "code": null, "e": 783, "s": 695, "text": "4. How many people used the internet service for those who unsubscribed and subscribed?" }, { "code": null, "e": 912, "s": 783, "text": "5. How many people used and using each subset of internet service for those who unsubscribed and who are paying for the service?" }, { "code": null, "e": 1067, "s": 912, "text": "6. What are the differences in each service internet service for those who are still in service with LTV higher than the average LTV of leaked customers,?" }, { "code": null, "e": 1181, "s": 1067, "text": "7. How many subscribed to each kind of contract for those who unsubscribed and still are paying for the service,?" }, { "code": null, "e": 1335, "s": 1181, "text": "8. Among ‘gender’, ‘Partner’, ‘Dependents’,’PhoneService’, ‘InternetService’, ‘contract’, and ‘PaymentMethod’, which variables affected the LTV the most?" }, { "code": null, "e": 1398, "s": 1335, "text": "This dataset is IBM Sample Data Sets that I founded at Kaggle." }, { "code": null, "e": 1511, "s": 1398, "text": "Each row represents a customer; each column contains the customer’s attributes described in the column Metadata." }, { "code": null, "e": 1552, "s": 1511, "text": "The data set includes information about:" }, { "code": null, "e": 1623, "s": 1552, "text": "Customers who left within the last month — the column is called Churn." }, { "code": null, "e": 1797, "s": 1623, "text": "Services that each customer has signed up for — phone, multiple lines, internet, online security, online backup, device protection, tech support, and streaming TV and movies" }, { "code": null, "e": 1942, "s": 1797, "text": "Customer account information — how long they’ve been a customer, contract, payment method, paperless billing, monthly charges, and total charges" }, { "code": null, "e": 2037, "s": 1942, "text": "Demographic info about customers — gender, age range, and if they have partners and dependents" }, { "code": null, "e": 2109, "s": 2037, "text": "Let’s start by explaining my whole data analysis steps in this project:" }, { "code": null, "e": 2133, "s": 2109, "text": "Step 1: Gather the data" }, { "code": null, "e": 2167, "s": 2133, "text": "Step 2: Assess and clean the data" }, { "code": null, "e": 2284, "s": 2167, "text": "Step 3: Conduct exploratory data analysis to answer the questions & create visualizations (Final visualization code)" }, { "code": null, "e": 2319, "s": 2284, "text": "Step 4: Understand the limilations" }, { "code": null, "e": 2337, "s": 2319, "text": "Step 5: Summaries" }, { "code": null, "e": 2365, "s": 2337, "text": "Step 6: Actionable insights" }, { "code": null, "e": 2389, "s": 2365, "text": "Step 1: Gather the data" }, { "code": null, "e": 2507, "s": 2389, "text": "For the statsmodels.api module, since I will use multiple linear regression analysis for question 8, I included here." }, { "code": null, "e": 2541, "s": 2507, "text": "Step 2: Assess and clean the data" }, { "code": null, "e": 2828, "s": 2541, "text": "Here, since the purpose of this article is to show what I did and my process of conducting a data analysis project broadly, so I won’t go over every detail. Instead, I will pick the most important procedures that I did. In case you really want to check out every detail I did, see here." }, { "code": null, "e": 2926, "s": 2828, "text": "Usually, I would love to view all the columns all at once, so I use pandas.set_option to do this:" }, { "code": null, "e": 2940, "s": 2926, "text": "df.describe()" }, { "code": null, "e": 2967, "s": 2940, "text": "df.Contract.value_counts()" }, { "code": null, "e": 3029, "s": 2967, "text": "Month-to-month: one-year: two-year is approximately 2.5: 1: 1" }, { "code": null, "e": 3098, "s": 3029, "text": "# show the distribution of tenure.plt.hist(data = df, x = 'tenure');" }, { "code": null, "e": 3315, "s": 3098, "text": "This is apparently not a normal distribution. And with two peaks, there are two extreme kinds of people among all customers, and I will investigate what services have kept those who stay more than 70 months the most." }, { "code": null, "e": 3430, "s": 3315, "text": "There is no tidiness issue and only 2 issues here to consider a very clean dataset. Here are the 2 Quality issues:" }, { "code": null, "e": 3517, "s": 3430, "text": "The data type of “TotalCharges” should be the float64 type instead of the object type." }, { "code": null, "e": 3592, "s": 3517, "text": "Many rows of “TotalCharges” do not equal each tenue times monthly charges." }, { "code": null, "e": 3648, "s": 3592, "text": "First thing first, we should copy our original dataset:" }, { "code": null, "e": 3668, "s": 3648, "text": "df_copy = df.copy()" }, { "code": null, "e": 3780, "s": 3668, "text": "Action: Give None value to all rows, then convert it to the data type of float64. (I will recalculate it later)" }, { "code": null, "e": 3863, "s": 3780, "text": "df_copy.TotalCharges = Nonedf_copy.TotalCharges=df_copy.TotalCharges.astype(float)" }, { "code": null, "e": 3881, "s": 3863, "text": "Test the results:" }, { "code": null, "e": 3908, "s": 3881, "text": "df_copy.TotalCharges.dtype" }, { "code": null, "e": 3933, "s": 3908, "text": "Output: dtype(‘float64’)" }, { "code": null, "e": 3996, "s": 3933, "text": "Action: recalculate it, let each tenures times monthly charges" }, { "code": null, "e": 4059, "s": 3996, "text": "df_copy.TotalCharges = df_copy.tenure * df_copy.MonthlyCharges" }, { "code": null, "e": 4077, "s": 4059, "text": "Test the results:" }, { "code": null, "e": 4156, "s": 4077, "text": "df_copy[df_copy.tenure * df_copy.MonthlyCharges != df_copy.TotalCharges].shape" }, { "code": null, "e": 4172, "s": 4156, "text": "Output: (0, 21)" }, { "code": null, "e": 4227, "s": 4172, "text": "The final step of the cleaning process: save the data." }, { "code": null, "e": 4328, "s": 4227, "text": "# store the clean datadf_copy.reset_index(drop=True)df_copy.to_csv('Telco-Customer-Churn_clean.csv')" }, { "code": null, "e": 4445, "s": 4328, "text": "Step 3: Conduct exploratory data analysis to answer the questions & create visualizations (Final visualization code)" }, { "code": null, "e": 4576, "s": 4445, "text": "Before writing any visualization, I like to create a reusable function, so I can save lots of time without writing the same codes:" }, { "code": null, "e": 4678, "s": 4576, "text": "Firstly, I extracted those who unsubscribed from the service and examined the distribution of tenure." }, { "code": null, "e": 4752, "s": 4678, "text": "Churn_df = clean_df.query('Churn==\"Yes\"')Churn_df.TotalCharges.describe()" }, { "code": null, "e": 4780, "s": 4752, "text": "Let’s see its distribution:" }, { "code": null, "e": 4827, "s": 4780, "text": "plt.hist(data = Churn_df, x = 'TotalCharges');" }, { "code": null, "e": 5059, "s": 4827, "text": "After viewing the distribution and the 5-number summary, I found that around 80% of the data are extremely high, so I decided to divide them to 80% and the rest 20% to see each data distribution. (Applying 80/20 rule in real life.)" }, { "code": null, "e": 5149, "s": 5059, "text": "#find the 80th percentile of the data in total chargesChurn_df.TotalCharges.quantile(0.8)" }, { "code": null, "e": 5176, "s": 5149, "text": "Output: 2827.5900000000006" }, { "code": null, "e": 5422, "s": 5176, "text": "# Divide the data by the 80th percentile of the data, and show the distribution of its TotalCharges under 80th percentile TotalCharges_under80 = Churn_df.query('TotalCharges<=2827.59')TotalCharges_above80 = Churn_df.query('TotalCharges>2827.59')" }, { "code": null, "e": 5489, "s": 5422, "text": "Let’s visualize our unsubscribed customers divided by 80/20 group:" }, { "code": null, "e": 5589, "s": 5489, "text": "Ok, now, let's see the graph that combines those who unsubscribed and those paying for the service." }, { "code": null, "e": 6029, "s": 5589, "text": "Note: 80%(low LTV) of leaked customers only stayed under 10 months. And, the average LTV of 80% of those who unsubscribed is 750 dollars. On the other hand, the average LTV of the top 20% of unsubscribed is 4750 dollars. And the ratio by the sum of total LTV by each group is 750*4: 4750 = 1: 1.6, which suggests we should focus on serving those 20% customers with high LTV, which brought 60%(1.6/2.6) of our revenue from leaked customers." }, { "code": null, "e": 6107, "s": 6029, "text": "Note: 100% of those who brought high LTV used and are using internet service." }, { "code": null, "e": 6271, "s": 6107, "text": "Note: 81% of those who bring high LTVs tend to used lines. There is no big difference between those who are still paying for the service or those who unsubscribed." }, { "code": null, "e": 6505, "s": 6271, "text": "Note: Those who bring high LTVs, loved to use Fiber optic(75%-90%) and DSL(10–20%), and none of them used internet service. While those who bring low LTVs, in terms of current customers, around 30% of them don’t use internet service." }, { "code": null, "e": 6585, "s": 6505, "text": "Now, let’s dive deeper to see the situation of each subset of internet service." }, { "code": null, "e": 6757, "s": 6585, "text": "Firstly, Extract 80% with low LTV who used the internet service, and save each proportion of subsets of internet service in the variable “proportion_internet_sub_service”:" }, { "code": null, "e": 6937, "s": 6757, "text": "And then extract 20% with high LTV who used the internet service, and save each proportion of subsets of internet service in the variable “proportion_internet_sub_service_above80”" }, { "code": null, "e": 7124, "s": 6937, "text": "Secondly, Extract 80% with low LTV who used the internet service, and save each proportion of subsets of internet service in the variable “paying_proportion_internet_sub_service_under80”" }, { "code": null, "e": 7311, "s": 7124, "text": "And then extract 20% with high LTV who used the internet service, and save each proportion of subsets of internet service in the variable “paying_proportion_internet_sub_service_above80”" }, { "code": null, "e": 7331, "s": 7311, "text": "Let’s visualize it:" }, { "code": null, "e": 7766, "s": 7331, "text": "Note: Among 80%(low LTVs) of data of current customers, all the subsets of internet services are equally used by 40% of people. And among 80% (low LTVs) of current customers, streaming movies and streaming TV are two top subsets of internet service people use, and device protection and online backup are the second places, and tech support and online security are both third places, the gaps between these are near 10% of whole data." }, { "code": null, "e": 7839, "s": 7766, "text": "First thing first, I extracted the groups of data I want to investigate:" }, { "code": null, "e": 8055, "s": 7839, "text": "Note: Among 80% of current customers, those whose LTV is more than the average LTV of 80% of leaked customers are 10% more likely to use multiple lines and internet service than the average 80% of current customers." }, { "code": null, "e": 8170, "s": 8055, "text": "Note: 89% of those who leaked used monthly contracts, while only 42% of current customers used a monthly contract." }, { "code": null, "e": 8333, "s": 8170, "text": "I used multiple linear regression for these questions, so first, because most of them are categorical variables, so I needed to convert them into dummy variables:" }, { "code": null, "e": 8365, "s": 8333, "text": "Use multiple linear regression:" }, { "code": null, "e": 8493, "s": 8365, "text": "Note: Whether people use internet service is the most important factor in creating high LTV, and the yearly contract is second." }, { "code": null, "e": 8605, "s": 8493, "text": "Note: Among all the subsets of internet services, online backup is the most important factor to create high LTV" }, { "code": null, "e": 8640, "s": 8605, "text": "Step 4: Understand the limitations" }, { "code": null, "e": 8832, "s": 8640, "text": "Before drawing any conclusion, it is always better to inform the limitations. During the process of assessing data and conducting the exploratory data analysis, I have found some limitations:" }, { "code": null, "e": 9122, "s": 8832, "text": "Limitation 1: In this dataset, we can only see one type of each variable instead of a real-world situation of changing different options as time passes, i.e., in the real world, people might want to try streaming services, but they might change their minds to use tech supports next month." }, { "code": null, "e": 9412, "s": 9122, "text": "Limitation 2: We cannot consider all these variables as the exact reasons why customers left because they might leave for the better price offered by competitors or the bad economy at a certain time, etc. We cannot see the time they leaked, so it’s hard to infer those external situations." }, { "code": null, "e": 9430, "s": 9412, "text": "Step 5: Summaries" }, { "code": null, "e": 11181, "s": 9430, "text": "80%(low LTV) of leaked customers only stayed under 10 months. And, their average is 750 dollars. On the other hand, the average LTV of the top 20% of those who leaked is 4750 dollars. And the ratio by the sum of total LTV by each group is 750*4: 4750 = 1: 1.6, which suggests we should focus on serving those 20% customers with high LTV, which brought 60%(1.6/2.6) of our revenue from leaked customers81% of those who bring high LTVs tend to used lines. There is no big difference between those who are still paying for the service or those who unsubscribed.Those who bring high LTVs loved to use Fiber optic(75%-90%) and DSL(10–20%), and none of them used internet service. While those who bring low LTVs, in terms of current customers, around 30% of them don’t use internet service.Among 80%(low LTVs) of current customers, all the subsets of internet services are equally used by 40% of people. And among 80% (low LTVs) of current customers, streaming movies and streaming TV are two top subsets of internet service people use, and device protection and online backup are the second places, and tech support and online security are both third places, the gaps between these are near 10% of whole data.Among 80% of current customers, those whose LTV is more than the average LTV of 80% of leaked customers are 10% more likely to use multiple lines and internet service than the average 80% of current customers.89% of those who leaked used a monthly contract, while only 42% of current customers use a monthly contract.Whether people use internet service is the most important factor in creating high LTV, and the yearly contract is second.Among all the subsets of internet services, online backup is the most important factor in creating high LTV." }, { "code": null, "e": 11583, "s": 11181, "text": "80%(low LTV) of leaked customers only stayed under 10 months. And, their average is 750 dollars. On the other hand, the average LTV of the top 20% of those who leaked is 4750 dollars. And the ratio by the sum of total LTV by each group is 750*4: 4750 = 1: 1.6, which suggests we should focus on serving those 20% customers with high LTV, which brought 60%(1.6/2.6) of our revenue from leaked customers" }, { "code": null, "e": 11741, "s": 11583, "text": "81% of those who bring high LTVs tend to used lines. There is no big difference between those who are still paying for the service or those who unsubscribed." }, { "code": null, "e": 11968, "s": 11741, "text": "Those who bring high LTVs loved to use Fiber optic(75%-90%) and DSL(10–20%), and none of them used internet service. While those who bring low LTVs, in terms of current customers, around 30% of them don’t use internet service." }, { "code": null, "e": 12389, "s": 11968, "text": "Among 80%(low LTVs) of current customers, all the subsets of internet services are equally used by 40% of people. And among 80% (low LTVs) of current customers, streaming movies and streaming TV are two top subsets of internet service people use, and device protection and online backup are the second places, and tech support and online security are both third places, the gaps between these are near 10% of whole data." }, { "code": null, "e": 12599, "s": 12389, "text": "Among 80% of current customers, those whose LTV is more than the average LTV of 80% of leaked customers are 10% more likely to use multiple lines and internet service than the average 80% of current customers." }, { "code": null, "e": 12708, "s": 12599, "text": "89% of those who leaked used a monthly contract, while only 42% of current customers use a monthly contract." }, { "code": null, "e": 12830, "s": 12708, "text": "Whether people use internet service is the most important factor in creating high LTV, and the yearly contract is second." }, { "code": null, "e": 12939, "s": 12830, "text": "Among all the subsets of internet services, online backup is the most important factor in creating high LTV." }, { "code": null, "e": 12967, "s": 12939, "text": "Step 6: Actionable insights" }, { "code": null, "e": 12992, "s": 12967, "text": "For retaining customers:" }, { "code": null, "e": 13245, "s": 12992, "text": "Create marketing campaigns to upsell those currently subscribed to streaming movies and TV services on our other internet services. (Based on the graph from Q5, the more subsets of the internet service they’re paying for, the longer they tend to stay.)" }, { "code": null, "e": 13498, "s": 13245, "text": "Create marketing campaigns to upsell those currently subscribed to streaming movies and TV services on our other internet services. (Based on the graph from Q5, the more subsets of the internet service they’re paying for, the longer they tend to stay.)" }, { "code": null, "e": 13541, "s": 13498, "text": "For increasing customers’ lifetime values:" }, { "code": null, "e": 13982, "s": 13541, "text": "Increase our marketing budget on our streaming movie and TV service since these two sectors have the biggest gaps between those who brought 80%(low LTV) and 20%(high LTV). (Based on the graph from Q5)Increase our marketing budget on online backup, which is the most important factor contributing to a high LTV. (Based on the graph from Q8)Increasing our marketing budget on those who want to use multiple lines. (Based on the graph from Q6)" }, { "code": null, "e": 14183, "s": 13982, "text": "Increase our marketing budget on our streaming movie and TV service since these two sectors have the biggest gaps between those who brought 80%(low LTV) and 20%(high LTV). (Based on the graph from Q5)" }, { "code": null, "e": 14323, "s": 14183, "text": "Increase our marketing budget on online backup, which is the most important factor contributing to a high LTV. (Based on the graph from Q8)" }, { "code": null, "e": 14425, "s": 14323, "text": "Increasing our marketing budget on those who want to use multiple lines. (Based on the graph from Q6)" }, { "code": null, "e": 14636, "s": 14425, "text": "Finally, data has a better idea, but you should always doubt any insight and the data to be some degree wrong or have some biases, no matter who provided them to you are experts or people with high credibility." }, { "code": null, "e": 14688, "s": 14636, "text": "Thanks for spending your time reading this article." }, { "code": null, "e": 14825, "s": 14688, "text": "If you’re an employer wanting to find a data analyst intern, here is my LinkedIn or contact me through my email([email protected])" } ]
std::remove, std::remove_if in c++ - GeeksforGeeks
08 Mar, 2021 std :: remove It is defined in <algorithm> library. It removes value from range. Transforms the range [first,last) into a range with all the elements that compare equal to val removed, and returns an iterator to the new end of that range. The function cannot alter the properties of the object containing the range of elements (i.e., it cannot alter the size of an array or a container). The relative order of the elements not removed is preserved, while the elements between the returned iterator and last are left in a valid but unspecified state. The function uses operator== to compare the individual elements to val. Function Template : ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val) first,last : The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last. val : Value to be removed. Return value : An iterator to the element that follows the last element not removed. The range between first and this iterator includes all the elements in the sequence that do not compare equal to val. Example: Input : 10 20 30 30 20 10 10 20 Output : 10 30 30 10 10 // Value removed is 20. std :: remove_if Transforms the range [first,last) into a range with all the elements for which pred returns true removed, and returns an iterator to the new end of that range. Function Template : ForwardIterator remove_if (ForwardIterator first, ForwardIterator last, UnaryPredicate pred); pred Unary function that accepts an element in the range as argument, and returns a value convertible to bool. The value returned indicates whether the element is to be removed (if true, it is removed). The function shall not modify its argument. This can either be a function pointer or a function object. Example: Input : 1 2 3 4 5 6 7 8 9 10 Output : 2 4 6 8 10 // Odd elements removed. CPP // CPP program to illustrate// std::remove and std::remove_if// algorithm#include <bits/stdc++.h> // Function to check whether// the element is odd or not.bool IsOdd(int i) { return ((i % 2) == 1); } // Driver codeint main(){ std ::vector<int> vec1{ 10, 20, 30, 30, 20, 10, 10, 20 }; std ::vector<int> vec2{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Print original vector std ::cout << "Original vector : "; for (int i = 0; i < vec1.size(); i++) std ::cout << " " << vec1[i]; std ::cout << "\n"; // Iterator that store the position of last element std ::vector<int>::iterator pend; // std ::remove function call pend = std ::remove(vec1.begin(), vec1.end(), 20); // Print the vector std ::cout << "After remove : "; for (std ::vector<int>::iterator p = vec1.begin(); p != pend; ++p) std ::cout << ' ' << *p; std ::cout << '\n'; // Print original vector std ::cout << "\nOriginal vector : "; for (int i = 0; i < vec2.size(); i++) std ::cout << " " << vec2[i]; std ::cout << "\n"; // std ::remove_if function call pend = std ::remove_if(vec2.begin(), vec2.end(), IsOdd); // the same of the above can be done using lambda // function in 1 line pend = std ::remove_if( vec2.begin(), vec2.end(), [](int i) { return ((i % 2) == 1); }); // Print the vector std ::cout << "After remove_if : "; for (std ::vector<int>::iterator q = vec2.begin(); q != pend; ++q) std ::cout << ' ' << *q; std ::cout << '\n'; return 0;} Output: Original vector : 10 20 30 30 20 10 10 20 After remove : 10 30 30 10 10 Original vector : 1 2 3 4 5 6 7 8 9 10 After remove_if : 2 4 6 8 10 This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sriramvuppuluri cpp-algorithm-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Inline Functions in C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++
[ { "code": null, "e": 25367, "s": 25339, "text": "\n08 Mar, 2021" }, { "code": null, "e": 25381, "s": 25367, "text": "std :: remove" }, { "code": null, "e": 25607, "s": 25381, "text": "It is defined in <algorithm> library. It removes value from range. Transforms the range [first,last) into a range with all the elements that compare equal to val removed, and returns an iterator to the new end of that range. " }, { "code": null, "e": 25756, "s": 25607, "text": "The function cannot alter the properties of the object containing the range of elements (i.e., it cannot alter the size of an array or a container)." }, { "code": null, "e": 25918, "s": 25756, "text": "The relative order of the elements not removed is preserved, while the elements between the returned iterator and last are left in a valid but unspecified state." }, { "code": null, "e": 25990, "s": 25918, "text": "The function uses operator== to compare the individual elements to val." }, { "code": null, "e": 26012, "s": 25990, "text": "Function Template : " }, { "code": null, "e": 26508, "s": 26012, "text": "ForwardIterator remove (ForwardIterator first,\nForwardIterator last, const T& val)\n\nfirst,last :\n The range used is [first,last), which contains all the\nelements between first and last, including the element\npointed by first but not the element pointed by last.\n\nval :\nValue to be removed.\n\nReturn value :\nAn iterator to the element that follows the last element not removed.\nThe range between first and this iterator includes all the elements\nin the sequence that do not compare equal to val." }, { "code": null, "e": 26519, "s": 26508, "text": "Example: " }, { "code": null, "e": 26602, "s": 26519, "text": "Input : 10 20 30 30 20 10 10 20\nOutput : 10 30 30 10 10 // Value removed is 20." }, { "code": null, "e": 26619, "s": 26602, "text": "std :: remove_if" }, { "code": null, "e": 26801, "s": 26619, "text": "Transforms the range [first,last) into a range with all the elements for which pred returns true removed, and returns an iterator to the new end of that range. Function Template : " }, { "code": null, "e": 27207, "s": 26801, "text": " ForwardIterator remove_if (ForwardIterator first,\n ForwardIterator last, UnaryPredicate pred);\n\npred\nUnary function that accepts an element in the range as\nargument, and returns a value convertible to bool. The\nvalue returned indicates whether the element is to be\nremoved (if true, it is removed).\nThe function shall not modify its argument.\nThis can either be a function pointer or a function object." }, { "code": null, "e": 27218, "s": 27207, "text": "Example: " }, { "code": null, "e": 27296, "s": 27218, "text": "Input : 1 2 3 4 5 6 7 8 9 10\nOutput : 2 4 6 8 10 // Odd elements removed. " }, { "code": null, "e": 27300, "s": 27296, "text": "CPP" }, { "code": "// CPP program to illustrate// std::remove and std::remove_if// algorithm#include <bits/stdc++.h> // Function to check whether// the element is odd or not.bool IsOdd(int i) { return ((i % 2) == 1); } // Driver codeint main(){ std ::vector<int> vec1{ 10, 20, 30, 30, 20, 10, 10, 20 }; std ::vector<int> vec2{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Print original vector std ::cout << \"Original vector : \"; for (int i = 0; i < vec1.size(); i++) std ::cout << \" \" << vec1[i]; std ::cout << \"\\n\"; // Iterator that store the position of last element std ::vector<int>::iterator pend; // std ::remove function call pend = std ::remove(vec1.begin(), vec1.end(), 20); // Print the vector std ::cout << \"After remove : \"; for (std ::vector<int>::iterator p = vec1.begin(); p != pend; ++p) std ::cout << ' ' << *p; std ::cout << '\\n'; // Print original vector std ::cout << \"\\nOriginal vector : \"; for (int i = 0; i < vec2.size(); i++) std ::cout << \" \" << vec2[i]; std ::cout << \"\\n\"; // std ::remove_if function call pend = std ::remove_if(vec2.begin(), vec2.end(), IsOdd); // the same of the above can be done using lambda // function in 1 line pend = std ::remove_if( vec2.begin(), vec2.end(), [](int i) { return ((i % 2) == 1); }); // Print the vector std ::cout << \"After remove_if : \"; for (std ::vector<int>::iterator q = vec2.begin(); q != pend; ++q) std ::cout << ' ' << *q; std ::cout << '\\n'; return 0;}", "e": 28864, "s": 27300, "text": null }, { "code": null, "e": 28873, "s": 28864, "text": "Output: " }, { "code": null, "e": 29018, "s": 28873, "text": "Original vector : 10 20 30 30 20 10 10 20\nAfter remove : 10 30 30 10 10\n\nOriginal vector : 1 2 3 4 5 6 7 8 9 10\nAfter remove_if : 2 4 6 8 10" }, { "code": null, "e": 29443, "s": 29018, "text": "This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 29459, "s": 29443, "text": "sriramvuppuluri" }, { "code": null, "e": 29481, "s": 29459, "text": "cpp-algorithm-library" }, { "code": null, "e": 29485, "s": 29481, "text": "STL" }, { "code": null, "e": 29489, "s": 29485, "text": "C++" }, { "code": null, "e": 29493, "s": 29489, "text": "STL" }, { "code": null, "e": 29497, "s": 29493, "text": "CPP" }, { "code": null, "e": 29595, "s": 29497, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29623, "s": 29595, "text": "Operator Overloading in C++" }, { "code": null, "e": 29643, "s": 29623, "text": "Polymorphism in C++" }, { "code": null, "e": 29667, "s": 29643, "text": "Sorting a vector in C++" }, { "code": null, "e": 29700, "s": 29667, "text": "Friend class and function in C++" }, { "code": null, "e": 29725, "s": 29700, "text": "std::string class in C++" }, { "code": null, "e": 29769, "s": 29725, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 29814, "s": 29769, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 29838, "s": 29814, "text": "Inline Functions in C++" }, { "code": null, "e": 29891, "s": 29838, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
What is widgets in Flutter? - GeeksforGeeks
17 Nov, 2020 Flutter is Google’s UI toolkit for crafting beautiful, natively compiled iOS and Android apps from a single code base. To build any application we start with widgets – The building block of flutter applications. Widgets describe what their view should look like given their current configuration and state. It includes a text widget, row widget, column widget, container widget, and many more. Widgets: Each element on a screen of the Flutter app is a widget. The view of the screen completely depends upon the choice and sequence of the widgets used to build the app. And the structure of the code of an app is a tree of widgets. Category of Widgets: There are mainly 14 categories in which the flutter widgets are divided. They are mainly segregated on the basis of the functionality they provide in a flutter application. Accessibility: These are the set of widgets that make a flutter app more easily accessible.Animation and Motion: These widgets add animation to other widgets.Assets, Images, and Icons: These widgets take charge of assets such as display images and show icons.Async: These provide async functionality in the flutter application.Basics: These are the bundle of widgets which are absolutely necessary for the development of any flutter application.Cupertino: These are the ios designed widgets.Input: This set of widgets provide input functionality in a flutter application.Interaction Models: These widgets are here to manage touch events and route users to different views in the application. Layout: This bundle of widgets helps in placing the other widgets on the screen as needed.Material Components: This is a set of widgets that mainly follow material design by Google.Painting and effects: This is the set of widgets which apply visual changes to their child widgets without changing their layout or shape.Scrolling: This provides sacrollability of to a set of other widgets that are not scrollable by default.Styling: This deals with the theme, responsiveness, and sizing of the app.Text: This display text. Accessibility: These are the set of widgets that make a flutter app more easily accessible. Animation and Motion: These widgets add animation to other widgets. Assets, Images, and Icons: These widgets take charge of assets such as display images and show icons. Async: These provide async functionality in the flutter application. Basics: These are the bundle of widgets which are absolutely necessary for the development of any flutter application. Cupertino: These are the ios designed widgets. Input: This set of widgets provide input functionality in a flutter application. Interaction Models: These widgets are here to manage touch events and route users to different views in the application. Layout: This bundle of widgets helps in placing the other widgets on the screen as needed. Material Components: This is a set of widgets that mainly follow material design by Google. Painting and effects: This is the set of widgets which apply visual changes to their child widgets without changing their layout or shape. Scrolling: This provides sacrollability of to a set of other widgets that are not scrollable by default. Styling: This deals with the theme, responsiveness, and sizing of the app. Text: This display text. Types of Widgets: There are broadly two types of widgets in the flutter: Stateless WidgetStateful Widget Stateless Widget Stateful Widget Example: The Layout Tree of basic app screen: Dart import 'package:flutter/material.dart'; void main() => runApp(GeeksforGeeks()); class GeeksforGeeks extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( backgroundColor: Colors.lightGreen, appBar: AppBar( backgroundColor: Colors.green, title: Text("GeeksforGeeks"), ), body: Container( child: Center( child: Text("Hello Geeks!!"), ), ), ), ); } } Description of the Widgets Used: Scaffold – Implements the basic material design visual layout structure. AppBar – To create a bar at the top of the screen. Text To write anything on the screen. Container – To contain any widget. Center – To provide center alignment to other widgets. Output: ankit_kumar_ Flutter Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Asset Image Splash Screen in Flutter Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget ListView Class in Flutter Getter and Setter Methods in Dart Flutter - Flexible Widget How to Append or Concatenate Strings in Dart?
[ { "code": null, "e": 27183, "s": 27155, "text": "\n17 Nov, 2020" }, { "code": null, "e": 27578, "s": 27183, "text": "Flutter is Google’s UI toolkit for crafting beautiful, natively compiled iOS and Android apps from a single code base. To build any application we start with widgets – The building block of flutter applications. Widgets describe what their view should look like given their current configuration and state. It includes a text widget, row widget, column widget, container widget, and many more. " }, { "code": null, "e": 27816, "s": 27578, "text": "Widgets: Each element on a screen of the Flutter app is a widget. The view of the screen completely depends upon the choice and sequence of the widgets used to build the app. And the structure of the code of an app is a tree of widgets. " }, { "code": null, "e": 28010, "s": 27816, "text": "Category of Widgets: There are mainly 14 categories in which the flutter widgets are divided. They are mainly segregated on the basis of the functionality they provide in a flutter application." }, { "code": null, "e": 29224, "s": 28010, "text": "Accessibility: These are the set of widgets that make a flutter app more easily accessible.Animation and Motion: These widgets add animation to other widgets.Assets, Images, and Icons: These widgets take charge of assets such as display images and show icons.Async: These provide async functionality in the flutter application.Basics: These are the bundle of widgets which are absolutely necessary for the development of any flutter application.Cupertino: These are the ios designed widgets.Input: This set of widgets provide input functionality in a flutter application.Interaction Models: These widgets are here to manage touch events and route users to different views in the application. Layout: This bundle of widgets helps in placing the other widgets on the screen as needed.Material Components: This is a set of widgets that mainly follow material design by Google.Painting and effects: This is the set of widgets which apply visual changes to their child widgets without changing their layout or shape.Scrolling: This provides sacrollability of to a set of other widgets that are not scrollable by default.Styling: This deals with the theme, responsiveness, and sizing of the app.Text: This display text." }, { "code": null, "e": 29316, "s": 29224, "text": "Accessibility: These are the set of widgets that make a flutter app more easily accessible." }, { "code": null, "e": 29384, "s": 29316, "text": "Animation and Motion: These widgets add animation to other widgets." }, { "code": null, "e": 29486, "s": 29384, "text": "Assets, Images, and Icons: These widgets take charge of assets such as display images and show icons." }, { "code": null, "e": 29555, "s": 29486, "text": "Async: These provide async functionality in the flutter application." }, { "code": null, "e": 29674, "s": 29555, "text": "Basics: These are the bundle of widgets which are absolutely necessary for the development of any flutter application." }, { "code": null, "e": 29721, "s": 29674, "text": "Cupertino: These are the ios designed widgets." }, { "code": null, "e": 29802, "s": 29721, "text": "Input: This set of widgets provide input functionality in a flutter application." }, { "code": null, "e": 29923, "s": 29802, "text": "Interaction Models: These widgets are here to manage touch events and route users to different views in the application." }, { "code": null, "e": 30015, "s": 29923, "text": " Layout: This bundle of widgets helps in placing the other widgets on the screen as needed." }, { "code": null, "e": 30107, "s": 30015, "text": "Material Components: This is a set of widgets that mainly follow material design by Google." }, { "code": null, "e": 30246, "s": 30107, "text": "Painting and effects: This is the set of widgets which apply visual changes to their child widgets without changing their layout or shape." }, { "code": null, "e": 30351, "s": 30246, "text": "Scrolling: This provides sacrollability of to a set of other widgets that are not scrollable by default." }, { "code": null, "e": 30426, "s": 30351, "text": "Styling: This deals with the theme, responsiveness, and sizing of the app." }, { "code": null, "e": 30451, "s": 30426, "text": "Text: This display text." }, { "code": null, "e": 30525, "s": 30451, "text": "Types of Widgets: There are broadly two types of widgets in the flutter: " }, { "code": null, "e": 30557, "s": 30525, "text": "Stateless WidgetStateful Widget" }, { "code": null, "e": 30574, "s": 30557, "text": "Stateless Widget" }, { "code": null, "e": 30590, "s": 30574, "text": "Stateful Widget" }, { "code": null, "e": 30637, "s": 30590, "text": "Example: The Layout Tree of basic app screen: " }, { "code": null, "e": 30642, "s": 30637, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(GeeksforGeeks()); class GeeksforGeeks extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( backgroundColor: Colors.lightGreen, appBar: AppBar( backgroundColor: Colors.green, title: Text(\"GeeksforGeeks\"), ), body: Container( child: Center( child: Text(\"Hello Geeks!!\"), ), ), ), ); } } ", "e": 31173, "s": 30642, "text": null }, { "code": null, "e": 31210, "s": 31176, "text": "Description of the Widgets Used: " }, { "code": null, "e": 31283, "s": 31210, "text": "Scaffold – Implements the basic material design visual layout structure." }, { "code": null, "e": 31334, "s": 31283, "text": "AppBar – To create a bar at the top of the screen." }, { "code": null, "e": 31373, "s": 31334, "text": "Text To write anything on the screen." }, { "code": null, "e": 31408, "s": 31373, "text": "Container – To contain any widget." }, { "code": null, "e": 31463, "s": 31408, "text": "Center – To provide center alignment to other widgets." }, { "code": null, "e": 31473, "s": 31463, "text": "Output: " }, { "code": null, "e": 31492, "s": 31479, "text": "ankit_kumar_" }, { "code": null, "e": 31500, "s": 31492, "text": "Flutter" }, { "code": null, "e": 31505, "s": 31500, "text": "Dart" }, { "code": null, "e": 31603, "s": 31505, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31635, "s": 31603, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 31663, "s": 31635, "text": "Listview.builder in Flutter" }, { "code": null, "e": 31685, "s": 31663, "text": "Flutter - Asset Image" }, { "code": null, "e": 31710, "s": 31685, "text": "Splash Screen in Flutter" }, { "code": null, "e": 31749, "s": 31710, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 31775, "s": 31749, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 31801, "s": 31775, "text": "ListView Class in Flutter" }, { "code": null, "e": 31835, "s": 31801, "text": "Getter and Setter Methods in Dart" }, { "code": null, "e": 31861, "s": 31835, "text": "Flutter - Flexible Widget" } ]
Null object Design Pattern - GeeksforGeeks
04 Oct, 2019 The Null object pattern is a design pattern that simplifies the use of dependencies that can be undefined. This is achieved by using instances of a concrete class that implements a known interface, instead of null references.We create an abstract class specifying various operations to be done, concrete classes extending this class and a null object class providing do nothing implementation of this class and will be used seamlessly where we need to check null value. UML Diagram for Null object Design pattern Design components Client : This class has a dependency that may or may not be required. Where no functionality is required in the dependency, it will execute the methods of a null object. DependencyBase : This abstract class is the base class for the various available dependencies that the Client may use. This is also the base class for the null object class. Where the base class provides no shared functionality, it may be replaced with an interface. Dependency : This class is a functional dependency that may be used by the Client. NullObject : This is the null object class that can be used as a dependency by the Client. It contains no functionality but implements all of the members defined by the DependencyBase abstract class. Let’s see an example of Null object design pattern. // Java program to illustrate Null// Object Design Pattern abstract class Emp{ protected String name; public abstract boolean isNull(); public abstract String getName();} class Coder extends Emp{ public Coder(String name) { this.name = name; } @Override public String getName() { return name; } @Override public boolean isNull() { return false; }} class NoClient extends Emp{ @Override public String getName() { return "Not Available"; } @Override public boolean isNull() { return true; }} class EmpData { public static final String[] names = {"Lokesh", "Kushagra", "Vikram"}; public static Emp getClient(String name) { for (int i = 0; i < names.length; i++) { if (names[i].equalsIgnoreCase(name)) { return new Coder(name); } } return new NoClient(); }} public class Main { public static void main(String[] args) { Emp emp1 = EmpData.getClient("Lokesh"); Emp emp2 = EmpData.getClient("Kushagra"); Emp emp3 = EmpData.getClient("Vikram"); Emp emp4 = EmpData.getClient("Rishabh"); System.out.println(emp1.getName()); System.out.println(emp2.getName()); System.out.println(emp3.getName()); System.out.println(emp4.getName()); }} Output: Lokesh Kushagra Vikram Not Available Advantages : It defines class hierarchies consisting of real objects and null objects. Null objects can be used in place of real objects when the object is expected to do nothing. Whenever client code expects a real object, it can also take a null object. Also makes the client code simple. Clients can treat real collaborators and null collaborators uniformly. Clients normally don’t know whether they’re dealing with a real or a null collaborator. This simplifies client code, because it avoids having to write testing code which handles the null collaborator specially. Disadvantages : Can be difficult to implement if various clients do not agree on how the null object should do nothing as when your AbstractObject interface is not well defined. Can necessitate creating a new NullObject class for every new AbstractObject class. This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nidhi_biet Design Pattern Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Sequence diagram and Collaboration diagram Strategy Pattern | Set 1 (Introduction) Template Method Design Pattern State Design Pattern Conceptual Model of the Unified Modeling Language (UML) Command Pattern Visitor design pattern Difference between Sequence Diagram and Activity Diagram Observer Pattern | Set 2 (Implementation)
[ { "code": null, "e": 25883, "s": 25855, "text": "\n04 Oct, 2019" }, { "code": null, "e": 26353, "s": 25883, "text": "The Null object pattern is a design pattern that simplifies the use of dependencies that can be undefined. This is achieved by using instances of a concrete class that implements a known interface, instead of null references.We create an abstract class specifying various operations to be done, concrete classes extending this class and a null object class providing do nothing implementation of this class and will be used seamlessly where we need to check null value." }, { "code": null, "e": 26396, "s": 26353, "text": "UML Diagram for Null object Design pattern" }, { "code": null, "e": 26414, "s": 26396, "text": "Design components" }, { "code": null, "e": 26584, "s": 26414, "text": "Client : This class has a dependency that may or may not be required. Where no functionality is required in the dependency, it will execute the methods of a null object." }, { "code": null, "e": 26851, "s": 26584, "text": "DependencyBase : This abstract class is the base class for the various available dependencies that the Client may use. This is also the base class for the null object class. Where the base class provides no shared functionality, it may be replaced with an interface." }, { "code": null, "e": 26934, "s": 26851, "text": "Dependency : This class is a functional dependency that may be used by the Client." }, { "code": null, "e": 27134, "s": 26934, "text": "NullObject : This is the null object class that can be used as a dependency by the Client. It contains no functionality but implements all of the members defined by the DependencyBase abstract class." }, { "code": null, "e": 27186, "s": 27134, "text": "Let’s see an example of Null object design pattern." }, { "code": "// Java program to illustrate Null// Object Design Pattern abstract class Emp{ protected String name; public abstract boolean isNull(); public abstract String getName();} class Coder extends Emp{ public Coder(String name) { this.name = name; } @Override public String getName() { return name; } @Override public boolean isNull() { return false; }} class NoClient extends Emp{ @Override public String getName() { return \"Not Available\"; } @Override public boolean isNull() { return true; }} class EmpData { public static final String[] names = {\"Lokesh\", \"Kushagra\", \"Vikram\"}; public static Emp getClient(String name) { for (int i = 0; i < names.length; i++) { if (names[i].equalsIgnoreCase(name)) { return new Coder(name); } } return new NoClient(); }} public class Main { public static void main(String[] args) { Emp emp1 = EmpData.getClient(\"Lokesh\"); Emp emp2 = EmpData.getClient(\"Kushagra\"); Emp emp3 = EmpData.getClient(\"Vikram\"); Emp emp4 = EmpData.getClient(\"Rishabh\"); System.out.println(emp1.getName()); System.out.println(emp2.getName()); System.out.println(emp3.getName()); System.out.println(emp4.getName()); }}", "e": 28590, "s": 27186, "text": null }, { "code": null, "e": 28598, "s": 28590, "text": "Output:" }, { "code": null, "e": 28636, "s": 28598, "text": "Lokesh\nKushagra\nVikram\nNot Available\n" }, { "code": null, "e": 28649, "s": 28636, "text": "Advantages :" }, { "code": null, "e": 28892, "s": 28649, "text": "It defines class hierarchies consisting of real objects and null objects. Null objects can be used in place of real objects when the object is expected to do nothing. Whenever client code expects a real object, it can also take a null object." }, { "code": null, "e": 29209, "s": 28892, "text": "Also makes the client code simple. Clients can treat real collaborators and null collaborators uniformly. Clients normally don’t know whether they’re dealing with a real or a null collaborator. This simplifies client code, because it avoids having to write testing code which handles the null collaborator specially." }, { "code": null, "e": 29225, "s": 29209, "text": "Disadvantages :" }, { "code": null, "e": 29387, "s": 29225, "text": "Can be difficult to implement if various clients do not agree on how the null object should do nothing as when your AbstractObject interface is not well defined." }, { "code": null, "e": 29471, "s": 29387, "text": "Can necessitate creating a new NullObject class for every new AbstractObject class." }, { "code": null, "e": 29770, "s": 29471, "text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29895, "s": 29770, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29906, "s": 29895, "text": "nidhi_biet" }, { "code": null, "e": 29921, "s": 29906, "text": "Design Pattern" }, { "code": null, "e": 30019, "s": 29921, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30081, "s": 30019, "text": "Difference between Sequence diagram and Collaboration diagram" }, { "code": null, "e": 30121, "s": 30081, "text": "Strategy Pattern | Set 1 (Introduction)" }, { "code": null, "e": 30152, "s": 30121, "text": "Template Method Design Pattern" }, { "code": null, "e": 30173, "s": 30152, "text": "State Design Pattern" }, { "code": null, "e": 30229, "s": 30173, "text": "Conceptual Model of the Unified Modeling Language (UML)" }, { "code": null, "e": 30245, "s": 30229, "text": "Command Pattern" }, { "code": null, "e": 30268, "s": 30245, "text": "Visitor design pattern" }, { "code": null, "e": 30325, "s": 30268, "text": "Difference between Sequence Diagram and Activity Diagram" } ]
What is the difference between React Native and React? - GeeksforGeeks
23 Apr, 2019 Basic Introduction of React or ReactJS: It is an open source Javascript library created by Facebook for better UI development and Efficient DOM manipulation. React have a virtual DOM concept. When any data is received from the server then this virtual DOM has modified accordingly then this updated virtual DOM is matched with Real DOM by some algorithm and only those portion of Real DOM is updated which is different from Virtual Dom. ReactJS React is used for creating websites, web apps, SPAs etc.React is a Javascript library used for creating UI hierarchy.It is responsible for rendering of UI components, It is considered as V part Of MVC framework.React’s virtual DOM is faster than the conventional full refresh model, since the virtual DOM refreshes only parts of the page, Thus decreasing the page refresh time.React uses components as basic unit of UI which can be reused this saves coding time.Simple and easy to learn. React is used for creating websites, web apps, SPAs etc. React is a Javascript library used for creating UI hierarchy. It is responsible for rendering of UI components, It is considered as V part Of MVC framework. React’s virtual DOM is faster than the conventional full refresh model, since the virtual DOM refreshes only parts of the page, Thus decreasing the page refresh time. React uses components as basic unit of UI which can be reused this saves coding time. Simple and easy to learn. React sample code import React, { Component } from 'react';import ReactDOM from 'react-dom'; // every component is created by // extending the React Component class. class Clock extends React.Component { constructor(props) { super(props); // constructor creates an instance of this class. this.state = {date: new Date()}; } componentDidMount() { // this function is called immediately // after component is mounted on DOM. this.timerID = setInterval( () => this.tick(), 1000 ); } componentWillUnmount() { // called before component will unmount from DOM. clearInterval(this.timerID); } tick() { // this function is used to update the // state of Clock component. this.setState({ date: new Date() }); } render() { return ( <div> <h1>Today Date and Time</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div> ); }}// code will not run needs specific environment setupReactDOM.render( <Clock />, document.getElementById('root')); Basic Introduction Of React Native:REACT Native helps you create real and exciting mobile applications using JavaScript only, which is supportable for both Android and iOS platforms devices. Just code once, and the REACT Native apps are available for both iOS and Android platforms which helps to save a lot of development time. Found great popularity created by Facebook. REACT Native, has a huge community support today. React Native is built on top of ReactJS which is a good alternative to AngularJS. Though there are some similarities and difference between React Native and ReactJS.React Native React Native is a framework that is used to create cross-platform Native apps. It means you can create native apps and the same app will run on Android and ios.React native have all the benefits of ReactJSReact native allows developers to create native apps in web-style approach.Front end developer can become mobile developer easily. React Native is a framework that is used to create cross-platform Native apps. It means you can create native apps and the same app will run on Android and ios. React native have all the benefits of ReactJS React native allows developers to create native apps in web-style approach. Front end developer can become mobile developer easily. Sample React Native code import React, { Component } from 'react';import { Text, View } from 'react-native'; class ReactNative extends Component { render() { return ( // it is a container, layout support with flexbox think // of it like a div with a container class. <View> <Text>// A react component for displaying text. If you like React on the web, you'll like React Native. </Text> <Text> You just use native components like 'View' and 'Text', instead of web components like 'div' and 'span'. </Text> </View> ); }} Picked react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript How to create footer to stay at the bottom of a Web page? Differences between Functional Components and Class Components in React Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? File uploading in React.js How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 25755, "s": 25727, "text": "\n23 Apr, 2019" }, { "code": null, "e": 26192, "s": 25755, "text": "Basic Introduction of React or ReactJS: It is an open source Javascript library created by Facebook for better UI development and Efficient DOM manipulation. React have a virtual DOM concept. When any data is received from the server then this virtual DOM has modified accordingly then this updated virtual DOM is matched with Real DOM by some algorithm and only those portion of Real DOM is updated which is different from Virtual Dom." }, { "code": null, "e": 26200, "s": 26192, "text": "ReactJS" }, { "code": null, "e": 26688, "s": 26200, "text": "React is used for creating websites, web apps, SPAs etc.React is a Javascript library used for creating UI hierarchy.It is responsible for rendering of UI components, It is considered as V part Of MVC framework.React’s virtual DOM is faster than the conventional full refresh model, since the virtual DOM refreshes only parts of the page, Thus decreasing the page refresh time.React uses components as basic unit of UI which can be reused this saves coding time.Simple and easy to learn." }, { "code": null, "e": 26745, "s": 26688, "text": "React is used for creating websites, web apps, SPAs etc." }, { "code": null, "e": 26807, "s": 26745, "text": "React is a Javascript library used for creating UI hierarchy." }, { "code": null, "e": 26902, "s": 26807, "text": "It is responsible for rendering of UI components, It is considered as V part Of MVC framework." }, { "code": null, "e": 27069, "s": 26902, "text": "React’s virtual DOM is faster than the conventional full refresh model, since the virtual DOM refreshes only parts of the page, Thus decreasing the page refresh time." }, { "code": null, "e": 27155, "s": 27069, "text": "React uses components as basic unit of UI which can be reused this saves coding time." }, { "code": null, "e": 27181, "s": 27155, "text": "Simple and easy to learn." }, { "code": null, "e": 27199, "s": 27181, "text": "React sample code" }, { "code": "import React, { Component } from 'react';import ReactDOM from 'react-dom'; // every component is created by // extending the React Component class. class Clock extends React.Component { constructor(props) { super(props); // constructor creates an instance of this class. this.state = {date: new Date()}; } componentDidMount() { // this function is called immediately // after component is mounted on DOM. this.timerID = setInterval( () => this.tick(), 1000 ); } componentWillUnmount() { // called before component will unmount from DOM. clearInterval(this.timerID); } tick() { // this function is used to update the // state of Clock component. this.setState({ date: new Date() }); } render() { return ( <div> <h1>Today Date and Time</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div> ); }}// code will not run needs specific environment setupReactDOM.render( <Clock />, document.getElementById('root'));", "e": 28218, "s": 27199, "text": null }, { "code": null, "e": 28819, "s": 28218, "text": "Basic Introduction Of React Native:REACT Native helps you create real and exciting mobile applications using JavaScript only, which is supportable for both Android and iOS platforms devices. Just code once, and the REACT Native apps are available for both iOS and Android platforms which helps to save a lot of development time. Found great popularity created by Facebook. REACT Native, has a huge community support today. React Native is built on top of ReactJS which is a good alternative to AngularJS. Though there are some similarities and difference between React Native and ReactJS.React Native" }, { "code": null, "e": 29155, "s": 28819, "text": "React Native is a framework that is used to create cross-platform Native apps. It means you can create native apps and the same app will run on Android and ios.React native have all the benefits of ReactJSReact native allows developers to create native apps in web-style approach.Front end developer can become mobile developer easily." }, { "code": null, "e": 29316, "s": 29155, "text": "React Native is a framework that is used to create cross-platform Native apps. It means you can create native apps and the same app will run on Android and ios." }, { "code": null, "e": 29362, "s": 29316, "text": "React native have all the benefits of ReactJS" }, { "code": null, "e": 29438, "s": 29362, "text": "React native allows developers to create native apps in web-style approach." }, { "code": null, "e": 29494, "s": 29438, "text": "Front end developer can become mobile developer easily." }, { "code": null, "e": 29519, "s": 29494, "text": "Sample React Native code" }, { "code": "import React, { Component } from 'react';import { Text, View } from 'react-native'; class ReactNative extends Component { render() { return ( // it is a container, layout support with flexbox think // of it like a div with a container class. <View> <Text>// A react component for displaying text. If you like React on the web, you'll like React Native. </Text> <Text> You just use native components like 'View' and 'Text', instead of web components like 'div' and 'span'. </Text> </View> ); }}", "e": 30098, "s": 29519, "text": null }, { "code": null, "e": 30105, "s": 30098, "text": "Picked" }, { "code": null, "e": 30114, "s": 30105, "text": "react-js" }, { "code": null, "e": 30131, "s": 30114, "text": "Web Technologies" }, { "code": null, "e": 30229, "s": 30131, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30269, "s": 30229, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30314, "s": 30269, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30357, "s": 30314, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30418, "s": 30357, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30476, "s": 30418, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 30548, "s": 30476, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 30581, "s": 30548, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 30641, "s": 30581, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 30668, "s": 30641, "text": "File uploading in React.js" } ]
Tweet using Python - GeeksforGeeks
21 Nov, 2017 Twitter is an online news and social networking service where users post and interact with messages. These posts are known as “tweets”. Twitter is known as the social media site for robots. We can use Python for posting the tweets without even opening the website. There is a Python library which is used for accessing the Python API, known as tweepy. Here, we are going to use tweepy for doing the same.Tweepy is not the native library. You need to install it before using it. Installation is easy when you have pip. In the Terminal or Command Prompt, type the following command to install tweepy. sudo install pip tweepy In case you don’t have pip, install it as an external library.Don’t forget to change the change the application type from “Read only” to “Read and write” in the settings. This given the permission to tweet as well.After this, go to https://apps.twitter.com/. This is used to create a link between your script and Twitter. In “Keys and Access Tokens” tab, get the Consumer Key (API Key), Consumer Secret (API secret), Access Token and Access Token Secret. # importing the moduleimport tweepy # personal detailsconsumer_key ="xxxxxxxxxxxxxxxx"consumer_secret ="xxxxxxxxxxxxxxxx"access_token ="xxxxxxxxxxxxxxxx"access_token_secret ="xxxxxxxxxxxxxxxx" # authentication of consumer key and secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # authentication of access token and secretauth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth) # update the statusapi.update_status(status ="Hello Everyone !") This is the simple method which will set the tweet “Hello Everyone!”. This is an easy process and doesn’t hold much any importance in real life. It is integrated into bigger programs for some useful work. We can use for loop to tweet a large number of tweets. For maintaining the time period between any two tweets in the loop, we can use sleep() function from the time module as shown. time.sleep(600) # waits for 600 seconds This was all about posting a text tweet. What if we want to post a tweet with a media file, there is a separate method for that. Sometimes, a user wants to post a tweet with a media file which is quite simple if we use the website interface. Posting with the help of Python takes some effort. It is same as posting the text-only tweet with just two lines of code addition. # importing the moduleimport tweepy # personal informationconsumer_key ="xxxxxxxxxxxxxxxx"consumer_secret ="xxxxxxxxxxxxxxxx"access_token ="xxxxxxxxxxxxxxxx"access_token_secret ="xxxxxxxxxxxxxxxx" # authenticationauth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth)tweet ="Text part of the tweet" # toDoimage_path ="path of the image" # toDo # to attach the media filestatus = api.update_with_media(image_path, tweet) api.update_status(status = tweet) Please don’t forget to change the Application type as stated above. Without changing it, we can’t have the access to post. This article is contributed by Rishabh Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. python-utility Twitter Python Twitter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 25671, "s": 25643, "text": "\n21 Nov, 2017" }, { "code": null, "e": 26270, "s": 25671, "text": "Twitter is an online news and social networking service where users post and interact with messages. These posts are known as “tweets”. Twitter is known as the social media site for robots. We can use Python for posting the tweets without even opening the website. There is a Python library which is used for accessing the Python API, known as tweepy. Here, we are going to use tweepy for doing the same.Tweepy is not the native library. You need to install it before using it. Installation is easy when you have pip. In the Terminal or Command Prompt, type the following command to install tweepy." }, { "code": null, "e": 26295, "s": 26270, "text": "sudo install pip tweepy\n" }, { "code": null, "e": 26750, "s": 26295, "text": "In case you don’t have pip, install it as an external library.Don’t forget to change the change the application type from “Read only” to “Read and write” in the settings. This given the permission to tweet as well.After this, go to https://apps.twitter.com/. This is used to create a link between your script and Twitter. In “Keys and Access Tokens” tab, get the Consumer Key (API Key), Consumer Secret (API secret), Access Token and Access Token Secret." }, { "code": "# importing the moduleimport tweepy # personal detailsconsumer_key =\"xxxxxxxxxxxxxxxx\"consumer_secret =\"xxxxxxxxxxxxxxxx\"access_token =\"xxxxxxxxxxxxxxxx\"access_token_secret =\"xxxxxxxxxxxxxxxx\" # authentication of consumer key and secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # authentication of access token and secretauth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth) # update the statusapi.update_status(status =\"Hello Everyone !\")", "e": 27235, "s": 26750, "text": null }, { "code": null, "e": 27622, "s": 27235, "text": "This is the simple method which will set the tweet “Hello Everyone!”. This is an easy process and doesn’t hold much any importance in real life. It is integrated into bigger programs for some useful work. We can use for loop to tweet a large number of tweets. For maintaining the time period between any two tweets in the loop, we can use sleep() function from the time module as shown." }, { "code": "time.sleep(600) # waits for 600 seconds", "e": 27662, "s": 27622, "text": null }, { "code": null, "e": 27791, "s": 27662, "text": "This was all about posting a text tweet. What if we want to post a tweet with a media file, there is a separate method for that." }, { "code": null, "e": 28035, "s": 27791, "text": "Sometimes, a user wants to post a tweet with a media file which is quite simple if we use the website interface. Posting with the help of Python takes some effort. It is same as posting the text-only tweet with just two lines of code addition." }, { "code": "# importing the moduleimport tweepy # personal informationconsumer_key =\"xxxxxxxxxxxxxxxx\"consumer_secret =\"xxxxxxxxxxxxxxxx\"access_token =\"xxxxxxxxxxxxxxxx\"access_token_secret =\"xxxxxxxxxxxxxxxx\" # authenticationauth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth)tweet =\"Text part of the tweet\" # toDoimage_path =\"path of the image\" # toDo # to attach the media filestatus = api.update_with_media(image_path, tweet) api.update_status(status = tweet)", "e": 28576, "s": 28035, "text": null }, { "code": null, "e": 28699, "s": 28576, "text": "Please don’t forget to change the Application type as stated above. Without changing it, we can’t have the access to post." }, { "code": null, "e": 29001, "s": 28699, "text": "This article is contributed by Rishabh Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29126, "s": 29001, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29141, "s": 29126, "text": "python-utility" }, { "code": null, "e": 29149, "s": 29141, "text": "Twitter" }, { "code": null, "e": 29156, "s": 29149, "text": "Python" }, { "code": null, "e": 29164, "s": 29156, "text": "Twitter" }, { "code": null, "e": 29262, "s": 29164, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29280, "s": 29262, "text": "Python Dictionary" }, { "code": null, "e": 29312, "s": 29280, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29334, "s": 29312, "text": "Enumerate() in Python" }, { "code": null, "e": 29376, "s": 29334, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29402, "s": 29376, "text": "Python String | replace()" }, { "code": null, "e": 29431, "s": 29402, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29475, "s": 29431, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29512, "s": 29475, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29548, "s": 29512, "text": "Convert integer to string in Python" } ]
Javascript Program To Check If A Singly Linked List Is Palindrome - GeeksforGeeks
14 Dec, 2021 Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false. METHOD 1 (Use a Stack) A simple solution is to use a stack of list nodes. This mainly involves three steps. Traverse the given list from head to tail and push every visited node to stack. Traverse the list again. For every visited node, pop a node from the stack and compare data of popped node with the currently visited node. If all nodes matched, then return true, else false. Below image is a dry run of the above approach: Below is the implementation of the above approach : Javascript <script>// JavaScript program to check if// linked list is palindrome recursivelyclass Node{ constructor(val) { this.data = val; this.ptr = null; }} var one = new Node(1);var two = new Node(2);var three = new Node(3);var four = new Node(4);var five = new Node(3);var six = new Node(2);var seven = new Node(1);one.ptr = two;two.ptr = three;three.ptr = four;four.ptr = five;five.ptr = six;six.ptr = seven;var condition = isPalindrome(one);document.write("isPalidrome: " + condition); function isPalindrome(head){ var slow = head; var ispalin = true; var stack = []; while (slow != null) { stack.push(slow.data); slow = slow.ptr; } while (head != null) { var i = stack.pop(); if (head.data == i) { ispalin = true; } else { ispalin = false; break; } head = head.ptr; } return ispalin;}// This code is contributed by todaysgaurav</script> Output: isPalindrome: true Time complexity: O(n). METHOD 2 (By reversing the list): This method takes O(n) time and O(1) extra space. 1) Get the middle of the linked list. 2) Reverse the second half of the linked list. 3) Check if the first half and second half are identical. 4) Construct the original linked list by reversing the second half again and attaching it back to the first half To divide the list into two halves, method 2 of this post is used. When a number of nodes are even, the first and second half contains exactly half nodes. The challenging thing in this method is to handle the case when the number of nodes is odd. We don’t want the middle node as part of the lists as we are going to compare them for equality. For odd cases, we use a separate variable ‘midnode’. Javascript <script>// Javascript program to check if// linked list is palindrome // Head of listvar head;var slow_ptr, fast_ptr, second_half; // Linked list Nodeclass Node{ constructor(val) { this.data = val; this.next = null; }} // Function to check if given linked list// is palindrome or notfunction isPalindrome(head){ slow_ptr = head; fast_ptr = head; var prev_of_slow_ptr = head; // To handle odd size list var midnode = null; // Initialize result var res = true; if (head != null && head.next != null) { // Get the middle of the list. // Move slow_ptr by 1 and fast_ptrr // by 2, slow_ptr will have the middle node while (fast_ptr != null && fast_ptr.next != null) { fast_ptr = fast_ptr.next.next; // We need previous of the slow_ptr for // linked lists with odd elements prev_of_slow_ptr = slow_ptr; slow_ptr = slow_ptr.next; } // fast_ptr would become NULL when there are // even elements in the list and not NULL for // odd elements. We need to skip the middle // node for odd case and store it somewhere // so that we can restore the original list if (fast_ptr != null) { midnode = slow_ptr; slow_ptr = slow_ptr.next; } // Now reverse the second half and // compare it with first half second_half = slow_ptr; // NULL terminate first half prev_of_slow_ptr.next = null; // Reverse the second half reverse(); // compare res = compareLists(head, second_half); // Construct the original list back // Reverse the second half again reverse(); if (midnode != null) { // If there was a mid node (odd size case) // which was not part of either first half // or second half. prev_of_slow_ptr.next = midnode; midnode.next = second_half; } else prev_of_slow_ptr.next = second_half; } return res;} // Function to reverse the linked list.// Note that this function may change the// headfunction reverse(){ var prev = null; var current = second_half; var next; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } second_half = prev;} // Function to check if two input// lists have same datafunction compareLists(head1, head2){ var temp1 = head1; var temp2 = head2; while (temp1 != null && temp2 != null) { if (temp1.data == temp2.data) { temp1 = temp1.next; temp2 = temp2.next; } else return false; } // Both are empty return 1 if (temp1 == null && temp2 == null) return true; //Will reach here when one is NULL // and other is not return false;} // Push a node to the linked list.// Note that this function changes the headfunction push(new_data){ // Allocate the Node & Put in the data var new_node = new Node(new_data); // link the old list off the new one new_node.next = head; // Move the head to point to new Node head = new_node;} // A utility function to point a// given linked listfunction printList(ptr){ while (ptr != null) { document.write(ptr.data + "->"); ptr = ptr.next; } document.write("NULL<br/>");} // Driver code // Start with the empty listvar str = ['a', 'b', 'a', 'c', 'a', 'b', 'a'];var string = str.toString(); for (i = 0; i < 7; i++){ push(str[i]); printList(head); if (isPalindrome(head) != false) { document.write("Is Palindrome"); document.write("<br/>"); } else { document.write("Not Palindrome"); document.write("<br/>"); }}// This code is contributed by gauravrajput1</script> Output: a->NULL Is Palindrome b->a->NULL Not Palindrome a->b->a->NULL Is Palindrome c->a->b->a->NULL Not Palindrome a->c->a->b->a->NULL Not Palindrome b->a->c->a->b->a->NULL Not Palindrome a->b->a->c->a->b->a->NULL Is Palindrome Time Complexity: O(n) Auxiliary Space: O(1) METHOD 3 (Using Recursion): Use two pointers left and right. Move right and left using recursion and check for following in each recursive call. 1) Sub-list is a palindrome. 2) Value at current left and right are matching. If both above conditions are true then return true. The idea is to use function call stack as a container. Recursively traverse till the end of the list. When we return from the last NULL, we will be at the last node. The last node is to be compared with the first node of the list. In order to access the first node of the list, we need the list head to be available in the last call of recursion. Hence, we pass head also to the recursive function. If they both match we need to compare (2, n-2) nodes. Again when recursion falls back to (n-2)nd node, we need a reference to 2nd node from the head. We advance the head pointer in the previous call, to refer to the next node in the list.However, the trick is identifying a double-pointer. Passing a single pointer is as good as pass-by-value, and we will pass the same pointer again and again. We need to pass the address of the head pointer for reflecting the changes in parent recursive calls.Thanks to Sharad Chandra for suggesting this approach. Javascript <script>// Javascript program to implement// the above approach // Head of the listvar head;var left; class Node{ constructor(val) { this.data = val; this.next = null; }} // Initial parameters to this function// are &head and headfunction isPalindromeUtil(right){ left = head; // Stop recursion when right // becomes null if (right == null) return true; // If sub-list is not palindrome then // no need to check for the current // left and right, return false var isp = isPalindromeUtil(right.next); if (isp == false) return false; // Check values at current left and right var isp1 = (right.data == left.data); left = left.next; // Move left to next node; return isp1;} // A wrapper over isPalindrome(Node head)function isPalindrome(head){ var result = isPalindromeUtil(head); return result;} // Push a node to linked list.// Note that this function changes// the headfunction push(new_data){ // Allocate the node and // put in the data var new_node = new Node(new_data); // Link the old list off the // the new one new_node.next = head; // Move the head to point to new node head = new_node;} // A utility function to point a// given linked listfunction printList(ptr){ while (ptr != null) { document.write(ptr.data + "->"); ptr = ptr.next; } document.write("Null "); document.write("<br>"); } // Driver Codevar str = ['a', 'b', 'a', 'c', 'a', 'b', 'a'];for (var i = 0; i < 7; i++){ push(str[i]); printList(head); if (isPalindrome(head)) { document.write("Is Palindrome"); document.write("<br/>"); document.write("<br>"); } else { document.write("Not Palindrome"); document.write("<br/>"); document.write("<br/>"); }}// This code is contributed by aashish1995/script> Output: a->NULL Not Palindrome b->a->NULL Not Palindrome a->b->a->NULL Is Palindrome c->a->b->a->NULL Not Palindrome a->c->a->b->a->NULL Not Palindrome b->a->c->a->b->a->NULL Not Palindrome a->b->a->c->a->b->a->NULL Is Palindrome Time Complexity: O(n) Auxiliary Space: O(n) if Function Call Stack size is considered, otherwise O(1). Please refer complete article on Function to check if a singly linked list is palindrome for more details! khushboogoyal499 Accolite Adobe Amazon KLA Tencor Kritikal Solutions Linked Lists Microsoft palindrome Snapdeal Yodlee Infotech JavaScript Linked List Accolite Amazon Microsoft Snapdeal Adobe Yodlee Infotech KLA Tencor Kritikal Solutions Linked List palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array 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 ? Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node)
[ { "code": null, "e": 26611, "s": 26583, "text": "\n14 Dec, 2021" }, { "code": null, "e": 26735, "s": 26611, "text": "Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false." }, { "code": null, "e": 26759, "s": 26735, "text": "METHOD 1 (Use a Stack) " }, { "code": null, "e": 26844, "s": 26759, "text": "A simple solution is to use a stack of list nodes. This mainly involves three steps." }, { "code": null, "e": 26924, "s": 26844, "text": "Traverse the given list from head to tail and push every visited node to stack." }, { "code": null, "e": 27064, "s": 26924, "text": "Traverse the list again. For every visited node, pop a node from the stack and compare data of popped node with the currently visited node." }, { "code": null, "e": 27116, "s": 27064, "text": "If all nodes matched, then return true, else false." }, { "code": null, "e": 27165, "s": 27116, "text": "Below image is a dry run of the above approach: " }, { "code": null, "e": 27218, "s": 27165, "text": "Below is the implementation of the above approach : " }, { "code": null, "e": 27229, "s": 27218, "text": "Javascript" }, { "code": "<script>// JavaScript program to check if// linked list is palindrome recursivelyclass Node{ constructor(val) { this.data = val; this.ptr = null; }} var one = new Node(1);var two = new Node(2);var three = new Node(3);var four = new Node(4);var five = new Node(3);var six = new Node(2);var seven = new Node(1);one.ptr = two;two.ptr = three;three.ptr = four;four.ptr = five;five.ptr = six;six.ptr = seven;var condition = isPalindrome(one);document.write(\"isPalidrome: \" + condition); function isPalindrome(head){ var slow = head; var ispalin = true; var stack = []; while (slow != null) { stack.push(slow.data); slow = slow.ptr; } while (head != null) { var i = stack.pop(); if (head.data == i) { ispalin = true; } else { ispalin = false; break; } head = head.ptr; } return ispalin;}// This code is contributed by todaysgaurav</script>", "e": 28229, "s": 27229, "text": null }, { "code": null, "e": 28238, "s": 28229, "text": "Output: " }, { "code": null, "e": 28258, "s": 28238, "text": " isPalindrome: true" }, { "code": null, "e": 28281, "s": 28258, "text": "Time complexity: O(n)." }, { "code": null, "e": 28621, "s": 28281, "text": "METHOD 2 (By reversing the list): This method takes O(n) time and O(1) extra space. 1) Get the middle of the linked list. 2) Reverse the second half of the linked list. 3) Check if the first half and second half are identical. 4) Construct the original linked list by reversing the second half again and attaching it back to the first half" }, { "code": null, "e": 28689, "s": 28621, "text": "To divide the list into two halves, method 2 of this post is used. " }, { "code": null, "e": 29020, "s": 28689, "text": "When a number of nodes are even, the first and second half contains exactly half nodes. The challenging thing in this method is to handle the case when the number of nodes is odd. We don’t want the middle node as part of the lists as we are going to compare them for equality. For odd cases, we use a separate variable ‘midnode’. " }, { "code": null, "e": 29031, "s": 29020, "text": "Javascript" }, { "code": "<script>// Javascript program to check if// linked list is palindrome // Head of listvar head;var slow_ptr, fast_ptr, second_half; // Linked list Nodeclass Node{ constructor(val) { this.data = val; this.next = null; }} // Function to check if given linked list// is palindrome or notfunction isPalindrome(head){ slow_ptr = head; fast_ptr = head; var prev_of_slow_ptr = head; // To handle odd size list var midnode = null; // Initialize result var res = true; if (head != null && head.next != null) { // Get the middle of the list. // Move slow_ptr by 1 and fast_ptrr // by 2, slow_ptr will have the middle node while (fast_ptr != null && fast_ptr.next != null) { fast_ptr = fast_ptr.next.next; // We need previous of the slow_ptr for // linked lists with odd elements prev_of_slow_ptr = slow_ptr; slow_ptr = slow_ptr.next; } // fast_ptr would become NULL when there are // even elements in the list and not NULL for // odd elements. We need to skip the middle // node for odd case and store it somewhere // so that we can restore the original list if (fast_ptr != null) { midnode = slow_ptr; slow_ptr = slow_ptr.next; } // Now reverse the second half and // compare it with first half second_half = slow_ptr; // NULL terminate first half prev_of_slow_ptr.next = null; // Reverse the second half reverse(); // compare res = compareLists(head, second_half); // Construct the original list back // Reverse the second half again reverse(); if (midnode != null) { // If there was a mid node (odd size case) // which was not part of either first half // or second half. prev_of_slow_ptr.next = midnode; midnode.next = second_half; } else prev_of_slow_ptr.next = second_half; } return res;} // Function to reverse the linked list.// Note that this function may change the// headfunction reverse(){ var prev = null; var current = second_half; var next; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } second_half = prev;} // Function to check if two input// lists have same datafunction compareLists(head1, head2){ var temp1 = head1; var temp2 = head2; while (temp1 != null && temp2 != null) { if (temp1.data == temp2.data) { temp1 = temp1.next; temp2 = temp2.next; } else return false; } // Both are empty return 1 if (temp1 == null && temp2 == null) return true; //Will reach here when one is NULL // and other is not return false;} // Push a node to the linked list.// Note that this function changes the headfunction push(new_data){ // Allocate the Node & Put in the data var new_node = new Node(new_data); // link the old list off the new one new_node.next = head; // Move the head to point to new Node head = new_node;} // A utility function to point a// given linked listfunction printList(ptr){ while (ptr != null) { document.write(ptr.data + \"->\"); ptr = ptr.next; } document.write(\"NULL<br/>\");} // Driver code // Start with the empty listvar str = ['a', 'b', 'a', 'c', 'a', 'b', 'a'];var string = str.toString(); for (i = 0; i < 7; i++){ push(str[i]); printList(head); if (isPalindrome(head) != false) { document.write(\"Is Palindrome\"); document.write(\"<br/>\"); } else { document.write(\"Not Palindrome\"); document.write(\"<br/>\"); }}// This code is contributed by gauravrajput1</script>", "e": 33028, "s": 29031, "text": null }, { "code": null, "e": 33037, "s": 33028, "text": "Output: " }, { "code": null, "e": 33264, "s": 33037, "text": "a->NULL\nIs Palindrome\n\nb->a->NULL\nNot Palindrome\n\na->b->a->NULL\nIs Palindrome\n\nc->a->b->a->NULL\nNot Palindrome\n\na->c->a->b->a->NULL\nNot Palindrome\n\nb->a->c->a->b->a->NULL\nNot Palindrome\n\na->b->a->c->a->b->a->NULL\nIs Palindrome" }, { "code": null, "e": 33310, "s": 33264, "text": "Time Complexity: O(n) Auxiliary Space: O(1) " }, { "code": null, "e": 33533, "s": 33310, "text": "METHOD 3 (Using Recursion): Use two pointers left and right. Move right and left using recursion and check for following in each recursive call. 1) Sub-list is a palindrome. 2) Value at current left and right are matching." }, { "code": null, "e": 33585, "s": 33533, "text": "If both above conditions are true then return true." }, { "code": null, "e": 33816, "s": 33585, "text": "The idea is to use function call stack as a container. Recursively traverse till the end of the list. When we return from the last NULL, we will be at the last node. The last node is to be compared with the first node of the list." }, { "code": null, "e": 34535, "s": 33816, "text": "In order to access the first node of the list, we need the list head to be available in the last call of recursion. Hence, we pass head also to the recursive function. If they both match we need to compare (2, n-2) nodes. Again when recursion falls back to (n-2)nd node, we need a reference to 2nd node from the head. We advance the head pointer in the previous call, to refer to the next node in the list.However, the trick is identifying a double-pointer. Passing a single pointer is as good as pass-by-value, and we will pass the same pointer again and again. We need to pass the address of the head pointer for reflecting the changes in parent recursive calls.Thanks to Sharad Chandra for suggesting this approach." }, { "code": null, "e": 34546, "s": 34535, "text": "Javascript" }, { "code": "<script>// Javascript program to implement// the above approach // Head of the listvar head;var left; class Node{ constructor(val) { this.data = val; this.next = null; }} // Initial parameters to this function// are &head and headfunction isPalindromeUtil(right){ left = head; // Stop recursion when right // becomes null if (right == null) return true; // If sub-list is not palindrome then // no need to check for the current // left and right, return false var isp = isPalindromeUtil(right.next); if (isp == false) return false; // Check values at current left and right var isp1 = (right.data == left.data); left = left.next; // Move left to next node; return isp1;} // A wrapper over isPalindrome(Node head)function isPalindrome(head){ var result = isPalindromeUtil(head); return result;} // Push a node to linked list.// Note that this function changes// the headfunction push(new_data){ // Allocate the node and // put in the data var new_node = new Node(new_data); // Link the old list off the // the new one new_node.next = head; // Move the head to point to new node head = new_node;} // A utility function to point a// given linked listfunction printList(ptr){ while (ptr != null) { document.write(ptr.data + \"->\"); ptr = ptr.next; } document.write(\"Null \"); document.write(\"<br>\"); } // Driver Codevar str = ['a', 'b', 'a', 'c', 'a', 'b', 'a'];for (var i = 0; i < 7; i++){ push(str[i]); printList(head); if (isPalindrome(head)) { document.write(\"Is Palindrome\"); document.write(\"<br/>\"); document.write(\"<br>\"); } else { document.write(\"Not Palindrome\"); document.write(\"<br/>\"); document.write(\"<br/>\"); }}// This code is contributed by aashish1995/script>", "e": 36451, "s": 34546, "text": null }, { "code": null, "e": 36460, "s": 36451, "text": "Output: " }, { "code": null, "e": 36688, "s": 36460, "text": "a->NULL\nNot Palindrome\n\nb->a->NULL\nNot Palindrome\n\na->b->a->NULL\nIs Palindrome\n\nc->a->b->a->NULL\nNot Palindrome\n\na->c->a->b->a->NULL\nNot Palindrome\n\nb->a->c->a->b->a->NULL\nNot Palindrome\n\na->b->a->c->a->b->a->NULL\nIs Palindrome" }, { "code": null, "e": 36791, "s": 36688, "text": "Time Complexity: O(n) Auxiliary Space: O(n) if Function Call Stack size is considered, otherwise O(1)." }, { "code": null, "e": 36899, "s": 36791, "text": "Please refer complete article on Function to check if a singly linked list is palindrome for more details! " }, { "code": null, "e": 36916, "s": 36899, "text": "khushboogoyal499" }, { "code": null, "e": 36925, "s": 36916, "text": "Accolite" }, { "code": null, "e": 36931, "s": 36925, "text": "Adobe" }, { "code": null, "e": 36938, "s": 36931, "text": "Amazon" }, { "code": null, "e": 36949, "s": 36938, "text": "KLA Tencor" }, { "code": null, "e": 36968, "s": 36949, "text": "Kritikal Solutions" }, { "code": null, "e": 36981, "s": 36968, "text": "Linked Lists" }, { "code": null, "e": 36991, "s": 36981, "text": "Microsoft" }, { "code": null, "e": 37002, "s": 36991, "text": "palindrome" }, { "code": null, "e": 37011, "s": 37002, "text": "Snapdeal" }, { "code": null, "e": 37027, "s": 37011, "text": "Yodlee Infotech" }, { "code": null, "e": 37038, "s": 37027, "text": "JavaScript" }, { "code": null, "e": 37050, "s": 37038, "text": "Linked List" }, { "code": null, "e": 37059, "s": 37050, "text": "Accolite" }, { "code": null, "e": 37066, "s": 37059, "text": "Amazon" }, { "code": null, "e": 37076, "s": 37066, "text": "Microsoft" }, { "code": null, "e": 37085, "s": 37076, "text": "Snapdeal" }, { "code": null, "e": 37091, "s": 37085, "text": "Adobe" }, { "code": null, "e": 37107, "s": 37091, "text": "Yodlee Infotech" }, { "code": null, "e": 37118, "s": 37107, "text": "KLA Tencor" }, { "code": null, "e": 37137, "s": 37118, "text": "Kritikal Solutions" }, { "code": null, "e": 37149, "s": 37137, "text": "Linked List" }, { "code": null, "e": 37160, "s": 37149, "text": "palindrome" }, { "code": null, "e": 37258, "s": 37160, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37298, "s": 37258, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 37343, "s": 37298, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 37404, "s": 37343, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 37476, "s": 37404, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 37528, "s": 37476, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 37563, "s": 37528, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 37602, "s": 37563, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 37624, "s": 37602, "text": "Reverse a linked list" }, { "code": null, "e": 37672, "s": 37624, "text": "Stack Data Structure (Introduction and Program)" } ]
Implement Delete Messages Functionality in Social Media Android App - GeeksforGeeks
06 Jan, 2022 This is the Part 15 of “Build a Social Media App on Android Studio” tutorial, and we are going to cover the following functionalities in this article: We are going to delete the message in the ChatActivity. We are going to delete text and image messages. When we click on a text then an AlertBox will come. There will be two options to either delete that message or cancel the event. After Click on delete message will be deleted from both sides. Step 1: Working with the AdapterChat.java file We can delete a message only if we are the sender of the message. There are two methods to delete the message. You can use any one of them. In one, we have removed the value using datasnapshot and in another, we have updated the message as “This Message Was Deleted” as we see in WhatsApp. if(dataSnapshot1.child("sender").getValue().equals(myuid)) { // any two of below can be used dataSnapshot1.getRef().removeValue(); // <-----------------------------------> HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("message", "This Message Was Deleted"); dataSnapshot1.getRef().updateChildren(hashMap); Toast.makeText(context,"Message Deleted.....",Toast.LENGTH_LONG).show(); } Below is the code for the AdapterChat.java file. Java package com.example.socialmediaapp; import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.text.format.DateFormat;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query;import com.google.firebase.database.ValueEventListener; import java.util.Calendar;import java.util.List;import java.util.Locale; import de.hdodenhof.circleimageview.CircleImageView; public class AdapterChat extends RecyclerView.Adapter<com.example.socialmediaapp.AdapterChat.Myholder> { private static final int MSG_TYPE_LEFT = 0; private static final int MSG_TYPR_RIGHT = 1; Context context; List<ModelChat> list; String imageurl; FirebaseUser firebaseUser; public AdapterChat(Context context, List<ModelChat> list, String imageurl) { this.context = context; this.list = list; this.imageurl = imageurl; } @NonNull @Override public Myholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if (viewType == MSG_TYPE_LEFT) { View view = LayoutInflater.from(context).inflate(R.layout.row_chat_left, parent, false); return new Myholder(view); } else { View view = LayoutInflater.from(context).inflate(R.layout.row_chat_right, parent, false); return new Myholder(view); } } @Override public void onBindViewHolder(@NonNull Myholder holder, final int position) { String message = list.get(position).getMessage(); String timeStamp = list.get(position).getTimestamp(); String type = list.get(position).getType(); Calendar calendar = Calendar.getInstance(Locale.ENGLISH); calendar.setTimeInMillis(Long.parseLong(timeStamp)); String timedate = DateFormat.format("dd/MM/yyyy hh:mm aa", calendar).toString(); holder.message.setText(message); holder.time.setText(timedate); try { Glide.with(context).load(imageurl).into(holder.image); } catch (Exception e) { } if (type.equals("text")) { holder.message.setVisibility(View.VISIBLE); holder.mimage.setVisibility(View.GONE); holder.message.setText(message); } else { holder.message.setVisibility(View.GONE); holder.mimage.setVisibility(View.VISIBLE); Glide.with(context).load(message).into(holder.mimage); } holder.msglayput.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Delete Message"); builder.setMessage("Are You Sure To Delete This Message"); builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteMsg(position); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } }); } private void deleteMsg(int position) { final String myuid = FirebaseAuth.getInstance().getCurrentUser().getUid(); String msgtimestmp = list.get(position).getTimestamp(); DatabaseReference dbref = FirebaseDatabase.getInstance().getReference().child("Chats"); Query query = dbref.orderByChild("timestamp").equalTo(msgtimestmp); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { if (dataSnapshot1.child("sender").getValue().equals(myuid)) { // any two of below can be used dataSnapshot1.getRef().removeValue(); /* HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("message", "This Message Was Deleted"); dataSnapshot1.getRef().updateChildren(hashMap); Toast.makeText(context,"Message Deleted.....",Toast.LENGTH_LONG).show();*/ } else { Toast.makeText(context, "you can delete only your msg....", Toast.LENGTH_LONG).show(); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public int getItemCount() { return list.size(); } @Override public int getItemViewType(int position) { firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); if (list.get(position).getSender().equals(firebaseUser.getUid())) { return MSG_TYPR_RIGHT; } else { return MSG_TYPE_LEFT; } } class Myholder extends RecyclerView.ViewHolder { CircleImageView image; ImageView mimage; TextView message, time, isSee; LinearLayout msglayput; public Myholder(@NonNull View itemView) { super(itemView); image = itemView.findViewById(R.id.profilec); message = itemView.findViewById(R.id.msgc); time = itemView.findViewById(R.id.timetv); isSee = itemView.findViewById(R.id.isSeen); msglayput = itemView.findViewById(R.id.msglayout); mimage = itemView.findViewById(R.id.images); } }} Output: For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing Below is the file structure after performing these operations: surinderdawra388 Firebase Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26381, "s": 26353, "text": "\n06 Jan, 2022" }, { "code": null, "e": 26532, "s": 26381, "text": "This is the Part 15 of “Build a Social Media App on Android Studio” tutorial, and we are going to cover the following functionalities in this article:" }, { "code": null, "e": 26588, "s": 26532, "text": "We are going to delete the message in the ChatActivity." }, { "code": null, "e": 26688, "s": 26588, "text": "We are going to delete text and image messages. When we click on a text then an AlertBox will come." }, { "code": null, "e": 26828, "s": 26688, "text": "There will be two options to either delete that message or cancel the event. After Click on delete message will be deleted from both sides." }, { "code": null, "e": 26875, "s": 26828, "text": "Step 1: Working with the AdapterChat.java file" }, { "code": null, "e": 27165, "s": 26875, "text": "We can delete a message only if we are the sender of the message. There are two methods to delete the message. You can use any one of them. In one, we have removed the value using datasnapshot and in another, we have updated the message as “This Message Was Deleted” as we see in WhatsApp." }, { "code": null, "e": 27567, "s": 27165, "text": "if(dataSnapshot1.child(\"sender\").getValue().equals(myuid)) {\n// any two of below can be used\ndataSnapshot1.getRef().removeValue();\n\n// <-----------------------------------> \nHashMap<String, Object> hashMap = new HashMap<>();\nhashMap.put(\"message\", \"This Message Was Deleted\");\ndataSnapshot1.getRef().updateChildren(hashMap);\nToast.makeText(context,\"Message Deleted.....\",Toast.LENGTH_LONG).show();\n}" }, { "code": null, "e": 27616, "s": 27567, "text": "Below is the code for the AdapterChat.java file." }, { "code": null, "e": 27621, "s": 27616, "text": "Java" }, { "code": "package com.example.socialmediaapp; import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.text.format.DateFormat;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query;import com.google.firebase.database.ValueEventListener; import java.util.Calendar;import java.util.List;import java.util.Locale; import de.hdodenhof.circleimageview.CircleImageView; public class AdapterChat extends RecyclerView.Adapter<com.example.socialmediaapp.AdapterChat.Myholder> { private static final int MSG_TYPE_LEFT = 0; private static final int MSG_TYPR_RIGHT = 1; Context context; List<ModelChat> list; String imageurl; FirebaseUser firebaseUser; public AdapterChat(Context context, List<ModelChat> list, String imageurl) { this.context = context; this.list = list; this.imageurl = imageurl; } @NonNull @Override public Myholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if (viewType == MSG_TYPE_LEFT) { View view = LayoutInflater.from(context).inflate(R.layout.row_chat_left, parent, false); return new Myholder(view); } else { View view = LayoutInflater.from(context).inflate(R.layout.row_chat_right, parent, false); return new Myholder(view); } } @Override public void onBindViewHolder(@NonNull Myholder holder, final int position) { String message = list.get(position).getMessage(); String timeStamp = list.get(position).getTimestamp(); String type = list.get(position).getType(); Calendar calendar = Calendar.getInstance(Locale.ENGLISH); calendar.setTimeInMillis(Long.parseLong(timeStamp)); String timedate = DateFormat.format(\"dd/MM/yyyy hh:mm aa\", calendar).toString(); holder.message.setText(message); holder.time.setText(timedate); try { Glide.with(context).load(imageurl).into(holder.image); } catch (Exception e) { } if (type.equals(\"text\")) { holder.message.setVisibility(View.VISIBLE); holder.mimage.setVisibility(View.GONE); holder.message.setText(message); } else { holder.message.setVisibility(View.GONE); holder.mimage.setVisibility(View.VISIBLE); Glide.with(context).load(message).into(holder.mimage); } holder.msglayput.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(\"Delete Message\"); builder.setMessage(\"Are You Sure To Delete This Message\"); builder.setPositiveButton(\"Delete\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteMsg(position); } }); builder.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } }); } private void deleteMsg(int position) { final String myuid = FirebaseAuth.getInstance().getCurrentUser().getUid(); String msgtimestmp = list.get(position).getTimestamp(); DatabaseReference dbref = FirebaseDatabase.getInstance().getReference().child(\"Chats\"); Query query = dbref.orderByChild(\"timestamp\").equalTo(msgtimestmp); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { if (dataSnapshot1.child(\"sender\").getValue().equals(myuid)) { // any two of below can be used dataSnapshot1.getRef().removeValue(); /* HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put(\"message\", \"This Message Was Deleted\"); dataSnapshot1.getRef().updateChildren(hashMap); Toast.makeText(context,\"Message Deleted.....\",Toast.LENGTH_LONG).show();*/ } else { Toast.makeText(context, \"you can delete only your msg....\", Toast.LENGTH_LONG).show(); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public int getItemCount() { return list.size(); } @Override public int getItemViewType(int position) { firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); if (list.get(position).getSender().equals(firebaseUser.getUid())) { return MSG_TYPR_RIGHT; } else { return MSG_TYPE_LEFT; } } class Myholder extends RecyclerView.ViewHolder { CircleImageView image; ImageView mimage; TextView message, time, isSee; LinearLayout msglayput; public Myholder(@NonNull View itemView) { super(itemView); image = itemView.findViewById(R.id.profilec); message = itemView.findViewById(R.id.msgc); time = itemView.findViewById(R.id.timetv); isSee = itemView.findViewById(R.id.isSeen); msglayput = itemView.findViewById(R.id.msglayout); mimage = itemView.findViewById(R.id.images); } }}", "e": 34016, "s": 27621, "text": null }, { "code": null, "e": 34025, "s": 34016, "text": "Output: " }, { "code": null, "e": 34184, "s": 34025, "text": "For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing" }, { "code": null, "e": 34247, "s": 34184, "text": "Below is the file structure after performing these operations:" }, { "code": null, "e": 34266, "s": 34249, "text": "surinderdawra388" }, { "code": null, "e": 34275, "s": 34266, "text": "Firebase" }, { "code": null, "e": 34283, "s": 34275, "text": "Android" }, { "code": null, "e": 34288, "s": 34283, "text": "Java" }, { "code": null, "e": 34293, "s": 34288, "text": "Java" }, { "code": null, "e": 34301, "s": 34293, "text": "Android" }, { "code": null, "e": 34399, "s": 34301, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34437, "s": 34399, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 34476, "s": 34437, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 34526, "s": 34476, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 34568, "s": 34526, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 34619, "s": 34568, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 34634, "s": 34619, "text": "Arrays in Java" }, { "code": null, "e": 34678, "s": 34634, "text": "Split() String method in Java with examples" }, { "code": null, "e": 34700, "s": 34678, "text": "For-each loop in Java" }, { "code": null, "e": 34751, "s": 34700, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
How to create a file upload button in HTML ? - GeeksforGeeks
27 Sep, 2021 In this article, we will see how to make a file upload button to upload a file using HTML. As we know, uploading a file is an important aspect in simple HTML form. The file upload button is used to upload a user photo or any type of file in a form. Approach: For uploading the file using HTML, we will create a HTML document that contains an <input> tag. use the type attribute which is set to value “file”. Syntax: <input type="file"> Example: HTML <!DOCTYPE html><html> <head> <title>HTML input type file</title> <!--CSS code--> <style> h1 { color: green; } h2, h3 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h2>GeeksforGeeks</h2> <h3> How to create a file Upload Button using html? </h3> <label> Choose the File to upload: </label> <input type="file" id="myFile" /> <br /><br /> <input type="submit" value="submit" /></body> </html> Output: You can see that after the file is uploaded, the name of the file is displayed in front of the button. File upload button in HTML Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. simranarora5sos HTML-Questions HTML-Tags HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26139, "s": 26111, "text": "\n27 Sep, 2021" }, { "code": null, "e": 26389, "s": 26139, "text": "In this article, we will see how to make a file upload button to upload a file using HTML. As we know, uploading a file is an important aspect in simple HTML form. The file upload button is used to upload a user photo or any type of file in a form. " }, { "code": null, "e": 26442, "s": 26389, "text": "Approach: For uploading the file using HTML, we will" }, { "code": null, "e": 26495, "s": 26442, "text": "create a HTML document that contains an <input> tag." }, { "code": null, "e": 26548, "s": 26495, "text": "use the type attribute which is set to value “file”." }, { "code": null, "e": 26556, "s": 26548, "text": "Syntax:" }, { "code": null, "e": 26576, "s": 26556, "text": "<input type=\"file\">" }, { "code": null, "e": 26585, "s": 26576, "text": "Example:" }, { "code": null, "e": 26590, "s": 26585, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML input type file</title> <!--CSS code--> <style> h1 { color: green; } h2, h3 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h2>GeeksforGeeks</h2> <h3> How to create a file Upload Button using html? </h3> <label> Choose the File to upload: </label> <input type=\"file\" id=\"myFile\" /> <br /><br /> <input type=\"submit\" value=\"submit\" /></body> </html>", "e": 27149, "s": 26590, "text": null }, { "code": null, "e": 27261, "s": 27149, "text": "Output: You can see that after the file is uploaded, the name of the file is displayed in front of the button. " }, { "code": null, "e": 27288, "s": 27261, "text": "File upload button in HTML" }, { "code": null, "e": 27425, "s": 27288, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27441, "s": 27425, "text": "simranarora5sos" }, { "code": null, "e": 27456, "s": 27441, "text": "HTML-Questions" }, { "code": null, "e": 27466, "s": 27456, "text": "HTML-Tags" }, { "code": null, "e": 27471, "s": 27466, "text": "HTML" }, { "code": null, "e": 27488, "s": 27471, "text": "Web Technologies" }, { "code": null, "e": 27493, "s": 27488, "text": "HTML" }, { "code": null, "e": 27591, "s": 27493, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27615, "s": 27591, "text": "REST API (Introduction)" }, { "code": null, "e": 27656, "s": 27615, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 27693, "s": 27656, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27722, "s": 27693, "text": "Form validation using jQuery" }, { "code": null, "e": 27742, "s": 27722, "text": "Angular File Upload" }, { "code": null, "e": 27782, "s": 27742, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27815, "s": 27782, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27860, "s": 27815, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27903, "s": 27860, "text": "How to fetch data from an API in ReactJS ?" } ]
Print all the permutations of a string without repetition using Collections in Java - GeeksforGeeks
03 Sep, 2019 Given a string str, the task is to print all the permutations of str. A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement. A permutation should not have repeated strings in the output. Examples: Input: str = “aa”Output:aaNote that “aa” will be printed only onceas duplicates are not allowed. Input: str = “ab”Output:abba Approach: Write a recursive function that removes a character one by one from the original string and generates a new string by appending these removed characters. The base condition will be when all the characters have been used. In that case, insert the generated string (a permutation of the original string) in a set in order to avoid duplicates. Below is the implementation of the above approach: // Java implementation of the approachimport java.util.*;public class GFG { static Set<String> hash_Set = new HashSet<>(); // Recursive function to generate // permutations of the string static void Permutation(String str, String ans) { // If string is empty if (str.length() == 0) { // Add the generated permutation to the // set in order to avoid duplicates hash_Set.add(ans); return; } for (int i = 0; i < str.length(); i++) { // ith character of str char ch = str.charAt(i); // Rest of the string after excluding // the ith character String ros = str.substring(0, i) + str.substring(i + 1); // Recurvise call Permutation(ros, ans + ch); } } // Driver code public static void main(String[] args) { String s = "ab"; // Generate permutations Permutation(s, ""); // Print the generated permutations hash_Set.forEach((n) -> System.out.println(n)); }} ab ba java-hashset Backtracking Recursion Recursion Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path of more than k length from a source Difference between Backtracking and Branch-N-Bound technique Tug of War Minimum Cost Path in a directed graph via given set of intermediate nodes N-Queen Problem | Local Search using Hill climbing with random neighbour Recursion Recursive Practice Problems with Solutions Program for Sum of the digits of a given number Print all possible combinations of r elements in a given array of size n Write a program to reverse digits of a number
[ { "code": null, "e": 26203, "s": 26175, "text": "\n03 Sep, 2019" }, { "code": null, "e": 26448, "s": 26203, "text": "Given a string str, the task is to print all the permutations of str. A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement. A permutation should not have repeated strings in the output." }, { "code": null, "e": 26458, "s": 26448, "text": "Examples:" }, { "code": null, "e": 26555, "s": 26458, "text": "Input: str = “aa”Output:aaNote that “aa” will be printed only onceas duplicates are not allowed." }, { "code": null, "e": 26584, "s": 26555, "text": "Input: str = “ab”Output:abba" }, { "code": null, "e": 26935, "s": 26584, "text": "Approach: Write a recursive function that removes a character one by one from the original string and generates a new string by appending these removed characters. The base condition will be when all the characters have been used. In that case, insert the generated string (a permutation of the original string) in a set in order to avoid duplicates." }, { "code": null, "e": 26986, "s": 26935, "text": "Below is the implementation of the above approach:" }, { "code": "// Java implementation of the approachimport java.util.*;public class GFG { static Set<String> hash_Set = new HashSet<>(); // Recursive function to generate // permutations of the string static void Permutation(String str, String ans) { // If string is empty if (str.length() == 0) { // Add the generated permutation to the // set in order to avoid duplicates hash_Set.add(ans); return; } for (int i = 0; i < str.length(); i++) { // ith character of str char ch = str.charAt(i); // Rest of the string after excluding // the ith character String ros = str.substring(0, i) + str.substring(i + 1); // Recurvise call Permutation(ros, ans + ch); } } // Driver code public static void main(String[] args) { String s = \"ab\"; // Generate permutations Permutation(s, \"\"); // Print the generated permutations hash_Set.forEach((n) -> System.out.println(n)); }}", "e": 28103, "s": 26986, "text": null }, { "code": null, "e": 28110, "s": 28103, "text": "ab\nba\n" }, { "code": null, "e": 28123, "s": 28110, "text": "java-hashset" }, { "code": null, "e": 28136, "s": 28123, "text": "Backtracking" }, { "code": null, "e": 28146, "s": 28136, "text": "Recursion" }, { "code": null, "e": 28156, "s": 28146, "text": "Recursion" }, { "code": null, "e": 28169, "s": 28156, "text": "Backtracking" }, { "code": null, "e": 28267, "s": 28169, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28327, "s": 28267, "text": "Find if there is a path of more than k length from a source" }, { "code": null, "e": 28388, "s": 28327, "text": "Difference between Backtracking and Branch-N-Bound technique" }, { "code": null, "e": 28399, "s": 28388, "text": "Tug of War" }, { "code": null, "e": 28473, "s": 28399, "text": "Minimum Cost Path in a directed graph via given set of intermediate nodes" }, { "code": null, "e": 28546, "s": 28473, "text": "N-Queen Problem | Local Search using Hill climbing with random neighbour" }, { "code": null, "e": 28556, "s": 28546, "text": "Recursion" }, { "code": null, "e": 28599, "s": 28556, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 28647, "s": 28599, "text": "Program for Sum of the digits of a given number" }, { "code": null, "e": 28720, "s": 28647, "text": "Print all possible combinations of r elements in a given array of size n" } ]
Python program to Sort Matrix by Maximum Row element - GeeksforGeeks
11 Oct, 2020 Given a Matrix, sort rows by maximum element. Input : test_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Explanation : 18, 10, 8 and 5 are maximum elements in rows, hence sorted.Input : test_list = [[9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [0, 3, 5]] Explanation : 18, 10, and 5 are maximum elements in rows, hence sorted. Method #1 : Using sort() + max() In this, we perform task of sorting using sort() with key being maximum element from each row. The reverse keyword is used to sort by keeping maximum element rows at start and decreasing from there. Python3 # Python3 code to demonstrate working of # Sort Matrix by Maximum Row element# Using sort() + max() def max_sort(row): return max(row) # initializing listtest_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] # printing original listprint("The original list is : " + str(test_list)) # sort() for sorting, max to get maximum valuestest_list.sort(key = max_sort, reverse = True) # printing result print("The maximum sorted Matrix : " + str(test_list)) Output: The original list is : [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]]The maximum sorted Matrix : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Method #2 : Using sorted() + lambda + max() In this, we perform task of sorting using sorted() for non-inplace sort, and lambda function is used instead of external function to include maximum element from row logic. Python3 # Python3 code to demonstrate working of # Sort Matrix by Maximum Row element# Using sorted() + lambda + max() # initializing listtest_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] # printing original listprint("The original list is : " + str(test_list)) # sorted() for sorting, max to get maximum values# reverse for reversed orderres = sorted(test_list, key = lambda row : max(row), reverse=True) # printing result print("The maximum sorted Matrix : " + str(res)) Output: The original list is : [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]]The maximum sorted Matrix : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25943, "s": 25915, "text": "\n11 Oct, 2020" }, { "code": null, "e": 25989, "s": 25943, "text": "Given a Matrix, sort rows by maximum element." }, { "code": null, "e": 26364, "s": 25989, "text": "Input : test_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Explanation : 18, 10, 8 and 5 are maximum elements in rows, hence sorted.Input : test_list = [[9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [0, 3, 5]] Explanation : 18, 10, and 5 are maximum elements in rows, hence sorted. " }, { "code": null, "e": 26397, "s": 26364, "text": "Method #1 : Using sort() + max()" }, { "code": null, "e": 26596, "s": 26397, "text": "In this, we perform task of sorting using sort() with key being maximum element from each row. The reverse keyword is used to sort by keeping maximum element rows at start and decreasing from there." }, { "code": null, "e": 26604, "s": 26596, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Sort Matrix by Maximum Row element# Using sort() + max() def max_sort(row): return max(row) # initializing listtest_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] # printing original listprint(\"The original list is : \" + str(test_list)) # sort() for sorting, max to get maximum valuestest_list.sort(key = max_sort, reverse = True) # printing result print(\"The maximum sorted Matrix : \" + str(test_list))", "e": 27079, "s": 26604, "text": null }, { "code": null, "e": 27087, "s": 27079, "text": "Output:" }, { "code": null, "e": 27233, "s": 27087, "text": "The original list is : [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]]The maximum sorted Matrix : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]]" }, { "code": null, "e": 27277, "s": 27233, "text": "Method #2 : Using sorted() + lambda + max()" }, { "code": null, "e": 27450, "s": 27277, "text": "In this, we perform task of sorting using sorted() for non-inplace sort, and lambda function is used instead of external function to include maximum element from row logic." }, { "code": null, "e": 27458, "s": 27450, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Sort Matrix by Maximum Row element# Using sorted() + lambda + max() # initializing listtest_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] # printing original listprint(\"The original list is : \" + str(test_list)) # sorted() for sorting, max to get maximum values# reverse for reversed orderres = sorted(test_list, key = lambda row : max(row), reverse=True) # printing result print(\"The maximum sorted Matrix : \" + str(res))", "e": 27949, "s": 27458, "text": null }, { "code": null, "e": 27957, "s": 27949, "text": "Output:" }, { "code": null, "e": 28103, "s": 27957, "text": "The original list is : [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]]The maximum sorted Matrix : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]]" }, { "code": null, "e": 28124, "s": 28103, "text": "Python list-programs" }, { "code": null, "e": 28131, "s": 28124, "text": "Python" }, { "code": null, "e": 28147, "s": 28131, "text": "Python Programs" }, { "code": null, "e": 28245, "s": 28147, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28263, "s": 28245, "text": "Python Dictionary" }, { "code": null, "e": 28298, "s": 28263, "text": "Read a file line by line in Python" }, { "code": null, "e": 28330, "s": 28298, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28352, "s": 28330, "text": "Enumerate() in Python" }, { "code": null, "e": 28394, "s": 28352, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28437, "s": 28394, "text": "Python program to convert a list to string" }, { "code": null, "e": 28459, "s": 28437, "text": "Defaultdict in Python" }, { "code": null, "e": 28498, "s": 28459, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28544, "s": 28498, "text": "Python | Split string into list of characters" } ]
Enumeration Interface In Java - GeeksforGeeks
15 Dec, 2021 java.util.Enumeration interface is one of the predefined interfaces, whose object is used for retrieving the data from collections framework variable( like Stack, Vector, HashTable etc.) in a forward direction only and not in the backward direction. This interface has been superceded by an iterator. The Enumeration Interface defines the functions by which we can enumerate the elements in a collection of elements. For new code, Enumeration is considered obsolete. However, several methods of the legacy classes such as vectors and properties, several API classes, application codes use this Enumeration interface. Important Features Enumeration is Synchronized. It does not support adding, removing, or replacing elements. Elements of legacy Collections can be accessed in a forward direction using Enumeration. Legacy classes have methods to work with enumeration and returns Enumeration objects. Declaration public interface Enumeration<E> Where E is the type of elements stored in a Collection. The sub-interfaces of Enumeration interface is NamingEnumeration and implementing class is StringTokenizer. Creating Enumeration Object Vector ve = new Vector(); Enumeration e = v.elements(); Example: Java // Java program to test Enumerationimport java.util.Vector;import java.util.Enumeration; public class EnumerationClass { public static void main(String args[]) { Enumeration months; Vector<String> monthNames = new Vector<>(); monthNames.add("January"); monthNames.add("February"); monthNames.add("March"); monthNames.add("April"); monthNames.add("May"); monthNames.add("June"); monthNames.add("July"); monthNames.add("August"); monthNames.add("September"); monthNames.add("October"); monthNames.add("November"); monthNames.add("December"); months = monthNames.elements(); while (months.hasMoreElements()) { System.out.println(months.nextElement()); } }} January February March April May June July August September October November December Java Enumeration Interface With SequenceInputStream Java import java.io.*;import java.util.*;class GFG { public static void main(String args[]) throws IOException { // creating the FileInputStream objects for all the // files FileInputStream fin = new FileInputStream("file1.txt"); FileInputStream fin2 = new FileInputStream("file2.txt"); FileInputStream fin3 = new FileInputStream("file3.txt"); FileInputStream fin4 = new FileInputStream("file4.txt"); // creating Vector object to all the stream Vector v = new Vector(); v.add(fin); v.add(fin2); v.add(fin3); v.add(fin4); // creating enumeration object by calling the // elements method Enumeration e = v.elements(); // passing the enumeration object in the constructor SequenceInputStream bin = new SequenceInputStream(e); int i = 0; while ((i = bin.read()) != -1) { System.out.print((char)i); } bin.close(); fin.close(); fin2.close(); }} Creation Of Custom Enumeration Java import java.util.Enumeration;import java.lang.reflect.Array; public class EnumerationClass implements Enumeration { private int size; private int cursor; private final Object array; public EnumerationClass(Object obj) { Class type = obj.getClass(); if (!type.isArray()) { throw new IllegalArgumentException( "Invalid type: " + type); } size = Array.getLength(obj); array = obj; } public boolean hasMoreElements() { return (cursor < size); } public object nextElements() { return Array.get(array, cursor++); }} Creation of Java Enumeration using String Array Java import java.util.*;import java.io.*; public class EnumerationExample { public static void main(String args[]) { // String Array Creation String str[] = { "apple", "facebook", "google" }; // Array Enumeration Creation ArrayEnumeration aenum = new ArrayEnumeration(str); // usageof array enumeration while (aenum.hasMoreElements()) { System.out.println(aenum.nextElement()); } }} E – type of elements Modifier And Type Method Explanation rajeev0719singh surindertarika1234 simmytarika5 Java-Enumeration Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Internal Working of HashMap in Java Comparator Interface in Java with Examples Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n15 Dec, 2021" }, { "code": null, "e": 25526, "s": 25225, "text": "java.util.Enumeration interface is one of the predefined interfaces, whose object is used for retrieving the data from collections framework variable( like Stack, Vector, HashTable etc.) in a forward direction only and not in the backward direction. This interface has been superceded by an iterator." }, { "code": null, "e": 25842, "s": 25526, "text": "The Enumeration Interface defines the functions by which we can enumerate the elements in a collection of elements. For new code, Enumeration is considered obsolete. However, several methods of the legacy classes such as vectors and properties, several API classes, application codes use this Enumeration interface." }, { "code": null, "e": 25861, "s": 25842, "text": "Important Features" }, { "code": null, "e": 25890, "s": 25861, "text": "Enumeration is Synchronized." }, { "code": null, "e": 25951, "s": 25890, "text": "It does not support adding, removing, or replacing elements." }, { "code": null, "e": 26040, "s": 25951, "text": "Elements of legacy Collections can be accessed in a forward direction using Enumeration." }, { "code": null, "e": 26126, "s": 26040, "text": "Legacy classes have methods to work with enumeration and returns Enumeration objects." }, { "code": null, "e": 26138, "s": 26126, "text": "Declaration" }, { "code": null, "e": 26170, "s": 26138, "text": "public interface Enumeration<E>" }, { "code": null, "e": 26226, "s": 26170, "text": "Where E is the type of elements stored in a Collection." }, { "code": null, "e": 26334, "s": 26226, "text": "The sub-interfaces of Enumeration interface is NamingEnumeration and implementing class is StringTokenizer." }, { "code": null, "e": 26362, "s": 26334, "text": "Creating Enumeration Object" }, { "code": null, "e": 26418, "s": 26362, "text": "Vector ve = new Vector();\nEnumeration e = v.elements();" }, { "code": null, "e": 26427, "s": 26418, "text": "Example:" }, { "code": null, "e": 26432, "s": 26427, "text": "Java" }, { "code": "// Java program to test Enumerationimport java.util.Vector;import java.util.Enumeration; public class EnumerationClass { public static void main(String args[]) { Enumeration months; Vector<String> monthNames = new Vector<>(); monthNames.add(\"January\"); monthNames.add(\"February\"); monthNames.add(\"March\"); monthNames.add(\"April\"); monthNames.add(\"May\"); monthNames.add(\"June\"); monthNames.add(\"July\"); monthNames.add(\"August\"); monthNames.add(\"September\"); monthNames.add(\"October\"); monthNames.add(\"November\"); monthNames.add(\"December\"); months = monthNames.elements(); while (months.hasMoreElements()) { System.out.println(months.nextElement()); } }}", "e": 27228, "s": 26432, "text": null }, { "code": null, "e": 27314, "s": 27228, "text": "January\nFebruary\nMarch\nApril\nMay\nJune\nJuly\nAugust\nSeptember\nOctober\nNovember\nDecember" }, { "code": null, "e": 27367, "s": 27314, "text": "Java Enumeration Interface With SequenceInputStream " }, { "code": null, "e": 27372, "s": 27367, "text": "Java" }, { "code": "import java.io.*;import java.util.*;class GFG { public static void main(String args[]) throws IOException { // creating the FileInputStream objects for all the // files FileInputStream fin = new FileInputStream(\"file1.txt\"); FileInputStream fin2 = new FileInputStream(\"file2.txt\"); FileInputStream fin3 = new FileInputStream(\"file3.txt\"); FileInputStream fin4 = new FileInputStream(\"file4.txt\"); // creating Vector object to all the stream Vector v = new Vector(); v.add(fin); v.add(fin2); v.add(fin3); v.add(fin4); // creating enumeration object by calling the // elements method Enumeration e = v.elements(); // passing the enumeration object in the constructor SequenceInputStream bin = new SequenceInputStream(e); int i = 0; while ((i = bin.read()) != -1) { System.out.print((char)i); } bin.close(); fin.close(); fin2.close(); }}", "e": 28451, "s": 27372, "text": null }, { "code": null, "e": 28483, "s": 28451, "text": "Creation Of Custom Enumeration " }, { "code": null, "e": 28488, "s": 28483, "text": "Java" }, { "code": "import java.util.Enumeration;import java.lang.reflect.Array; public class EnumerationClass implements Enumeration { private int size; private int cursor; private final Object array; public EnumerationClass(Object obj) { Class type = obj.getClass(); if (!type.isArray()) { throw new IllegalArgumentException( \"Invalid type: \" + type); } size = Array.getLength(obj); array = obj; } public boolean hasMoreElements() { return (cursor < size); } public object nextElements() { return Array.get(array, cursor++); }}", "e": 29109, "s": 28488, "text": null }, { "code": null, "e": 29159, "s": 29109, "text": " Creation of Java Enumeration using String Array " }, { "code": null, "e": 29164, "s": 29159, "text": "Java" }, { "code": "import java.util.*;import java.io.*; public class EnumerationExample { public static void main(String args[]) { // String Array Creation String str[] = { \"apple\", \"facebook\", \"google\" }; // Array Enumeration Creation ArrayEnumeration aenum = new ArrayEnumeration(str); // usageof array enumeration while (aenum.hasMoreElements()) { System.out.println(aenum.nextElement()); } }}", "e": 29613, "s": 29164, "text": null }, { "code": null, "e": 29634, "s": 29613, "text": "E – type of elements" }, { "code": null, "e": 29654, "s": 29634, "text": "Modifier And Type " }, { "code": null, "e": 29675, "s": 29654, "text": "Method " }, { "code": null, "e": 29687, "s": 29675, "text": "Explanation" }, { "code": null, "e": 29705, "s": 29689, "text": "rajeev0719singh" }, { "code": null, "e": 29724, "s": 29705, "text": "surindertarika1234" }, { "code": null, "e": 29737, "s": 29724, "text": "simmytarika5" }, { "code": null, "e": 29754, "s": 29737, "text": "Java-Enumeration" }, { "code": null, "e": 29759, "s": 29754, "text": "Java" }, { "code": null, "e": 29764, "s": 29759, "text": "Java" }, { "code": null, "e": 29862, "s": 29764, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29877, "s": 29862, "text": "Stream In Java" }, { "code": null, "e": 29898, "s": 29877, "text": "Constructors in Java" }, { "code": null, "e": 29917, "s": 29898, "text": "Exceptions in Java" }, { "code": null, "e": 29947, "s": 29917, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29993, "s": 29947, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 30010, "s": 29993, "text": "Generics in Java" }, { "code": null, "e": 30031, "s": 30010, "text": "Introduction to Java" }, { "code": null, "e": 30067, "s": 30031, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 30110, "s": 30067, "text": "Comparator Interface in Java with Examples" } ]
Loops in Go Language
19 Nov, 2019 Go language contains only a single loop that is for-loop. A for loop is a repetition control structure that allows us to write a loop that is executed a specific number of times. In Go language, this for loop can be used in the different forms and the forms are: 1. As simple for loop It is similar that we use in other programming languages like C, C++, Java, C#, etc. Syntax: for initialization; condition; post{ // statements.... } Here, The initialization statement is optional and executes before for loop starts. The initialization statement is always in a simple statement like variable declarations, increment or assignment statements, or function calls. The condition statement holds a boolean expression, which is evaluated at the starting of each iteration of the loop. If the value of the conditional statement is true, then the loop executes. The post statement is executed after the body of the for-loop. After the post statement, the condition statement evaluates again if the value of the conditional statement is false, then the loop ends. Example: // Go program to illustrate the // use of simple for loop package main import "fmt" // Main functionfunc main() { // for loop // This loop starts when i = 0 // executes till i<4 condition is true // post statement is i++ for i := 0; i < 4; i++{ fmt.Printf("GeeksforGeeks\n") } } Output: GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks 2. For loop as Infinite Loop: A for loop is also used as an infinite loop by removing all the three expressions from the for loop. When the user did not write condition statement in for loop it means the condition statement is true and the loop goes into an infinite loop. Syntax: for{ // Statement... } Example: // Go program to illustrate the // use of an infinite loop package main import "fmt" // Main functionfunc main() { // Infinite loop for { fmt.Printf("GeeksforGeeks\n") } } Output: GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks ........... 3. for loop as while Loop: A for loop can also work as a while loop. This loop is executed until the given condition is true. When the value of the given condition is false the loop ends. Syntax: for condition{ // statement.. } Example: // Go program to illustrate the // the for loop as while Looppackage main import "fmt" // Main functionfunc main() { // while loop // for loop executes till // i < 3 condition is true i:= 0 for i < 3 { i += 2 } fmt.Println(i) } Output: 4 4. Simple range in for loop: You can also use the range in the for loop. Syntax: for i, j:= range rvariable{ // statement.. } Here, i and j are the variables in which the values of the iteration are assigned. They are also known as iteration variables. The second variable, i.e, j is optional. The range expression is evaluated once before the starting of the loop. Example: // Go program to illustrate the // use of simple range loop package main import "fmt" // Main functionfunc main() { // Here rvariable is a array rvariable:= []string{"GFG", "Geeks", "GeeksforGeeks"} // i and j stores the value of rvariable // i store index number of individual string and // j store individual string of the given array for i, j:= range rvariable { fmt.Println(i, j) } } Output: 0 GFG 1 Geeks 2 GeeksforGeeks 5. Using for loop for strings: A for loop can iterate over the Unicode code point for a string. Syntax: for index, chr:= range str{ // Statement.. } Here, The index is the variable which store the first byte of UTF-8 encoded code point and chr store the characters of the given string and str is a string. Example: // Go program to illustrate the // use for loop using stringpackage main import "fmt" // Main functionfunc main() { // String as a range in the for loop for i, j:= range "XabCd" { fmt.Printf("The index number of %U is %d\n", j, i) } } Output: The index number of U+0058 is 0 The index number of U+0061 is 1 The index number of U+0062 is 2 The index number of U+0043 is 3 The index number of U+0064 is 4 6. For Maps: A for loop can iterate over the key and value pairs of the map. Syntax: for key, value := range map { // Statement.. } Example: // Go program to illustrate the // use for loop using mapspackage main import "fmt" // Main functionfunc main() { // using maps mmap := map[int]string{ 22:"Geeks", 33:"GFG", 44:"GeeksforGeeks", } for key, value:= range mmap { fmt.Println(key, value) } } Output: 22 Geeks 33 GFG 44 GeeksforGeeks 7. For Channel: A for loop can iterate over the sequential values sent on the channel until it closed. Syntax: for item := range Chnl { // statements.. } Example: // Go program to illustrate the // use for loop using channelpackage main import "fmt" // Main functionfunc main() { // using channel chnl := make(chan int) go func(){ chnl <- 100 chnl <- 1000 chnl <- 10000 chnl <- 100000 close(chnl) }() for i:= range chnl { fmt.Println(i) } } Output: 100 1000 10000 100000 Important Points: Parentheses are not used around the three statements of a for loop. The curly braces are mandatory in for loop. The opening brace should be in the same line in which post statement exists. If the array, string, slice, or map is empty, then for loop does not give an error and continue its flow. Or in other words, if the array, string, slice, or map is nil then the number of iterations of the for loop is zero. Akanksha_Rai Go-Control-Flow Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to concatenate two strings in Golang time.Sleep() Function in Golang With Examples strings.Replace() Function in Golang With Examples strings.Contains Function in Golang with Examples fmt.Sprintf() Function in Golang With Examples Golang Maps Time Formatting in Golang Interfaces in Golang How to Parse JSON in Golang? How to convert a string in lower case in Golang?
[ { "code": null, "e": 53, "s": 25, "text": "\n19 Nov, 2019" }, { "code": null, "e": 316, "s": 53, "text": "Go language contains only a single loop that is for-loop. A for loop is a repetition control structure that allows us to write a loop that is executed a specific number of times. In Go language, this for loop can be used in the different forms and the forms are:" }, { "code": null, "e": 423, "s": 316, "text": "1. As simple for loop It is similar that we use in other programming languages like C, C++, Java, C#, etc." }, { "code": null, "e": 431, "s": 423, "text": "Syntax:" }, { "code": null, "e": 496, "s": 431, "text": "for initialization; condition; post{\n // statements....\n}\n" }, { "code": null, "e": 502, "s": 496, "text": "Here," }, { "code": null, "e": 724, "s": 502, "text": "The initialization statement is optional and executes before for loop starts. The initialization statement is always in a simple statement like variable declarations, increment or assignment statements, or function calls." }, { "code": null, "e": 917, "s": 724, "text": "The condition statement holds a boolean expression, which is evaluated at the starting of each iteration of the loop. If the value of the conditional statement is true, then the loop executes." }, { "code": null, "e": 1118, "s": 917, "text": "The post statement is executed after the body of the for-loop. After the post statement, the condition statement evaluates again if the value of the conditional statement is false, then the loop ends." }, { "code": null, "e": 1127, "s": 1118, "text": "Example:" }, { "code": "// Go program to illustrate the // use of simple for loop package main import \"fmt\" // Main functionfunc main() { // for loop // This loop starts when i = 0 // executes till i<4 condition is true // post statement is i++ for i := 0; i < 4; i++{ fmt.Printf(\"GeeksforGeeks\\n\") } }", "e": 1445, "s": 1127, "text": null }, { "code": null, "e": 1453, "s": 1445, "text": "Output:" }, { "code": null, "e": 1510, "s": 1453, "text": "GeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\n" }, { "code": null, "e": 1783, "s": 1510, "text": "2. For loop as Infinite Loop: A for loop is also used as an infinite loop by removing all the three expressions from the for loop. When the user did not write condition statement in for loop it means the condition statement is true and the loop goes into an infinite loop." }, { "code": null, "e": 1791, "s": 1783, "text": "Syntax:" }, { "code": null, "e": 1821, "s": 1791, "text": "for{\n // Statement...\n}\n\n" }, { "code": null, "e": 1830, "s": 1821, "text": "Example:" }, { "code": "// Go program to illustrate the // use of an infinite loop package main import \"fmt\" // Main functionfunc main() { // Infinite loop for { fmt.Printf(\"GeeksforGeeks\\n\") } }", "e": 2030, "s": 1830, "text": null }, { "code": null, "e": 2038, "s": 2030, "text": "Output:" }, { "code": null, "e": 2191, "s": 2038, "text": "GeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\n...........\n" }, { "code": null, "e": 2379, "s": 2191, "text": "3. for loop as while Loop: A for loop can also work as a while loop. This loop is executed until the given condition is true. When the value of the given condition is false the loop ends." }, { "code": null, "e": 2387, "s": 2379, "text": "Syntax:" }, { "code": null, "e": 2424, "s": 2387, "text": "for condition{\n // statement..\n}\n" }, { "code": null, "e": 2433, "s": 2424, "text": "Example:" }, { "code": "// Go program to illustrate the // the for loop as while Looppackage main import \"fmt\" // Main functionfunc main() { // while loop // for loop executes till // i < 3 condition is true i:= 0 for i < 3 { i += 2 } fmt.Println(i) }", "e": 2696, "s": 2433, "text": null }, { "code": null, "e": 2704, "s": 2696, "text": "Output:" }, { "code": null, "e": 2706, "s": 2704, "text": "4" }, { "code": null, "e": 2779, "s": 2706, "text": "4. Simple range in for loop: You can also use the range in the for loop." }, { "code": null, "e": 2787, "s": 2779, "text": "Syntax:" }, { "code": null, "e": 2835, "s": 2787, "text": "for i, j:= range rvariable{\n // statement..\n}" }, { "code": null, "e": 2841, "s": 2835, "text": "Here," }, { "code": null, "e": 2962, "s": 2841, "text": "i and j are the variables in which the values of the iteration are assigned. They are also known as iteration variables." }, { "code": null, "e": 3003, "s": 2962, "text": "The second variable, i.e, j is optional." }, { "code": null, "e": 3075, "s": 3003, "text": "The range expression is evaluated once before the starting of the loop." }, { "code": null, "e": 3084, "s": 3075, "text": "Example:" }, { "code": "// Go program to illustrate the // use of simple range loop package main import \"fmt\" // Main functionfunc main() { // Here rvariable is a array rvariable:= []string{\"GFG\", \"Geeks\", \"GeeksforGeeks\"} // i and j stores the value of rvariable // i store index number of individual string and // j store individual string of the given array for i, j:= range rvariable { fmt.Println(i, j) } }", "e": 3519, "s": 3084, "text": null }, { "code": null, "e": 3527, "s": 3519, "text": "Output:" }, { "code": null, "e": 3558, "s": 3527, "text": "0 GFG\n1 Geeks\n2 GeeksforGeeks\n" }, { "code": null, "e": 3654, "s": 3558, "text": "5. Using for loop for strings: A for loop can iterate over the Unicode code point for a string." }, { "code": null, "e": 3662, "s": 3654, "text": "Syntax:" }, { "code": null, "e": 3713, "s": 3662, "text": "for index, chr:= range str{\n // Statement..\n}\n" }, { "code": null, "e": 3870, "s": 3713, "text": "Here, The index is the variable which store the first byte of UTF-8 encoded code point and chr store the characters of the given string and str is a string." }, { "code": null, "e": 3879, "s": 3870, "text": "Example:" }, { "code": "// Go program to illustrate the // use for loop using stringpackage main import \"fmt\" // Main functionfunc main() { // String as a range in the for loop for i, j:= range \"XabCd\" { fmt.Printf(\"The index number of %U is %d\\n\", j, i) } }", "e": 4142, "s": 3879, "text": null }, { "code": null, "e": 4150, "s": 4142, "text": "Output:" }, { "code": null, "e": 4311, "s": 4150, "text": "The index number of U+0058 is 0\nThe index number of U+0061 is 1\nThe index number of U+0062 is 2\nThe index number of U+0043 is 3\nThe index number of U+0064 is 4\n" }, { "code": null, "e": 4388, "s": 4311, "text": "6. For Maps: A for loop can iterate over the key and value pairs of the map." }, { "code": null, "e": 4396, "s": 4388, "text": "Syntax:" }, { "code": null, "e": 4451, "s": 4396, "text": "for key, value := range map { \n // Statement.. \n}\n" }, { "code": null, "e": 4460, "s": 4451, "text": "Example:" }, { "code": "// Go program to illustrate the // use for loop using mapspackage main import \"fmt\" // Main functionfunc main() { // using maps mmap := map[int]string{ 22:\"Geeks\", 33:\"GFG\", 44:\"GeeksforGeeks\", } for key, value:= range mmap { fmt.Println(key, value) } }", "e": 4769, "s": 4460, "text": null }, { "code": null, "e": 4777, "s": 4769, "text": "Output:" }, { "code": null, "e": 4811, "s": 4777, "text": "22 Geeks\n33 GFG\n44 GeeksforGeeks\n" }, { "code": null, "e": 4914, "s": 4811, "text": "7. For Channel: A for loop can iterate over the sequential values sent on the channel until it closed." }, { "code": null, "e": 4922, "s": 4914, "text": "Syntax:" }, { "code": null, "e": 4972, "s": 4922, "text": "for item := range Chnl { \n // statements..\n}\n" }, { "code": null, "e": 4981, "s": 4972, "text": "Example:" }, { "code": "// Go program to illustrate the // use for loop using channelpackage main import \"fmt\" // Main functionfunc main() { // using channel chnl := make(chan int) go func(){ chnl <- 100 chnl <- 1000 chnl <- 10000 chnl <- 100000 close(chnl) }() for i:= range chnl { fmt.Println(i) } }", "e": 5328, "s": 4981, "text": null }, { "code": null, "e": 5336, "s": 5328, "text": "Output:" }, { "code": null, "e": 5359, "s": 5336, "text": "100\n1000\n10000\n100000\n" }, { "code": null, "e": 5377, "s": 5359, "text": "Important Points:" }, { "code": null, "e": 5445, "s": 5377, "text": "Parentheses are not used around the three statements of a for loop." }, { "code": null, "e": 5489, "s": 5445, "text": "The curly braces are mandatory in for loop." }, { "code": null, "e": 5566, "s": 5489, "text": "The opening brace should be in the same line in which post statement exists." }, { "code": null, "e": 5789, "s": 5566, "text": "If the array, string, slice, or map is empty, then for loop does not give an error and continue its flow. Or in other words, if the array, string, slice, or map is nil then the number of iterations of the for loop is zero." }, { "code": null, "e": 5802, "s": 5789, "text": "Akanksha_Rai" }, { "code": null, "e": 5818, "s": 5802, "text": "Go-Control-Flow" }, { "code": null, "e": 5830, "s": 5818, "text": "Go Language" }, { "code": null, "e": 5928, "s": 5830, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5980, "s": 5928, "text": "Different ways to concatenate two strings in Golang" }, { "code": null, "e": 6026, "s": 5980, "text": "time.Sleep() Function in Golang With Examples" }, { "code": null, "e": 6077, "s": 6026, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 6127, "s": 6077, "text": "strings.Contains Function in Golang with Examples" }, { "code": null, "e": 6174, "s": 6127, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 6186, "s": 6174, "text": "Golang Maps" }, { "code": null, "e": 6212, "s": 6186, "text": "Time Formatting in Golang" }, { "code": null, "e": 6233, "s": 6212, "text": "Interfaces in Golang" }, { "code": null, "e": 6262, "s": 6233, "text": "How to Parse JSON in Golang?" } ]
PyQt5 – How to create circular image from any image ?
26 Mar, 2020 In this article, we will see how to display only circular/round image from any image with any width and height i.e In order to do so we have to do the following steps : 1. Load the image2. Crop image to make it square3. Mask it and make circle from it using Painter4. Convert it back to pixmap image Code : Below is the original image : # importing librariesfrom PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * # function to alter imagedef mask_image(imgdata, imgtype ='png', size = 64): # Load image image = QImage.fromData(imgdata, imgtype) # convert image to 32-bit ARGB (adds an alpha # channel ie transparency factor): image.convertToFormat(QImage.Format_ARGB32) # Crop image to a square: imgsize = min(image.width(), image.height()) rect = QRect( (image.width() - imgsize) / 2, (image.height() - imgsize) / 2, imgsize, imgsize, ) image = image.copy(rect) # Create the output image with the same dimensions # and an alpha channel and make it completely transparent: out_img = QImage(imgsize, imgsize, QImage.Format_ARGB32) out_img.fill(Qt.transparent) # Create a texture brush and paint a circle # with the original image onto the output image: brush = QBrush(image) # Paint the output image painter = QPainter(out_img) painter.setBrush(brush) # Don't draw an outline painter.setPen(Qt.NoPen) # drawing circle painter.drawEllipse(0, 0, imgsize, imgsize) # closing painter event painter.end() # Convert the image to a pixmap and rescale it. pr = QWindow().devicePixelRatio() pm = QPixmap.fromImage(out_img) pm.setDevicePixelRatio(pr) size *= pr pm = pm.scaled(size, size, Qt.KeepAspectRatio, Qt.SmoothTransformation) # return back the pixmap data return pm class Window(QWidget): """Simple window that shows our masked image and text label.""" def __init__(self): super().__init__() # setting up the geometry self.setGeometry(100, 100, 600, 400) # image path imgpath = "image.png" # loading image imgdata = open(imgpath, 'rb').read() # calling the function pixmap = mask_image(imgdata) # creating label self.ilabel = QLabel(self) # putting image on label self.ilabel.setPixmap(pixmap) # moving the label self.ilabel.move(240, 180) # another label to put text self.tlabel = QLabel('This is circular image', self) self.tlabel.move(200, 250) # main functionif __name__ == '__main__': import sys from PyQt5.QtWidgets import QApplication # app created app = QApplication(sys.argv) w = Window() w.show() # begin the app sys.exit(app.exec_()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 143, "s": 28, "text": "In this article, we will see how to display only circular/round image from any image with any width and height i.e" }, { "code": null, "e": 197, "s": 143, "text": "In order to do so we have to do the following steps :" }, { "code": null, "e": 328, "s": 197, "text": "1. Load the image2. Crop image to make it square3. Mask it and make circle from it using Painter4. Convert it back to pixmap image" }, { "code": null, "e": 335, "s": 328, "text": "Code :" }, { "code": null, "e": 365, "s": 335, "text": "Below is the original image :" }, { "code": "# importing librariesfrom PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * # function to alter imagedef mask_image(imgdata, imgtype ='png', size = 64): # Load image image = QImage.fromData(imgdata, imgtype) # convert image to 32-bit ARGB (adds an alpha # channel ie transparency factor): image.convertToFormat(QImage.Format_ARGB32) # Crop image to a square: imgsize = min(image.width(), image.height()) rect = QRect( (image.width() - imgsize) / 2, (image.height() - imgsize) / 2, imgsize, imgsize, ) image = image.copy(rect) # Create the output image with the same dimensions # and an alpha channel and make it completely transparent: out_img = QImage(imgsize, imgsize, QImage.Format_ARGB32) out_img.fill(Qt.transparent) # Create a texture brush and paint a circle # with the original image onto the output image: brush = QBrush(image) # Paint the output image painter = QPainter(out_img) painter.setBrush(brush) # Don't draw an outline painter.setPen(Qt.NoPen) # drawing circle painter.drawEllipse(0, 0, imgsize, imgsize) # closing painter event painter.end() # Convert the image to a pixmap and rescale it. pr = QWindow().devicePixelRatio() pm = QPixmap.fromImage(out_img) pm.setDevicePixelRatio(pr) size *= pr pm = pm.scaled(size, size, Qt.KeepAspectRatio, Qt.SmoothTransformation) # return back the pixmap data return pm class Window(QWidget): \"\"\"Simple window that shows our masked image and text label.\"\"\" def __init__(self): super().__init__() # setting up the geometry self.setGeometry(100, 100, 600, 400) # image path imgpath = \"image.png\" # loading image imgdata = open(imgpath, 'rb').read() # calling the function pixmap = mask_image(imgdata) # creating label self.ilabel = QLabel(self) # putting image on label self.ilabel.setPixmap(pixmap) # moving the label self.ilabel.move(240, 180) # another label to put text self.tlabel = QLabel('This is circular image', self) self.tlabel.move(200, 250) # main functionif __name__ == '__main__': import sys from PyQt5.QtWidgets import QApplication # app created app = QApplication(sys.argv) w = Window() w.show() # begin the app sys.exit(app.exec_())", "e": 2883, "s": 365, "text": null }, { "code": null, "e": 2892, "s": 2883, "text": "Output :" }, { "code": null, "e": 2903, "s": 2892, "text": "Python-gui" }, { "code": null, "e": 2915, "s": 2903, "text": "Python-PyQt" }, { "code": null, "e": 2922, "s": 2915, "text": "Python" } ]
Comparing Intel i3, i5 and i7 processors
19 Apr, 2017 Do you often get confused with the Intel’s processor line-up? Ever wondered which chipset is best for your requirements? Which is more compatible with your needs? One should look beyond the Core i branding and check the number of cores, Clock Speed, Turbo Boost and Hyper-Threading to truly understand the magnitude of power it generates. Different processor families have different levels of efficiency, so how much they get done with each clock cycle is more important than the GHz number itself. Intel’s current core processors are divided into three ranges(Core i3, Core i5 and Core i7), with several models in each range.The differences between these ranges aren’t same on laptop chips as on desktops. Desktop chips follow a more logical pattern as compared to laptop chips, but many of the technologies and terms, we are about to discuss, such as cache memory, the number of cores, Turbo boost and Hyper-Threading concepts is same. Laptop processors have to balance power efficiency with performance – a constraint that doesn’t really apply to desktop chips. Similar is the case with the Mobile processors.Let’s start differentiating the processors on the basis of the concepts discussed below! Concepts and Technologies Total number of cores present: Out of all differences between the intel processor ranges, this is one that will affect performance the most.Having several cores can also drastically increase the speed at which certain programs run. The Core i3 range is entirely dual core, while Core i5 and i7 processors have four cores.It is difficult for an application to take advantage of the multicore system. Each core is effectively its own processor – your PC would still work (slowly) with just one core enabled. Having multiple cores means that the computer can work on more than one task at a time more efficiently.Personal ComputerIntel Core i3Intel Core i5Intel Core i7Number of Cores244 What is Turbo Boost in processors? This may be interesting, the slowest Core i3 chips runs at a faster speed than the base Core i5 and Core i7. This is where clock speed comes into the scenario.Let’s first define, What is Clock speed?The GHz represents the number of clock cycles (calculations) a processor can manage in a second. Putting simply, a bigger number means a faster processor.Examples: 2.4GHz means 2,400,000,000 clock cycles. Personal ComputerIntel Core i3Intel Core i5Intel Core i7Clock Speed Range(Several Models)3.4GHz – 4.2GHz2.4GHz – 3.8GHz2.9GHz – 4.2GHzTurbo Boost has nothing to do with fans or forced induction but is Intel’s marketing name for the technology that allows a processor to increase its core clock speed dynamically whenever the need arises. Core i3 processors don’t have Turbo Boost, but Core i5 and Core i7s do. Turbo Boost dynamically increases the clock speed of Core i5 and i7 processors when more power is required. This means that the chip can draw less power, produce less heat and only boost when it needs to. For example, although a Core i3-7300 runs at 4GHz compared to 3.5GHz for the Core i5-7600, the Core i5 chip can boost up to 4.1GHz when required, so will end up being quicker. A processor can only Turbo Boost for a limited amount of time. It is a significant part of the reason why Core i5 and Core i7 processors outperform Core i3 models in single-core-optimised tasks, even though they have lower base clock speeds.Personal ComputerIntel Core i3Intel Core i5Intel Core i7Turbo BoostNoYesYesNote:If a processor model ends with a K, it means it is unlocked and can be ‘overclocked’. This means you can force the CPU to run at a higher speed than its base speed all the time for better performance. 2.4GHz means 2,400,000,000 clock cycles. Turbo Boost has nothing to do with fans or forced induction but is Intel’s marketing name for the technology that allows a processor to increase its core clock speed dynamically whenever the need arises. Core i3 processors don’t have Turbo Boost, but Core i5 and Core i7s do. Turbo Boost dynamically increases the clock speed of Core i5 and i7 processors when more power is required. This means that the chip can draw less power, produce less heat and only boost when it needs to. For example, although a Core i3-7300 runs at 4GHz compared to 3.5GHz for the Core i5-7600, the Core i5 chip can boost up to 4.1GHz when required, so will end up being quicker. A processor can only Turbo Boost for a limited amount of time. It is a significant part of the reason why Core i5 and Core i7 processors outperform Core i3 models in single-core-optimised tasks, even though they have lower base clock speeds. Note:If a processor model ends with a K, it means it is unlocked and can be ‘overclocked’. This means you can force the CPU to run at a higher speed than its base speed all the time for better performance. Cache memory: A processor’s performance isn’t only determined by clock speed and number of cores, though. Other factors such as cache memory size also play a part. When a CPU finds it is using the same data over and over, it stores that data in its cache. Cache is even faster than RAM because it’s part of the processor itself.Here, bigger is better. Core i3 chips have 3- or 4MB, while i5s have 6MB and the Core i7s have 8MB.Personal ComputerIntel Core i3Intel Core i5Intel Core i7Cache Memory3 – 4MB4 – 6MB8MB What is Hyper-Threading?It’s one of the concepts which is a little confusing to explain, but also confuses as it’s available on Core i7 and Core i3, but not on the mid-range core i5. A little shocking, right? Normally we assume that we get more features as we go higher towards the processor range, but not here. Back to the concept, A thread in computing terms is a sequence of programmed instructions that the CPU has to process. For example: If a CPU consists of one core, it can process only one thread at once, so can only do one thing at once.Hyper-Threading is a clever way to let a single core handle multiple threads. It essentially tricks operating system into thinking that each physical processor core is, in fact, two virtual (logical) cores. A two-core Core i3 processor will appear as four virtual cores in Task Manager, and a four-core i7 chip will appear as eight cores. Whereas, the current Core i5 range doesn’t have Hyper-Threading so can also only process four cores. Due to Hyper-Threading operating system is able to share processing tasks between these virtual cores in order to help certain applications run more quickly, and to maintain system performance when more than one application is running at once.Personal ComputerIntel Core i3Intel Core i5Intel Core i7Hyper-ThreadingYesNoYes From these, we conclude why Core i7 processors are the creme de la creme. Not only are they quad cores, they also support Hyper-Threading. Thus, a total of eight threads can run on them at the same time. Combine that with 8MB of cache and Intel Turbo Boost Technology, which all of them have, and you’ll see what sets the Core i7 apart from its siblings.On the other side, it totally depends on the requirements, to choose a processor. References: https://en.wikipedia.org/wiki/Intel_Core http://www.expertreviews.co.uk/pcs/cpus/1400962/whats-the-difference-between-core-i3-i5-and-i7-processors This article is contributed by Prashant Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Technical Scripter TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Apr, 2017" }, { "code": null, "e": 391, "s": 52, "text": "Do you often get confused with the Intel’s processor line-up? Ever wondered which chipset is best for your requirements? Which is more compatible with your needs? One should look beyond the Core i branding and check the number of cores, Clock Speed, Turbo Boost and Hyper-Threading to truly understand the magnitude of power it generates." }, { "code": null, "e": 551, "s": 391, "text": "Different processor families have different levels of efficiency, so how much they get done with each clock cycle is more important than the GHz number itself." }, { "code": null, "e": 1253, "s": 551, "text": "Intel’s current core processors are divided into three ranges(Core i3, Core i5 and Core i7), with several models in each range.The differences between these ranges aren’t same on laptop chips as on desktops. Desktop chips follow a more logical pattern as compared to laptop chips, but many of the technologies and terms, we are about to discuss, such as cache memory, the number of cores, Turbo boost and Hyper-Threading concepts is same. Laptop processors have to balance power efficiency with performance – a constraint that doesn’t really apply to desktop chips. Similar is the case with the Mobile processors.Let’s start differentiating the processors on the basis of the concepts discussed below!" }, { "code": null, "e": 1279, "s": 1253, "text": "Concepts and Technologies" }, { "code": null, "e": 1964, "s": 1279, "text": "Total number of cores present: Out of all differences between the intel processor ranges, this is one that will affect performance the most.Having several cores can also drastically increase the speed at which certain programs run. The Core i3 range is entirely dual core, while Core i5 and i7 processors have four cores.It is difficult for an application to take advantage of the multicore system. Each core is effectively its own processor – your PC would still work (slowly) with just one core enabled. Having multiple cores means that the computer can work on more than one task at a time more efficiently.Personal ComputerIntel Core i3Intel Core i5Intel Core i7Number of Cores244" }, { "code": null, "e": 3716, "s": 1964, "text": "What is Turbo Boost in processors? This may be interesting, the slowest Core i3 chips runs at a faster speed than the base Core i5 and Core i7. This is where clock speed comes into the scenario.Let’s first define, What is Clock speed?The GHz represents the number of clock cycles (calculations) a processor can manage in a second. Putting simply, a bigger number means a faster processor.Examples: 2.4GHz means 2,400,000,000 clock cycles.\nPersonal ComputerIntel Core i3Intel Core i5Intel Core i7Clock Speed Range(Several Models)3.4GHz – 4.2GHz2.4GHz – 3.8GHz2.9GHz – 4.2GHzTurbo Boost has nothing to do with fans or forced induction but is Intel’s marketing name for the technology that allows a processor to increase its core clock speed dynamically whenever the need arises. Core i3 processors don’t have Turbo Boost, but Core i5 and Core i7s do. Turbo Boost dynamically increases the clock speed of Core i5 and i7 processors when more power is required. This means that the chip can draw less power, produce less heat and only boost when it needs to. For example, although a Core i3-7300 runs at 4GHz compared to 3.5GHz for the Core i5-7600, the Core i5 chip can boost up to 4.1GHz when required, so will end up being quicker. A processor can only Turbo Boost for a limited amount of time. It is a significant part of the reason why Core i5 and Core i7 processors outperform Core i3 models in single-core-optimised tasks, even though they have lower base clock speeds.Personal ComputerIntel Core i3Intel Core i5Intel Core i7Turbo BoostNoYesYesNote:If a processor model ends with a K, it means it is unlocked and can be ‘overclocked’. This means you can force the CPU to run at a higher speed than its base speed all the time for better performance." }, { "code": null, "e": 3759, "s": 3716, "text": " 2.4GHz means 2,400,000,000 clock cycles.\n" }, { "code": null, "e": 4658, "s": 3759, "text": "Turbo Boost has nothing to do with fans or forced induction but is Intel’s marketing name for the technology that allows a processor to increase its core clock speed dynamically whenever the need arises. Core i3 processors don’t have Turbo Boost, but Core i5 and Core i7s do. Turbo Boost dynamically increases the clock speed of Core i5 and i7 processors when more power is required. This means that the chip can draw less power, produce less heat and only boost when it needs to. For example, although a Core i3-7300 runs at 4GHz compared to 3.5GHz for the Core i5-7600, the Core i5 chip can boost up to 4.1GHz when required, so will end up being quicker. A processor can only Turbo Boost for a limited amount of time. It is a significant part of the reason why Core i5 and Core i7 processors outperform Core i3 models in single-core-optimised tasks, even though they have lower base clock speeds." }, { "code": null, "e": 4864, "s": 4658, "text": "Note:If a processor model ends with a K, it means it is unlocked and can be ‘overclocked’. This means you can force the CPU to run at a higher speed than its base speed all the time for better performance." }, { "code": null, "e": 5377, "s": 4864, "text": "Cache memory: A processor’s performance isn’t only determined by clock speed and number of cores, though. Other factors such as cache memory size also play a part. When a CPU finds it is using the same data over and over, it stores that data in its cache. Cache is even faster than RAM because it’s part of the processor itself.Here, bigger is better. Core i3 chips have 3- or 4MB, while i5s have 6MB and the Core i7s have 8MB.Personal ComputerIntel Core i3Intel Core i5Intel Core i7Cache Memory3 – 4MB4 – 6MB8MB" }, { "code": null, "e": 6689, "s": 5377, "text": "What is Hyper-Threading?It’s one of the concepts which is a little confusing to explain, but also confuses as it’s available on Core i7 and Core i3, but not on the mid-range core i5. A little shocking, right? Normally we assume that we get more features as we go higher towards the processor range, but not here. Back to the concept, A thread in computing terms is a sequence of programmed instructions that the CPU has to process. For example: If a CPU consists of one core, it can process only one thread at once, so can only do one thing at once.Hyper-Threading is a clever way to let a single core handle multiple threads. It essentially tricks operating system into thinking that each physical processor core is, in fact, two virtual (logical) cores. A two-core Core i3 processor will appear as four virtual cores in Task Manager, and a four-core i7 chip will appear as eight cores. Whereas, the current Core i5 range doesn’t have Hyper-Threading so can also only process four cores. Due to Hyper-Threading operating system is able to share processing tasks between these virtual cores in order to help certain applications run more quickly, and to maintain system performance when more than one application is running at once.Personal ComputerIntel Core i3Intel Core i5Intel Core i7Hyper-ThreadingYesNoYes" }, { "code": null, "e": 7125, "s": 6689, "text": "From these, we conclude why Core i7 processors are the creme de la creme. Not only are they quad cores, they also support Hyper-Threading. Thus, a total of eight threads can run on them at the same time. Combine that with 8MB of cache and Intel Turbo Boost Technology, which all of them have, and you’ll see what sets the Core i7 apart from its siblings.On the other side, it totally depends on the requirements, to choose a processor." }, { "code": null, "e": 7137, "s": 7125, "text": "References:" }, { "code": null, "e": 7178, "s": 7137, "text": "https://en.wikipedia.org/wiki/Intel_Core" }, { "code": null, "e": 7284, "s": 7178, "text": "http://www.expertreviews.co.uk/pcs/cpus/1400962/whats-the-difference-between-core-i3-i5-and-i7-processors" }, { "code": null, "e": 7588, "s": 7284, "text": "This article is contributed by Prashant Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 7713, "s": 7588, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7732, "s": 7713, "text": "Technical Scripter" }, { "code": null, "e": 7741, "s": 7732, "text": "TechTips" } ]
Flat & Nested Distributed Transactions
10 Nov, 2021 Introduction : A transaction is a series of object operations that must be done in an ACID-compliant manner. Atomicity – The transaction is completed entirely or not at all. Consistency – It is a term that refers to the transition from one consistent state to another. Isolation – It is carried out separately from other transactions. Durability – Once completed, it is long lasting. Transactions – Commands : Begin –initiate a new transaction. Commit – End a transaction and the changes made during the transaction are saved. Also, it allows other transactions to see the modifications you’ve made. Abort – End a transaction and all changes made during the transaction will be undone. Various roles are allocated to running a transaction successfully : Client – The transactions are issued by the clients. Coordinator – The execution of the entire transaction is controlled by it (handles Begin, commit & abort). Server –Every component that accesses or modifies a resource is subject to transaction control. The coordinator must be known by the transactional server. The transactional server registers its participation in a transaction with the coordinator. A flat or nested transaction that accesses objects handled by different servers is referred to as a distributed transaction.When a distributed transaction reaches its end, in order to maintain the atomicity property of the transaction , it is mandatory that all of the servers involved in the transaction either commit the transaction or abort it. To do this, one of the servers takes on the job of coordinator, which entails ensuring that the same outcome is achieved across all servers. The method by which the coordinator accomplishes this is determined by the protocol selected. The most widely used protocol is the ‘two-phase commit protocol.’ This protocol enables the servers to communicate with one another in order to come to a joint decision on whether to commit or abort the complete transaction. Flat & Nested Distributed Transactions :If a client transaction calls actions on multiple servers, it is said to be distributed. Distributed transactions can be structured in two different ways: Flat transactionsNested transactions Flat transactions Nested transactions FLAT TRANSACTIONS :A flat transaction has a single initiating point(Begin) and a single end point(Commit or abort). They are usually very simple and are generally used for short activities rather than larger ones.A client makes requests to multiple servers in a flat transaction. Transaction T, for example, is a flat transaction that performs operations on objects in servers X, Y, and Z. Before moving on to the next request, a flat client transaction completes the previous one. As a result, each transaction visits the server object in order. A transaction can only wait for one object at a time when servers utilize locking. Flat Transaction Limitations of a flat Transaction : All work is lost in the event of a crash. Only one DBMS may be used at a time. No partial rollback is possible. NESTED TRANSACTIONS :A transaction that includes other transactions within its initiating point and a end point are known as nested transactions. So the nesting of the transactions is done in a transaction. The nested transactions here are called sub-transactions.The top-level transaction in a nested transaction can open sub-transactions, and each sub-transaction can open more sub-transactions down to any depth of nesting. A client’s transaction T opens up two sub-transactions, T1 and T2, which access objects on servers X and Y, as shown in the diagram below. T1.1, T1.2, T2.1, and T2.2, which access the objects on the servers M,N, and P, are opened by the sub-transactions T1 and T2. Nested Transaction Concurrent Execution of the Sub-transactions is done which are at the same level – in the nested transaction strategy.Here, in the above diagram, T1 and T2 invoke objects on different servers and hence they can run in parallel and are therefore concurrent.T1.1, T1.2, T2.1, and T2.2 are four sub-transactions. These sub-transactions can also run in parallel. Consider a distributed transaction (T) in which a customer transfers : Rs. 105 from account A to account C and Subsequently, Rs. 205 from account B to account D. It can be viewed/ thought of as : Transaction T : Start Transfer Rs 105 from A to C : Deduct Rs 105 from A(withdraw from A) & Add Rs 105 to C(depopsit to C) Transfer Rs 205 from B to D : Deduct Rs 205 from B (withdraw from B)& Add Rs 205 to D(depopsit to D) End Assuming : Account A is on server XAccount B is on server Y,andAccounts C and D are on server Z. Account A is on server X Account B is on server Y,and Accounts C and D are on server Z. The transaction T involves four requests – 2 for deposits and 2 for withdrawals. Now they can be treated as sub transactions (T1, T2, T3, T4) of the transaction T.As shown in the figure below, transaction T is designed as a set of four nested transactions : T1, T2, T3 and T4. Advantage : The performance is higher than a single transaction in which four operations are invoked one after the other in sequence. Nested Transaction So, the Transaction T may be divided into sub-transactions as : //Start the Transaction T = open transaction //T1 openSubtransaction a.withdraw(105); //T2 openSubtransaction b.withdraw(205); //T3 openSubtransaction c.deposit(105); //T4 openSubtransaction d.deposit(205); //End the trsnaction close Transaction Role of coordinator :When the Distributed Transaction commits, the servers that are involved in the transaction execution,for proper coordination, must be able to communicate with one another .When a client initiates a transaction, an “openTransaction” request is sent to any coordinator server. The contacted coordinator carries out the “openTransaction” and returns the transaction identifier to the client. Distributed transaction identifiers must be unique within the distributed system. A simple way is to generate a TID contains two parts – the ‘server identifier” (example : IP address) of the server that created it and a number unique to the server.The coordinator who initiated the transaction becomes the distributed transaction’s coordinator and has the responsibility of either aborting it or committing it. Every server that manages an object accessed by a transaction is a participant in the transaction & provides an object we call the participant. The participants are responsible for working together with the coordinator to complete the commit process. The coordinator every time, records the new participant in the participants list. Each participant knows the coordinator & the coordinator knows all the participants. This enables them to collect the information that will be needed at the time of commit and hence work in coordination. surinderdawra388 DBMS-SQL DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS Difference between OLAP and OLTP in DBMS MySQL | Regular expressions (Regexp) What is Temporary Table in SQL? SQL | DDL, DML, TCL and DCL Difference between Where and Having Clause in SQL Relational Model in DBMS Introduction of Relational Algebra in DBMS Difference between File System and DBMS Difference between Star Schema and Snowflake Schema
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Nov, 2021" }, { "code": null, "e": 163, "s": 54, "text": "Introduction : A transaction is a series of object operations that must be done in an ACID-compliant manner." }, { "code": null, "e": 228, "s": 163, "text": "Atomicity – The transaction is completed entirely or not at all." }, { "code": null, "e": 323, "s": 228, "text": "Consistency – It is a term that refers to the transition from one consistent state to another." }, { "code": null, "e": 389, "s": 323, "text": "Isolation – It is carried out separately from other transactions." }, { "code": null, "e": 438, "s": 389, "text": "Durability – Once completed, it is long lasting." }, { "code": null, "e": 464, "s": 438, "text": "Transactions – Commands :" }, { "code": null, "e": 499, "s": 464, "text": "Begin –initiate a new transaction." }, { "code": null, "e": 654, "s": 499, "text": "Commit – End a transaction and the changes made during the transaction are saved. Also, it allows other transactions to see the modifications you’ve made." }, { "code": null, "e": 740, "s": 654, "text": "Abort – End a transaction and all changes made during the transaction will be undone." }, { "code": null, "e": 808, "s": 740, "text": "Various roles are allocated to running a transaction successfully :" }, { "code": null, "e": 861, "s": 808, "text": "Client – The transactions are issued by the clients." }, { "code": null, "e": 968, "s": 861, "text": "Coordinator – The execution of the entire transaction is controlled by it (handles Begin, commit & abort)." }, { "code": null, "e": 1215, "s": 968, "text": "Server –Every component that accesses or modifies a resource is subject to transaction control. The coordinator must be known by the transactional server. The transactional server registers its participation in a transaction with the coordinator." }, { "code": null, "e": 2025, "s": 1215, "text": "A flat or nested transaction that accesses objects handled by different servers is referred to as a distributed transaction.When a distributed transaction reaches its end, in order to maintain the atomicity property of the transaction , it is mandatory that all of the servers involved in the transaction either commit the transaction or abort it. To do this, one of the servers takes on the job of coordinator, which entails ensuring that the same outcome is achieved across all servers. The method by which the coordinator accomplishes this is determined by the protocol selected. The most widely used protocol is the ‘two-phase commit protocol.’ This protocol enables the servers to communicate with one another in order to come to a joint decision on whether to commit or abort the complete transaction. " }, { "code": null, "e": 2221, "s": 2025, "text": "Flat & Nested Distributed Transactions :If a client transaction calls actions on multiple servers, it is said to be distributed. Distributed transactions can be structured in two different ways: " }, { "code": null, "e": 2258, "s": 2221, "text": "Flat transactionsNested transactions" }, { "code": null, "e": 2276, "s": 2258, "text": "Flat transactions" }, { "code": null, "e": 2296, "s": 2276, "text": "Nested transactions" }, { "code": null, "e": 2926, "s": 2296, "text": "FLAT TRANSACTIONS :A flat transaction has a single initiating point(Begin) and a single end point(Commit or abort). They are usually very simple and are generally used for short activities rather than larger ones.A client makes requests to multiple servers in a flat transaction. Transaction T, for example, is a flat transaction that performs operations on objects in servers X, Y, and Z. Before moving on to the next request, a flat client transaction completes the previous one. As a result, each transaction visits the server object in order. A transaction can only wait for one object at a time when servers utilize locking." }, { "code": null, "e": 2943, "s": 2926, "text": "Flat Transaction" }, { "code": null, "e": 2979, "s": 2943, "text": "Limitations of a flat Transaction :" }, { "code": null, "e": 3021, "s": 2979, "text": "All work is lost in the event of a crash." }, { "code": null, "e": 3058, "s": 3021, "text": "Only one DBMS may be used at a time." }, { "code": null, "e": 3091, "s": 3058, "text": "No partial rollback is possible." }, { "code": null, "e": 3784, "s": 3091, "text": "NESTED TRANSACTIONS :A transaction that includes other transactions within its initiating point and a end point are known as nested transactions. So the nesting of the transactions is done in a transaction. The nested transactions here are called sub-transactions.The top-level transaction in a nested transaction can open sub-transactions, and each sub-transaction can open more sub-transactions down to any depth of nesting. A client’s transaction T opens up two sub-transactions, T1 and T2, which access objects on servers X and Y, as shown in the diagram below. T1.1, T1.2, T2.1, and T2.2, which access the objects on the servers M,N, and P, are opened by the sub-transactions T1 and T2. " }, { "code": null, "e": 3803, "s": 3784, "text": "Nested Transaction" }, { "code": null, "e": 4165, "s": 3803, "text": "Concurrent Execution of the Sub-transactions is done which are at the same level – in the nested transaction strategy.Here, in the above diagram, T1 and T2 invoke objects on different servers and hence they can run in parallel and are therefore concurrent.T1.1, T1.2, T2.1, and T2.2 are four sub-transactions. These sub-transactions can also run in parallel. " }, { "code": null, "e": 4237, "s": 4165, "text": "Consider a distributed transaction (T) in which a customer transfers :" }, { "code": null, "e": 4277, "s": 4237, "text": "Rs. 105 from account A to account C and" }, { "code": null, "e": 4328, "s": 4277, "text": "Subsequently, Rs. 205 from account B to account D." }, { "code": null, "e": 4362, "s": 4328, "text": "It can be viewed/ thought of as :" }, { "code": null, "e": 4592, "s": 4362, "text": "Transaction T :\nStart\nTransfer Rs 105 from A to C : \nDeduct Rs 105 from A(withdraw from A) & Add Rs 105 to C(depopsit to C)\nTransfer Rs 205 from B to D : \nDeduct Rs 205 from B (withdraw from B)& Add Rs 205 to D(depopsit to D)\nEnd" }, { "code": null, "e": 4603, "s": 4592, "text": "Assuming :" }, { "code": null, "e": 4689, "s": 4603, "text": "Account A is on server XAccount B is on server Y,andAccounts C and D are on server Z." }, { "code": null, "e": 4714, "s": 4689, "text": "Account A is on server X" }, { "code": null, "e": 4743, "s": 4714, "text": "Account B is on server Y,and" }, { "code": null, "e": 4777, "s": 4743, "text": "Accounts C and D are on server Z." }, { "code": null, "e": 5054, "s": 4777, "text": "The transaction T involves four requests – 2 for deposits and 2 for withdrawals. Now they can be treated as sub transactions (T1, T2, T3, T4) of the transaction T.As shown in the figure below, transaction T is designed as a set of four nested transactions : T1, T2, T3 and T4." }, { "code": null, "e": 5191, "s": 5054, "text": "Advantage : The performance is higher than a single transaction in which four operations are invoked one after the other in sequence. " }, { "code": null, "e": 5210, "s": 5191, "text": "Nested Transaction" }, { "code": null, "e": 5274, "s": 5210, "text": "So, the Transaction T may be divided into sub-transactions as :" }, { "code": null, "e": 5521, "s": 5274, "text": "//Start the Transaction\nT = open transaction\n//T1\nopenSubtransaction\na.withdraw(105);\n//T2\nopenSubtransaction\nb.withdraw(205);\n//T3\nopenSubtransaction\nc.deposit(105);\n//T4\nopenSubtransaction\nd.deposit(205);\n//End the trsnaction\nclose Transaction" }, { "code": null, "e": 5933, "s": 5521, "text": "Role of coordinator :When the Distributed Transaction commits, the servers that are involved in the transaction execution,for proper coordination, must be able to communicate with one another .When a client initiates a transaction, an “openTransaction” request is sent to any coordinator server. The contacted coordinator carries out the “openTransaction” and returns the transaction identifier to the client." }, { "code": null, "e": 6349, "s": 5933, "text": "Distributed transaction identifiers must be unique within the distributed system. A simple way is to generate a TID contains two parts – the ‘server identifier” (example : IP address) of the server that created it and a number unique to the server.The coordinator who initiated the transaction becomes the distributed transaction’s coordinator and has the responsibility of either aborting it or committing it. " }, { "code": null, "e": 6601, "s": 6349, "text": "Every server that manages an object accessed by a transaction is a participant in the transaction & provides an object we call the participant. The participants are responsible for working together with the coordinator to complete the commit process. " }, { "code": null, "e": 6889, "s": 6601, "text": "The coordinator every time, records the new participant in the participants list. Each participant knows the coordinator & the coordinator knows all the participants. This enables them to collect the information that will be needed at the time of commit and hence work in coordination." }, { "code": null, "e": 6906, "s": 6889, "text": "surinderdawra388" }, { "code": null, "e": 6915, "s": 6906, "text": "DBMS-SQL" }, { "code": null, "e": 6920, "s": 6915, "text": "DBMS" }, { "code": null, "e": 6925, "s": 6920, "text": "DBMS" }, { "code": null, "e": 7023, "s": 6925, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7064, "s": 7023, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 7105, "s": 7064, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 7142, "s": 7105, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 7174, "s": 7142, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 7202, "s": 7174, "text": "SQL | DDL, DML, TCL and DCL" }, { "code": null, "e": 7252, "s": 7202, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 7277, "s": 7252, "text": "Relational Model in DBMS" }, { "code": null, "e": 7320, "s": 7277, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 7360, "s": 7320, "text": "Difference between File System and DBMS" } ]
Python | Numpy np.coords() method
03 Nov, 2019 With the help of np.coords() method, we can get the coordinates of a next value in iteration using np.coords() method. Syntax : np.coords()Return : Return the coordinates of next iterator. Example #1 :In this example we can see that by using np.coords() method, we are able to get the coordinates of a next iterator using this method. # import numpyimport numpy as np a = np.array([1, 2, 3])# using np.coords() methodgfg = a.flatnext(gfg)print(gfg.coords) Output : (1, ) Example #2 : # import numpyimport numpy as np a = np.array([[1, 2, 3], [4, 5, 6]])# using np.coords() methodgfg = a.flatnext(gfg)next(gfg)next(gfg)next(gfg)print(gfg.coords) Output : (1, 1) Python numpy-arrayManipulation 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": "\n03 Nov, 2019" }, { "code": null, "e": 147, "s": 28, "text": "With the help of np.coords() method, we can get the coordinates of a next value in iteration using np.coords() method." }, { "code": null, "e": 217, "s": 147, "text": "Syntax : np.coords()Return : Return the coordinates of next iterator." }, { "code": null, "e": 363, "s": 217, "text": "Example #1 :In this example we can see that by using np.coords() method, we are able to get the coordinates of a next iterator using this method." }, { "code": "# import numpyimport numpy as np a = np.array([1, 2, 3])# using np.coords() methodgfg = a.flatnext(gfg)print(gfg.coords)", "e": 485, "s": 363, "text": null }, { "code": null, "e": 494, "s": 485, "text": "Output :" }, { "code": null, "e": 500, "s": 494, "text": "(1, )" }, { "code": null, "e": 513, "s": 500, "text": "Example #2 :" }, { "code": "# import numpyimport numpy as np a = np.array([[1, 2, 3], [4, 5, 6]])# using np.coords() methodgfg = a.flatnext(gfg)next(gfg)next(gfg)next(gfg)print(gfg.coords)", "e": 675, "s": 513, "text": null }, { "code": null, "e": 684, "s": 675, "text": "Output :" }, { "code": null, "e": 691, "s": 684, "text": "(1, 1)" }, { "code": null, "e": 722, "s": 691, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 735, "s": 722, "text": "Python-numpy" }, { "code": null, "e": 742, "s": 735, "text": "Python" } ]
Polynomial Time Approximation Scheme
07 Jul, 2022 It is a very well known fact that there is no known polynomial time solution for NP Complete problems and these problems occur a lot in real world (See this, this and this for example). So there must be a way to handle them. We have seen algorithms to these problems which are p approximate (For example 2 approximate for Travelling Salesman). Can we do better? Polynomial Time Approximation Scheme (PTAS) is a type of approximate algorithms that provide user to control over accuracy which is a desirable feature. These algorithms take an additional parameter ε > 0 and provide a solution that is (1 + ε) approximate for minimization and (1 – ε) for maximization. For example consider a minimization problem, if ε is 0.5, then the solution provided by the PTAS algorithm is 1.5 approximate. The running time of PTAS must be polynomial in terms of n, however, it can be exponential in terms of ε. In PTAS algorithms, the exponent of the polynomial can increase dramatically as ε reduces, for example if the runtime is O(n(1/ε)!) which is a problem. There is a stricter scheme, Fully Polynomial Time Approximation Scheme (FPTAS). In FPTAS, algorithm need to polynomial in both the problem size n and 1/ε. Example (0-1 knapsack problem): We know that 0-1 knapsack is NP Complete. There is a DP based pseudo polynomial solution for this. But if input values are high, then the solution becomes infeasible and there is a need of approximate solution. One approximate solution is to use Greedy Approach (compute value per kg for all items and put the highest value per kg first if it is smaller than W), but Greedy approach is not PTAS, so we don’t have control over accuracy. Below is a FPTAS solution for 0-1 Knapsack problem:Input:W (Capacity of Knapsack)val[0..n-1] (Values of Items)wt[0..n-1] (Weights of Items) Find the maximum valued item, i.e., find maximum value in val[]. Let this maximum value be maxVal.Compute adjustment factor k for all values k = (maxVal * ε) / nAdjust all values, i.e., create a new array val'[] that values divided by k. Do following for every value val[i]. val'[i] = floor(val[i] / k)Run DP based solution for reduced values, i,e, val'[0..n-1] and all other parameter same. Find the maximum valued item, i.e., find maximum value in val[]. Let this maximum value be maxVal. Compute adjustment factor k for all values k = (maxVal * ε) / n k = (maxVal * ε) / n Adjust all values, i.e., create a new array val'[] that values divided by k. Do following for every value val[i]. val'[i] = floor(val[i] / k) val'[i] = floor(val[i] / k) Run DP based solution for reduced values, i,e, val'[0..n-1] and all other parameter same. The above solution works in polynomial time in terms of both n and ε. The solution provided by this FPTAS is (1 – ε) approximate. The idea is to rounds off some of the least significant digits of values then they will be bounded by a polynomial and 1/ε. Example: val[] = {12, 16, 4, 8} wt[] = {3, 4, 5, 2} W = 10 ε = 0.5 maxVal = 16 [maximum value in val[]] Adjustment factor, k = (16 * 0.5)/4 = 2.0 Now we apply DP based solution on below modified instance of problem. val'[] = {6, 8, 2, 4} [ val'[i] = floor(val[i]/k) ] wt[] = {3, 4, 5, 2} W = 10 How is the solution (1 – ε) * OPT?Here OPT is the optimal value. Let S be the set produced by above FPTAS algorithm and total value of S be val(S). We need to show that val(S) >= (1 - ε)*OPT Let O be the set produced by optimal solution (the solution with total value OPT), i.e., val(O) = OPT. val(O) - k*val'(O) <= n*k [Because val'[i] = floor(val[i]/k) ] After the dynamic programming step, we get a set that is optimal for the scaled instanceand therefore must be at least as good as choosing the set O with the smaller profits. From that, we can conclude, val'(S) >= k . val'(O) >= val(O) - nk >= OPT - ε * maxVal >= OPT - ε * OPT [OPT >= maxVal] >= (1 - ε) * OPT Sources:http://math.mit.edu/~goemans/18434S06/knapsack-katherine.pdfhttps://en.wikipedia.org/wiki/Polynomial-time_approximation_scheme This article is contributed by Dheeraj Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jokic07 shubhamagarwal0312 shreelakshmijoshi1 Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2022" }, { "code": null, "e": 416, "s": 54, "text": "It is a very well known fact that there is no known polynomial time solution for NP Complete problems and these problems occur a lot in real world (See this, this and this for example). So there must be a way to handle them. We have seen algorithms to these problems which are p approximate (For example 2 approximate for Travelling Salesman). Can we do better?" }, { "code": null, "e": 951, "s": 416, "text": "Polynomial Time Approximation Scheme (PTAS) is a type of approximate algorithms that provide user to control over accuracy which is a desirable feature. These algorithms take an additional parameter ε > 0 and provide a solution that is (1 + ε) approximate for minimization and (1 – ε) for maximization. For example consider a minimization problem, if ε is 0.5, then the solution provided by the PTAS algorithm is 1.5 approximate. The running time of PTAS must be polynomial in terms of n, however, it can be exponential in terms of ε." }, { "code": null, "e": 1258, "s": 951, "text": "In PTAS algorithms, the exponent of the polynomial can increase dramatically as ε reduces, for example if the runtime is O(n(1/ε)!) which is a problem. There is a stricter scheme, Fully Polynomial Time Approximation Scheme (FPTAS). In FPTAS, algorithm need to polynomial in both the problem size n and 1/ε." }, { "code": null, "e": 1731, "s": 1258, "text": "Example (0-1 knapsack problem): We know that 0-1 knapsack is NP Complete. There is a DP based pseudo polynomial solution for this. But if input values are high, then the solution becomes infeasible and there is a need of approximate solution. One approximate solution is to use Greedy Approach (compute value per kg for all items and put the highest value per kg first if it is smaller than W), but Greedy approach is not PTAS, so we don’t have control over accuracy." }, { "code": null, "e": 1871, "s": 1731, "text": "Below is a FPTAS solution for 0-1 Knapsack problem:Input:W (Capacity of Knapsack)val[0..n-1] (Values of Items)wt[0..n-1] (Weights of Items)" }, { "code": null, "e": 2274, "s": 1871, "text": "Find the maximum valued item, i.e., find maximum value in val[]. Let this maximum value be maxVal.Compute adjustment factor k for all values k = (maxVal * ε) / nAdjust all values, i.e., create a new array val'[] that values divided by k. Do following for every value val[i]. val'[i] = floor(val[i] / k)Run DP based solution for reduced values, i,e, val'[0..n-1] and all other parameter same." }, { "code": null, "e": 2373, "s": 2274, "text": "Find the maximum valued item, i.e., find maximum value in val[]. Let this maximum value be maxVal." }, { "code": null, "e": 2443, "s": 2373, "text": "Compute adjustment factor k for all values k = (maxVal * ε) / n" }, { "code": null, "e": 2471, "s": 2443, "text": " k = (maxVal * ε) / n" }, { "code": null, "e": 2618, "s": 2471, "text": "Adjust all values, i.e., create a new array val'[] that values divided by k. Do following for every value val[i]. val'[i] = floor(val[i] / k)" }, { "code": null, "e": 2652, "s": 2618, "text": " val'[i] = floor(val[i] / k)" }, { "code": null, "e": 2742, "s": 2652, "text": "Run DP based solution for reduced values, i,e, val'[0..n-1] and all other parameter same." }, { "code": null, "e": 2996, "s": 2742, "text": "The above solution works in polynomial time in terms of both n and ε. The solution provided by this FPTAS is (1 – ε) approximate. The idea is to rounds off some of the least significant digits of values then they will be bounded by a polynomial and 1/ε." }, { "code": null, "e": 3005, "s": 2996, "text": "Example:" }, { "code": null, "e": 3299, "s": 3005, "text": "val[] = {12, 16, 4, 8}\nwt[] = {3, 4, 5, 2}\nW = 10\nε = 0.5\n \nmaxVal = 16 [maximum value in val[]]\nAdjustment factor, k = (16 * 0.5)/4 = 2.0\n\nNow we apply DP based solution on below modified \ninstance of problem.\n\nval'[] = {6, 8, 2, 4} [ val'[i] = floor(val[i]/k) ]\nwt[] = {3, 4, 5, 2}\nW = 10\n" }, { "code": null, "e": 3468, "s": 3299, "text": "How is the solution (1 – ε) * OPT?Here OPT is the optimal value. Let S be the set produced by above FPTAS algorithm and total value of S be val(S). We need to show that" }, { "code": null, "e": 3498, "s": 3468, "text": " val(S) >= (1 - ε)*OPT " }, { "code": null, "e": 3601, "s": 3498, "text": "Let O be the set produced by optimal solution (the solution with total value OPT), i.e., val(O) = OPT." }, { "code": null, "e": 3680, "s": 3601, "text": " val(O) - k*val'(O) <= n*k \n [Because val'[i] = floor(val[i]/k) ] " }, { "code": null, "e": 3883, "s": 3680, "text": "After the dynamic programming step, we get a set that is optimal for the scaled instanceand therefore must be at least as good as choosing the set O with the smaller profits. From that, we can conclude," }, { "code": null, "e": 4054, "s": 3883, "text": " val'(S) >= k . val'(O)\n >= val(O) - nk\n >= OPT - ε * maxVal\n >= OPT - ε * OPT [OPT >= maxVal]\n >= (1 - ε) * OPT " }, { "code": null, "e": 4189, "s": 4054, "text": "Sources:http://math.mit.edu/~goemans/18434S06/knapsack-katherine.pdfhttps://en.wikipedia.org/wiki/Polynomial-time_approximation_scheme" }, { "code": null, "e": 4456, "s": 4189, "text": "This article is contributed by Dheeraj Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 4580, "s": 4456, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 4588, "s": 4580, "text": "jokic07" }, { "code": null, "e": 4607, "s": 4588, "text": "shubhamagarwal0312" }, { "code": null, "e": 4626, "s": 4607, "text": "shreelakshmijoshi1" }, { "code": null, "e": 4637, "s": 4626, "text": "Algorithms" }, { "code": null, "e": 4648, "s": 4637, "text": "Algorithms" } ]
Render Django Form Fields Manually
22 Jul, 2021 Django form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). We have already covered on How to create and use a form in Django?. A form comes with 3 in-built methods that can be used to render Django form fields. {{ form.as_table }} will render them as table cells wrapped in <tr> tags {{ form.as_p }} will render them wrapped in <p> tags {{ form.as_ul }} will render them wrapped in <li> tags These render the form automatically but if you want to create a beautiful form with some CSS effects, you need to render the form fields manually. This article revolves around how to render the form fields manually. Illustration of Rendering Django Forms Manually using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? In your geeks app make a new file called forms.py where you would be making all your forms. To create a Django form you need to use Django Form Class. Let’s demonstrate how, In your forms.py Enter the following, Python3 from django import forms # creating a form class InputForm(forms.Form): first_name = forms.CharField(max_length = 200) last_name = forms.CharField(max_length = 200) roll_number = forms.IntegerField( help_text = "Enter 6 digit roll number" ) password = forms.CharField(widget = forms.PasswordInput()) Let’s explain what exactly is happening, left side denotes the name of the field and to right of it, you define various functionalities of an input field correspondingly. A field’s syntax is denoted as Syntax : Field_name = forms.FieldType(attributes) Now to render this form into a view, move to views.py and create a home_view as below. Python3 from django.shortcuts import renderfrom .forms import InputForm # Create your views here.def home_view(request): context ={} context['form']= InputForm() return render(request, "home.html", context) In view one needs to just create an instance of the form class created above in forms.py. Now let’s edit templates > home.html html <form action = "" method = "post"> {% csrf_token %} {{form }} <input type="submit" value=Submit"></form> All set to check if form is working or not let’s visit http://localhost:8000/ . Form is working properly but visuals are disappointing, We can render these fields manually to improve some visual stuff. Each field is available as an attribute of the form using {{ form.name_of_field }}, and in a Django template, will be rendered appropriately. For example: {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.subject.errors }} <label for="{{ form.subject.id_for_label }}">Email subject:</label> {{ form.subject }} </div> .Let’s modify our form to look pretty impressive, html <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <style> .i-am-centered { margin: auto; max-width: 300px; padding-top: 20%; } </style></head> <body> <div class="i-am-centered"> <form method="POST"> {% csrf_token %} <div class="form-group"> <label>First Name </label> {{ form.first_name }} </div> <div class="form-group"> <label>Last Name </label> {{ form.last_name }} </div> <div class="form-group"> <label>Roll Number</label> {{ form.roll_number }} </div> <div class="form-group"> <label>Password</label> {{ form.password }} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div></body> </html> Now visit http://localhost:8000/ and check modified form. These were just some basic modifications using Bootstrap. One can customize it to an advanced level using various CSS tricks and methods. {{ field.label }} The label of the field, e.g. Email address. {{ field.label_tag }} The field’s label wrapped in the appropriate HTML tag. This includes the form’s label_suffix. For example, the default label_suffix is a colon: <label for="id_email">Email address:</label> {{ field.id_for_label }} The ID that will be used for this field (id_email in the example above). If you are constructing the label manually, you may want to use this in place of label_tag. It’s also useful, for example, if you have some inline JavaScript and want to avoid hardcoding the field’s ID. {{ field.value }} The value of the field. e.g [email protected]. {{ field.html_name }} The name of the field that will be used in the input element’s name field. This takes the form prefix into account, if it has been set. {{ field.help_text }} Any help text that has been associated with the field. {{ field.errors }} Outputs a <ul class=”errorlist”> containing any validation errors corresponding to this field. You can customize the presentation of the errors with a {% for error in field.errors %} loop. In this case, each object in the loop is a string containing the error message. {{ field.is_hidden }} This attribute is True if the form field is a hidden field and False otherwise. It’s not particularly useful as a template variable, but could be useful in conditional tests such as: {% if field.is_hidden %} {# Do something special #} {% endif %} {% if field.is_hidden %} {# Do something special #} {% endif %} {{ field.field }} The Field instance from the form class that this BoundField wraps. You can use it to access Field attributes, e.g. {{ char_field.field.max_length }} anikaseth98 Django-forms Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jul, 2021" }, { "code": null, "e": 354, "s": 28, "text": "Django form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). We have already covered on How to create and use a form in Django?. A form comes with 3 in-built methods that can be used to render Django form fields. " }, { "code": null, "e": 427, "s": 354, "text": "{{ form.as_table }} will render them as table cells wrapped in <tr> tags" }, { "code": null, "e": 480, "s": 427, "text": "{{ form.as_p }} will render them wrapped in <p> tags" }, { "code": null, "e": 535, "s": 480, "text": "{{ form.as_ul }} will render them wrapped in <li> tags" }, { "code": null, "e": 752, "s": 535, "text": "These render the form automatically but if you want to create a beautiful form with some CSS effects, you need to render the form fields manually. This article revolves around how to render the form fields manually. " }, { "code": null, "e": 886, "s": 752, "text": "Illustration of Rendering Django Forms Manually using an Example. Consider a project named geeksforgeeks having an app named geeks. " }, { "code": null, "e": 975, "s": 886, "text": "Refer to the following articles to check how to create a project and an app in Django. " }, { "code": null, "e": 1026, "s": 975, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 1059, "s": 1026, "text": "How to Create an App in Django ?" }, { "code": null, "e": 1273, "s": 1059, "text": "In your geeks app make a new file called forms.py where you would be making all your forms. To create a Django form you need to use Django Form Class. Let’s demonstrate how, In your forms.py Enter the following, " }, { "code": null, "e": 1281, "s": 1273, "text": "Python3" }, { "code": "from django import forms # creating a form class InputForm(forms.Form): first_name = forms.CharField(max_length = 200) last_name = forms.CharField(max_length = 200) roll_number = forms.IntegerField( help_text = \"Enter 6 digit roll number\" ) password = forms.CharField(widget = forms.PasswordInput())", "e": 1636, "s": 1281, "text": null }, { "code": null, "e": 1849, "s": 1636, "text": "Let’s explain what exactly is happening, left side denotes the name of the field and to right of it, you define various functionalities of an input field correspondingly. A field’s syntax is denoted as Syntax : " }, { "code": null, "e": 1890, "s": 1849, "text": "Field_name = forms.FieldType(attributes)" }, { "code": null, "e": 1979, "s": 1890, "text": "Now to render this form into a view, move to views.py and create a home_view as below. " }, { "code": null, "e": 1987, "s": 1979, "text": "Python3" }, { "code": "from django.shortcuts import renderfrom .forms import InputForm # Create your views here.def home_view(request): context ={} context['form']= InputForm() return render(request, \"home.html\", context)", "e": 2196, "s": 1987, "text": null }, { "code": null, "e": 2325, "s": 2196, "text": "In view one needs to just create an instance of the form class created above in forms.py. Now let’s edit templates > home.html " }, { "code": null, "e": 2330, "s": 2325, "text": "html" }, { "code": "<form action = \"\" method = \"post\"> {% csrf_token %} {{form }} <input type=\"submit\" value=Submit\"></form>", "e": 2444, "s": 2330, "text": null }, { "code": null, "e": 2524, "s": 2444, "text": "All set to check if form is working or not let’s visit http://localhost:8000/ " }, { "code": null, "e": 2805, "s": 2524, "text": ". Form is working properly but visuals are disappointing, We can render these fields manually to improve some visual stuff. Each field is available as an attribute of the form using {{ form.name_of_field }}, and in a Django template, will be rendered appropriately. For example: " }, { "code": null, "e": 2992, "s": 2805, "text": "{{ form.non_field_errors }}\n<div class=\"fieldWrapper\">\n {{ form.subject.errors }}\n <label for=\"{{ form.subject.id_for_label }}\">Email subject:</label>\n {{ form.subject }}\n</div>" }, { "code": null, "e": 3044, "s": 2992, "text": ".Let’s modify our form to look pretty impressive, " }, { "code": null, "e": 3049, "s": 3044, "text": "html" }, { "code": "<html> <head> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\"> <style> .i-am-centered { margin: auto; max-width: 300px; padding-top: 20%; } </style></head> <body> <div class=\"i-am-centered\"> <form method=\"POST\"> {% csrf_token %} <div class=\"form-group\"> <label>First Name </label> {{ form.first_name }} </div> <div class=\"form-group\"> <label>Last Name </label> {{ form.last_name }} </div> <div class=\"form-group\"> <label>Roll Number</label> {{ form.roll_number }} </div> <div class=\"form-group\"> <label>Password</label> {{ form.password }} </div> <button type=\"submit\" class=\"btn btn-primary\">Submit</button> </form> </div></body> </html>", "e": 4061, "s": 3049, "text": null }, { "code": null, "e": 4121, "s": 4061, "text": "Now visit http://localhost:8000/ and check modified form. " }, { "code": null, "e": 4261, "s": 4121, "text": "These were just some basic modifications using Bootstrap. One can customize it to an advanced level using various CSS tricks and methods. " }, { "code": null, "e": 4325, "s": 4263, "text": "{{ field.label }} The label of the field, e.g. Email address." }, { "code": null, "e": 4493, "s": 4325, "text": "{{ field.label_tag }} The field’s label wrapped in the appropriate HTML tag. This includes the form’s label_suffix. For example, the default label_suffix is a colon: " }, { "code": null, "e": 4538, "s": 4493, "text": "<label for=\"id_email\">Email address:</label>" }, { "code": null, "e": 4839, "s": 4538, "text": "{{ field.id_for_label }} The ID that will be used for this field (id_email in the example above). If you are constructing the label manually, you may want to use this in place of label_tag. It’s also useful, for example, if you have some inline JavaScript and want to avoid hardcoding the field’s ID." }, { "code": null, "e": 4906, "s": 4839, "text": "{{ field.value }} The value of the field. e.g [email protected]." }, { "code": null, "e": 5064, "s": 4906, "text": "{{ field.html_name }} The name of the field that will be used in the input element’s name field. This takes the form prefix into account, if it has been set." }, { "code": null, "e": 5141, "s": 5064, "text": "{{ field.help_text }} Any help text that has been associated with the field." }, { "code": null, "e": 5429, "s": 5141, "text": "{{ field.errors }} Outputs a <ul class=”errorlist”> containing any validation errors corresponding to this field. You can customize the presentation of the errors with a {% for error in field.errors %} loop. In this case, each object in the loop is a string containing the error message." }, { "code": null, "e": 5702, "s": 5429, "text": "{{ field.is_hidden }} This attribute is True if the form field is a hidden field and False otherwise. It’s not particularly useful as a template variable, but could be useful in conditional tests such as: {% if field.is_hidden %}\n {# Do something special #}\n{% endif %}" }, { "code": null, "e": 5769, "s": 5702, "text": "{% if field.is_hidden %}\n {# Do something special #}\n{% endif %}" }, { "code": null, "e": 5936, "s": 5769, "text": "{{ field.field }} The Field instance from the form class that this BoundField wraps. You can use it to access Field attributes, e.g. {{ char_field.field.max_length }}" }, { "code": null, "e": 5948, "s": 5936, "text": "anikaseth98" }, { "code": null, "e": 5961, "s": 5948, "text": "Django-forms" }, { "code": null, "e": 5975, "s": 5961, "text": "Python Django" }, { "code": null, "e": 5982, "s": 5975, "text": "Python" } ]
String matching where one string contains wildcard characters
22 Jun, 2022 Given two strings where first string may contain wild card characters and second string is a normal string. Write a function that returns true if the two strings match. The following are allowed wild card characters in first string. * --> Matches with 0 or more instances of any character or set of characters. ? --> Matches with any one character. For example, “g*ks” matches with “geeks” match. And string “ge?ks*” matches with “geeksforgeeks” (note ‘*’ at the end of first string). But “g*k” doesn’t match with “gee” as character ‘k’ is not present in second string. C++ Java Python3 C# Javascript // A C program to match wild card characters#include <stdbool.h>#include <stdio.h> // The main function that checks if two given strings// match. The first string may contain wildcard charactersbool match(char* first, char* second){ // If we reach at the end of both strings, we are done if (*first == '\0' && *second == '\0') return true; // Make sure to eliminate consecutive '*' if (*first == '*') { while (*(first + 1) == '*') first++; } // Make sure that the characters after '*' are present // in second string. This function assumes that the // first string will not contain two consecutive '*' if (*first == '*' && *(first + 1) != '\0' && *second == '\0') return false; // If the first string contains '?', or current // characters of both strings match if (*first == '?' || *first == *second) return match(first + 1, second + 1); // If there is *, then there are two possibilities // a) We consider current character of second string // b) We ignore current character of second string. if (*first == '*') return match(first + 1, second) || match(first, second + 1); return false;} // A function to run test casesvoid test(char* first, char* second){ match(first, second) ? puts("Yes") : puts("No");} // Driver program to test above functionsint main(){ test("g*ks", "geeks"); // Yes test("ge?ks*", "geeksforgeeks"); // Yes test("g*k", "gee"); // No because 'k' is not in second test("*pqrs", "pqrst"); // No because 't' is not in first test("abc*bcd", "abcdhghgbcd"); // Yes test("abc*c?d", "abcd"); // No because second must have // 2 instances of 'c' test("*c*d", "abcd"); // Yes test("*?c*d", "abcd"); // Yes test("geeks**", "geeks"); // Yes return 0;} // Java program to match wild card charactersclass GFG{ // The main function that checks if// two given strings match. The first string// may contain wildcard charactersstatic boolean match(String first, String second){ // If we reach at the end of both strings, // we are done if (first.length() == 0 && second.length() == 0) return true; // Make sure to eliminate consecutive '*' if (first.length() > 1 &&first.charAt(0) == '*') { int i=0; while (i+1<first.length() && first.charAt(i+1) == '*') i++; first=first.substring(i); } // Make sure that the characters after '*' // are present in second string. // This function assumes that the first // string will not contain two consecutive '*' if (first.length() > 1 && first.charAt(0) == '*' && second.length() == 0) return false; // If the first string contains '?', // or current characters of both strings match if ((first.length() > 1 && first.charAt(0) == '?') || (first.length() != 0 && second.length() != 0 && first.charAt(0) == second.charAt(0))) return match(first.substring(1), second.substring(1)); // If there is *, then there are two possibilities // a) We consider current character of second string // b) We ignore current character of second string. if (first.length() > 0 && first.charAt(0) == '*') return match(first.substring(1), second) || match(first, second.substring(1)); return false;} // A function to run test casesstatic void test(String first, String second){ if (match(first, second)) System.out.println("Yes"); else System.out.println("No");} // Driver Codepublic static void main(String[] args){ test("g*ks", "geeks"); // Yes test("ge?ks*", "geeksforgeeks"); // Yes test("g*k", "gee"); // No because 'k' is not in second test("*pqrs", "pqrst"); // No because 't' is not in first test("abc*bcd", "abcdhghgbcd"); // Yes test("abc*c?d", "abcd"); // No because second must have 2 // instances of 'c' test("*c*d", "abcd"); // Yes test("*?c*d", "abcd"); // Yes test("geeks**", "geeks"); // Yes}} // This code is contributed by// sanjeev2552 # Python program to match wild card characters # The main function that checks if two given strings match.# The first string may contain wildcard characters def match(first, second): # If we reach at the end of both strings, we are done if len(first) == 0 and len(second) == 0: return True # Make sure to eliminate consecutive '*' if len(first) > 1 and first[0] == '*': i = 0 while i+1 < len(first) and first[i+1] == '*': i = i+1 first = first[i:] # Make sure that the characters after '*' are present # in second string. This function assumes that the first # string will not contain two consecutive '*' if len(first) > 1 and first[0] == '*' and len(second) == 0: return False # If the first string contains '?', or current characters # of both strings match if (len(first) > 1 and first[0] == '?') or (len(first) != 0 and len(second) != 0 and first[0] == second[0]): return match(first[1:], second[1:]) # If there is *, then there are two possibilities # a) We consider current character of second string # b) We ignore current character of second string. if len(first) != 0 and first[0] == '*': return match(first[1:], second) or match(first, second[1:]) return False # A function to run test cases def test(first, second): if match(first, second): print("Yes") else: print("No") # Driver programtest("g*ks", "geeks") # Yestest("ge?ks*", "geeksforgeeks") # Yestest("g*k", "gee") # No because 'k' is not in secondtest("*pqrs", "pqrst") # No because 't' is not in firsttest("abc*bcd", "abcdhghgbcd") # Yestest("abc*c?d", "abcd") # No because second must have 2 instances of 'c'test("*c*d", "abcd") # Yestest("*?c*d", "abcd") # Yestest("geeks**", "geeks") # Yes # This code is contributed by BHAVYA JAIN and ROHIT SIKKA // C# program to match wild card charactersusing System; class GFG { // The main function that checks if // two given strings match. The first string // may contain wildcard characters static bool match(String first, String second) { // If we reach at the end of both strings, // we are done if (first.Length == 0 && second.Length == 0) return true; // Make sure to eliminate consecutive '*' if (first.Length > 1 && first[0] == '*') { int i = 0; while (i + 1 < first.Length && first[i + 1] == '*') i++; first = first.Substring(i); } // Make sure that the characters after '*' // are present in second string. // This function assumes that the first // string will not contain two consecutive '*' if (first.Length > 1 && first[0] == '*' && second.Length == 0) return false; // If the first string contains '?', // or current characters of both strings match if ((first.Length > 1 && first[0] == '?') || (first.Length != 0 && second.Length != 0 && first[0] == second[0])) return match(first.Substring(1), second.Substring(1)); // If there is *, then there are two possibilities // a) We consider current character of second string // b) We ignore current character of second string. if (first.Length > 0 && first[0] == '*') return match(first.Substring(1), second) || match(first, second.Substring(1)); return false; } // A function to run test cases static void test(String first, String second) { if (match(first, second)) Console.WriteLine("Yes"); else Console.WriteLine("No"); } // Driver Code public static void Main(String[] args) { test("g*ks", "geeks"); // Yes test("ge?ks*", "geeksforgeeks"); // Yes test("g*k", "gee"); // No because 'k' is not in second test("*pqrs", "pqrst"); // No because 't' is not in first test("abc*bcd", "abcdhghgbcd"); // Yes test("abc*c?d", "abcd"); // No because second must // have 2 instances of 'c' test("*c*d", "abcd"); // Yes test("*?c*d", "abcd"); // Yes test("geeks**", "geeks"); // Yes }} // This code is contributed by Rajput-Ji <script> // Javascript program to match wild card characters // The main function that checks if// two given strings match. The first string// may contain wildcard charactersfunction match(first, second){ // If we reach at the end of both strings, // we are done if (first.length == 0 && second.length == 0) return true; // Make sure that the characters after '*' // are present in second string. // This function assumes that the first // string will not contain two consecutive '*' if (first.length > 1 && first[0] == '*' && second.length == 0) return false; // If the first string contains '?', // or current characters of both strings match if ((first.length > 1 && first[0] == '?') || (first.length != 0 && second.length != 0 && first[0] == second[0])) return match(first.substring(1), second.substring(1)); // If there is *, then there are two possibilities // a) We consider current character of second string // b) We ignore current character of second string. if (first.length > 0 && first[0] == '*') return match(first.substring(1), second) || match(first, second.substring(1)); return false;} // A function to run test casesfunction test(first, second){ if (match(first, second)) document.write("Yes" + "<br>"); else document.write("No" + "<br>");} // Driver codeass="plain">test("g*ks", "geeks"); // Yestest("ge?ks*", "geeksforgeeks"); // Yestest("g*k", "gee"); // No because 'k' is not in secondtest("*pqrs", "pqrst"); // No because 't' is not in firsttest("abc*bcd", "abcdhghgbcd"); // Yestest("abc*c?d", "abcd"); // No because second must have 2 // instances of 'c'test("*c*d", "abcd"); // Yestest("*?c*d", "abcd"); // Yes // This code is contributed by SoumikMondal </script> Output: Yes Yes No No Yes No Yes Yes Yes Time Complexity: O(n) Auxiliary Space: O(1) String matching where one string contains wildcard characters | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersString matching where one string contains wildcard characters | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Q6ZX95GadA8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Exercise 1) In the above solution, all non-wild characters of first string must be there is second string and all characters of second string must match with either a normal character or wildcard character of first string. Extend the above solution to work like other pattern searching solutions where the first string is pattern and second string is text and we should print all occurrences of first string in second. 2) Write a pattern searching function where the meaning of ‘?’ is same, but ‘*’ means 0 or more occurrences of the character just before ‘*’. For example, if first string is ‘a*b’, then it matches with ‘aaab’, but doesn’t match with ‘abb’. This article is compiled by Vishal Chaudhary and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sanjeev2552 Rajput-Ji SoumikMondal amartyaghoshgfg dheerukd2002 akashish__ Amazon Ola Cabs Pattern Searching Strings Amazon Ola Cabs Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 286, "s": 52, "text": "Given two strings where first string may contain wild card characters and second string is a normal string. Write a function that returns true if the two strings match. The following are allowed wild card characters in first string. " }, { "code": null, "e": 402, "s": 286, "text": "* --> Matches with 0 or more instances of any character or set of characters.\n? --> Matches with any one character." }, { "code": null, "e": 624, "s": 402, "text": "For example, “g*ks” matches with “geeks” match. And string “ge?ks*” matches with “geeksforgeeks” (note ‘*’ at the end of first string). But “g*k” doesn’t match with “gee” as character ‘k’ is not present in second string. " }, { "code": null, "e": 628, "s": 624, "text": "C++" }, { "code": null, "e": 633, "s": 628, "text": "Java" }, { "code": null, "e": 641, "s": 633, "text": "Python3" }, { "code": null, "e": 644, "s": 641, "text": "C#" }, { "code": null, "e": 655, "s": 644, "text": "Javascript" }, { "code": "// A C program to match wild card characters#include <stdbool.h>#include <stdio.h> // The main function that checks if two given strings// match. The first string may contain wildcard charactersbool match(char* first, char* second){ // If we reach at the end of both strings, we are done if (*first == '\\0' && *second == '\\0') return true; // Make sure to eliminate consecutive '*' if (*first == '*') { while (*(first + 1) == '*') first++; } // Make sure that the characters after '*' are present // in second string. This function assumes that the // first string will not contain two consecutive '*' if (*first == '*' && *(first + 1) != '\\0' && *second == '\\0') return false; // If the first string contains '?', or current // characters of both strings match if (*first == '?' || *first == *second) return match(first + 1, second + 1); // If there is *, then there are two possibilities // a) We consider current character of second string // b) We ignore current character of second string. if (*first == '*') return match(first + 1, second) || match(first, second + 1); return false;} // A function to run test casesvoid test(char* first, char* second){ match(first, second) ? puts(\"Yes\") : puts(\"No\");} // Driver program to test above functionsint main(){ test(\"g*ks\", \"geeks\"); // Yes test(\"ge?ks*\", \"geeksforgeeks\"); // Yes test(\"g*k\", \"gee\"); // No because 'k' is not in second test(\"*pqrs\", \"pqrst\"); // No because 't' is not in first test(\"abc*bcd\", \"abcdhghgbcd\"); // Yes test(\"abc*c?d\", \"abcd\"); // No because second must have // 2 instances of 'c' test(\"*c*d\", \"abcd\"); // Yes test(\"*?c*d\", \"abcd\"); // Yes test(\"geeks**\", \"geeks\"); // Yes return 0;}", "e": 2512, "s": 655, "text": null }, { "code": "// Java program to match wild card charactersclass GFG{ // The main function that checks if// two given strings match. The first string// may contain wildcard charactersstatic boolean match(String first, String second){ // If we reach at the end of both strings, // we are done if (first.length() == 0 && second.length() == 0) return true; // Make sure to eliminate consecutive '*' if (first.length() > 1 &&first.charAt(0) == '*') { int i=0; while (i+1<first.length() && first.charAt(i+1) == '*') i++; first=first.substring(i); } // Make sure that the characters after '*' // are present in second string. // This function assumes that the first // string will not contain two consecutive '*' if (first.length() > 1 && first.charAt(0) == '*' && second.length() == 0) return false; // If the first string contains '?', // or current characters of both strings match if ((first.length() > 1 && first.charAt(0) == '?') || (first.length() != 0 && second.length() != 0 && first.charAt(0) == second.charAt(0))) return match(first.substring(1), second.substring(1)); // If there is *, then there are two possibilities // a) We consider current character of second string // b) We ignore current character of second string. if (first.length() > 0 && first.charAt(0) == '*') return match(first.substring(1), second) || match(first, second.substring(1)); return false;} // A function to run test casesstatic void test(String first, String second){ if (match(first, second)) System.out.println(\"Yes\"); else System.out.println(\"No\");} // Driver Codepublic static void main(String[] args){ test(\"g*ks\", \"geeks\"); // Yes test(\"ge?ks*\", \"geeksforgeeks\"); // Yes test(\"g*k\", \"gee\"); // No because 'k' is not in second test(\"*pqrs\", \"pqrst\"); // No because 't' is not in first test(\"abc*bcd\", \"abcdhghgbcd\"); // Yes test(\"abc*c?d\", \"abcd\"); // No because second must have 2 // instances of 'c' test(\"*c*d\", \"abcd\"); // Yes test(\"*?c*d\", \"abcd\"); // Yes test(\"geeks**\", \"geeks\"); // Yes}} // This code is contributed by// sanjeev2552", "e": 4798, "s": 2512, "text": null }, { "code": "# Python program to match wild card characters # The main function that checks if two given strings match.# The first string may contain wildcard characters def match(first, second): # If we reach at the end of both strings, we are done if len(first) == 0 and len(second) == 0: return True # Make sure to eliminate consecutive '*' if len(first) > 1 and first[0] == '*': i = 0 while i+1 < len(first) and first[i+1] == '*': i = i+1 first = first[i:] # Make sure that the characters after '*' are present # in second string. This function assumes that the first # string will not contain two consecutive '*' if len(first) > 1 and first[0] == '*' and len(second) == 0: return False # If the first string contains '?', or current characters # of both strings match if (len(first) > 1 and first[0] == '?') or (len(first) != 0 and len(second) != 0 and first[0] == second[0]): return match(first[1:], second[1:]) # If there is *, then there are two possibilities # a) We consider current character of second string # b) We ignore current character of second string. if len(first) != 0 and first[0] == '*': return match(first[1:], second) or match(first, second[1:]) return False # A function to run test cases def test(first, second): if match(first, second): print(\"Yes\") else: print(\"No\") # Driver programtest(\"g*ks\", \"geeks\") # Yestest(\"ge?ks*\", \"geeksforgeeks\") # Yestest(\"g*k\", \"gee\") # No because 'k' is not in secondtest(\"*pqrs\", \"pqrst\") # No because 't' is not in firsttest(\"abc*bcd\", \"abcdhghgbcd\") # Yestest(\"abc*c?d\", \"abcd\") # No because second must have 2 instances of 'c'test(\"*c*d\", \"abcd\") # Yestest(\"*?c*d\", \"abcd\") # Yestest(\"geeks**\", \"geeks\") # Yes # This code is contributed by BHAVYA JAIN and ROHIT SIKKA", "e": 6711, "s": 4798, "text": null }, { "code": "// C# program to match wild card charactersusing System; class GFG { // The main function that checks if // two given strings match. The first string // may contain wildcard characters static bool match(String first, String second) { // If we reach at the end of both strings, // we are done if (first.Length == 0 && second.Length == 0) return true; // Make sure to eliminate consecutive '*' if (first.Length > 1 && first[0] == '*') { int i = 0; while (i + 1 < first.Length && first[i + 1] == '*') i++; first = first.Substring(i); } // Make sure that the characters after '*' // are present in second string. // This function assumes that the first // string will not contain two consecutive '*' if (first.Length > 1 && first[0] == '*' && second.Length == 0) return false; // If the first string contains '?', // or current characters of both strings match if ((first.Length > 1 && first[0] == '?') || (first.Length != 0 && second.Length != 0 && first[0] == second[0])) return match(first.Substring(1), second.Substring(1)); // If there is *, then there are two possibilities // a) We consider current character of second string // b) We ignore current character of second string. if (first.Length > 0 && first[0] == '*') return match(first.Substring(1), second) || match(first, second.Substring(1)); return false; } // A function to run test cases static void test(String first, String second) { if (match(first, second)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); } // Driver Code public static void Main(String[] args) { test(\"g*ks\", \"geeks\"); // Yes test(\"ge?ks*\", \"geeksforgeeks\"); // Yes test(\"g*k\", \"gee\"); // No because 'k' is not in second test(\"*pqrs\", \"pqrst\"); // No because 't' is not in first test(\"abc*bcd\", \"abcdhghgbcd\"); // Yes test(\"abc*c?d\", \"abcd\"); // No because second must // have 2 instances of 'c' test(\"*c*d\", \"abcd\"); // Yes test(\"*?c*d\", \"abcd\"); // Yes test(\"geeks**\", \"geeks\"); // Yes }} // This code is contributed by Rajput-Ji", "e": 9208, "s": 6711, "text": null }, { "code": "<script> // Javascript program to match wild card characters // The main function that checks if// two given strings match. The first string// may contain wildcard charactersfunction match(first, second){ // If we reach at the end of both strings, // we are done if (first.length == 0 && second.length == 0) return true; // Make sure that the characters after '*' // are present in second string. // This function assumes that the first // string will not contain two consecutive '*' if (first.length > 1 && first[0] == '*' && second.length == 0) return false; // If the first string contains '?', // or current characters of both strings match if ((first.length > 1 && first[0] == '?') || (first.length != 0 && second.length != 0 && first[0] == second[0])) return match(first.substring(1), second.substring(1)); // If there is *, then there are two possibilities // a) We consider current character of second string // b) We ignore current character of second string. if (first.length > 0 && first[0] == '*') return match(first.substring(1), second) || match(first, second.substring(1)); return false;} // A function to run test casesfunction test(first, second){ if (match(first, second)) document.write(\"Yes\" + \"<br>\"); else document.write(\"No\" + \"<br>\");} // Driver codeass=\"plain\">test(\"g*ks\", \"geeks\"); // Yestest(\"ge?ks*\", \"geeksforgeeks\"); // Yestest(\"g*k\", \"gee\"); // No because 'k' is not in secondtest(\"*pqrs\", \"pqrst\"); // No because 't' is not in firsttest(\"abc*bcd\", \"abcdhghgbcd\"); // Yestest(\"abc*c?d\", \"abcd\"); // No because second must have 2 // instances of 'c'test(\"*c*d\", \"abcd\"); // Yestest(\"*?c*d\", \"abcd\"); // Yes // This code is contributed by SoumikMondal </script>", "e": 11093, "s": 9208, "text": null }, { "code": null, "e": 11102, "s": 11093, "text": "Output: " }, { "code": null, "e": 11135, "s": 11102, "text": "Yes\nYes\nNo\nNo\nYes\nNo\nYes\nYes\nYes" }, { "code": null, "e": 11157, "s": 11135, "text": "Time Complexity: O(n)" }, { "code": null, "e": 11179, "s": 11157, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 12119, "s": 11179, "text": "String matching where one string contains wildcard characters | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersString matching where one string contains wildcard characters | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:51•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Q6ZX95GadA8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 12985, "s": 12119, "text": "Exercise 1) In the above solution, all non-wild characters of first string must be there is second string and all characters of second string must match with either a normal character or wildcard character of first string. Extend the above solution to work like other pattern searching solutions where the first string is pattern and second string is text and we should print all occurrences of first string in second. 2) Write a pattern searching function where the meaning of ‘?’ is same, but ‘*’ means 0 or more occurrences of the character just before ‘*’. For example, if first string is ‘a*b’, then it matches with ‘aaab’, but doesn’t match with ‘abb’. This article is compiled by Vishal Chaudhary and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 12997, "s": 12985, "text": "sanjeev2552" }, { "code": null, "e": 13007, "s": 12997, "text": "Rajput-Ji" }, { "code": null, "e": 13020, "s": 13007, "text": "SoumikMondal" }, { "code": null, "e": 13036, "s": 13020, "text": "amartyaghoshgfg" }, { "code": null, "e": 13049, "s": 13036, "text": "dheerukd2002" }, { "code": null, "e": 13060, "s": 13049, "text": "akashish__" }, { "code": null, "e": 13067, "s": 13060, "text": "Amazon" }, { "code": null, "e": 13076, "s": 13067, "text": "Ola Cabs" }, { "code": null, "e": 13094, "s": 13076, "text": "Pattern Searching" }, { "code": null, "e": 13102, "s": 13094, "text": "Strings" }, { "code": null, "e": 13109, "s": 13102, "text": "Amazon" }, { "code": null, "e": 13118, "s": 13109, "text": "Ola Cabs" }, { "code": null, "e": 13126, "s": 13118, "text": "Strings" }, { "code": null, "e": 13144, "s": 13126, "text": "Pattern Searching" } ]
Java & MySQL - Delete Records Example
This chapter provides an example on how to delete records from a table using JDBC application. Before executing following example, make sure you have the following in place − To execute the following example you can replace the username and password with your actual user name and password. To execute the following example you can replace the username and password with your actual user name and password. Your MySQL database you are using is up and running. Your MySQL database you are using is up and running. The following steps are required to create a new Database using JDBC application − Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database. Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database. Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete records from a table. This Query makes use of the WHERE clause to delete conditional records. Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete records from a table. This Query makes use of the WHERE clause to delete conditional records. Clean up the environment − try with resources automatically closes the resources. Clean up the environment − try with resources automatically closes the resources. Copy and paste the following example in TestApplication.java, compile and run as follows − import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestApplication { static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT"; static final String USER = "guest"; static final String PASS = "guest123"; static final String QUERY = "SELECT id, first, last, age FROM Registration"; public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); ) { String sql = "DELETE FROM Registration " + "WHERE id = 101"; stmt.executeUpdate(sql); ResultSet rs = stmt.executeQuery(QUERY); while(rs.next()){ //Display values System.out.print("ID: " + rs.getInt("id")); System.out.print(", Age: " + rs.getInt("age")); System.out.print(", First: " + rs.getString("first")); System.out.println(", Last: " + rs.getString("last")); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } Now let us compile the above example as follows − C:\>javac TestApplication.java C:\> When you run TestApplication, it produces the following result − C:\>java TestApplication ID: 100, Age: 30, First: Zara, Last: Ali ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal C:\> 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2861, "s": 2686, "text": "This chapter provides an example on how to delete records from a table using JDBC application. Before executing following example, make sure you have the following in place −" }, { "code": null, "e": 2977, "s": 2861, "text": "To execute the following example you can replace the username and password with your actual user name and password." }, { "code": null, "e": 3093, "s": 2977, "text": "To execute the following example you can replace the username and password with your actual user name and password." }, { "code": null, "e": 3146, "s": 3093, "text": "Your MySQL database you are using is up and running." }, { "code": null, "e": 3199, "s": 3146, "text": "Your MySQL database you are using is up and running." }, { "code": null, "e": 3282, "s": 3199, "text": "The following steps are required to create a new Database using JDBC application −" }, { "code": null, "e": 3454, "s": 3282, "text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice." }, { "code": null, "e": 3626, "s": 3454, "text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice." }, { "code": null, "e": 3751, "s": 3626, "text": "Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database." }, { "code": null, "e": 3876, "s": 3751, "text": "Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database." }, { "code": null, "e": 4046, "s": 3876, "text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server." }, { "code": null, "e": 4216, "s": 4046, "text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server." }, { "code": null, "e": 4426, "s": 4216, "text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete records from a table. This Query makes use of the WHERE clause to delete conditional records." }, { "code": null, "e": 4636, "s": 4426, "text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete records from a table. This Query makes use of the WHERE clause to delete conditional records." }, { "code": null, "e": 4718, "s": 4636, "text": "Clean up the environment − try with resources automatically closes the resources." }, { "code": null, "e": 4800, "s": 4718, "text": "Clean up the environment − try with resources automatically closes the resources." }, { "code": null, "e": 4891, "s": 4800, "text": "Copy and paste the following example in TestApplication.java, compile and run as follows −" }, { "code": null, "e": 6100, "s": 4891, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class TestApplication {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT id, first, last, age FROM Registration\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ) {\t\t \n String sql = \"DELETE FROM Registration \" +\n \"WHERE id = 101\";\n stmt.executeUpdate(sql);\n ResultSet rs = stmt.executeQuery(QUERY);\n while(rs.next()){\n //Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n rs.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}" }, { "code": null, "e": 6150, "s": 6100, "text": "Now let us compile the above example as follows −" }, { "code": null, "e": 6187, "s": 6150, "text": "C:\\>javac TestApplication.java\nC:\\>\n" }, { "code": null, "e": 6252, "s": 6187, "text": "When you run TestApplication, it produces the following result −" }, { "code": null, "e": 6411, "s": 6252, "text": "C:\\>java TestApplication\nID: 100, Age: 30, First: Zara, Last: Ali\nID: 102, Age: 30, First: Zaid, Last: Khan\nID: 103, Age: 28, First: Sumit, Last: Mittal\nC:\\>\n" }, { "code": null, "e": 6444, "s": 6411, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 6460, "s": 6444, "text": " Malhar Lathkar" }, { "code": null, "e": 6493, "s": 6460, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 6509, "s": 6493, "text": " Malhar Lathkar" }, { "code": null, "e": 6544, "s": 6509, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6558, "s": 6544, "text": " Anadi Sharma" }, { "code": null, "e": 6592, "s": 6558, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 6606, "s": 6592, "text": " Tushar Kale" }, { "code": null, "e": 6643, "s": 6606, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6658, "s": 6643, "text": " Monica Mittal" }, { "code": null, "e": 6691, "s": 6658, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 6710, "s": 6691, "text": " Arnab Chakraborty" }, { "code": null, "e": 6717, "s": 6710, "text": " Print" }, { "code": null, "e": 6728, "s": 6717, "text": " Add Notes" } ]
Unix Mock Test
This section presents you various set of Mock Tests related to Unix Framework. You can download these sample mock tests at your local machine and solve offline at your convenience. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Q 1 - Choose the odd one out. A - csh B - bsh C - ksh D - Kernel Kernel is the core part of the OS and is odd one the rest are popular shells. Q 2 - What is the option to create symbolic link for a file? A - –s B - –l C - –f D - None of the above. -s is the option to create a symbolic/soft link and applicable for only files. Q 3 - What is the option to create hard link for a directory? A - –s B - –l C - –f D - None of the above. It is error to create a hard link for a directory. Q 4 - The following command can list out all the current active logins. A - whoami B - who am i C - who D - None of the above. who lists out all the current active logins with the associated terminal types, time and host machine name. Q 5 - Choose the command to print the current working directory A - cwd B - pwd C - wd D - nwd pwd (present working directory). Q 6 - What is the file descriptor number which represents the STDOUT? A - 0 B - 1 C - 2 D - None of the above. 0-STDIN, 1-STDOUT & 2-STDERR Q 7 - What does the following command would do $ cp ../file. A - Copies the file from current directory to parent directory B - Copies the file from parent directory to its parent directory C - Copies the file from parent directory to current directory D - Error in the command Dot dot (..) represents parent directory and Dot (.) represents current working directory. Q 8 - Identify the environment variable which designates secondary prompt. A - PP1 B - SP2 C - PS1 D - PS2 PS2 stands for primary string two. Q 9 - A process is ___ A - Collection of threads B - A thread C - Software D - A running program A program in the execution state is called as process. Q 10 - What is PPID? A - Previous process identification B - Priority process identification C - Parent process identification D - Pre Parent identification The parent process id of a child process. Q 11 - Which key combination can yank a line in vi? A - yw B - yc C - yy D - yl Yanking is the process of holding a text in the buffer. Q 12 - She-bang line in a shell script begins with__ A - # B - #! C - !# D - None of the above. It tell the system to use which shell for executing the script file. Q 13 - How does a comment can begin in a shell script file. A - Beginning with # B - Beginning with $ C - Beginning with ! D - None of the above. A comment line begin with # (pound symbol) and is ignored by the shell. Q 14 - What does the following command will do? $ chmod 888 file A - It enables r,w,x premissions for all users B - It disable r,w,x permissions for all users C - It enables r,w,x permissions only for owner of the file D - None of the above. We can provide the permission values in octal number system and 888 is not a valid octal number. Q 15 - Which shell variable holds the first command line argument for a shell script? A - $0 B - $1 C - #0 D - None of the above $0 represent the shell script file name itself. Starting with $1, are actual command line arguments sent to the shell script. Q 16 - Let a = 5, b = 6. Choose the proper command to perform multiplication? A - expr $a * $b B - expr $a \* $b C - $(a*b) D - None of the above. As * hold special meaning suppress it by escaping with \. Q 17 - Which filter can be applied on lines of text for arranging in ascending or descending order? A - sort B - arrange C - collate D - None of the above. Sort command, a filter used to sort the text in Lexi logical or numerical order. Q 18 - Which shell operator can be used to place a command to execute in background? A - | B - & C - && D - > Syntax is command &. Q 19 - We can kill any background executing process. A - True B - False False. We can kill only the processes for which we are owner. Q 20 - Which of the following is correct to create an alias name for 'ls' as 'list'? A - alias list=”ls” B - alias list “ls” C - alias “list” as “ls” D - alias “ls” as “list” Syntax is alias alias-name=”command”. Q 21 - Choose the correct from below to search for lines beginning with the pattern using grep. A - ^pattern B - pattern^ C - $pattern D - pattern$ The pattern can be enclosed in single quotes to suppress meaning of all the meta-characters special meanings. Q 22 - Copy all the .doc extension files with file name having only 3 characters into the directory called “confi”, which is in parent directory. A - cp ???.doc ../confi B - cp [1-3].doc ../confi C - cp ???.doc /confi D - None of the above. ??? -> to match for any 3 characters. Dot dot (..) represents parent directory. Q 23 - Which command can be used to remove a non-empty directory? A - rmdir B - rd C - ddir D - rm rmdir can be used only if the directory is empty. We can remove the directory if non-empty using recursive option with ‘rm’, as a directory is even a file for UNIX/Linux. Q 24 - Choose the option to remove write permission for group & others for a file “a.txt”. A - Select disable write for group and others where file=”a.txt” B - chmod go-w a.txt C - chmod w-go a.txt D - chmod go=”r-x” a.txt Q 25 - Choose the command to list only the file “error.txt” A - ls *err*.txt B - ls e*.txt C - ls error.??? D - ls error.txt 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": 3032, "s": 2747, "text": "This section presents you various set of Mock Tests related to Unix Framework. You can download these sample mock tests at your local machine and solve offline at your convenience. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself." }, { "code": null, "e": 3062, "s": 3032, "text": "Q 1 - Choose the odd one out." }, { "code": null, "e": 3070, "s": 3062, "text": "A - csh" }, { "code": null, "e": 3078, "s": 3070, "text": "B - bsh" }, { "code": null, "e": 3086, "s": 3078, "text": "C - ksh" }, { "code": null, "e": 3097, "s": 3086, "text": "D - Kernel" }, { "code": null, "e": 3175, "s": 3097, "text": "Kernel is the core part of the OS and is odd one the rest are popular shells." }, { "code": null, "e": 3236, "s": 3175, "text": "Q 2 - What is the option to create symbolic link for a file?" }, { "code": null, "e": 3243, "s": 3236, "text": "A - –s" }, { "code": null, "e": 3250, "s": 3243, "text": "B - –l" }, { "code": null, "e": 3257, "s": 3250, "text": "C - –f" }, { "code": null, "e": 3280, "s": 3257, "text": "D - None of the above." }, { "code": null, "e": 3359, "s": 3280, "text": "-s is the option to create a symbolic/soft link and applicable for only files." }, { "code": null, "e": 3421, "s": 3359, "text": "Q 3 - What is the option to create hard link for a directory?" }, { "code": null, "e": 3428, "s": 3421, "text": "A - –s" }, { "code": null, "e": 3435, "s": 3428, "text": "B - –l" }, { "code": null, "e": 3442, "s": 3435, "text": "C - –f" }, { "code": null, "e": 3465, "s": 3442, "text": "D - None of the above." }, { "code": null, "e": 3516, "s": 3465, "text": "It is error to create a hard link for a directory." }, { "code": null, "e": 3588, "s": 3516, "text": "Q 4 - The following command can list out all the current active logins." }, { "code": null, "e": 3599, "s": 3588, "text": "A - whoami" }, { "code": null, "e": 3612, "s": 3599, "text": "B - who am i" }, { "code": null, "e": 3620, "s": 3612, "text": "C - who" }, { "code": null, "e": 3643, "s": 3620, "text": "D - None of the above." }, { "code": null, "e": 3751, "s": 3643, "text": "who lists out all the current active logins with the associated terminal types, time and host machine name." }, { "code": null, "e": 3815, "s": 3751, "text": "Q 5 - Choose the command to print the current working directory" }, { "code": null, "e": 3823, "s": 3815, "text": "A - cwd" }, { "code": null, "e": 3831, "s": 3823, "text": "B - pwd" }, { "code": null, "e": 3838, "s": 3831, "text": "C - wd" }, { "code": null, "e": 3846, "s": 3838, "text": "D - nwd" }, { "code": null, "e": 3879, "s": 3846, "text": "pwd (present working directory)." }, { "code": null, "e": 3949, "s": 3879, "text": "Q 6 - What is the file descriptor number which represents the STDOUT?" }, { "code": null, "e": 3955, "s": 3949, "text": "A - 0" }, { "code": null, "e": 3961, "s": 3955, "text": "B - 1" }, { "code": null, "e": 3967, "s": 3961, "text": "C - 2" }, { "code": null, "e": 3990, "s": 3967, "text": "D - None of the above." }, { "code": null, "e": 4019, "s": 3990, "text": "0-STDIN, 1-STDOUT & 2-STDERR" }, { "code": null, "e": 4066, "s": 4019, "text": "Q 7 - What does the following command would do" }, { "code": null, "e": 4083, "s": 4066, "text": " $ cp ../file." }, { "code": null, "e": 4146, "s": 4083, "text": "A - Copies the file from current directory to parent directory" }, { "code": null, "e": 4212, "s": 4146, "text": "B - Copies the file from parent directory to its parent directory" }, { "code": null, "e": 4275, "s": 4212, "text": "C - Copies the file from parent directory to current directory" }, { "code": null, "e": 4300, "s": 4275, "text": "D - Error in the command" }, { "code": null, "e": 4391, "s": 4300, "text": "Dot dot (..) represents parent directory and Dot (.) represents current working directory." }, { "code": null, "e": 4466, "s": 4391, "text": "Q 8 - Identify the environment variable which designates secondary prompt." }, { "code": null, "e": 4474, "s": 4466, "text": "A - PP1" }, { "code": null, "e": 4482, "s": 4474, "text": "B - SP2" }, { "code": null, "e": 4490, "s": 4482, "text": "C - PS1" }, { "code": null, "e": 4498, "s": 4490, "text": "D - PS2" }, { "code": null, "e": 4533, "s": 4498, "text": "PS2 stands for primary string two." }, { "code": null, "e": 4556, "s": 4533, "text": "Q 9 - A process is ___" }, { "code": null, "e": 4582, "s": 4556, "text": "A - Collection of threads" }, { "code": null, "e": 4595, "s": 4582, "text": "B - A thread" }, { "code": null, "e": 4608, "s": 4595, "text": "C - Software" }, { "code": null, "e": 4630, "s": 4608, "text": "D - A running program" }, { "code": null, "e": 4685, "s": 4630, "text": "A program in the execution state is called as process." }, { "code": null, "e": 4706, "s": 4685, "text": "Q 10 - What is PPID?" }, { "code": null, "e": 4742, "s": 4706, "text": "A - Previous process identification" }, { "code": null, "e": 4778, "s": 4742, "text": "B - Priority process identification" }, { "code": null, "e": 4812, "s": 4778, "text": "C - Parent process identification" }, { "code": null, "e": 4842, "s": 4812, "text": "D - Pre Parent identification" }, { "code": null, "e": 4884, "s": 4842, "text": "The parent process id of a child process." }, { "code": null, "e": 4936, "s": 4884, "text": "Q 11 - Which key combination can yank a line in vi?" }, { "code": null, "e": 4943, "s": 4936, "text": "A - yw" }, { "code": null, "e": 4950, "s": 4943, "text": "B - yc" }, { "code": null, "e": 4957, "s": 4950, "text": "C - yy" }, { "code": null, "e": 4964, "s": 4957, "text": "D - yl" }, { "code": null, "e": 5020, "s": 4964, "text": "Yanking is the process of holding a text in the buffer." }, { "code": null, "e": 5073, "s": 5020, "text": "Q 12 - She-bang line in a shell script begins with__" }, { "code": null, "e": 5079, "s": 5073, "text": "A - #" }, { "code": null, "e": 5086, "s": 5079, "text": "B - #!" }, { "code": null, "e": 5093, "s": 5086, "text": "C - !#" }, { "code": null, "e": 5116, "s": 5093, "text": "D - None of the above." }, { "code": null, "e": 5185, "s": 5116, "text": "It tell the system to use which shell for executing the script file." }, { "code": null, "e": 5245, "s": 5185, "text": "Q 13 - How does a comment can begin in a shell script file." }, { "code": null, "e": 5266, "s": 5245, "text": "A - Beginning with #" }, { "code": null, "e": 5287, "s": 5266, "text": "B - Beginning with $" }, { "code": null, "e": 5308, "s": 5287, "text": "C - Beginning with !" }, { "code": null, "e": 5331, "s": 5308, "text": "D - None of the above." }, { "code": null, "e": 5403, "s": 5331, "text": "A comment line begin with # (pound symbol) and is ignored by the shell." }, { "code": null, "e": 5451, "s": 5403, "text": "Q 14 - What does the following command will do?" }, { "code": null, "e": 5471, "s": 5451, "text": " $ chmod 888 file" }, { "code": null, "e": 5518, "s": 5471, "text": "A - It enables r,w,x premissions for all users" }, { "code": null, "e": 5565, "s": 5518, "text": "B - It disable r,w,x permissions for all users" }, { "code": null, "e": 5625, "s": 5565, "text": "C - It enables r,w,x permissions only for owner of the file" }, { "code": null, "e": 5648, "s": 5625, "text": "D - None of the above." }, { "code": null, "e": 5745, "s": 5648, "text": "We can provide the permission values in octal number system and 888 is not a valid octal number." }, { "code": null, "e": 5831, "s": 5745, "text": "Q 15 - Which shell variable holds the first command line argument for a shell script?" }, { "code": null, "e": 5838, "s": 5831, "text": "A - $0" }, { "code": null, "e": 5845, "s": 5838, "text": "B - $1" }, { "code": null, "e": 5852, "s": 5845, "text": "C - #0" }, { "code": null, "e": 5874, "s": 5852, "text": "D - None of the above" }, { "code": null, "e": 6000, "s": 5874, "text": "$0 represent the shell script file name itself. Starting with $1, are actual command line arguments sent to the shell script." }, { "code": null, "e": 6078, "s": 6000, "text": "Q 16 - Let a = 5, b = 6. Choose the proper command to perform multiplication?" }, { "code": null, "e": 6095, "s": 6078, "text": "A - expr $a * $b" }, { "code": null, "e": 6113, "s": 6095, "text": "B - expr $a \\* $b" }, { "code": null, "e": 6124, "s": 6113, "text": "C - $(a*b)" }, { "code": null, "e": 6147, "s": 6124, "text": "D - None of the above." }, { "code": null, "e": 6205, "s": 6147, "text": "As * hold special meaning suppress it by escaping with \\." }, { "code": null, "e": 6305, "s": 6205, "text": "Q 17 - Which filter can be applied on lines of text for arranging in ascending or descending order?" }, { "code": null, "e": 6314, "s": 6305, "text": "A - sort" }, { "code": null, "e": 6326, "s": 6314, "text": "B - arrange" }, { "code": null, "e": 6338, "s": 6326, "text": "C - collate" }, { "code": null, "e": 6361, "s": 6338, "text": "D - None of the above." }, { "code": null, "e": 6442, "s": 6361, "text": "Sort command, a filter used to sort the text in Lexi logical or numerical order." }, { "code": null, "e": 6527, "s": 6442, "text": "Q 18 - Which shell operator can be used to place a command to execute in background?" }, { "code": null, "e": 6533, "s": 6527, "text": "A - |" }, { "code": null, "e": 6539, "s": 6533, "text": "B - &" }, { "code": null, "e": 6546, "s": 6539, "text": "C - &&" }, { "code": null, "e": 6552, "s": 6546, "text": "D - >" }, { "code": null, "e": 6573, "s": 6552, "text": "Syntax is command &." }, { "code": null, "e": 6626, "s": 6573, "text": "Q 19 - We can kill any background executing process." }, { "code": null, "e": 6635, "s": 6626, "text": "A - True" }, { "code": null, "e": 6645, "s": 6635, "text": "B - False" }, { "code": null, "e": 6707, "s": 6645, "text": "False. We can kill only the processes for which we are owner." }, { "code": null, "e": 6792, "s": 6707, "text": "Q 20 - Which of the following is correct to create an alias name for 'ls' as 'list'?" }, { "code": null, "e": 6812, "s": 6792, "text": "A - alias list=”ls”" }, { "code": null, "e": 6832, "s": 6812, "text": "B - alias list “ls”" }, { "code": null, "e": 6857, "s": 6832, "text": "C - alias “list” as “ls”" }, { "code": null, "e": 6882, "s": 6857, "text": "D - alias “ls” as “list”" }, { "code": null, "e": 6920, "s": 6882, "text": "Syntax is alias alias-name=”command”." }, { "code": null, "e": 7016, "s": 6920, "text": "Q 21 - Choose the correct from below to search for lines beginning with the pattern using grep." }, { "code": null, "e": 7029, "s": 7016, "text": "A - ^pattern" }, { "code": null, "e": 7042, "s": 7029, "text": "B - pattern^" }, { "code": null, "e": 7055, "s": 7042, "text": "C - $pattern" }, { "code": null, "e": 7068, "s": 7055, "text": "D - pattern$" }, { "code": null, "e": 7178, "s": 7068, "text": "The pattern can be enclosed in single quotes to suppress meaning of all the meta-characters special meanings." }, { "code": null, "e": 7324, "s": 7178, "text": "Q 22 - Copy all the .doc extension files with file name having only 3 characters into the directory called “confi”, which is in parent directory." }, { "code": null, "e": 7348, "s": 7324, "text": "A - cp ???.doc ../confi" }, { "code": null, "e": 7374, "s": 7348, "text": "B - cp [1-3].doc ../confi" }, { "code": null, "e": 7396, "s": 7374, "text": "C - cp ???.doc /confi" }, { "code": null, "e": 7419, "s": 7396, "text": "D - None of the above." }, { "code": null, "e": 7499, "s": 7419, "text": "??? -> to match for any 3 characters. Dot dot (..) represents parent directory." }, { "code": null, "e": 7565, "s": 7499, "text": "Q 23 - Which command can be used to remove a non-empty directory?" }, { "code": null, "e": 7575, "s": 7565, "text": "A - rmdir" }, { "code": null, "e": 7582, "s": 7575, "text": "B - rd" }, { "code": null, "e": 7591, "s": 7582, "text": "C - ddir" }, { "code": null, "e": 7598, "s": 7591, "text": "D - rm" }, { "code": null, "e": 7769, "s": 7598, "text": "rmdir can be used only if the directory is empty. We can remove the directory if non-empty using recursive option with ‘rm’, as a directory is even a file for UNIX/Linux." }, { "code": null, "e": 7860, "s": 7769, "text": "Q 24 - Choose the option to remove write permission for group & others for a file “a.txt”." }, { "code": null, "e": 7925, "s": 7860, "text": "A - Select disable write for group and others where file=”a.txt”" }, { "code": null, "e": 7946, "s": 7925, "text": "B - chmod go-w a.txt" }, { "code": null, "e": 7967, "s": 7946, "text": "C - chmod w-go a.txt" }, { "code": null, "e": 7992, "s": 7967, "text": "D - chmod go=”r-x” a.txt" }, { "code": null, "e": 8054, "s": 7994, "text": "Q 25 - Choose the command to list only the file “error.txt”" }, { "code": null, "e": 8071, "s": 8054, "text": "A - ls *err*.txt" }, { "code": null, "e": 8085, "s": 8071, "text": "B - ls e*.txt" }, { "code": null, "e": 8102, "s": 8085, "text": "C - ls error.???" }, { "code": null, "e": 8119, "s": 8102, "text": "D - ls error.txt" }, { "code": null, "e": 8156, "s": 8121, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 8184, "s": 8156, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8218, "s": 8184, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8235, "s": 8218, "text": " Frahaan Hussain" }, { "code": null, "e": 8268, "s": 8235, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 8279, "s": 8268, "text": " Pradeep D" }, { "code": null, "e": 8314, "s": 8279, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8330, "s": 8314, "text": " Musab Zayadneh" }, { "code": null, "e": 8363, "s": 8330, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 8375, "s": 8363, "text": " GUHARAJANM" }, { "code": null, "e": 8407, "s": 8375, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 8415, "s": 8407, "text": " Uplatz" }, { "code": null, "e": 8422, "s": 8415, "text": " Print" }, { "code": null, "e": 8433, "s": 8422, "text": " Add Notes" } ]
How to get the child node index in JavaScript? - GeeksforGeeks
12 Sep, 2019 The task is to get the index of child element among other children. Here are few techniques discussed.Approach 1: Select the child element of parent element. Select the parent by .parentNode property. Use Array.prototype.indexOf.call(Children_of_parent, current_child) to get the index. Example 1: This example using the approach discussed above. <!DOCTYPE HTML><html> <head> <title> How to get the child node index in JavaScript? </title> <style> .parent { background: green; color: white; } #child1 { background: blue; color: white; margin: 10px; } #child2 { background: red; color: white; margin: 10px; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <div class="parent" id="parent"> Parent <div id="child1"> Child1 </div> <div id="child2"> Child2 </div> </div> <br> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button get the index of child element."; function GFG_Fun() { var child = document.getElementById('child2'); var parent = child.parentNode; down.innerHTML = "The index of element with id = 'child2' is = " + Array.prototype.indexOf.call(parent.children, child); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: Select the child element of parent element. First select the parent and then select the all children of parent element. make an array of children and use indexOf() method to get the index. Example 2: This example using the approach discussed above. <!DOCTYPE HTML><html> <head> <title> How to get the child node index in JavaScript? </title> <style> .parent { background: green; color: white; } #child1 { background: blue; color: white; margin: 10px; } #child2 { background: red; color: white; margin: 10px; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <div class="parent" id="parent"> Parent <div id="child1"> Child1 </div> <div id="child2"> Child2 </div> </div> <br> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button get the index of child element."; function GFG_Fun() { var child = document.getElementById('child2'); down.innerHTML = "The index of element with id = 'child2' is = " + Array.from(child.parentNode.children).indexOf(child); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc 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 Difference Between PUT and PATCH Request Set the value of an input field 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": 25364, "s": 25336, "text": "\n12 Sep, 2019" }, { "code": null, "e": 25478, "s": 25364, "text": "The task is to get the index of child element among other children. Here are few techniques discussed.Approach 1:" }, { "code": null, "e": 25522, "s": 25478, "text": "Select the child element of parent element." }, { "code": null, "e": 25565, "s": 25522, "text": "Select the parent by .parentNode property." }, { "code": null, "e": 25651, "s": 25565, "text": "Use Array.prototype.indexOf.call(Children_of_parent, current_child) to get the index." }, { "code": null, "e": 25711, "s": 25651, "text": "Example 1: This example using the approach discussed above." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to get the child node index in JavaScript? </title> <style> .parent { background: green; color: white; } #child1 { background: blue; color: white; margin: 10px; } #child2 { background: red; color: white; margin: 10px; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <div class=\"parent\" id=\"parent\"> Parent <div id=\"child1\"> Child1 </div> <div id=\"child2\"> Child2 </div> </div> <br> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on the button get the index of child element.\"; function GFG_Fun() { var child = document.getElementById('child2'); var parent = child.parentNode; down.innerHTML = \"The index of element with id = 'child2' is = \" + Array.prototype.indexOf.call(parent.children, child); } </script></body> </html>", "e": 27243, "s": 25711, "text": null }, { "code": null, "e": 27251, "s": 27243, "text": "Output:" }, { "code": null, "e": 27282, "s": 27251, "text": "Before clicking on the button:" }, { "code": null, "e": 27312, "s": 27282, "text": "After clicking on the button:" }, { "code": null, "e": 27324, "s": 27312, "text": "Approach 2:" }, { "code": null, "e": 27368, "s": 27324, "text": "Select the child element of parent element." }, { "code": null, "e": 27444, "s": 27368, "text": "First select the parent and then select the all children of parent element." }, { "code": null, "e": 27513, "s": 27444, "text": "make an array of children and use indexOf() method to get the index." }, { "code": null, "e": 27573, "s": 27513, "text": "Example 2: This example using the approach discussed above." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to get the child node index in JavaScript? </title> <style> .parent { background: green; color: white; } #child1 { background: blue; color: white; margin: 10px; } #child2 { background: red; color: white; margin: 10px; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <div class=\"parent\" id=\"parent\"> Parent <div id=\"child1\"> Child1 </div> <div id=\"child2\"> Child2 </div> </div> <br> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on the button get the index of child element.\"; function GFG_Fun() { var child = document.getElementById('child2'); down.innerHTML = \"The index of element with id = 'child2' is = \" + Array.from(child.parentNode.children).indexOf(child); } </script></body> </html>", "e": 29032, "s": 27573, "text": null }, { "code": null, "e": 29040, "s": 29032, "text": "Output:" }, { "code": null, "e": 29071, "s": 29040, "text": "Before clicking on the button:" }, { "code": null, "e": 29101, "s": 29071, "text": "After clicking on the button:" }, { "code": null, "e": 29117, "s": 29101, "text": "JavaScript-Misc" }, { "code": null, "e": 29128, "s": 29117, "text": "JavaScript" }, { "code": null, "e": 29145, "s": 29128, "text": "Web Technologies" }, { "code": null, "e": 29172, "s": 29145, "text": "Web technologies Questions" }, { "code": null, "e": 29270, "s": 29172, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29279, "s": 29270, "text": "Comments" }, { "code": null, "e": 29292, "s": 29279, "text": "Old Comments" }, { "code": null, "e": 29337, "s": 29292, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29398, "s": 29337, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29470, "s": 29398, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29511, "s": 29470, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29557, "s": 29511, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 29599, "s": 29557, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29632, "s": 29599, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29675, "s": 29632, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29737, "s": 29675, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
DAX Date & Time - YEARFRAC function
Calculates the fraction of the year represented by the number of whole days between two dates. YEARFRAC (<start_date>, <end_date>, [<basis>]) start_date The start date in datetime format. end_date The end date in datetime format. basis Optional. The type of day count basis to use. An integer between 0 and 4. If not an integer, the parameter will be truncated. 0 - US (NASD) 30/360. 1 - Actual/actual. 2 - Actual/360. 3 - Actual/365. 4 - European 30/360. If omitted, default is 0. A decimal number. The internal data type is a signed IEEE 64-bit (8-byte) double-precision floating-point number. You can use the YEARFRAC function to identify the proportion of a whole year's benefits or obligations to assign to a specific term. DAX uses a datetime format to work with dates and times. If start_date or end_date are not valid dates, YEARFRAC returns an error. If basis < 0 or if basis > 4, YEARFRAC returns an error. = YEARFRAC ([InventoryDate], [UsageDate]) This formula returns a calculated column with fraction values representing InventoryDuration. 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2096, "s": 2001, "text": "Calculates the fraction of the year represented by the number of whole days between two dates." }, { "code": null, "e": 2145, "s": 2096, "text": "YEARFRAC (<start_date>, <end_date>, [<basis>]) \n" }, { "code": null, "e": 2156, "s": 2145, "text": "start_date" }, { "code": null, "e": 2191, "s": 2156, "text": "The start date in datetime format." }, { "code": null, "e": 2200, "s": 2191, "text": "end_date" }, { "code": null, "e": 2233, "s": 2200, "text": "The end date in datetime format." }, { "code": null, "e": 2239, "s": 2233, "text": "basis" }, { "code": null, "e": 2249, "s": 2239, "text": "Optional." }, { "code": null, "e": 2285, "s": 2249, "text": "The type of day count basis to use." }, { "code": null, "e": 2365, "s": 2285, "text": "An integer between 0 and 4. If not an integer, the parameter will be truncated." }, { "code": null, "e": 2387, "s": 2365, "text": "0 - US (NASD) 30/360." }, { "code": null, "e": 2406, "s": 2387, "text": "1 - Actual/actual." }, { "code": null, "e": 2422, "s": 2406, "text": "2 - Actual/360." }, { "code": null, "e": 2438, "s": 2422, "text": "3 - Actual/365." }, { "code": null, "e": 2459, "s": 2438, "text": "4 - European 30/360." }, { "code": null, "e": 2485, "s": 2459, "text": "If omitted, default is 0." }, { "code": null, "e": 2599, "s": 2485, "text": "A decimal number. The internal data type is a signed IEEE 64-bit (8-byte) double-precision floating-point number." }, { "code": null, "e": 2732, "s": 2599, "text": "You can use the YEARFRAC function to identify the proportion of a whole year's benefits or obligations to assign to a specific term." }, { "code": null, "e": 2789, "s": 2732, "text": "DAX uses a datetime format to work with dates and times." }, { "code": null, "e": 2863, "s": 2789, "text": "If start_date or end_date are not valid dates, YEARFRAC returns an error." }, { "code": null, "e": 2920, "s": 2863, "text": "If basis < 0 or if basis > 4, YEARFRAC returns an error." }, { "code": null, "e": 2963, "s": 2920, "text": "= YEARFRAC ([InventoryDate], [UsageDate]) " }, { "code": null, "e": 3057, "s": 2963, "text": "This formula returns a calculated column with fraction values representing InventoryDuration." }, { "code": null, "e": 3092, "s": 3057, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3106, "s": 3092, "text": " Abhay Gadiya" }, { "code": null, "e": 3139, "s": 3106, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3153, "s": 3139, "text": " Randy Minder" }, { "code": null, "e": 3188, "s": 3153, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3202, "s": 3188, "text": " Randy Minder" }, { "code": null, "e": 3209, "s": 3202, "text": " Print" }, { "code": null, "e": 3220, "s": 3209, "text": " Add Notes" } ]
Picking the right tool for geospatial data enrichment (part 2) | by Bart Grasza | Towards Data Science
If you didn’t read the introduction, you can find it in part 1. As a reminder, tools selected in part 1 of the series were: Geopandas, PostGIS and BigQuery. Let’s talk about their pros and cons. GeoPandas Geospatial extension for Pandas that under the hood uses Shapely (Python library to manipulate and analyze geometric objects) Supports most important spatial functions, enough to solve even quite complex problems Relatively easy to master if you are familiar with Pandas Slower than PostGIS Similarly to Pandas, operates on single core, but together with Dask (dask.org) can be parallelized Built-in plotting function (directly in jupyter notebook) that will be enough for very simple data visualization/validation cases Supports most common input/output formats PostGIS PostGIS extends standard (PostgreSQL) SQL language with spatial functions Takes time to get familiar with some of the concepts but writing actual queries is quite simple Can solve almost any geospatial-like problem, supports even functions like Nearest Neighbor Many data loading and converting functions Fast but query execution is limited to one core Like any RDB, can crunch larger than memory queries, but when dealing with real “Big Data”, it might not be enough Has many associated open source tools that will help you e.g. visualize your data (QGIS being my favorite) Great documentation and online community When linked together with PostgreSQL procedural language (PL/pgSQL), gives quite a powerful pipeline to process queries without “leaving” database BigQuery’s geospatial functions Processes queries in Google Cloud and if you know SQL then you will feel at home Part of Google Cloud ecosystem where it’s easy to load, transform and export data using various APIs Can crunch gigabytes within seconds Supported input formats: CSV with geospatial column in WKT format and GeoJSON as a column in JSON format (new-line delimited) Has inbuilt plotting tools, Big data ready Charges per data storage and query running time which can greatly reduce your costs even if you’re crunching through terabytes of data Supports joins between BigQuery data and Cloud SQL (which can also use PostgreSQL as an engine) data in single query Less functions that PostGIS, but all essential manipulations and analysis related ones are already there No procedural language like PL/pgSQL but (BigQuery in general) can mimic it to some extent using (SQL) WITH function You are familiar with Pandas and SQL isn’t your strong side Want to quickly explore / preprocess your geospatial data and you’re not planning to do complex transformations Your geospatial dataframe doesn’t go into millions of records (Can process more but will make you wait for the results ; Dask can mitigate that problem to some point) Your use case is rather simple and you want to get going asap Pick PostGIS if: Geopandas isn’t enough. Either because your problem was to difficult for Geopandas or it made you wait too long for results You might end up manipulating more (larger than memory) records You need complete set of geospatial functions You have more time to familiarize yourself with a bit more complex tool than Geopandas Pick BigQuery if ... you have to process Big Data! 🙂 Ok, we’re finally ready to do some real work. Imagine following problem:Your company has an app that each day generates large number of locations (longitude and latitude) where users interacted with your app. You were given 3 separate cases to work on. Given user’s coordinates:1. Assign it to the city’s district2. Find the distance (in meters) to the nearest shopping mall, bus station and hospital (straight line distance)3. Generate aggregate statistics like e.g. count of number of app interactions per district Notice that in the task 1 the number of shapes (city districts) won’t probably exceed 100 records in the database.Second task is derivative of first one where the output of the computation has as many records as the number of city districts.As for the third task, there might be more than 100.000 POI (Points of interest) you’d need to check against location of your users, but the actual POIs will not change that often and can be updated e.g. on a weekly basis. All of this is actually great news because it means that the geospatial data preprocessing can take place e.g. directly on your laptop with Geopandas or PostGIS. What kind of preprocessing steps would be required before merging with our users locations? Of course it highly depends on your case, but let’s talk about most common ones. First you need to get actual geo-data (e.g. shapefile or GeoJSON representing city’s districts) and import the file to your tool (let’s assume it’s on your laptop). With Geopandas is one-liner: Notice in the example above I used bbox (bounding box) parameter to “throw away” all data that is outside of defined area. Function read_file() can do more, e.g. load files directly from internet and in ZIP format (details on https://geopandas.org/io.html). Next step is is to clean the data and change SRID if needed. # Changing SRID (projection) in Geopandas# (where "df" is you geodataframe)df.to_crs("EPSG:4326")# Changing SRID in PostGISUPDATE my_tableSET geometry=ST_Transform(geometry) Then, a good practice (especially if the data was downloaded from the internet) is to check if shapes are valid (e.g. polygon that lines don’t cross itself). # Checking if shapes are valid in Geopandas# (where "geometry" is your geometry column)df.geometry.is_valid.all()# If invalid you can try to a quick fixdf.geometry.buffer(0.00001)# Checking if shapes are valid in PostGIS# Returns number of valid and invalid geometriesSELECT count(1), ST_IsValid(geometry)FROM my_tableGROUP BY ST_IsValid(geometry) Sometimes buffer function won’t fix it or you can’t use it because your polygons/multipolygons are hollow inside (and using buffer would remove them). In that case you’ll need to take additional steps like e.g. exporting to PostGIS and trying to fix in there: # Geopandas supports saving geometry directly to PostGIS but from my experience this is safer solution:# 1. Create additional column with geometry converted to WKTdf['geom_wkt'] = df.geometry.apply(lambda x: x.wkt)# 2. Save dataframe to table "my_table" but export geometry in WKT format instead of actual "geometry" columnconnection_str='postgres://<username>:<password>@localhost:<port>/<db_name>'df.drop('geometry', axis=1).to_sql( 'my_table', con=connection_str, if_exists='replace', dtype={'geometry': Geometry})# 3. (Inside PostreSQL database) fix the geometry# Function ST_GeomFromEWKT translates WKT back to geometry# Function ST_MakeValid fixes geometryINSERT INTO my_table_fixedSELECT ST_MakeValid(ST_GeomFromEWKT(geom_wkt)), <other columns>FROM my_table# 4. Load it back into Geopandas dataframesql = 'SELECT * FROM my_table_fixed'new_df = pd.read_postgis(sql=sql, con=connection_str) Apart from learning how to fix the geometry, now you know how fast and easy can be moving data between these two systems. So in any case you’d be missing a function in Geopandas, you can always do it to PostGIS. Lastly comes Q&A process where you’d e.g. visualize the data to check if everything is ok. In Geopandas you can use simply use .plot() : If that’s not enough, you might need to save the data back to SHP or GeoJSON and load them using external application like QGIS. In Geopandas we need to transform our users dataframe to geodataframe: import geopandas as gpd# Load users data into Pandas dataframeusers_df = <load function># Convert to geodataframeusers_gdf = gpd.GeoDataFrame(users_df, geometry=gpd.points_from_xy( users_df.longitude, users_df.latitude)) Now the data is ready to be merged with your users locations. For our Task 1 it would simply be: # Perform spatial joingpd.sjoin(users_gdf, geo_dataframe, how="inner", op='intersects') Similar operation (Task 1) in PostGIS: INSERT INTO merged_tableSELECT * FROM geo_table g, users_table uST_Intersects( ST_SetSRID(ST_MakePoint(u.longitude, u.latitude), 4326), g.geometry)# In this line :# ST_SetSRID(ST_MakePoint(u.longitude, u.latitude), 4326)# we are converting our users coordinates to POINT and setting SRID Task 2 is equally simple: INSERT INTO count_interactions_by_districts_tableSELECT COUNT(1) user_count, geo_table.district_nameFROM geo_table g, users_table uST_Intersects( ST_SetSRID(ST_MakePoint(u.longitude, u.latitude), 4326), g.geometry)GROUP BY geo_table.district_name Task 3 is a bit more challenging: WITH poi_with_point as ( SELECT *, ST_SetSRID( ST_MakePoint( u.longitude, u.latitude), 4326)::geography AS geog FROM poi WHERE p.poi_type='shopping mall')SELECT p.id, p.longitude, p.latitude, min(ST_Distance(p.geog, u.geog)) shopping_mall_min_distance FROM users u, poi_with_point p WHERE ST_DWithin(p.geog, u.geog, 8000)GROUP by p.id, p.longitude, p.latitude Where: The top WITH part of the query is generating “temporary view” called poi_with_point. It extends original table poi (that contains all of our POI locations) by adding POINT column called “geog”. It also filters out all POIs that aren’t shopping malls. ST_DWithin can significantly speed up your query execution. It prevents checking every user’s location against every shopping mall by adding maximum distance of (arbitrary) 8 km between them: Things get interesting when the size of our users database is gigabytes in size. With GeoPandas (by default on a single thread) will take forever and you’d need to process it in batches if dataset exceeds your working memory. If you happen to have Dask cluster running on multiple workers then you might consider using it but it probably still won’t be an optimal solution. I’ve explained batching and running on cluster in my other article “Simplest way to enrich your Pandas dataframe” and both solutions require only few lines of code.Hint: for batching in Dask cluster, use map_partitions function and in each partition separately: load your geospatial data and perform e.g. spatial join operation with “mapped” chunk of user data. PostGIS will be able to crunch through the data but execution time might be sub-optimal. If your PostGIS server is not part of the production environment and you don’t mind waiting the you should go for it. If not our last option is ... BigQuery First we will make few assumptions:1. You have registered Google Cloud account and activated Google Cloud Storage (GCS)2. Your users data is already loaded into BigQuery table3. You have installed google “toolbelt” on your laptop and commands “gsutil“ and “bq” are available in your terminal4. You have permissions to create datasets and tables in BigQuery5. You have set (in terminal, using google “toolbelt”) your default projectTip: Keep GCS and and all BigQuery datasets in the same region, otherwise you might not be able to load it or perform JOIN. As we already know from, BigQuery can import geography data in GeoJSON or WKT formats. We already learned how to convert to WKT so let’s save as CSV and transfer to BigQuery. First we will save it to CSV: # Assuming your geography is already in WKTdf.to_csv('output_file.csv') Loading directly from laptop to BigQuery is possible but has limitations so we’re going to send it to GCS first: # (In your terminal)gsutil cp output_file.csv gs://your_bucket_name_in_gcs Create dataset, table that will store your data and populate it from GCS: # (In your terminal)# Create datasetbq --location=US mk --dataset your_dataset# Create tablebq mk --table your_dataset.geo_table \id:INTEGER,geom_wkt:STRING,<other columns># Load CSV into BigQuery tablebq load \--source_format=CSV \your_dataset.geo_table \gs://your_bucket_name_in_gcs/output_file.csv \id:INTEGER,geom_wkt:STRING,<other columns> BigQuery syntax is almost identical to PostGIS: # Task 1 in BigQueryINSERT INTO merged_tableSELECT * FROM your_users_dataset.users_table u, your_dataset.geo_table gWHERE ST_Intersects( ST_GEOGPOINT(u.longitude, u.latitude), g.geometry) Task 2 is almost identical in BigQuery and PostGIS so I will skip the snippet. As for our 3rd Task, Notice that the resulting number of rows is very small, no more than the number of districts. In that case (or similar where you know that data will fit into your working memory of e.g. your laptop) you can use BigQuery Python client and download result directly into Pandas dataframe: from google.cloud import bigqueryclient = bigquery.Client()sql = """SELECT COUNT(1) as user_count, g.district FROM your_users_dataset.users_table u, your_dataset.geo_table gWHERE ST_Intersects( ST_GEOGPOINT(u.longitude, u.latitude), g.geometry)GROUP BY g.district"""df = client.query(sql).to_dataframe() The goal of the series was to show how to process or enrich your data with external geospatial information. I wanted to show you how you can mix and match available tools, easily transfer data between them and which one will be the most useful to quickly do your job.
[ { "code": null, "e": 236, "s": 172, "text": "If you didn’t read the introduction, you can find it in part 1." }, { "code": null, "e": 367, "s": 236, "text": "As a reminder, tools selected in part 1 of the series were: Geopandas, PostGIS and BigQuery. Let’s talk about their pros and cons." }, { "code": null, "e": 377, "s": 367, "text": "GeoPandas" }, { "code": null, "e": 503, "s": 377, "text": "Geospatial extension for Pandas that under the hood uses Shapely (Python library to manipulate and analyze geometric objects)" }, { "code": null, "e": 590, "s": 503, "text": "Supports most important spatial functions, enough to solve even quite complex problems" }, { "code": null, "e": 648, "s": 590, "text": "Relatively easy to master if you are familiar with Pandas" }, { "code": null, "e": 668, "s": 648, "text": "Slower than PostGIS" }, { "code": null, "e": 768, "s": 668, "text": "Similarly to Pandas, operates on single core, but together with Dask (dask.org) can be parallelized" }, { "code": null, "e": 898, "s": 768, "text": "Built-in plotting function (directly in jupyter notebook) that will be enough for very simple data visualization/validation cases" }, { "code": null, "e": 940, "s": 898, "text": "Supports most common input/output formats" }, { "code": null, "e": 948, "s": 940, "text": "PostGIS" }, { "code": null, "e": 1022, "s": 948, "text": "PostGIS extends standard (PostgreSQL) SQL language with spatial functions" }, { "code": null, "e": 1118, "s": 1022, "text": "Takes time to get familiar with some of the concepts but writing actual queries is quite simple" }, { "code": null, "e": 1210, "s": 1118, "text": "Can solve almost any geospatial-like problem, supports even functions like Nearest Neighbor" }, { "code": null, "e": 1253, "s": 1210, "text": "Many data loading and converting functions" }, { "code": null, "e": 1301, "s": 1253, "text": "Fast but query execution is limited to one core" }, { "code": null, "e": 1416, "s": 1301, "text": "Like any RDB, can crunch larger than memory queries, but when dealing with real “Big Data”, it might not be enough" }, { "code": null, "e": 1523, "s": 1416, "text": "Has many associated open source tools that will help you e.g. visualize your data (QGIS being my favorite)" }, { "code": null, "e": 1564, "s": 1523, "text": "Great documentation and online community" }, { "code": null, "e": 1711, "s": 1564, "text": "When linked together with PostgreSQL procedural language (PL/pgSQL), gives quite a powerful pipeline to process queries without “leaving” database" }, { "code": null, "e": 1743, "s": 1711, "text": "BigQuery’s geospatial functions" }, { "code": null, "e": 1824, "s": 1743, "text": "Processes queries in Google Cloud and if you know SQL then you will feel at home" }, { "code": null, "e": 1925, "s": 1824, "text": "Part of Google Cloud ecosystem where it’s easy to load, transform and export data using various APIs" }, { "code": null, "e": 1961, "s": 1925, "text": "Can crunch gigabytes within seconds" }, { "code": null, "e": 2087, "s": 1961, "text": "Supported input formats: CSV with geospatial column in WKT format and GeoJSON as a column in JSON format (new-line delimited)" }, { "code": null, "e": 2130, "s": 2087, "text": "Has inbuilt plotting tools, Big data ready" }, { "code": null, "e": 2265, "s": 2130, "text": "Charges per data storage and query running time which can greatly reduce your costs even if you’re crunching through terabytes of data" }, { "code": null, "e": 2382, "s": 2265, "text": "Supports joins between BigQuery data and Cloud SQL (which can also use PostgreSQL as an engine) data in single query" }, { "code": null, "e": 2487, "s": 2382, "text": "Less functions that PostGIS, but all essential manipulations and analysis related ones are already there" }, { "code": null, "e": 2604, "s": 2487, "text": "No procedural language like PL/pgSQL but (BigQuery in general) can mimic it to some extent using (SQL) WITH function" }, { "code": null, "e": 2664, "s": 2604, "text": "You are familiar with Pandas and SQL isn’t your strong side" }, { "code": null, "e": 2776, "s": 2664, "text": "Want to quickly explore / preprocess your geospatial data and you’re not planning to do complex transformations" }, { "code": null, "e": 2943, "s": 2776, "text": "Your geospatial dataframe doesn’t go into millions of records (Can process more but will make you wait for the results ; Dask can mitigate that problem to some point)" }, { "code": null, "e": 3005, "s": 2943, "text": "Your use case is rather simple and you want to get going asap" }, { "code": null, "e": 3022, "s": 3005, "text": "Pick PostGIS if:" }, { "code": null, "e": 3146, "s": 3022, "text": "Geopandas isn’t enough. Either because your problem was to difficult for Geopandas or it made you wait too long for results" }, { "code": null, "e": 3210, "s": 3146, "text": "You might end up manipulating more (larger than memory) records" }, { "code": null, "e": 3256, "s": 3210, "text": "You need complete set of geospatial functions" }, { "code": null, "e": 3343, "s": 3256, "text": "You have more time to familiarize yourself with a bit more complex tool than Geopandas" }, { "code": null, "e": 3396, "s": 3343, "text": "Pick BigQuery if ... you have to process Big Data! 🙂" }, { "code": null, "e": 3649, "s": 3396, "text": "Ok, we’re finally ready to do some real work. Imagine following problem:Your company has an app that each day generates large number of locations (longitude and latitude) where users interacted with your app. You were given 3 separate cases to work on." }, { "code": null, "e": 3913, "s": 3649, "text": "Given user’s coordinates:1. Assign it to the city’s district2. Find the distance (in meters) to the nearest shopping mall, bus station and hospital (straight line distance)3. Generate aggregate statistics like e.g. count of number of app interactions per district" }, { "code": null, "e": 4377, "s": 3913, "text": "Notice that in the task 1 the number of shapes (city districts) won’t probably exceed 100 records in the database.Second task is derivative of first one where the output of the computation has as many records as the number of city districts.As for the third task, there might be more than 100.000 POI (Points of interest) you’d need to check against location of your users, but the actual POIs will not change that often and can be updated e.g. on a weekly basis." }, { "code": null, "e": 4539, "s": 4377, "text": "All of this is actually great news because it means that the geospatial data preprocessing can take place e.g. directly on your laptop with Geopandas or PostGIS." }, { "code": null, "e": 4712, "s": 4539, "text": "What kind of preprocessing steps would be required before merging with our users locations? Of course it highly depends on your case, but let’s talk about most common ones." }, { "code": null, "e": 4906, "s": 4712, "text": "First you need to get actual geo-data (e.g. shapefile or GeoJSON representing city’s districts) and import the file to your tool (let’s assume it’s on your laptop). With Geopandas is one-liner:" }, { "code": null, "e": 5164, "s": 4906, "text": "Notice in the example above I used bbox (bounding box) parameter to “throw away” all data that is outside of defined area. Function read_file() can do more, e.g. load files directly from internet and in ZIP format (details on https://geopandas.org/io.html)." }, { "code": null, "e": 5225, "s": 5164, "text": "Next step is is to clean the data and change SRID if needed." }, { "code": null, "e": 5399, "s": 5225, "text": "# Changing SRID (projection) in Geopandas# (where \"df\" is you geodataframe)df.to_crs(\"EPSG:4326\")# Changing SRID in PostGISUPDATE my_tableSET geometry=ST_Transform(geometry)" }, { "code": null, "e": 5557, "s": 5399, "text": "Then, a good practice (especially if the data was downloaded from the internet) is to check if shapes are valid (e.g. polygon that lines don’t cross itself)." }, { "code": null, "e": 5905, "s": 5557, "text": "# Checking if shapes are valid in Geopandas# (where \"geometry\" is your geometry column)df.geometry.is_valid.all()# If invalid you can try to a quick fixdf.geometry.buffer(0.00001)# Checking if shapes are valid in PostGIS# Returns number of valid and invalid geometriesSELECT count(1), ST_IsValid(geometry)FROM my_tableGROUP BY ST_IsValid(geometry)" }, { "code": null, "e": 6165, "s": 5905, "text": "Sometimes buffer function won’t fix it or you can’t use it because your polygons/multipolygons are hollow inside (and using buffer would remove them). In that case you’ll need to take additional steps like e.g. exporting to PostGIS and trying to fix in there:" }, { "code": null, "e": 7067, "s": 6165, "text": "# Geopandas supports saving geometry directly to PostGIS but from my experience this is safer solution:# 1. Create additional column with geometry converted to WKTdf['geom_wkt'] = df.geometry.apply(lambda x: x.wkt)# 2. Save dataframe to table \"my_table\" but export geometry in WKT format instead of actual \"geometry\" columnconnection_str='postgres://<username>:<password>@localhost:<port>/<db_name>'df.drop('geometry', axis=1).to_sql( 'my_table', con=connection_str, if_exists='replace', dtype={'geometry': Geometry})# 3. (Inside PostreSQL database) fix the geometry# Function ST_GeomFromEWKT translates WKT back to geometry# Function ST_MakeValid fixes geometryINSERT INTO my_table_fixedSELECT ST_MakeValid(ST_GeomFromEWKT(geom_wkt)), <other columns>FROM my_table# 4. Load it back into Geopandas dataframesql = 'SELECT * FROM my_table_fixed'new_df = pd.read_postgis(sql=sql, con=connection_str)" }, { "code": null, "e": 7279, "s": 7067, "text": "Apart from learning how to fix the geometry, now you know how fast and easy can be moving data between these two systems. So in any case you’d be missing a function in Geopandas, you can always do it to PostGIS." }, { "code": null, "e": 7416, "s": 7279, "text": "Lastly comes Q&A process where you’d e.g. visualize the data to check if everything is ok. In Geopandas you can use simply use .plot() :" }, { "code": null, "e": 7545, "s": 7416, "text": "If that’s not enough, you might need to save the data back to SHP or GeoJSON and load them using external application like QGIS." }, { "code": null, "e": 7616, "s": 7545, "text": "In Geopandas we need to transform our users dataframe to geodataframe:" }, { "code": null, "e": 7848, "s": 7616, "text": "import geopandas as gpd# Load users data into Pandas dataframeusers_df = <load function># Convert to geodataframeusers_gdf = gpd.GeoDataFrame(users_df, geometry=gpd.points_from_xy( users_df.longitude, users_df.latitude))" }, { "code": null, "e": 7945, "s": 7848, "text": "Now the data is ready to be merged with your users locations. For our Task 1 it would simply be:" }, { "code": null, "e": 8033, "s": 7945, "text": "# Perform spatial joingpd.sjoin(users_gdf, geo_dataframe, how=\"inner\", op='intersects')" }, { "code": null, "e": 8072, "s": 8033, "text": "Similar operation (Task 1) in PostGIS:" }, { "code": null, "e": 8366, "s": 8072, "text": "INSERT INTO merged_tableSELECT * FROM geo_table g, users_table uST_Intersects( ST_SetSRID(ST_MakePoint(u.longitude, u.latitude), 4326), g.geometry)# In this line :# ST_SetSRID(ST_MakePoint(u.longitude, u.latitude), 4326)# we are converting our users coordinates to POINT and setting SRID" }, { "code": null, "e": 8392, "s": 8366, "text": "Task 2 is equally simple:" }, { "code": null, "e": 8645, "s": 8392, "text": "INSERT INTO count_interactions_by_districts_tableSELECT COUNT(1) user_count, geo_table.district_nameFROM geo_table g, users_table uST_Intersects( ST_SetSRID(ST_MakePoint(u.longitude, u.latitude), 4326), g.geometry)GROUP BY geo_table.district_name" }, { "code": null, "e": 8679, "s": 8645, "text": "Task 3 is a bit more challenging:" }, { "code": null, "e": 9073, "s": 8679, "text": "WITH poi_with_point as ( SELECT *, ST_SetSRID( ST_MakePoint( u.longitude, u.latitude), 4326)::geography AS geog FROM poi WHERE p.poi_type='shopping mall')SELECT p.id, p.longitude, p.latitude, min(ST_Distance(p.geog, u.geog)) shopping_mall_min_distance FROM users u, poi_with_point p WHERE ST_DWithin(p.geog, u.geog, 8000)GROUP by p.id, p.longitude, p.latitude" }, { "code": null, "e": 9080, "s": 9073, "text": "Where:" }, { "code": null, "e": 9331, "s": 9080, "text": "The top WITH part of the query is generating “temporary view” called poi_with_point. It extends original table poi (that contains all of our POI locations) by adding POINT column called “geog”. It also filters out all POIs that aren’t shopping malls." }, { "code": null, "e": 9523, "s": 9331, "text": "ST_DWithin can significantly speed up your query execution. It prevents checking every user’s location against every shopping mall by adding maximum distance of (arbitrary) 8 km between them:" }, { "code": null, "e": 9604, "s": 9523, "text": "Things get interesting when the size of our users database is gigabytes in size." }, { "code": null, "e": 10259, "s": 9604, "text": "With GeoPandas (by default on a single thread) will take forever and you’d need to process it in batches if dataset exceeds your working memory. If you happen to have Dask cluster running on multiple workers then you might consider using it but it probably still won’t be an optimal solution. I’ve explained batching and running on cluster in my other article “Simplest way to enrich your Pandas dataframe” and both solutions require only few lines of code.Hint: for batching in Dask cluster, use map_partitions function and in each partition separately: load your geospatial data and perform e.g. spatial join operation with “mapped” chunk of user data." }, { "code": null, "e": 10505, "s": 10259, "text": "PostGIS will be able to crunch through the data but execution time might be sub-optimal. If your PostGIS server is not part of the production environment and you don’t mind waiting the you should go for it. If not our last option is ... BigQuery" }, { "code": null, "e": 11060, "s": 10505, "text": "First we will make few assumptions:1. You have registered Google Cloud account and activated Google Cloud Storage (GCS)2. Your users data is already loaded into BigQuery table3. You have installed google “toolbelt” on your laptop and commands “gsutil“ and “bq” are available in your terminal4. You have permissions to create datasets and tables in BigQuery5. You have set (in terminal, using google “toolbelt”) your default projectTip: Keep GCS and and all BigQuery datasets in the same region, otherwise you might not be able to load it or perform JOIN." }, { "code": null, "e": 11265, "s": 11060, "text": "As we already know from, BigQuery can import geography data in GeoJSON or WKT formats. We already learned how to convert to WKT so let’s save as CSV and transfer to BigQuery. First we will save it to CSV:" }, { "code": null, "e": 11337, "s": 11265, "text": "# Assuming your geography is already in WKTdf.to_csv('output_file.csv')" }, { "code": null, "e": 11450, "s": 11337, "text": "Loading directly from laptop to BigQuery is possible but has limitations so we’re going to send it to GCS first:" }, { "code": null, "e": 11525, "s": 11450, "text": "# (In your terminal)gsutil cp output_file.csv gs://your_bucket_name_in_gcs" }, { "code": null, "e": 11599, "s": 11525, "text": "Create dataset, table that will store your data and populate it from GCS:" }, { "code": null, "e": 11944, "s": 11599, "text": "# (In your terminal)# Create datasetbq --location=US mk --dataset your_dataset# Create tablebq mk --table your_dataset.geo_table \\id:INTEGER,geom_wkt:STRING,<other columns># Load CSV into BigQuery tablebq load \\--source_format=CSV \\your_dataset.geo_table \\gs://your_bucket_name_in_gcs/output_file.csv \\id:INTEGER,geom_wkt:STRING,<other columns>" }, { "code": null, "e": 11992, "s": 11944, "text": "BigQuery syntax is almost identical to PostGIS:" }, { "code": null, "e": 12194, "s": 11992, "text": "# Task 1 in BigQueryINSERT INTO merged_tableSELECT * FROM your_users_dataset.users_table u, your_dataset.geo_table gWHERE ST_Intersects( ST_GEOGPOINT(u.longitude, u.latitude), g.geometry)" }, { "code": null, "e": 12273, "s": 12194, "text": "Task 2 is almost identical in BigQuery and PostGIS so I will skip the snippet." }, { "code": null, "e": 12580, "s": 12273, "text": "As for our 3rd Task, Notice that the resulting number of rows is very small, no more than the number of districts. In that case (or similar where you know that data will fit into your working memory of e.g. your laptop) you can use BigQuery Python client and download result directly into Pandas dataframe:" }, { "code": null, "e": 12898, "s": 12580, "text": "from google.cloud import bigqueryclient = bigquery.Client()sql = \"\"\"SELECT COUNT(1) as user_count, g.district FROM your_users_dataset.users_table u, your_dataset.geo_table gWHERE ST_Intersects( ST_GEOGPOINT(u.longitude, u.latitude), g.geometry)GROUP BY g.district\"\"\"df = client.query(sql).to_dataframe()" } ]
Search by value in a Map in C++ - GeeksforGeeks
03 Mar, 2021 Given set of N pairs as a (key, value) pairs in a map and an integers K, task is to find all the keys mapped to the give value K. If there is no key value mapped to K then print “-1”.Examples: Input: Map[] = { {1, 3}, {2, 3}, {4, -1}, {7, 2}, {10, 3} }, K = 3 Output: 1 2 10 Explanation: The 3 key value that is mapped to value 3 are 1, 2, 10.Input: Map[] = { {1, 3}, {2, 3}, {4, -1}, {7, 2}, {10, 3} }, K = 10 Output: -1 Explanation: There is no any key value that is mapped to value 10. Approach: The idea is to traverse the given map and print all the key value which are mapped to the given value K. Below is the loop used to find all the key value: for(auto &it : Map) { if(it.second == K) { print(it.first) } } If there is no value mapped with K then print “-1”.Below is the implementation of the above approach: CPP // C++ program for the above approach#include "bits/stdc++.h"using namespace std; // Function to find the key values// according to given mapped value Kvoid printKey(map<int, int>& Map, int K){ // If a is true, then we have // not key-value mapped to K bool a = true; // Traverse the map for (auto& it : Map) { // If mapped value is K, // then print the key value if (it.second == K) { cout << it.first << ' '; a = false; } } // If there is not key mapped with K, // then print -1 if (a) { cout << "-1"; }} // Driver Codeint main(){ map<int, int> Map; // Given map Map[1] = 3; Map[2] = 3; Map[4] = -1; Map[7] = 2; Map[10] = 3; // Given value K int K = 3; // Function call printKey(Map, K); return 0;} 1 2 10 Time Complexity: O(N), where N is the number of pairs stored in map. This is because we are traversing all the pairs once.Auxiliary Space: O(1) ParthKapadia cpp-map C++ Programs Searching Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C++ Program for QuickSort CSV file management using C++ delete keyword in C++ Shallow Copy and Deep Copy in C++ cin in C++ Binary Search Linear Search Maximum and minimum of an array using minimum number of comparisons Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1
[ { "code": null, "e": 24750, "s": 24722, "text": "\n03 Mar, 2021" }, { "code": null, "e": 24944, "s": 24750, "text": "Given set of N pairs as a (key, value) pairs in a map and an integers K, task is to find all the keys mapped to the give value K. If there is no key value mapped to K then print “-1”.Examples: " }, { "code": null, "e": 25241, "s": 24944, "text": "Input: Map[] = { {1, 3}, {2, 3}, {4, -1}, {7, 2}, {10, 3} }, K = 3 Output: 1 2 10 Explanation: The 3 key value that is mapped to value 3 are 1, 2, 10.Input: Map[] = { {1, 3}, {2, 3}, {4, -1}, {7, 2}, {10, 3} }, K = 10 Output: -1 Explanation: There is no any key value that is mapped to value 10. " }, { "code": null, "e": 25407, "s": 25241, "text": "Approach: The idea is to traverse the given map and print all the key value which are mapped to the given value K. Below is the loop used to find all the key value: " }, { "code": null, "e": 25472, "s": 25407, "text": "for(auto &it : Map) { if(it.second == K) { print(it.first) } } " }, { "code": null, "e": 25574, "s": 25472, "text": "If there is no value mapped with K then print “-1”.Below is the implementation of the above approach:" }, { "code": null, "e": 25578, "s": 25574, "text": "CPP" }, { "code": "// C++ program for the above approach#include \"bits/stdc++.h\"using namespace std; // Function to find the key values// according to given mapped value Kvoid printKey(map<int, int>& Map, int K){ // If a is true, then we have // not key-value mapped to K bool a = true; // Traverse the map for (auto& it : Map) { // If mapped value is K, // then print the key value if (it.second == K) { cout << it.first << ' '; a = false; } } // If there is not key mapped with K, // then print -1 if (a) { cout << \"-1\"; }} // Driver Codeint main(){ map<int, int> Map; // Given map Map[1] = 3; Map[2] = 3; Map[4] = -1; Map[7] = 2; Map[10] = 3; // Given value K int K = 3; // Function call printKey(Map, K); return 0;}", "e": 26422, "s": 25578, "text": null }, { "code": null, "e": 26429, "s": 26422, "text": "1 2 10" }, { "code": null, "e": 26575, "s": 26431, "text": "Time Complexity: O(N), where N is the number of pairs stored in map. This is because we are traversing all the pairs once.Auxiliary Space: O(1)" }, { "code": null, "e": 26588, "s": 26575, "text": "ParthKapadia" }, { "code": null, "e": 26596, "s": 26588, "text": "cpp-map" }, { "code": null, "e": 26609, "s": 26596, "text": "C++ Programs" }, { "code": null, "e": 26619, "s": 26609, "text": "Searching" }, { "code": null, "e": 26629, "s": 26619, "text": "Searching" }, { "code": null, "e": 26727, "s": 26629, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26736, "s": 26727, "text": "Comments" }, { "code": null, "e": 26749, "s": 26736, "text": "Old Comments" }, { "code": null, "e": 26775, "s": 26749, "text": "C++ Program for QuickSort" }, { "code": null, "e": 26805, "s": 26775, "text": "CSV file management using C++" }, { "code": null, "e": 26827, "s": 26805, "text": "delete keyword in C++" }, { "code": null, "e": 26861, "s": 26827, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 26872, "s": 26861, "text": "cin in C++" }, { "code": null, "e": 26886, "s": 26872, "text": "Binary Search" }, { "code": null, "e": 26900, "s": 26886, "text": "Linear Search" }, { "code": null, "e": 26968, "s": 26900, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 26992, "s": 26968, "text": "Find the Missing Number" } ]
Widening Primitive Conversion in Java - GeeksforGeeks
18 Dec, 2021 Whenever we do use double quotes around a letter or string as we all know it is treated as a string but when we do use a single quote round letter alongside performing some computations then they are treated as integers values while printing for which we must have knowledge of ASCII table concept as in computer for every character being case sensitive there is a specific integer value assigned to it at the backend which pops out widening of primitive datatype conversion. Refer to this ASCII table and just peek out as you no longer need to remember the value corresponding to each just remember popular values as it is sequentially defined over some intervals such as “a”, “A” and so on. Illustration: Widening primitive conversion is applied to convert either or both operands as specified by the following rules. The result of adding Java chars, shorts, or bytes is an int datatype under the following conditions as listed: If either operand is of type double, the other is converted to double. Otherwise, if either operand is of type float, the other is converted to float. Otherwise, if either operand is of type long, the other is converted to long. Otherwise, both operands are converted to type int Example 1: Java // Java Program to Illustrate// Widening Datatype Conversion// No Computations // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Printing values on console System.out.print("Y" + "O"); System.out.print('L'); System.out.print('O'); }} YOLO Output explanation: This will now print “YOLO” instead of “YO7679”. It is because the widening primitive conversion happens only when an operator like ‘+’ is present which expects at least an integer on both sides. Now let us adhere forward proposing another case as follows: Example 2: Java // Java Program to Illustrate// Widening Datatype Conversion// Computations is Carried Out // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Printing values on console System.out.print("Y" + "O"); // here computations is carried between letter // literal System.out.print('L' + 'O'); }} YO155 Output explanation: When we use double quotes, the text is treated as a string and “YO” is printed, but when we use single quotes, the characters ‘L’ and ‘O’ are converted to int. This is called widening primitive conversion. After conversion to integer, the numbers are added ( ‘L’ is 76 and ‘O’ is 79) and 155 is printed. This article is contributed by Anurag Rai. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. harshgundecha solankimayank kk773572498 Java-Data Types Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Object Oriented Programming (OOPs) Concept in Java Initialize an ArrayList in Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Multidimensional Arrays in Java Singleton Class in Java Multithreading in Java Set in Java
[ { "code": null, "e": 24358, "s": 24330, "text": "\n18 Dec, 2021" }, { "code": null, "e": 25051, "s": 24358, "text": "Whenever we do use double quotes around a letter or string as we all know it is treated as a string but when we do use a single quote round letter alongside performing some computations then they are treated as integers values while printing for which we must have knowledge of ASCII table concept as in computer for every character being case sensitive there is a specific integer value assigned to it at the backend which pops out widening of primitive datatype conversion. Refer to this ASCII table and just peek out as you no longer need to remember the value corresponding to each just remember popular values as it is sequentially defined over some intervals such as “a”, “A” and so on." }, { "code": null, "e": 25065, "s": 25051, "text": "Illustration:" }, { "code": null, "e": 25289, "s": 25065, "text": "Widening primitive conversion is applied to convert either or both operands as specified by the following rules. The result of adding Java chars, shorts, or bytes is an int datatype under the following conditions as listed:" }, { "code": null, "e": 25360, "s": 25289, "text": "If either operand is of type double, the other is converted to double." }, { "code": null, "e": 25440, "s": 25360, "text": "Otherwise, if either operand is of type float, the other is converted to float." }, { "code": null, "e": 25518, "s": 25440, "text": "Otherwise, if either operand is of type long, the other is converted to long." }, { "code": null, "e": 25569, "s": 25518, "text": "Otherwise, both operands are converted to type int" }, { "code": null, "e": 25580, "s": 25569, "text": "Example 1:" }, { "code": null, "e": 25585, "s": 25580, "text": "Java" }, { "code": "// Java Program to Illustrate// Widening Datatype Conversion// No Computations // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Printing values on console System.out.print(\"Y\" + \"O\"); System.out.print('L'); System.out.print('O'); }}", "e": 25932, "s": 25585, "text": null }, { "code": null, "e": 25937, "s": 25932, "text": "YOLO" }, { "code": null, "e": 25957, "s": 25937, "text": "Output explanation:" }, { "code": null, "e": 26213, "s": 25957, "text": "This will now print “YOLO” instead of “YO7679”. It is because the widening primitive conversion happens only when an operator like ‘+’ is present which expects at least an integer on both sides. Now let us adhere forward proposing another case as follows:" }, { "code": null, "e": 26224, "s": 26213, "text": "Example 2:" }, { "code": null, "e": 26229, "s": 26224, "text": "Java" }, { "code": "// Java Program to Illustrate// Widening Datatype Conversion// Computations is Carried Out // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Printing values on console System.out.print(\"Y\" + \"O\"); // here computations is carried between letter // literal System.out.print('L' + 'O'); }}", "e": 26639, "s": 26229, "text": null }, { "code": null, "e": 26645, "s": 26639, "text": "YO155" }, { "code": null, "e": 26666, "s": 26645, "text": "Output explanation: " }, { "code": null, "e": 26970, "s": 26666, "text": "When we use double quotes, the text is treated as a string and “YO” is printed, but when we use single quotes, the characters ‘L’ and ‘O’ are converted to int. This is called widening primitive conversion. After conversion to integer, the numbers are added ( ‘L’ is 76 and ‘O’ is 79) and 155 is printed." }, { "code": null, "e": 27235, "s": 26970, "text": "This article is contributed by Anurag Rai. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27251, "s": 27237, "text": "harshgundecha" }, { "code": null, "e": 27265, "s": 27251, "text": "solankimayank" }, { "code": null, "e": 27277, "s": 27265, "text": "kk773572498" }, { "code": null, "e": 27293, "s": 27277, "text": "Java-Data Types" }, { "code": null, "e": 27298, "s": 27293, "text": "Java" }, { "code": null, "e": 27303, "s": 27298, "text": "Java" }, { "code": null, "e": 27401, "s": 27303, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27410, "s": 27401, "text": "Comments" }, { "code": null, "e": 27423, "s": 27410, "text": "Old Comments" }, { "code": null, "e": 27453, "s": 27423, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27504, "s": 27453, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27536, "s": 27504, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27555, "s": 27536, "text": "Interfaces in Java" }, { "code": null, "e": 27586, "s": 27555, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27604, "s": 27586, "text": "ArrayList in Java" }, { "code": null, "e": 27636, "s": 27604, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27660, "s": 27636, "text": "Singleton Class in Java" }, { "code": null, "e": 27683, "s": 27660, "text": "Multithreading in Java" } ]
Tiling with Dominoes - GeeksforGeeks
08 Nov, 2021 Given a 3 x n board, find the number of ways to fill it with 2 x 1 dominoes.Example 1 Following are all the 3 possible ways to fill up a 3 x 2 board. Example 2 Here is one possible way of filling a 3 x 8 board. You have to find all the possible ways to do so. Examples : Input : 2 Output : 3 Input : 8 Output : 153 Input : 12 Output : 2131 Defining Subproblems: At any point while filling the board, there are three possible states that the last column can be in: An = No. of ways to completely fill a 3 x n board. (We need to find this) Bn = No. of ways to fill a 3 x n board with top corner in last column not filled. Cn = No. of ways to fill a 3 x n board with bottom corner in last column not filled. Note: The following states are impossible to reach: Finding Reccurences Note: Even though Bn and Cn are different states, they will be equal for same ‘n’. i.e Bn = Cn Hence, we only need to calculate one of them.Calculating An: Calculating Bn: Final Recursive Relations are: Base Cases: C++ Java Python 3 C# Javascript PHP // C++ program to find no. of ways// to fill a 3xn board with 2x1 dominoes.#include <iostream>using namespace std; int countWays(int n){ int A[n + 1], B[n + 1]; A[0] = 1, A[1] = 0, B[0] = 0, B[1] = 1; for (int i = 2; i <= n; i++) { A[i] = A[i - 2] + 2 * B[i - 1]; B[i] = A[i - 1] + B[i - 2]; } return A[n];} int main(){ int n = 8; cout << countWays(n); return 0;} // Java program to find no. of ways// to fill a 3xn board with 2x1 dominoes.import java.io.*; class GFG { static int countWays(int n) { int []A = new int[n+1]; int []B = new int[n+1]; A[0] = 1; A[1] = 0; B[0] = 0; B[1] = 1; for (int i = 2; i <= n; i++) { A[i] = A[i - 2] + 2 * B[i - 1]; B[i] = A[i - 1] + B[i - 2]; } return A[n]; } // Driver code public static void main (String[] args) { int n = 8; System.out.println(countWays(n)); }} // This code is contributed by anuj_67. # Python 3 program to find no. of ways# to fill a 3xn board with 2x1 dominoes. def countWays(n): A = [0] * (n + 1) B = [0] * (n + 1) A[0] = 1 A[1] = 0 B[0] = 0 B[1] = 1 for i in range(2, n+1): A[i] = A[i - 2] + 2 * B[i - 1] B[i] = A[i - 1] + B[i - 2] return A[n] n = 8print(countWays(n)) # This code is contributed by Smitha // C# program to find no. of ways// to fill a 3xn board with 2x1 dominoes.using System; class GFG { static int countWays(int n) { int []A = new int[n+1]; int []B = new int[n+1]; A[0] = 1; A[1] = 0; B[0] = 0; B[1] = 1; for (int i = 2; i <= n; i++) { A[i] = A[i - 2] + 2 * B[i - 1]; B[i] = A[i - 1] + B[i - 2]; } return A[n]; } // Driver code public static void Main () { int n = 8; Console.WriteLine(countWays(n)); }} // This code is contributed by anuj_67. <script> // Javascript program to find no. of ways // to fill a 3xn board with 2x1 dominoes. function countWays(n) { let A = new Array(n+1); let B = new Array(n+1); A[0] = 1; A[1] = 0; B[0] = 0; B[1] = 1; for (let i = 2; i <= n; i++) { A[i] = A[i - 2] + 2 * B[i - 1]; B[i] = A[i - 1] + B[i - 2]; } return A[n]; } let n = 8; document.write(countWays(n)); // This code is contributed by rameshtravel07.</script> <?php// PHP program to find no. of ways// to fill a 3xn board with 2x1 dominoes. function countWays($n){ $A = array(); $B = array(); $A[0] = 1; $A[1] = 0; $B[0] = 0; $B[1] = 1; for ( $i = 2; $i <= $n; $i++) { $A[$i] = $A[$i - 2] + 2 * $B[$i - 1]; $B[$i] = $A[$i - 1] + $B[$i - 2]; } return $A[$n];} // Driver Code$n = 8;echo countWays($n); // This code is contributed by anuj_67.?> 153 vt_m Smitha Dinesh Semwal rameshtravel07 Competitive Programming Dynamic Programming Recursion Dynamic Programming Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Breadth First Traversal ( BFS ) on a 2D array Shortest path in a directed graph by Dijkstra’s algorithm Runtime Errors Multistage Graph (Shortest Path) Most important type of Algorithms 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Largest Sum Contiguous Subarray Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23
[ { "code": null, "e": 25126, "s": 25098, "text": "\n08 Nov, 2021" }, { "code": null, "e": 25278, "s": 25126, "text": "Given a 3 x n board, find the number of ways to fill it with 2 x 1 dominoes.Example 1 Following are all the 3 possible ways to fill up a 3 x 2 board. " }, { "code": null, "e": 25390, "s": 25278, "text": "Example 2 Here is one possible way of filling a 3 x 8 board. You have to find all the possible ways to do so. " }, { "code": null, "e": 25403, "s": 25390, "text": "Examples : " }, { "code": null, "e": 25474, "s": 25403, "text": "Input : 2\nOutput : 3\n\nInput : 8\nOutput : 153\n\nInput : 12\nOutput : 2131" }, { "code": null, "e": 25602, "s": 25476, "text": "Defining Subproblems: At any point while filling the board, there are three possible states that the last column can be in: " }, { "code": null, "e": 25848, "s": 25604, "text": "An = No. of ways to completely fill a 3 x n board. (We need to find this)\nBn = No. of ways to fill a 3 x n board with top corner in last column not filled.\nCn = No. of ways to fill a 3 x n board with bottom corner in last column not filled." }, { "code": null, "e": 25902, "s": 25848, "text": "Note: The following states are impossible to reach: " }, { "code": null, "e": 26080, "s": 25902, "text": "Finding Reccurences Note: Even though Bn and Cn are different states, they will be equal for same ‘n’. i.e Bn = Cn Hence, we only need to calculate one of them.Calculating An: " }, { "code": null, "e": 26098, "s": 26080, "text": "Calculating Bn: " }, { "code": null, "e": 26131, "s": 26098, "text": "Final Recursive Relations are: " }, { "code": null, "e": 26147, "s": 26133, "text": "Base Cases: " }, { "code": null, "e": 26155, "s": 26151, "text": "C++" }, { "code": null, "e": 26160, "s": 26155, "text": "Java" }, { "code": null, "e": 26169, "s": 26160, "text": "Python 3" }, { "code": null, "e": 26172, "s": 26169, "text": "C#" }, { "code": null, "e": 26183, "s": 26172, "text": "Javascript" }, { "code": null, "e": 26187, "s": 26183, "text": "PHP" }, { "code": "// C++ program to find no. of ways// to fill a 3xn board with 2x1 dominoes.#include <iostream>using namespace std; int countWays(int n){ int A[n + 1], B[n + 1]; A[0] = 1, A[1] = 0, B[0] = 0, B[1] = 1; for (int i = 2; i <= n; i++) { A[i] = A[i - 2] + 2 * B[i - 1]; B[i] = A[i - 1] + B[i - 2]; } return A[n];} int main(){ int n = 8; cout << countWays(n); return 0;}", "e": 26590, "s": 26187, "text": null }, { "code": "// Java program to find no. of ways// to fill a 3xn board with 2x1 dominoes.import java.io.*; class GFG { static int countWays(int n) { int []A = new int[n+1]; int []B = new int[n+1]; A[0] = 1; A[1] = 0; B[0] = 0; B[1] = 1; for (int i = 2; i <= n; i++) { A[i] = A[i - 2] + 2 * B[i - 1]; B[i] = A[i - 1] + B[i - 2]; } return A[n]; } // Driver code public static void main (String[] args) { int n = 8; System.out.println(countWays(n)); }} // This code is contributed by anuj_67.", "e": 27187, "s": 26590, "text": null }, { "code": "# Python 3 program to find no. of ways# to fill a 3xn board with 2x1 dominoes. def countWays(n): A = [0] * (n + 1) B = [0] * (n + 1) A[0] = 1 A[1] = 0 B[0] = 0 B[1] = 1 for i in range(2, n+1): A[i] = A[i - 2] + 2 * B[i - 1] B[i] = A[i - 1] + B[i - 2] return A[n] n = 8print(countWays(n)) # This code is contributed by Smitha", "e": 27556, "s": 27187, "text": null }, { "code": "// C# program to find no. of ways// to fill a 3xn board with 2x1 dominoes.using System; class GFG { static int countWays(int n) { int []A = new int[n+1]; int []B = new int[n+1]; A[0] = 1; A[1] = 0; B[0] = 0; B[1] = 1; for (int i = 2; i <= n; i++) { A[i] = A[i - 2] + 2 * B[i - 1]; B[i] = A[i - 1] + B[i - 2]; } return A[n]; } // Driver code public static void Main () { int n = 8; Console.WriteLine(countWays(n)); }} // This code is contributed by anuj_67.", "e": 28133, "s": 27556, "text": null }, { "code": "<script> // Javascript program to find no. of ways // to fill a 3xn board with 2x1 dominoes. function countWays(n) { let A = new Array(n+1); let B = new Array(n+1); A[0] = 1; A[1] = 0; B[0] = 0; B[1] = 1; for (let i = 2; i <= n; i++) { A[i] = A[i - 2] + 2 * B[i - 1]; B[i] = A[i - 1] + B[i - 2]; } return A[n]; } let n = 8; document.write(countWays(n)); // This code is contributed by rameshtravel07.</script>", "e": 28669, "s": 28133, "text": null }, { "code": "<?php// PHP program to find no. of ways// to fill a 3xn board with 2x1 dominoes. function countWays($n){ $A = array(); $B = array(); $A[0] = 1; $A[1] = 0; $B[0] = 0; $B[1] = 1; for ( $i = 2; $i <= $n; $i++) { $A[$i] = $A[$i - 2] + 2 * $B[$i - 1]; $B[$i] = $A[$i - 1] + $B[$i - 2]; } return $A[$n];} // Driver Code$n = 8;echo countWays($n); // This code is contributed by anuj_67.?>", "e": 29122, "s": 28669, "text": null }, { "code": null, "e": 29126, "s": 29122, "text": "153" }, { "code": null, "e": 29133, "s": 29128, "text": "vt_m" }, { "code": null, "e": 29154, "s": 29133, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 29169, "s": 29154, "text": "rameshtravel07" }, { "code": null, "e": 29193, "s": 29169, "text": "Competitive Programming" }, { "code": null, "e": 29213, "s": 29193, "text": "Dynamic Programming" }, { "code": null, "e": 29223, "s": 29213, "text": "Recursion" }, { "code": null, "e": 29243, "s": 29223, "text": "Dynamic Programming" }, { "code": null, "e": 29253, "s": 29243, "text": "Recursion" }, { "code": null, "e": 29351, "s": 29253, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29397, "s": 29351, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 29455, "s": 29397, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 29470, "s": 29455, "text": "Runtime Errors" }, { "code": null, "e": 29503, "s": 29470, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 29537, "s": 29503, "text": "Most important type of Algorithms" }, { "code": null, "e": 29566, "s": 29537, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 29596, "s": 29566, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29628, "s": 29596, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 29662, "s": 29628, "text": "Longest Common Subsequence | DP-4" } ]
Static Keyword in C++ - GeeksQuiz
29 Jul, 2020 #include <iostream > using namespace std; class A { private: int x; public: A(int _x) { x = _x; } int get() { return x; } }; class B { static A a; public: static int get() { return a.get(); } }; A B::a(0); int main(void) { B b; cout << b.get(); return 0; } Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Product Based Companies Difference between var, let and const keywords in JavaScript Array of Objects in C++ with Examples How to Convert Categorical Variable to Numeric in Pandas? How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python C Program to read contents of Whole File How to Replace Values in a List in Python? How to Drop Rows that Contain a Specific String in Pandas? How to Read Text Files with Pandas?
[ { "code": null, "e": 27610, "s": 27582, "text": "\n29 Jul, 2020" }, { "code": null, "e": 27910, "s": 27610, "text": "#include <iostream >\nusing namespace std;\n\nclass A\n{\nprivate:\n int x;\npublic:\n A(int _x) { x = _x; }\n int get() { return x; }\n};\n\nclass B\n{\n static A a;\npublic:\n static int get()\n { return a.get(); }\n};\n\nA B::a(0);\n\nint main(void)\n{\n B b;\n cout << b.get();\n return 0;\n}\n" }, { "code": null, "e": 28008, "s": 27910, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 28061, "s": 28008, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 28122, "s": 28061, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28160, "s": 28122, "text": "Array of Objects in C++ with Examples" }, { "code": null, "e": 28218, "s": 28160, "text": "How to Convert Categorical Variable to Numeric in Pandas?" }, { "code": null, "e": 28280, "s": 28218, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 28360, "s": 28280, "text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python" }, { "code": null, "e": 28401, "s": 28360, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 28444, "s": 28401, "text": "How to Replace Values in a List in Python?" }, { "code": null, "e": 28503, "s": 28444, "text": "How to Drop Rows that Contain a Specific String in Pandas?" } ]
Scikit Learn - Bayesian Ridge Regression
Bayesian regression allows a natural mechanism to survive insufficient data or poorly distributed data by formulating linear regression using probability distributors rather than point estimates. The output or response ‘y’ is assumed to drawn from a probability distribution rather than estimated as a single value. Mathematically, to obtain a fully probabilistic model the response y is assumed to be Gaussian distributed around XwXas follows One of the most useful type of Bayesian regression is Bayesian Ridge regression which estimates a probabilistic model of the regression problem. Here the prior for the coefficient w is given by spherical Gaussian as follows − This resulting model is called Bayesian Ridge Regression and in scikit-learn sklearn.linear_model.BeyesianRidge module is used for Bayesian Ridge Regression. Followings table consist the parameters used by BayesianRidge module − n_iter − int, optional It represents the maximum number of iterations. The default value is 300 but the user-defined value must be greater than or equal to 1. fit_intercept − Boolean, optional, default True It decides whether to calculate the intercept for this model or not. No intercept will be used in calculation, if it will set to false. tol − float, optional, default=1.e-3 It represents the precision of the solution and will stop the algorithm if w has converged. alpha_1 − float, optional, default=1.e-6 It is the 1st hyperparameter which is a shape parameter for the Gamma distribution prior over the alpha parameter. alpha_2 − float, optional, default=1.e-6 It is the 2nd hyperparameter which is an inverse scale parameter for the Gamma distribution prior over the alpha parameter. lambda_1 − float, optional, default=1.e-6 It is the 1st hyperparameter which is a shape parameter for the Gamma distribution prior over the lambda parameter. lambda_2 − float, optional, default=1.e-6 It is the 2nd hyperparameter which is an inverse scale parameter for the Gamma distribution prior over the lambda parameter. copy_X − Boolean, optional, default = True By default, it is true which means X will be copied. But if it is set to false, X may be overwritten. compute_score − boolean, optional, default=False If set to true, it computes the log marginal likelihood at each iteration of the optimization. verbose − Boolean, optional, default=False By default, it is false but if set true, verbose mode will be enabled while fitting the model. Followings table consist the attributes used by BayesianRidge module − coef_ − array, shape = n_features This attribute provides the weight vectors. intercept_ − float It represents the independent term in decision function. alpha_ − float This attribute provides the estimated precision of the noise. lambda_ − float This attribute provides the estimated precision of the weight. n_iter_ − int It provides the actual number of iterations taken by the algorithm to reach the stopping criterion. sigma_ − array, shape = (n_features, n_features) It provides the estimated variance-covariance matrix of the weights. scores_ − array, shape = (n_iter_+1) It provides the value of the log marginal likelihood at each iteration of the optimisation. In the resulting score, the array starts with the value of the log marginal likelihood obtained for the initial values of aandλλ, and ends with the value obtained for estimated aandλ. Following Python script provides a simple example of fitting Bayesian Ridge Regression model using sklearn BayesianRidge module. from sklearn import linear_model X = [[0, 0], [1, 1], [2, 2], [3, 3]] Y = [0, 1, 2, 3] BayReg = linear_model.BayesianRidge() BayReg.fit(X, Y) BayesianRidge(alpha_1 = 1e-06, alpha_2 = 1e-06, compute_score = False, copy_X = True, fit_intercept = True, lambda_1 = 1e-06, lambda_2 = 1e-06, n_iter = 300, normalize = False, tol=0.001, verbose = False) From the above output, we can check model’s parameters used in the calculation. Now, once fitted, the model can predict new values as follows − BayReg.predict([[1,1]]) array([1.00000007]) Similarly, we can access the coefficient w of the model as follows − BayReg.coef_ array([0.49999993, 0.49999993]) 11 Lectures 2 hours PARTHA MAJUMDAR Print Add Notes Bookmark this page
[ { "code": null, "e": 2537, "s": 2221, "text": "Bayesian regression allows a natural mechanism to survive insufficient data or poorly distributed data by formulating linear regression using probability distributors rather than point estimates. The output or response ‘y’ is assumed to drawn from a probability distribution rather than estimated as a single value." }, { "code": null, "e": 2665, "s": 2537, "text": "Mathematically, to obtain a fully probabilistic model the response y is assumed to be Gaussian distributed around XwXas follows" }, { "code": null, "e": 2891, "s": 2665, "text": "One of the most useful type of Bayesian regression is Bayesian Ridge regression which estimates a probabilistic model of the regression problem. Here the prior for the coefficient w is given by spherical Gaussian as follows −" }, { "code": null, "e": 3049, "s": 2891, "text": "This resulting model is called Bayesian Ridge Regression and in scikit-learn sklearn.linear_model.BeyesianRidge module is used for Bayesian Ridge Regression." }, { "code": null, "e": 3120, "s": 3049, "text": "Followings table consist the parameters used by BayesianRidge module −" }, { "code": null, "e": 3143, "s": 3120, "text": "n_iter − int, optional" }, { "code": null, "e": 3279, "s": 3143, "text": "It represents the maximum number of iterations. The default value is 300 but the user-defined value must be greater than or equal to 1." }, { "code": null, "e": 3327, "s": 3279, "text": "fit_intercept − Boolean, optional, default True" }, { "code": null, "e": 3463, "s": 3327, "text": "It decides whether to calculate the intercept for this model or not. No intercept will be used in calculation, if it will set to false." }, { "code": null, "e": 3500, "s": 3463, "text": "tol − float, optional, default=1.e-3" }, { "code": null, "e": 3592, "s": 3500, "text": "It represents the precision of the solution and will stop the algorithm if w has converged." }, { "code": null, "e": 3633, "s": 3592, "text": "alpha_1 − float, optional, default=1.e-6" }, { "code": null, "e": 3748, "s": 3633, "text": "It is the 1st hyperparameter which is a shape parameter for the Gamma distribution prior over the alpha parameter." }, { "code": null, "e": 3789, "s": 3748, "text": "alpha_2 − float, optional, default=1.e-6" }, { "code": null, "e": 3913, "s": 3789, "text": "It is the 2nd hyperparameter which is an inverse scale parameter for the Gamma distribution prior over the alpha parameter." }, { "code": null, "e": 3955, "s": 3913, "text": "lambda_1 − float, optional, default=1.e-6" }, { "code": null, "e": 4071, "s": 3955, "text": "It is the 1st hyperparameter which is a shape parameter for the Gamma distribution prior over the lambda parameter." }, { "code": null, "e": 4113, "s": 4071, "text": "lambda_2 − float, optional, default=1.e-6" }, { "code": null, "e": 4238, "s": 4113, "text": "It is the 2nd hyperparameter which is an inverse scale parameter for the Gamma distribution prior over the lambda parameter." }, { "code": null, "e": 4281, "s": 4238, "text": "copy_X − Boolean, optional, default = True" }, { "code": null, "e": 4383, "s": 4281, "text": "By default, it is true which means X will be copied. But if it is set to false, X may be overwritten." }, { "code": null, "e": 4432, "s": 4383, "text": "compute_score − boolean, optional, default=False" }, { "code": null, "e": 4527, "s": 4432, "text": "If set to true, it computes the log marginal likelihood at each iteration of the optimization." }, { "code": null, "e": 4570, "s": 4527, "text": "verbose − Boolean, optional, default=False" }, { "code": null, "e": 4665, "s": 4570, "text": "By default, it is false but if set true, verbose mode will be enabled while fitting the model." }, { "code": null, "e": 4736, "s": 4665, "text": "Followings table consist the attributes used by BayesianRidge module −" }, { "code": null, "e": 4770, "s": 4736, "text": "coef_ − array, shape = n_features" }, { "code": null, "e": 4814, "s": 4770, "text": "This attribute provides the weight vectors." }, { "code": null, "e": 4833, "s": 4814, "text": "intercept_ − float" }, { "code": null, "e": 4890, "s": 4833, "text": "It represents the independent term in decision function." }, { "code": null, "e": 4905, "s": 4890, "text": "alpha_ − float" }, { "code": null, "e": 4967, "s": 4905, "text": "This attribute provides the estimated precision of the noise." }, { "code": null, "e": 4983, "s": 4967, "text": "lambda_ − float" }, { "code": null, "e": 5046, "s": 4983, "text": "This attribute provides the estimated precision of the weight." }, { "code": null, "e": 5060, "s": 5046, "text": "n_iter_ − int" }, { "code": null, "e": 5160, "s": 5060, "text": "It provides the actual number of iterations taken by the algorithm to reach the stopping criterion." }, { "code": null, "e": 5209, "s": 5160, "text": "sigma_ − array, shape = (n_features, n_features)" }, { "code": null, "e": 5278, "s": 5209, "text": "It provides the estimated variance-covariance matrix of the weights." }, { "code": null, "e": 5315, "s": 5278, "text": "scores_ − array, shape = (n_iter_+1)" }, { "code": null, "e": 5591, "s": 5315, "text": "It provides the value of the log marginal likelihood at each iteration of the optimisation. In the resulting score, the array starts with the value of the log marginal likelihood obtained for the initial values of aandλλ, and ends with the value obtained for estimated aandλ." }, { "code": null, "e": 5720, "s": 5591, "text": "Following Python script provides a simple example of fitting Bayesian Ridge Regression model using sklearn BayesianRidge module." }, { "code": null, "e": 5862, "s": 5720, "text": "from sklearn import linear_model\nX = [[0, 0], [1, 1], [2, 2], [3, 3]]\nY = [0, 1, 2, 3]\nBayReg = linear_model.BayesianRidge()\nBayReg.fit(X, Y)" }, { "code": null, "e": 6074, "s": 5862, "text": "BayesianRidge(alpha_1 = 1e-06, alpha_2 = 1e-06, compute_score = False, copy_X = True,\n fit_intercept = True, lambda_1 = 1e-06, lambda_2 = 1e-06, n_iter = 300,\n normalize = False, tol=0.001, verbose = False)\n" }, { "code": null, "e": 6154, "s": 6074, "text": "From the above output, we can check model’s parameters used in the calculation." }, { "code": null, "e": 6218, "s": 6154, "text": "Now, once fitted, the model can predict new values as follows −" }, { "code": null, "e": 6242, "s": 6218, "text": "BayReg.predict([[1,1]])" }, { "code": null, "e": 6263, "s": 6242, "text": "array([1.00000007])\n" }, { "code": null, "e": 6332, "s": 6263, "text": "Similarly, we can access the coefficient w of the model as follows −" }, { "code": null, "e": 6345, "s": 6332, "text": "BayReg.coef_" }, { "code": null, "e": 6378, "s": 6345, "text": "array([0.49999993, 0.49999993])\n" }, { "code": null, "e": 6411, "s": 6378, "text": "\n 11 Lectures \n 2 hours \n" }, { "code": null, "e": 6428, "s": 6411, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 6435, "s": 6428, "text": " Print" }, { "code": null, "e": 6446, "s": 6435, "text": " Add Notes" } ]
Sort by index of an array in JavaScript
Suppose we have the following array of objects − const arr = [ { 'name' : 'd', 'index' : 3 }, { 'name' : 'c', 'index' : 2 }, { 'name' : 'a', 'index' : 0 }, { 'name' : 'b', 'index' : 1 } ]; We are required to write a JavaScript function that takes in one such array. The function should sort this array in increasing order according to the index property of objects. Then the function should map the sorted array to an array of strings where each string is the corresponding name property value of the object. Therefore, for the above array, the final output should look like − const output = ["a", "b", "c", "d"]; The code for this will be − const arr = [ { 'name' : 'd', 'index' : 3 }, { 'name' : 'c', 'index' : 2 }, { 'name' : 'a', 'index' : 0 }, { 'name' : 'b', 'index' : 1 } ]; const sortAndMap = (arr = []) => { const copy = arr.slice(); const sorter = (a, b) => { return a['index'] - b['index']; }; copy.sort(sorter); const res = copy.map(({name, index}) => { return name; }); return res; }; console.log(sortAndMap(arr)); And the output in the console will be − [ 'a', 'b', 'c', 'd' ]
[ { "code": null, "e": 1111, "s": 1062, "text": "Suppose we have the following array of objects −" }, { "code": null, "e": 1323, "s": 1111, "text": "const arr = [\n {\n 'name' : 'd',\n 'index' : 3\n },\n {\n 'name' : 'c',\n 'index' : 2\n },\n {\n 'name' : 'a',\n 'index' : 0\n },\n {\n 'name' : 'b',\n 'index' : 1\n }\n];" }, { "code": null, "e": 1400, "s": 1323, "text": "We are required to write a JavaScript function that takes in one such array." }, { "code": null, "e": 1500, "s": 1400, "text": "The function should sort this array in increasing order according to the index property of objects." }, { "code": null, "e": 1643, "s": 1500, "text": "Then the function should map the sorted array to an array of strings where each string is the corresponding name property value of the object." }, { "code": null, "e": 1711, "s": 1643, "text": "Therefore, for the above array, the final output should look like −" }, { "code": null, "e": 1748, "s": 1711, "text": "const output = [\"a\", \"b\", \"c\", \"d\"];" }, { "code": null, "e": 1776, "s": 1748, "text": "The code for this will be −" }, { "code": null, "e": 2267, "s": 1776, "text": "const arr = [\n {\n 'name' : 'd',\n 'index' : 3\n },\n {\n 'name' : 'c',\n 'index' : 2\n },\n {\n 'name' : 'a',\n 'index' : 0\n },\n {\n 'name' : 'b',\n 'index' : 1\n }\n];\nconst sortAndMap = (arr = []) => {\n const copy = arr.slice();\n const sorter = (a, b) => {\n return a['index'] - b['index'];\n };\n copy.sort(sorter);\n const res = copy.map(({name, index}) => {\n return name;\n });\n return res;\n};\nconsole.log(sortAndMap(arr));" }, { "code": null, "e": 2307, "s": 2267, "text": "And the output in the console will be −" }, { "code": null, "e": 2330, "s": 2307, "text": "[ 'a', 'b', 'c', 'd' ]" } ]
Data Structures and Algorithms - Arrays
Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of Array. Element − Each item stored in an array is called an element. Element − Each item stored in an array is called an element. Index − Each location of an element in an array has a numerical index, which is used to identify the element. Index − Each location of an element in an array has a numerical index, which is used to identify the element. Arrays can be declared in various ways in different languages. For illustration, let's take C array declaration. Arrays can be declared in various ways in different languages. For illustration, let's take C array declaration. As per the above illustration, following are the important points to be considered. Index starts with 0. Index starts with 0. Array length is 10 which means it can store 10 elements. Array length is 10 which means it can store 10 elements. Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9. Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9. Following are the basic operations supported by an array. Traverse − print all the array elements one by one. Traverse − print all the array elements one by one. Insertion − Adds an element at the given index. Insertion − Adds an element at the given index. Deletion − Deletes an element at the given index. Deletion − Deletes an element at the given index. Search − Searches an element using the given index or by the value. Search − Searches an element using the given index or by the value. Update − Updates an element at the given index. Update − Updates an element at the given index. In C, when an array is initialized with size, then it assigns defaults values to its elements in following order. This operation is to traverse through the elements of an array. Following program traverses and prints the elements of an array: #include <stdio.h> main() { int LA[] = {1,3,5,7,8}; int item = 10, k = 3, n = 5; int i = 0, j = n; printf("The original array elements are :\n"); for(i = 0; i<n; i++) { printf("LA[%d] = %d \n", i, LA[i]); } } When we compile and execute the above program, it produces the following result − The original array elements are : LA[0] = 1 LA[1] = 3 LA[2] = 5 LA[3] = 7 LA[4] = 8 Insert operation is to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array. Here, we see a practical implementation of insertion operation, where we add data at the end of the array − Following is the implementation of the above algorithm − #include <stdio.h> main() { int LA[] = {1,3,5,7,8}; int item = 10, k = 3, n = 5; int i = 0, j = n; printf("The original array elements are :\n"); for(i = 0; i<n; i++) { printf("LA[%d] = %d \n", i, LA[i]); } n = n + 1; while( j >= k) { LA[j+1] = LA[j]; j = j - 1; } LA[k] = item; printf("The array elements after insertion :\n"); for(i = 0; i<n; i++) { printf("LA[%d] = %d \n", i, LA[i]); } } When we compile and execute the above program, it produces the following result − The original array elements are : LA[0] = 1 LA[1] = 3 LA[2] = 5 LA[3] = 7 LA[4] = 8 The array elements after insertion : LA[0] = 1 LA[1] = 3 LA[2] = 5 LA[3] = 10 LA[4] = 7 LA[5] = 8 For other variations of array insertion operation click here Deletion refers to removing an existing element from the array and re-organizing all elements of an array. Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Following is the algorithm to delete an element available at the Kth position of LA. 1. Start 2. Set J = K 3. Repeat steps 4 and 5 while J < N 4. Set LA[J] = LA[J + 1] 5. Set J = J+1 6. Set N = N-1 7. Stop Following is the implementation of the above algorithm − #include <stdio.h> void main() { int LA[] = {1,3,5,7,8}; int k = 3, n = 5; int i, j; printf("The original array elements are :\n"); for(i = 0; i<n; i++) { printf("LA[%d] = %d \n", i, LA[i]); } j = k; while( j < n) { LA[j-1] = LA[j]; j = j + 1; } n = n -1; printf("The array elements after deletion :\n"); for(i = 0; i<n; i++) { printf("LA[%d] = %d \n", i, LA[i]); } } When we compile and execute the above program, it produces the following result − The original array elements are : LA[0] = 1 LA[1] = 3 LA[2] = 5 LA[3] = 7 LA[4] = 8 The array elements after deletion : LA[0] = 1 LA[1] = 3 LA[2] = 7 LA[3] = 8 You can perform a search for an array element based on its value or its index. Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Following is the algorithm to find an element with a value of ITEM using sequential search. 1. Start 2. Set J = 0 3. Repeat steps 4 and 5 while J < N 4. IF LA[J] is equal ITEM THEN GOTO STEP 6 5. Set J = J +1 6. PRINT J, ITEM 7. Stop Following is the implementation of the above algorithm − #include <stdio.h> void main() { int LA[] = {1,3,5,7,8}; int item = 5, n = 5; int i = 0, j = 0; printf("The original array elements are :\n"); for(i = 0; i<n; i++) { printf("LA[%d] = %d \n", i, LA[i]); } while( j < n){ if( LA[j] == item ) { break; } j = j + 1; } printf("Found element %d at position %d\n", item, j+1); } When we compile and execute the above program, it produces the following result − The original array elements are : LA[0] = 1 LA[1] = 3 LA[2] = 5 LA[3] = 7 LA[4] = 8 Found element 5 at position 3 Update operation refers to updating an existing element from the array at a given index. Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Following is the algorithm to update an element available at the Kth position of LA. 1. Start 2. Set LA[K-1] = ITEM 3. Stop Following is the implementation of the above algorithm − #include <stdio.h> void main() { int LA[] = {1,3,5,7,8}; int k = 3, n = 5, item = 10; int i, j; printf("The original array elements are :\n"); for(i = 0; i<n; i++) { printf("LA[%d] = %d \n", i, LA[i]); } LA[k-1] = item; printf("The array elements after updation :\n"); for(i = 0; i<n; i++) { printf("LA[%d] = %d \n", i, LA[i]); } } When we compile and execute the above program, it produces the following result − The original array elements are : LA[0] = 1 LA[1] = 3 LA[2] = 5 LA[3] = 7 LA[4] = 8 The array elements after updation : LA[0] = 1 LA[1] = 3 LA[2] = 10 LA[3] = 7 LA[4] = 8 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2830, "s": 2580, "text": "Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of Array." }, { "code": null, "e": 2891, "s": 2830, "text": "Element − Each item stored in an array is called an element." }, { "code": null, "e": 2952, "s": 2891, "text": "Element − Each item stored in an array is called an element." }, { "code": null, "e": 3062, "s": 2952, "text": "Index − Each location of an element in an array has a numerical index, which is used to identify the element." }, { "code": null, "e": 3172, "s": 3062, "text": "Index − Each location of an element in an array has a numerical index, which is used to identify the element." }, { "code": null, "e": 3285, "s": 3172, "text": "Arrays can be declared in various ways in different languages. For illustration, let's take C array declaration." }, { "code": null, "e": 3398, "s": 3285, "text": "Arrays can be declared in various ways in different languages. For illustration, let's take C array declaration." }, { "code": null, "e": 3482, "s": 3398, "text": "As per the above illustration, following are the important points to be considered." }, { "code": null, "e": 3503, "s": 3482, "text": "Index starts with 0." }, { "code": null, "e": 3524, "s": 3503, "text": "Index starts with 0." }, { "code": null, "e": 3581, "s": 3524, "text": "Array length is 10 which means it can store 10 elements." }, { "code": null, "e": 3638, "s": 3581, "text": "Array length is 10 which means it can store 10 elements." }, { "code": null, "e": 3736, "s": 3638, "text": "Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9." }, { "code": null, "e": 3834, "s": 3736, "text": "Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9." }, { "code": null, "e": 3892, "s": 3834, "text": "Following are the basic operations supported by an array." }, { "code": null, "e": 3944, "s": 3892, "text": "Traverse − print all the array elements one by one." }, { "code": null, "e": 3996, "s": 3944, "text": "Traverse − print all the array elements one by one." }, { "code": null, "e": 4044, "s": 3996, "text": "Insertion − Adds an element at the given index." }, { "code": null, "e": 4092, "s": 4044, "text": "Insertion − Adds an element at the given index." }, { "code": null, "e": 4142, "s": 4092, "text": "Deletion − Deletes an element at the given index." }, { "code": null, "e": 4192, "s": 4142, "text": "Deletion − Deletes an element at the given index." }, { "code": null, "e": 4260, "s": 4192, "text": "Search − Searches an element using the given index or by the value." }, { "code": null, "e": 4328, "s": 4260, "text": "Search − Searches an element using the given index or by the value." }, { "code": null, "e": 4376, "s": 4328, "text": "Update − Updates an element at the given index." }, { "code": null, "e": 4424, "s": 4376, "text": "Update − Updates an element at the given index." }, { "code": null, "e": 4538, "s": 4424, "text": "In C, when an array is initialized with size, then it assigns defaults values to its elements in following order." }, { "code": null, "e": 4602, "s": 4538, "text": "This operation is to traverse through the elements of an array." }, { "code": null, "e": 4667, "s": 4602, "text": "Following program traverses and prints the elements of an array:" }, { "code": null, "e": 4903, "s": 4667, "text": "#include <stdio.h>\nmain() {\n int LA[] = {1,3,5,7,8};\n int item = 10, k = 3, n = 5;\n int i = 0, j = n; \n printf(\"The original array elements are :\\n\");\n for(i = 0; i<n; i++) {\n printf(\"LA[%d] = %d \\n\", i, LA[i]);\n }\n}" }, { "code": null, "e": 4985, "s": 4903, "text": "When we compile and execute the above program, it produces the following result −" }, { "code": null, "e": 5075, "s": 4985, "text": "The original array elements are :\nLA[0] = 1 \nLA[1] = 3 \nLA[2] = 5 \nLA[3] = 7 \nLA[4] = 8 \n" }, { "code": null, "e": 5251, "s": 5075, "text": "Insert operation is to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array." }, { "code": null, "e": 5359, "s": 5251, "text": "Here, we see a practical implementation of insertion operation, where we add data at the end of the array −" }, { "code": null, "e": 5416, "s": 5359, "text": "Following is the implementation of the above algorithm −" }, { "code": null, "e": 5883, "s": 5416, "text": "#include <stdio.h>\n\nmain() {\n int LA[] = {1,3,5,7,8};\n int item = 10, k = 3, n = 5;\n int i = 0, j = n;\n \n printf(\"The original array elements are :\\n\");\n\n for(i = 0; i<n; i++) {\n printf(\"LA[%d] = %d \\n\", i, LA[i]);\n }\n\n n = n + 1;\n\t\n while( j >= k) {\n LA[j+1] = LA[j];\n j = j - 1;\n }\n\n LA[k] = item;\n\n printf(\"The array elements after insertion :\\n\");\n\n for(i = 0; i<n; i++) {\n printf(\"LA[%d] = %d \\n\", i, LA[i]);\n }\n}" }, { "code": null, "e": 5965, "s": 5883, "text": "When we compile and execute the above program, it produces the following result −" }, { "code": null, "e": 6159, "s": 5965, "text": "The original array elements are :\nLA[0] = 1 \nLA[1] = 3 \nLA[2] = 5 \nLA[3] = 7 \nLA[4] = 8 \nThe array elements after insertion :\nLA[0] = 1 \nLA[1] = 3 \nLA[2] = 5 \nLA[3] = 10 \nLA[4] = 7 \nLA[5] = 8 \n" }, { "code": null, "e": 6220, "s": 6159, "text": "For other variations of array insertion operation click here" }, { "code": null, "e": 6327, "s": 6220, "text": "Deletion refers to removing an existing element from the array and re-organizing all elements of an array." }, { "code": null, "e": 6502, "s": 6327, "text": "Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Following is the algorithm to delete an element available at the Kth position of LA." }, { "code": null, "e": 6624, "s": 6502, "text": "1. Start\n2. Set J = K\n3. Repeat steps 4 and 5 while J < N\n4. Set LA[J] = LA[J + 1]\n5. Set J = J+1\n6. Set N = N-1\n7. Stop\n" }, { "code": null, "e": 6681, "s": 6624, "text": "Following is the implementation of the above algorithm −" }, { "code": null, "e": 7134, "s": 6681, "text": "#include <stdio.h>\n\nvoid main() {\n int LA[] = {1,3,5,7,8};\n int k = 3, n = 5;\n int i, j;\n \n printf(\"The original array elements are :\\n\");\n\t\n for(i = 0; i<n; i++) {\n printf(\"LA[%d] = %d \\n\", i, LA[i]);\n }\n \n j = k;\n\t\n while( j < n) {\n LA[j-1] = LA[j];\n j = j + 1;\n }\n\t\n n = n -1;\n \n printf(\"The array elements after deletion :\\n\");\n\t\n for(i = 0; i<n; i++) {\n printf(\"LA[%d] = %d \\n\", i, LA[i]);\n }\n}" }, { "code": null, "e": 7216, "s": 7134, "text": "When we compile and execute the above program, it produces the following result −" }, { "code": null, "e": 7386, "s": 7216, "text": "The original array elements are :\nLA[0] = 1 \nLA[1] = 3 \nLA[2] = 5 \nLA[3] = 7 \nLA[4] = 8 \nThe array elements after deletion :\nLA[0] = 1 \nLA[1] = 3 \nLA[2] = 7 \nLA[3] = 8 \n" }, { "code": null, "e": 7465, "s": 7386, "text": "You can perform a search for an array element based on its value or its index." }, { "code": null, "e": 7647, "s": 7465, "text": "Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Following is the algorithm to find an element with a value of ITEM using sequential search." }, { "code": null, "e": 7790, "s": 7647, "text": "1. Start\n2. Set J = 0\n3. Repeat steps 4 and 5 while J < N\n4. IF LA[J] is equal ITEM THEN GOTO STEP 6\n5. Set J = J +1\n6. PRINT J, ITEM\n7. Stop\n" }, { "code": null, "e": 7847, "s": 7790, "text": "Following is the implementation of the above algorithm −" }, { "code": null, "e": 8245, "s": 7847, "text": "#include <stdio.h>\n\nvoid main() {\n int LA[] = {1,3,5,7,8};\n int item = 5, n = 5;\n int i = 0, j = 0;\n \n printf(\"The original array elements are :\\n\");\n\t\n for(i = 0; i<n; i++) {\n printf(\"LA[%d] = %d \\n\", i, LA[i]);\n }\n \n while( j < n){\n if( LA[j] == item ) {\n break;\n }\n\t\t\n j = j + 1;\n }\n\t\n printf(\"Found element %d at position %d\\n\", item, j+1);\n}" }, { "code": null, "e": 8327, "s": 8245, "text": "When we compile and execute the above program, it produces the following result −" }, { "code": null, "e": 8447, "s": 8327, "text": "The original array elements are :\nLA[0] = 1 \nLA[1] = 3 \nLA[2] = 5 \nLA[3] = 7 \nLA[4] = 8 \nFound element 5 at position 3\n" }, { "code": null, "e": 8536, "s": 8447, "text": "Update operation refers to updating an existing element from the array at a given index." }, { "code": null, "e": 8711, "s": 8536, "text": "Consider LA is a linear array with N elements and K is a positive integer such that K<=N. Following is the algorithm to update an element available at the Kth position of LA." }, { "code": null, "e": 8751, "s": 8711, "text": "1. Start\n2. Set LA[K-1] = ITEM\n3. Stop\n" }, { "code": null, "e": 8808, "s": 8751, "text": "Following is the implementation of the above algorithm −" }, { "code": null, "e": 9197, "s": 8808, "text": "#include <stdio.h>\n\nvoid main() {\n int LA[] = {1,3,5,7,8};\n int k = 3, n = 5, item = 10;\n int i, j;\n \n printf(\"The original array elements are :\\n\");\n\t\n for(i = 0; i<n; i++) {\n printf(\"LA[%d] = %d \\n\", i, LA[i]);\n }\n \n LA[k-1] = item;\n\n printf(\"The array elements after updation :\\n\");\n\t\n for(i = 0; i<n; i++) {\n printf(\"LA[%d] = %d \\n\", i, LA[i]);\n }\n}" }, { "code": null, "e": 9279, "s": 9197, "text": "When we compile and execute the above program, it produces the following result −" }, { "code": null, "e": 9461, "s": 9279, "text": "The original array elements are :\nLA[0] = 1 \nLA[1] = 3 \nLA[2] = 5 \nLA[3] = 7 \nLA[4] = 8 \nThe array elements after updation :\nLA[0] = 1 \nLA[1] = 3 \nLA[2] = 10 \nLA[3] = 7 \nLA[4] = 8 \n" }, { "code": null, "e": 9496, "s": 9461, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9508, "s": 9496, "text": " Ravi Kiran" }, { "code": null, "e": 9543, "s": 9508, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 9562, "s": 9543, "text": " Arnab Chakraborty" }, { "code": null, "e": 9597, "s": 9562, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 9612, "s": 9597, "text": " Parth Panjabi" }, { "code": null, "e": 9645, "s": 9612, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 9664, "s": 9645, "text": " Arnab Chakraborty" }, { "code": null, "e": 9698, "s": 9664, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 9726, "s": 9698, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9762, "s": 9726, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 9790, "s": 9762, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9797, "s": 9790, "text": " Print" }, { "code": null, "e": 9808, "s": 9797, "text": " Add Notes" } ]
Python Pandas – Merge DataFrame with many-to-one relation
To merge Pandas DataFrame, use the merge() function. The many-to-one relation is implemented on both the DataFrames by setting under the “validate” parameter of the merge() function i.e. − validate = “many-to-one” or validate = “m:1” The many-to-one relation checks if merge keys are unique in right dataset. At first, let us create our 1st DataFrame − dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 110, 80, 110, 90] } ) Now, let us create our 2nd DataFrame − dataFrame2 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000] } ) Following is the code − # # Merge Pandas DataFrame with many-to-one relation # import pandas as pd # Create DataFrame1 dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 110, 80, 110, 90] } ) print("DataFrame1 ...\n",dataFrame1) # Create DataFrame2 dataFrame2 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000] } ) print("\nDataFrame2 ...\n",dataFrame2) # merge DataFrames with "many-to-one" in "validate" parameter mergedRes = pd.merge(dataFrame1, dataFrame2, validate ="many_to_one") print("\nMerged dataframe with many-to-one relation...\n", mergedRes) This will produce the following output − DataFrame1 ... Car Units 0 BMW 100 1 Audi 110 2 Mustang 80 3 Bentley 110 4 Jaguar 90 DataFrame1 ... Car Reg_Price 0 BMW 7000 1 Lexus 1500 2 Tesla 5000 3 Mustang 8000 4 Mercedes 9000 5 Jaguar 6000 Merged dataframe with many-to-one relation... Car Units Reg_Price 0 BMW 100 7000 1 Mustang 80 8000 2 Jaguar 90 6000
[ { "code": null, "e": 1251, "s": 1062, "text": "To merge Pandas DataFrame, use the merge() function. The many-to-one relation is implemented on both the DataFrames by setting under the “validate” parameter of the merge() function i.e. −" }, { "code": null, "e": 1296, "s": 1251, "text": "validate = “many-to-one”\nor\nvalidate = “m:1”" }, { "code": null, "e": 1371, "s": 1296, "text": "The many-to-one relation checks if merge keys are unique in right dataset." }, { "code": null, "e": 1415, "s": 1371, "text": "At first, let us create our 1st DataFrame −" }, { "code": null, "e": 1550, "s": 1415, "text": "dataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],\"Units\": [100, 110, 80, 110, 90]\n }\n)\n\n" }, { "code": null, "e": 1589, "s": 1550, "text": "Now, let us create our 2nd DataFrame −" }, { "code": null, "e": 1752, "s": 1589, "text": "dataFrame2 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000]\n }\n)\n\n" }, { "code": null, "e": 1776, "s": 1752, "text": "Following is the code −" }, { "code": null, "e": 2470, "s": 1776, "text": "#\n# Merge Pandas DataFrame with many-to-one relation\n#\n\nimport pandas as pd\n\n# Create DataFrame1\ndataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],\"Units\": [100, 110, 80, 110, 90]\n }\n)\n\nprint(\"DataFrame1 ...\\n\",dataFrame1)\n\n# Create DataFrame2\ndataFrame2 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000]\n\n }\n)\n\nprint(\"\\nDataFrame2 ...\\n\",dataFrame2)\n\n# merge DataFrames with \"many-to-one\" in \"validate\" parameter\nmergedRes = pd.merge(dataFrame1, dataFrame2, validate =\"many_to_one\")\nprint(\"\\nMerged dataframe with many-to-one relation...\\n\", mergedRes)" }, { "code": null, "e": 2511, "s": 2470, "text": "This will produce the following output −" }, { "code": null, "e": 2995, "s": 2511, "text": "DataFrame1 ...\n Car Units\n0 BMW 100\n1 Audi 110\n2 Mustang 80\n3 Bentley 110\n4 Jaguar 90\n\nDataFrame1 ...\n Car Reg_Price\n0 BMW 7000\n1 Lexus 1500\n2 Tesla 5000\n3 Mustang 8000\n4 Mercedes 9000\n5 Jaguar 6000\n\nMerged dataframe with many-to-one relation...\n Car Units Reg_Price\n0 BMW 100 7000\n1 Mustang 80 8000\n2 Jaguar 90 6000" } ]
Make palindromic string non-palindromic by rearranging its letters - GeeksforGeeks
03 Aug, 2021 Given string str containing lowercase alphabets (a – z). The task is to print the string after rearranging some characters such that the string becomes non-palindromic. If it’s impossible to make the string non-palindrome then print -1.Examples: Input: str = “abba” Output: aabbInput: str = “zzz” Output: -1 Approach: If all the characters in the string are the same then no matter how you rearrange the characters, the string will remain the same and will be palindromic. Now, if a non-palindromic arrangement exists, the best way to rearrange the characters is to sort the string which will form a continuous segment of the same characters and will never be palindromic. In order to reduce the time required to sort the string, we can store the frequencies of all 26 characters and print them in a sorted manner.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP Program to rearrange letters of string// to find a non-palindromic string if it exists#include <bits/stdc++.h>using namespace std; // Function to print the non-palindromic string// if it exists, otherwise prints -1void findNonPalinString(string s){ int freq[26] = { 0 }, flag = 0; for (int i = 0; i < s.size(); i++) { // If all characters are not // same, set flag to 1 if (s[i] != s[0]) flag = 1; // Update frequency of the current character freq[s[i] - 'a']++; } // If all characters are same if (!flag) cout << "-1"; else { // Print characters in sorted manner for (int i = 0; i < 26; i++) for (int j = 0; j < freq[i]; j++) cout << char('a' + i); }} // Driver Codeint main(){ string s = "abba"; findNonPalinString(s); return 0;} // Java Program to rearrange letters of string// to find a non-palindromic string if it existsclass GfG{ // Function to print the non-palindromic string// if it exists, otherwise prints -1static void findNonPalinString(char s[]){ int freq[] = new int[26]; int flag = 0; for (int i = 0; i < s.length; i++) { // If all characters are not // same, set flag to 1 if (s[i] != s[0]) flag = 1; // Update frequency of // the current character freq[s[i] - 'a']++; } // If all characters are same if (flag == 0) System.out.println("-1"); else { // Print characters in sorted manner for (int i = 0; i < 26; i++) for (int j = 0; j < freq[i]; j++) System.out.print((char)('a' + i)); }} // Driver Codepublic static void main(String[] args){ String s = "abba"; findNonPalinString(s.toCharArray());}} // This code is contributed by// Prerna Saini. # Python3 Program to rearrange letters of string# to find a non-palindromic string if it exists # Function to print the non-palindromic string# if it exists, otherwise prints -1def findNonPalinString(s): freq = [0] * (26) flag = 0 for i in range(0, len(s)): # If all characters are not same, # set flag to 1 if s[i] != s[0]: flag = 1 # Update frequency of the current # character freq[ord(s[i]) - ord('a')] += 1 # If all characters are same if not flag: print("-1") else: # Print characters in sorted manner for i in range(0, 26): for j in range(0, freq[i]): print(chr(ord('a') + i), end = "") # Driver Codeif __name__ == "__main__": s = "abba" findNonPalinString(s) # This code is contributed by# Rituraj Jain // C# Program to rearrange letters// of string to find a non-palindromic// string if it existsusing System; class GfG{ // Function to print the // non-palindromic string // if it exists, otherwise // prints -1 static void findNonPalinString(char []s) { int []freq = new int[26]; int flag = 0; for (int i = 0; i < s.Length; i++) { // If all characters are not // same, set flag to 1 if (s[i] != s[0]) flag = 1; // Update frequency of // the current character freq[s[i] - 'a']++; } // If all characters are same if (flag == 0) Console.WriteLine("-1"); else { // Print characters in sorted manner for (int i = 0; i < 26; i++) for (int j = 0; j < freq[i]; j++) Console.Write((char)('a' + i)); } } // Driver Code public static void Main() { string s = "abba"; findNonPalinString(s.ToCharArray()); }} // This code is contributed by Ryuga <script> // JavaScript Program to rearrange letters of string// to find a non-palindromic string if it exists // Function to print the non-palindromic string// if it exists, otherwise prints -1function findNonPalinString(s){ var freq = Array.from({length: 26}, (_, i) => 0); var flag = 0; for (var i = 0; i < s.length; i++) { // If all characters are not // same, set flag to 1 if (s[i] != s[0]) flag = 1; // Update frequency of // the current character freq[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // If all characters are same if (flag == 0) document.write("-1"); else { // Print characters in sorted manner for (var i = 0; i < 26; i++) for (var j = 0; j < freq[i]; j++) document.write(String.fromCharCode ('a'.charCodeAt(0) + i)); }} // Driver Codevar s = "abba"; findNonPalinString(s.split('')); // This code contributed by shikhasingrajput </script> aabb Time Complexity: O(N)Auxiliary Space: O(1) prerna saini rituraj_jain ankthon shikhasingrajput pankajsharmagfg frequency-counting palindrome Sorting Quiz Algorithms Sorting Strings Strings Sorting palindrome Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Understanding Time Complexity with Simple Examples Introduction to Algorithms How to write a Pseudo Code?
[ { "code": null, "e": 24938, "s": 24910, "text": "\n03 Aug, 2021" }, { "code": null, "e": 25186, "s": 24938, "text": "Given string str containing lowercase alphabets (a – z). The task is to print the string after rearranging some characters such that the string becomes non-palindromic. If it’s impossible to make the string non-palindrome then print -1.Examples: " }, { "code": null, "e": 25250, "s": 25186, "text": "Input: str = “abba” Output: aabbInput: str = “zzz” Output: -1 " }, { "code": null, "e": 25811, "s": 25252, "text": "Approach: If all the characters in the string are the same then no matter how you rearrange the characters, the string will remain the same and will be palindromic. Now, if a non-palindromic arrangement exists, the best way to rearrange the characters is to sort the string which will form a continuous segment of the same characters and will never be palindromic. In order to reduce the time required to sort the string, we can store the frequencies of all 26 characters and print them in a sorted manner.Below is the implementation of the above approach: " }, { "code": null, "e": 25815, "s": 25811, "text": "C++" }, { "code": null, "e": 25820, "s": 25815, "text": "Java" }, { "code": null, "e": 25828, "s": 25820, "text": "Python3" }, { "code": null, "e": 25831, "s": 25828, "text": "C#" }, { "code": null, "e": 25842, "s": 25831, "text": "Javascript" }, { "code": "// CPP Program to rearrange letters of string// to find a non-palindromic string if it exists#include <bits/stdc++.h>using namespace std; // Function to print the non-palindromic string// if it exists, otherwise prints -1void findNonPalinString(string s){ int freq[26] = { 0 }, flag = 0; for (int i = 0; i < s.size(); i++) { // If all characters are not // same, set flag to 1 if (s[i] != s[0]) flag = 1; // Update frequency of the current character freq[s[i] - 'a']++; } // If all characters are same if (!flag) cout << \"-1\"; else { // Print characters in sorted manner for (int i = 0; i < 26; i++) for (int j = 0; j < freq[i]; j++) cout << char('a' + i); }} // Driver Codeint main(){ string s = \"abba\"; findNonPalinString(s); return 0;}", "e": 26711, "s": 25842, "text": null }, { "code": "// Java Program to rearrange letters of string// to find a non-palindromic string if it existsclass GfG{ // Function to print the non-palindromic string// if it exists, otherwise prints -1static void findNonPalinString(char s[]){ int freq[] = new int[26]; int flag = 0; for (int i = 0; i < s.length; i++) { // If all characters are not // same, set flag to 1 if (s[i] != s[0]) flag = 1; // Update frequency of // the current character freq[s[i] - 'a']++; } // If all characters are same if (flag == 0) System.out.println(\"-1\"); else { // Print characters in sorted manner for (int i = 0; i < 26; i++) for (int j = 0; j < freq[i]; j++) System.out.print((char)('a' + i)); }} // Driver Codepublic static void main(String[] args){ String s = \"abba\"; findNonPalinString(s.toCharArray());}} // This code is contributed by// Prerna Saini.", "e": 27689, "s": 26711, "text": null }, { "code": "# Python3 Program to rearrange letters of string# to find a non-palindromic string if it exists # Function to print the non-palindromic string# if it exists, otherwise prints -1def findNonPalinString(s): freq = [0] * (26) flag = 0 for i in range(0, len(s)): # If all characters are not same, # set flag to 1 if s[i] != s[0]: flag = 1 # Update frequency of the current # character freq[ord(s[i]) - ord('a')] += 1 # If all characters are same if not flag: print(\"-1\") else: # Print characters in sorted manner for i in range(0, 26): for j in range(0, freq[i]): print(chr(ord('a') + i), end = \"\") # Driver Codeif __name__ == \"__main__\": s = \"abba\" findNonPalinString(s) # This code is contributed by# Rituraj Jain", "e": 28574, "s": 27689, "text": null }, { "code": "// C# Program to rearrange letters// of string to find a non-palindromic// string if it existsusing System; class GfG{ // Function to print the // non-palindromic string // if it exists, otherwise // prints -1 static void findNonPalinString(char []s) { int []freq = new int[26]; int flag = 0; for (int i = 0; i < s.Length; i++) { // If all characters are not // same, set flag to 1 if (s[i] != s[0]) flag = 1; // Update frequency of // the current character freq[s[i] - 'a']++; } // If all characters are same if (flag == 0) Console.WriteLine(\"-1\"); else { // Print characters in sorted manner for (int i = 0; i < 26; i++) for (int j = 0; j < freq[i]; j++) Console.Write((char)('a' + i)); } } // Driver Code public static void Main() { string s = \"abba\"; findNonPalinString(s.ToCharArray()); }} // This code is contributed by Ryuga", "e": 29715, "s": 28574, "text": null }, { "code": "<script> // JavaScript Program to rearrange letters of string// to find a non-palindromic string if it exists // Function to print the non-palindromic string// if it exists, otherwise prints -1function findNonPalinString(s){ var freq = Array.from({length: 26}, (_, i) => 0); var flag = 0; for (var i = 0; i < s.length; i++) { // If all characters are not // same, set flag to 1 if (s[i] != s[0]) flag = 1; // Update frequency of // the current character freq[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // If all characters are same if (flag == 0) document.write(\"-1\"); else { // Print characters in sorted manner for (var i = 0; i < 26; i++) for (var j = 0; j < freq[i]; j++) document.write(String.fromCharCode ('a'.charCodeAt(0) + i)); }} // Driver Codevar s = \"abba\"; findNonPalinString(s.split('')); // This code contributed by shikhasingrajput </script>", "e": 30732, "s": 29715, "text": null }, { "code": null, "e": 30737, "s": 30732, "text": "aabb" }, { "code": null, "e": 30782, "s": 30739, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 30795, "s": 30782, "text": "prerna saini" }, { "code": null, "e": 30808, "s": 30795, "text": "rituraj_jain" }, { "code": null, "e": 30816, "s": 30808, "text": "ankthon" }, { "code": null, "e": 30833, "s": 30816, "text": "shikhasingrajput" }, { "code": null, "e": 30849, "s": 30833, "text": "pankajsharmagfg" }, { "code": null, "e": 30868, "s": 30849, "text": "frequency-counting" }, { "code": null, "e": 30879, "s": 30868, "text": "palindrome" }, { "code": null, "e": 30892, "s": 30879, "text": "Sorting Quiz" }, { "code": null, "e": 30903, "s": 30892, "text": "Algorithms" }, { "code": null, "e": 30911, "s": 30903, "text": "Sorting" }, { "code": null, "e": 30919, "s": 30911, "text": "Strings" }, { "code": null, "e": 30927, "s": 30919, "text": "Strings" }, { "code": null, "e": 30935, "s": 30927, "text": "Sorting" }, { "code": null, "e": 30946, "s": 30935, "text": "palindrome" }, { "code": null, "e": 30957, "s": 30946, "text": "Algorithms" }, { "code": null, "e": 31055, "s": 30957, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31104, "s": 31055, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 31129, "s": 31104, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31180, "s": 31129, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 31207, "s": 31180, "text": "Introduction to Algorithms" } ]
MongoDB find() query for nested document?
To fetch a value from the nested document, use dot notation. Let us create a collection with documents − > db.demo591.insert([ ... { "Name": "John", "Age": 23 }, ... {"Name": "Carol", "Age": 26}, ... { "Name": "Robert", "Age": 29, ... details:[ ... { ... Email:"[email protected]",CountryName:"US"},{"Post":35} ... ]} ... ]); BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) Display all documents from a collection with the help of find() method − > db.demo591.find(); This will produce the following output − { "_id" : ObjectId("5e92dd08fd2d90c177b5bcd3"), "Name" : "John", "Age" : 23 } { "_id" : ObjectId("5e92dd08fd2d90c177b5bcd4"), "Name" : "Carol", "Age" : 26 } { "_id" : ObjectId("5e92dd08fd2d90c177b5bcd5"), "Name" : "Robert", "Age" : 29, "details" : [ { "Email" : "[email protected]", "CountryName" : "US" }, { "Post" : 35 } ] } Following is the query to fetch nested document using dot notation − > db.demo591.find({"details.Email": "[email protected]"}); This will produce the following output − { "_id" : ObjectId("5e92dd08fd2d90c177b5bcd5"), "Name" : "Robert", "Age" : 29, "details" : [ { "Email" : "[email protected]", "CountryName" : "US" }, { "Post" : 35 } ] }
[ { "code": null, "e": 1167, "s": 1062, "text": "To fetch a value from the nested document, use dot notation. Let us create a collection with\ndocuments −" }, { "code": null, "e": 1614, "s": 1167, "text": "> db.demo591.insert([\n... { \"Name\": \"John\", \"Age\": 23 },\n... {\"Name\": \"Carol\", \"Age\": 26},\n... { \"Name\": \"Robert\", \"Age\": 29,\n... details:[\n... {\n... Email:\"[email protected]\",CountryName:\"US\"},{\"Post\":35}\n... ]}\n... ]);\nBulkWriteResult({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 3,\n \"nUpserted\" : 0,\n \"nMatched\" : 0,\n \"nModified\" : 0,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})" }, { "code": null, "e": 1687, "s": 1614, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1708, "s": 1687, "text": "> db.demo591.find();" }, { "code": null, "e": 1749, "s": 1708, "text": "This will produce the following output −" }, { "code": null, "e": 2075, "s": 1749, "text": "{ \"_id\" : ObjectId(\"5e92dd08fd2d90c177b5bcd3\"), \"Name\" : \"John\", \"Age\" : 23 }\n{ \"_id\" : ObjectId(\"5e92dd08fd2d90c177b5bcd4\"), \"Name\" : \"Carol\", \"Age\" : 26 }\n{ \"_id\" : ObjectId(\"5e92dd08fd2d90c177b5bcd5\"), \"Name\" : \"Robert\", \"Age\" : 29, \"details\" : [ {\n\"Email\" : \"[email protected]\", \"CountryName\" : \"US\" }, { \"Post\" : 35 } ] }" }, { "code": null, "e": 2144, "s": 2075, "text": "Following is the query to fetch nested document using dot notation −" }, { "code": null, "e": 2202, "s": 2144, "text": "> db.demo591.find({\"details.Email\": \"[email protected]\"});" }, { "code": null, "e": 2243, "s": 2202, "text": "This will produce the following output −" }, { "code": null, "e": 2416, "s": 2243, "text": "{ \"_id\" : ObjectId(\"5e92dd08fd2d90c177b5bcd5\"), \"Name\" : \"Robert\", \"Age\" : 29, \"details\" : [\n { \"Email\" : \"[email protected]\", \"CountryName\" : \"US\" }, { \"Post\" : 35 } \n] }" } ]
Create a Homepage for Restaurant using HTML , CSS and Bootstrap - GeeksforGeeks
17 Jun, 2021 Prerequisites: HTML 5, CSS and Bootstrap HTML: HTML stands for Hyper Text Markup Language. It is used to design web pages using a markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. A markup language is used to define the text document within tag which defines the structure of web pages. CSS: Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. More importantly, CSS enables you to do this independent of the HTML that makes up each web page. BOOTSTRAP : Bootstrap is a free and open-source tool collection for creating responsive websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. Nowadays, the websites are perfect for all the browsers (IE, Firefox and Chrome) and for all sizes of screens (Desktop, Tablets, and Phones). All thanks to Bootstrap developers – Mark Otto and Jacob Thornton of Twitter, though it was later declared to be an open-source project. Below is the source code for construction of Restaurant Homepage: HTML section: File name is index.html HTML <!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="index.css"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <title>Restaurant Website</title></head> <body> <!-- navbar --> <nav> <ul class="nav-flex-row"> <li class="nav-item"> <a href="#about">About</a> </li> <li class="nav-item"> <a href="#reservation">Reservation</a> </li> <li class="nav-item"> <a href="#menu">Menu</a> </li> <li class="nav-item"> <a href="#shop">Shop</a> </li> </ul> </nav> <section class="section-intro"> <header> <h1> Welcome To Fooddddie's Kitchen</h1> </header> <div class="link-to-book-wrapper"> <a class="link-to-book" href="#reservations">Book a table</a> </div> </section> <section class="about-section"> <article> <h3> Section for the text why your restaurant is the best. </h3> <p> Lorem ipsum dolor sit, amet consectetur adipisicing elit. A quos, voluptatum illum mollitia dolores libero placeat nesciunt quasi adipisci impedit!Lorem ipsum dolor sit, amet consectetur adipisicing elit. A quos, voluptatum illum mollitia dolores libero placeat nesciunt quasi adipisci impedit! Lorem ipsum dolor sit, amet consectetur adipisicing elit. A quos, voluptatum illum mollitia dolores libero placeat nesciunt quasi adipisci impedit!Lorem ipsum dolor sit. </p> </article> </section> <!-- carousel section --> <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="img/food1.png" class="d-block w-100" alt="food"> </div> <div class="carousel-item"> <img src="img/food2.png" class="d-block w-100" alt="food"> </div> <div class="carousel-item"> <img src="img/food3.png" class="d-block w-100" alt="food"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"> </span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"> </span> <span class="sr-only">Next</span> </a> </div> <div class="container"> <div class="row-flex"> <div class="flex-column-form"> <h3> Make a booking </h3> <form class="media-centered"> <div class="form-group"> <p> Please leave your number we will call to make a reservation </p> <input type="name" class="form-control" id="exampleInputName1" aria-describedby="nameHelp" placeholder="Enter your name"> </div> <div class="form-group"> <input type="number" class="form-control" id="exampleInputphoneNumber1" placeholder="Enter your phone number"> </div> <button type="submit" class="btn btn-primary"> Submit </button> </form> </div> <div class="opening-time"> <h3> Opening times </h3> <p> <span>Monday—Thursday: 08:00 — 22:00</span> <span>Friday—Saturday: 09:00 — 23:00 </span> <span>Sunday: 10:00 — 17:00</span> </p> </div> <div class="contact-address"> <h3> Contact </h3> <p> <span>410-602-8008</span> <span>15 Florida Ave</span> <span>Palo-Alto, 1111 CA</span> </p> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"> </script></body> </html> CSS section: File name is index.css CSS @import url('https://fonts.googleapis.com/css?family=Big+Shoulders+Text:100, 300, 400, 500, 600, 700, 800, 900&display=swap'); /* font-family: 'Big Shoulders Text', cursive; */ .nav-flex-row { display: flex; flex-direction: row; justify-content: center; position: absolute; z-index: 100; left: 0; width: 100%; padding: 0;} .nav-flex-row li { text-decoration: none; list-style-type: none; padding: 20px 15px;} .nav-flex-row li a { font-family: 'Big Shoulders Text', cursive; color: #000; font-size: 1.5em; text-transform: uppercase; font-weight: 300;}.nav-flex-row li a:hover{ background: #E7E7E7;} .section-intro { height: 820px; background-image: url(img/foddiee.png); background-size: cover; display: flex; flex-direction: column; justify-content: center; align-items: center;} .section-intro h1 { text-align: center; color: #000; font-size: 4em; font-weight: 700;} .section-intro header { display: flex; flex: 4; flex-direction: row; justify-content: center; align-items: center;} .link-to-book-wrapper { flex: 1;} .about-section { display: flex; align-items: center; background-color: #f3f3f3c0; padding: 50px 30px;} .link-to-book { color: #ffffff; display: block; border: 2px solid #ffffff; padding: 5px 10px;} a.link-to-book:hover { background-color: #ffffff; color: #95999e; text-decoration: none;} .about-section p,.about-section h3 { text-align: center; width: 60%; margin: auto; font-family: 'Big Shoulders Text', cursive; font-size: 1.8em; text-transform: uppercase;} .carousel-inner { height: 700px;} .row-flex { display: flex; flex-direction: row;} .flex-column-form { display: flex; flex-direction: column; flex: 1; margin: 30px 20px;} .btn.btn-primary { font-family: 'Big Shoulders Text', cursive; color: #ffffff; background-color: #95999e; text-transform: uppercase; font-size: 16px; padding: 5px 10px; letter-spacing: 2px; border: 0;} .btn.btn-primary:hover { background-color: #747474;}.opening-time,.contact-address { flex: 1; margin: 30px 20px; font-size: 1.2em;} .form-group p { font-size: 1.2em;} .opening-time p span,.contact-address p span { display: block;} @media (min-width:577px) and (max-width: 800px) { .section-intro { height: 500px; } .about-section p, .about-section h3 { font-size: 20px; } .carousel-inner { height: auto; } .row-flex { display: flex; flex-direction: column; }} @media screen and (max-width: 576px) { .section-intro { height: 300px; } .about-section { padding: 30px; } .section-intro h1 { font-size: 2em; } .about-section p, .about-section h3 { font-size: 15px; } .carousel-inner { height: auto; } .row-flex { display: flex; flex-direction: column; } .row-flex h3 { font-size: 25px; text-align: center; } .form-group p { font-size: 15px; } .opening-time p span, .contact-address p span { font-size: 15px; text-align: center; } } Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. clintra Bootstrap-Misc CSS-Misc HTML-Misc Bootstrap CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to pass data into a bootstrap modal? How to set Bootstrap Timepicker using datetimepicker library ? How to Show Images on Click using HTML ? Difference between Bootstrap 4 and Bootstrap 5 How to Use Bootstrap with React? How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) CSS to put icon inside an input element in a form
[ { "code": null, "e": 24502, "s": 24474, "text": "\n17 Jun, 2021" }, { "code": null, "e": 24543, "s": 24502, "text": "Prerequisites: HTML 5, CSS and Bootstrap" }, { "code": null, "e": 24866, "s": 24543, "text": "HTML: HTML stands for Hyper Text Markup Language. It is used to design web pages using a markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. A markup language is used to define the text document within tag which defines the structure of web pages." }, { "code": null, "e": 25161, "s": 24866, "text": "CSS: Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. More importantly, CSS enables you to do this independent of the HTML that makes up each web page." }, { "code": null, "e": 25670, "s": 25161, "text": "BOOTSTRAP : Bootstrap is a free and open-source tool collection for creating responsive websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. Nowadays, the websites are perfect for all the browsers (IE, Firefox and Chrome) and for all sizes of screens (Desktop, Tablets, and Phones). All thanks to Bootstrap developers – Mark Otto and Jacob Thornton of Twitter, though it was later declared to be an open-source project." }, { "code": null, "e": 25737, "s": 25670, "text": "Below is the source code for construction of Restaurant Homepage: " }, { "code": null, "e": 25775, "s": 25737, "text": "HTML section: File name is index.html" }, { "code": null, "e": 25780, "s": 25775, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"index.css\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\"> <title>Restaurant Website</title></head> <body> <!-- navbar --> <nav> <ul class=\"nav-flex-row\"> <li class=\"nav-item\"> <a href=\"#about\">About</a> </li> <li class=\"nav-item\"> <a href=\"#reservation\">Reservation</a> </li> <li class=\"nav-item\"> <a href=\"#menu\">Menu</a> </li> <li class=\"nav-item\"> <a href=\"#shop\">Shop</a> </li> </ul> </nav> <section class=\"section-intro\"> <header> <h1> Welcome To Fooddddie's Kitchen</h1> </header> <div class=\"link-to-book-wrapper\"> <a class=\"link-to-book\" href=\"#reservations\">Book a table</a> </div> </section> <section class=\"about-section\"> <article> <h3> Section for the text why your restaurant is the best. </h3> <p> Lorem ipsum dolor sit, amet consectetur adipisicing elit. A quos, voluptatum illum mollitia dolores libero placeat nesciunt quasi adipisci impedit!Lorem ipsum dolor sit, amet consectetur adipisicing elit. A quos, voluptatum illum mollitia dolores libero placeat nesciunt quasi adipisci impedit! Lorem ipsum dolor sit, amet consectetur adipisicing elit. A quos, voluptatum illum mollitia dolores libero placeat nesciunt quasi adipisci impedit!Lorem ipsum dolor sit. </p> </article> </section> <!-- carousel section --> <div id=\"carouselExampleControls\" class=\"carousel slide\" data-ride=\"carousel\"> <div class=\"carousel-inner\"> <div class=\"carousel-item active\"> <img src=\"img/food1.png\" class=\"d-block w-100\" alt=\"food\"> </div> <div class=\"carousel-item\"> <img src=\"img/food2.png\" class=\"d-block w-100\" alt=\"food\"> </div> <div class=\"carousel-item\"> <img src=\"img/food3.png\" class=\"d-block w-100\" alt=\"food\"> </div> </div> <a class=\"carousel-control-prev\" href=\"#carouselExampleControls\" role=\"button\" data-slide=\"prev\"> <span class=\"carousel-control-prev-icon\" aria-hidden=\"true\"> </span> <span class=\"sr-only\">Previous</span> </a> <a class=\"carousel-control-next\" href=\"#carouselExampleControls\" role=\"button\" data-slide=\"next\"> <span class=\"carousel-control-next-icon\" aria-hidden=\"true\"> </span> <span class=\"sr-only\">Next</span> </a> </div> <div class=\"container\"> <div class=\"row-flex\"> <div class=\"flex-column-form\"> <h3> Make a booking </h3> <form class=\"media-centered\"> <div class=\"form-group\"> <p> Please leave your number we will call to make a reservation </p> <input type=\"name\" class=\"form-control\" id=\"exampleInputName1\" aria-describedby=\"nameHelp\" placeholder=\"Enter your name\"> </div> <div class=\"form-group\"> <input type=\"number\" class=\"form-control\" id=\"exampleInputphoneNumber1\" placeholder=\"Enter your phone number\"> </div> <button type=\"submit\" class=\"btn btn-primary\"> Submit </button> </form> </div> <div class=\"opening-time\"> <h3> Opening times </h3> <p> <span>Monday—Thursday: 08:00 — 22:00</span> <span>Friday—Saturday: 09:00 — 23:00 </span> <span>Sunday: 10:00 — 17:00</span> </p> </div> <div class=\"contact-address\"> <h3> Contact </h3> <p> <span>410-602-8008</span> <span>15 Florida Ave</span> <span>Palo-Alto, 1111 CA</span> </p> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\" integrity=\"sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\" integrity=\"sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM\" crossorigin=\"anonymous\"> </script></body> </html>", "e": 31799, "s": 25780, "text": null }, { "code": null, "e": 31835, "s": 31799, "text": "CSS section: File name is index.css" }, { "code": null, "e": 31839, "s": 31835, "text": "CSS" }, { "code": "@import url('https://fonts.googleapis.com/css?family=Big+Shoulders+Text:100, 300, 400, 500, 600, 700, 800, 900&display=swap'); /* font-family: 'Big Shoulders Text', cursive; */ .nav-flex-row { display: flex; flex-direction: row; justify-content: center; position: absolute; z-index: 100; left: 0; width: 100%; padding: 0;} .nav-flex-row li { text-decoration: none; list-style-type: none; padding: 20px 15px;} .nav-flex-row li a { font-family: 'Big Shoulders Text', cursive; color: #000; font-size: 1.5em; text-transform: uppercase; font-weight: 300;}.nav-flex-row li a:hover{ background: #E7E7E7;} .section-intro { height: 820px; background-image: url(img/foddiee.png); background-size: cover; display: flex; flex-direction: column; justify-content: center; align-items: center;} .section-intro h1 { text-align: center; color: #000; font-size: 4em; font-weight: 700;} .section-intro header { display: flex; flex: 4; flex-direction: row; justify-content: center; align-items: center;} .link-to-book-wrapper { flex: 1;} .about-section { display: flex; align-items: center; background-color: #f3f3f3c0; padding: 50px 30px;} .link-to-book { color: #ffffff; display: block; border: 2px solid #ffffff; padding: 5px 10px;} a.link-to-book:hover { background-color: #ffffff; color: #95999e; text-decoration: none;} .about-section p,.about-section h3 { text-align: center; width: 60%; margin: auto; font-family: 'Big Shoulders Text', cursive; font-size: 1.8em; text-transform: uppercase;} .carousel-inner { height: 700px;} .row-flex { display: flex; flex-direction: row;} .flex-column-form { display: flex; flex-direction: column; flex: 1; margin: 30px 20px;} .btn.btn-primary { font-family: 'Big Shoulders Text', cursive; color: #ffffff; background-color: #95999e; text-transform: uppercase; font-size: 16px; padding: 5px 10px; letter-spacing: 2px; border: 0;} .btn.btn-primary:hover { background-color: #747474;}.opening-time,.contact-address { flex: 1; margin: 30px 20px; font-size: 1.2em;} .form-group p { font-size: 1.2em;} .opening-time p span,.contact-address p span { display: block;} @media (min-width:577px) and (max-width: 800px) { .section-intro { height: 500px; } .about-section p, .about-section h3 { font-size: 20px; } .carousel-inner { height: auto; } .row-flex { display: flex; flex-direction: column; }} @media screen and (max-width: 576px) { .section-intro { height: 300px; } .about-section { padding: 30px; } .section-intro h1 { font-size: 2em; } .about-section p, .about-section h3 { font-size: 15px; } .carousel-inner { height: auto; } .row-flex { display: flex; flex-direction: column; } .row-flex h3 { font-size: 25px; text-align: center; } .form-group p { font-size: 15px; } .opening-time p span, .contact-address p span { font-size: 15px; text-align: center; } }", "e": 35052, "s": 31839, "text": null }, { "code": null, "e": 35061, "s": 35052, "text": "Output: " }, { "code": null, "e": 35200, "s": 35063, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 35208, "s": 35200, "text": "clintra" }, { "code": null, "e": 35223, "s": 35208, "text": "Bootstrap-Misc" }, { "code": null, "e": 35232, "s": 35223, "text": "CSS-Misc" }, { "code": null, "e": 35242, "s": 35232, "text": "HTML-Misc" }, { "code": null, "e": 35252, "s": 35242, "text": "Bootstrap" }, { "code": null, "e": 35256, "s": 35252, "text": "CSS" }, { "code": null, "e": 35261, "s": 35256, "text": "HTML" }, { "code": null, "e": 35278, "s": 35261, "text": "Web Technologies" }, { "code": null, "e": 35283, "s": 35278, "text": "HTML" }, { "code": null, "e": 35381, "s": 35283, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35390, "s": 35381, "text": "Comments" }, { "code": null, "e": 35403, "s": 35390, "text": "Old Comments" }, { "code": null, "e": 35444, "s": 35403, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 35507, "s": 35444, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 35548, "s": 35507, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 35595, "s": 35548, "text": "Difference between Bootstrap 4 and Bootstrap 5" }, { "code": null, "e": 35628, "s": 35595, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 35678, "s": 35628, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 35736, "s": 35678, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 35784, "s": 35736, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 35821, "s": 35784, "text": "Types of CSS (Cascading Style Sheet)" } ]
Encoding in BeautifulSoup - GeeksforGeeks
18 Oct, 2021 The character encoding plays a major role in the interpretation of the content of an HTML and XML document. A document does not only contain English characters but also non-English characters like Hebrew, Latin, Greek and much more. To let the parser know, which encoding method should be used, the documents will contain a dedicated tag and attribute to specify this. For example: In HTML documents <meta charset=”–encoding method name–” content=”text/html”> In XML documents <?xml version=”1.0′′ encoding=”–encoding method name–“?> These tags convey the browser which encoding method can be used for parsing. If the proper encoding method is not specified, either the content is rendered incorrectly or sometimes with the replacement character ‘�‘. The XML documents can be encoded in one of the formats listed below. UTF-8 UTF-16 Latin1 US-ASCII ISO-8859-1 to ISO-8859-10 Amongst these methods, UTF-8 is commonly found. UTF-16 allows 2 bytes for each character and the documents with ‘0xx’ are encoded by this method. Latin1 covers Western European characters. The HTML and HTML5 documents can be encoded by any one of the methods below. UTF-8 UTF-16 ISO-8859-1 UTF-16BE (Big Indian) UTF-16LE (Little Indian) WINDOWS-874 WINDOWS-1250 to WINDOWS-1258 For HTML5 documents, mostly UTF-8 is recommended. ISO-8859-1 is mostly used with XHTML documents. Some methods like UTF-7, UTF-32, BOCU-1, CESU-8 are explicitly mentioned not to use as they replace most of the characters with replacement character ‘�‘. The BeautifulSoup module, popularly imported as bs4, is a boon that makes HTML/XML parsing a cake-walk. It has a rich number of methods among which one helps to select contents by their tag name or by the attribute present in the tag, one helps to extract the content based on the hierarchy, printing content with indentation required for HTML, and so on. The bs4 module auto-detects the encoding method used in the documents and converts it to a suitable format efficiently. The returned BeautifulSoup object will have various attributes which give more information. However, sometimes it incorrectly predicts the encoding method. Thus, if the encoding method is known by the user, it is good to pass it as an argument. This article provides the various ways in which the encoding methods can be specified in the bs4 module. The bs4 module has a sub-library called Unicode, Dammit that finds the encoded method and uses that to convert to Unicode characters. The original_encoding attribute is used to return the detected encoding method. Example 1 : Given an HTML element parse it and find the encoding method used. Python3 from bs4 import BeautifulSoup # HTML element with contenth1 = b"<h1>Hello world!!</h1>" # parsing with html parserparsed = BeautifulSoup(h1, "html.parser") # tag foundprint("Tag foud :", parsed.h1.name) # the content inside the tagprint("Content :", parsed.h1.string) # the encoded methodprint("Encoding method :", parsed.original_encoding) Output: Here, the HTML element string is prefixed by ‘b‘, which means treat it as a byte literal. Thus, ASCII encoding method is detected and used by the parser. In real world situations, the original encoding will be the one mentioned in the HTML document Example 2: Given a URL, parse the contents and find the original encoding method. Python3 from bs4 import BeautifulSoupimport requests URL = 'https://www.geeksforgeeks.org/python-update-nested-dictionary/' # request the page from serverpage = requests.get(URL) # parse the contentes of the pagesoup = BeautifulSoup(page.content, "html.parser") # encoded methodprint("Encoded method :", soup.original_encoding) Output Enoded method : utf-8 Verifying the output : Python3 from bs4 import BeautifulSoup soup=BeautifulSoup(page.content,"html.parser") # fetching the <meta> tag's# charset attribute# of the content abovetag=soup.meta['charset'] print("Encoding method :",tag) Output Encoding method : UTF-8 This is a parameter that can be passed to the constructor BeautifulSoup(). This tells the bs4 module explicitly, which encoding method has to be used. This saves time and avoids incorrect parsing due to misprediction. Example : Python3 from bs4 import BeautifulSoup # HTML elementinput = b"<h1>\xa2\xf6`\xe0</h1>" # parsing contentsoup = BeautifulSoup(input) print("Content :",soup.h1.string) print("Encoding method :",soup.original_encoding) If the below warning is generated: /usr/lib/python3/dist-packages/bs4/__init__.py:166: UserWarning: No parser was explicitly specified, so I’m using the best available HTML parser for this system (“html5lib”). This usually isn’t a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently. To get rid of this warning, change this: BeautifulSoup([your markup]) to this: BeautifulSoup([your markup], “html5lib”) markup_type=markup_type)) Traceback (most recent call last): File “/home/98e5f50281480cda5f5e31e3bcafb085.py”, line 9, in <module> print(“Content :”,soup.h1.string) UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not in range(128) The editor in GeeksforGeeks tried to parse it with ASCII and ended up with an error. The output of executing the same code in the local machine gave the following output : But the content actually corresponds to “ISO-8859-8” and the interpreted characters are not the desired ones. Thus by explicitly mentioning the encoding method if known, the correct output will be given. Python3 from bs4 import BeautifulSoup # HTML elementinput = b"<h1>\xa2\xf6`\xe0</h1>" # parsing contentsoup = BeautifulSoup(input, "html.parser", from_encoding="iso-8859-8") print("Content :",soup.h1.string) print("Encoding method :",soup.original_encoding) Output: When the parsed HTML content has to be given as output, by default bs4 module delivers it as UTF-8 encoded document or sometimes with the mispredicted ones. If You want a document to be encoded by other methods without passing to the constructor, the following can be done : prettify() : This method is used to print the HTML content with correct indentation. The encoding method to be used can be passed as a parameter to this method, so that while printing it modifies the encoding method also. Example : Python3 # import modulefrom bs4 import BeautifulSoup # HTML elementinput = b'''<html><meta charset="iso-8859-8"/><body><h1>\xa2\xf6`\xe0</h1></body></html>''' # parsing contentsoup = BeautifulSoup(input,"html.parser") print(soup.prettify()) Output: Here, you can see the <meta> tag where encoding is set as UTF-8. To prevent this, one can write as below. Python3 from bs4 import BeautifulSoup # HTML elementinput = b'''<html><meta charset="iso-8859-8"/><body><h1>\xa2\xf6`\xe0</h1></body></html>''' # parsing contentsoup = BeautifulSoup(input,"html.parser") print(soup.prettify("iso-8859-8")) Output: b'<html>\n <meta charset="iso-8859-8"/>\n <body>\n <h1>\n \xa2\xf6`\xe0\n </h1>\n </body>\n</html>' encode() : The encoding method can be used to explicitly pass the required method. This replaces characters with the corresponding XML references. Example : Python3 from bs4 import BeautifulSoup # HTML elementinput = b"<html><head></head><body><h1>\xa2\xf6`\xe0</h1></body></html>" # parsing contentsoup = BeautifulSoup(input) print("Content :",soup.h1.string) print("Encoding method :",soup.original_encoding) print("After explicit encoding :",soup.html.encode("iso-8859-8")) Output: kapoorsagar226 Picked Python BeautifulSoup 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": "\n18 Oct, 2021" }, { "code": null, "e": 25937, "s": 25555, "text": "The character encoding plays a major role in the interpretation of the content of an HTML and XML document. A document does not only contain English characters but also non-English characters like Hebrew, Latin, Greek and much more. To let the parser know, which encoding method should be used, the documents will contain a dedicated tag and attribute to specify this. For example:" }, { "code": null, "e": 25955, "s": 25937, "text": "In HTML documents" }, { "code": null, "e": 26015, "s": 25955, "text": "<meta charset=”–encoding method name–” content=”text/html”>" }, { "code": null, "e": 26032, "s": 26015, "text": "In XML documents" }, { "code": null, "e": 26090, "s": 26032, "text": "<?xml version=”1.0′′ encoding=”–encoding method name–“?>" }, { "code": null, "e": 26308, "s": 26090, "text": "These tags convey the browser which encoding method can be used for parsing. If the proper encoding method is not specified, either the content is rendered incorrectly or sometimes with the replacement character ‘�‘. " }, { "code": null, "e": 26378, "s": 26308, "text": "The XML documents can be encoded in one of the formats listed below. " }, { "code": null, "e": 26385, "s": 26378, "text": "UTF-8 " }, { "code": null, "e": 26392, "s": 26385, "text": "UTF-16" }, { "code": null, "e": 26399, "s": 26392, "text": "Latin1" }, { "code": null, "e": 26408, "s": 26399, "text": "US-ASCII" }, { "code": null, "e": 26434, "s": 26408, "text": "ISO-8859-1 to ISO-8859-10" }, { "code": null, "e": 26623, "s": 26434, "text": "Amongst these methods, UTF-8 is commonly found. UTF-16 allows 2 bytes for each character and the documents with ‘0xx’ are encoded by this method. Latin1 covers Western European characters." }, { "code": null, "e": 26700, "s": 26623, "text": "The HTML and HTML5 documents can be encoded by any one of the methods below." }, { "code": null, "e": 26706, "s": 26700, "text": "UTF-8" }, { "code": null, "e": 26713, "s": 26706, "text": "UTF-16" }, { "code": null, "e": 26724, "s": 26713, "text": "ISO-8859-1" }, { "code": null, "e": 26746, "s": 26724, "text": "UTF-16BE (Big Indian)" }, { "code": null, "e": 26771, "s": 26746, "text": "UTF-16LE (Little Indian)" }, { "code": null, "e": 26783, "s": 26771, "text": "WINDOWS-874" }, { "code": null, "e": 26812, "s": 26783, "text": "WINDOWS-1250 to WINDOWS-1258" }, { "code": null, "e": 27065, "s": 26812, "text": "For HTML5 documents, mostly UTF-8 is recommended. ISO-8859-1 is mostly used with XHTML documents. Some methods like UTF-7, UTF-32, BOCU-1, CESU-8 are explicitly mentioned not to use as they replace most of the characters with replacement character ‘�‘." }, { "code": null, "e": 27891, "s": 27065, "text": "The BeautifulSoup module, popularly imported as bs4, is a boon that makes HTML/XML parsing a cake-walk. It has a rich number of methods among which one helps to select contents by their tag name or by the attribute present in the tag, one helps to extract the content based on the hierarchy, printing content with indentation required for HTML, and so on. The bs4 module auto-detects the encoding method used in the documents and converts it to a suitable format efficiently. The returned BeautifulSoup object will have various attributes which give more information. However, sometimes it incorrectly predicts the encoding method. Thus, if the encoding method is known by the user, it is good to pass it as an argument. This article provides the various ways in which the encoding methods can be specified in the bs4 module." }, { "code": null, "e": 28106, "s": 27891, "text": "The bs4 module has a sub-library called Unicode, Dammit that finds the encoded method and uses that to convert to Unicode characters. The original_encoding attribute is used to return the detected encoding method. " }, { "code": null, "e": 28118, "s": 28106, "text": "Example 1 :" }, { "code": null, "e": 28184, "s": 28118, "text": "Given an HTML element parse it and find the encoding method used." }, { "code": null, "e": 28192, "s": 28184, "text": "Python3" }, { "code": "from bs4 import BeautifulSoup # HTML element with contenth1 = b\"<h1>Hello world!!</h1>\" # parsing with html parserparsed = BeautifulSoup(h1, \"html.parser\") # tag foundprint(\"Tag foud :\", parsed.h1.name) # the content inside the tagprint(\"Content :\", parsed.h1.string) # the encoded methodprint(\"Encoding method :\", parsed.original_encoding)", "e": 28533, "s": 28192, "text": null }, { "code": null, "e": 28541, "s": 28533, "text": "Output:" }, { "code": null, "e": 28790, "s": 28541, "text": "Here, the HTML element string is prefixed by ‘b‘, which means treat it as a byte literal. Thus, ASCII encoding method is detected and used by the parser. In real world situations, the original encoding will be the one mentioned in the HTML document" }, { "code": null, "e": 28802, "s": 28790, "text": "Example 2: " }, { "code": null, "e": 28873, "s": 28802, "text": "Given a URL, parse the contents and find the original encoding method." }, { "code": null, "e": 28881, "s": 28873, "text": "Python3" }, { "code": "from bs4 import BeautifulSoupimport requests URL = 'https://www.geeksforgeeks.org/python-update-nested-dictionary/' # request the page from serverpage = requests.get(URL) # parse the contentes of the pagesoup = BeautifulSoup(page.content, \"html.parser\") # encoded methodprint(\"Encoded method :\", soup.original_encoding)", "e": 29201, "s": 28881, "text": null }, { "code": null, "e": 29208, "s": 29201, "text": "Output" }, { "code": null, "e": 29230, "s": 29208, "text": "Enoded method : utf-8" }, { "code": null, "e": 29253, "s": 29230, "text": "Verifying the output :" }, { "code": null, "e": 29261, "s": 29253, "text": "Python3" }, { "code": "from bs4 import BeautifulSoup soup=BeautifulSoup(page.content,\"html.parser\") # fetching the <meta> tag's# charset attribute# of the content abovetag=soup.meta['charset'] print(\"Encoding method :\",tag)", "e": 29462, "s": 29261, "text": null }, { "code": null, "e": 29469, "s": 29462, "text": "Output" }, { "code": null, "e": 29493, "s": 29469, "text": "Encoding method : UTF-8" }, { "code": null, "e": 29711, "s": 29493, "text": "This is a parameter that can be passed to the constructor BeautifulSoup(). This tells the bs4 module explicitly, which encoding method has to be used. This saves time and avoids incorrect parsing due to misprediction." }, { "code": null, "e": 29721, "s": 29711, "text": "Example :" }, { "code": null, "e": 29729, "s": 29721, "text": "Python3" }, { "code": "from bs4 import BeautifulSoup # HTML elementinput = b\"<h1>\\xa2\\xf6`\\xe0</h1>\" # parsing contentsoup = BeautifulSoup(input) print(\"Content :\",soup.h1.string) print(\"Encoding method :\",soup.original_encoding)", "e": 29936, "s": 29729, "text": null }, { "code": null, "e": 29971, "s": 29936, "text": "If the below warning is generated:" }, { "code": null, "e": 30313, "s": 29971, "text": "/usr/lib/python3/dist-packages/bs4/__init__.py:166: UserWarning: No parser was explicitly specified, so I’m using the best available HTML parser for this system (“html5lib”). This usually isn’t a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently." }, { "code": null, "e": 30354, "s": 30313, "text": "To get rid of this warning, change this:" }, { "code": null, "e": 30384, "s": 30354, "text": " BeautifulSoup([your markup])" }, { "code": null, "e": 30393, "s": 30384, "text": "to this:" }, { "code": null, "e": 30435, "s": 30393, "text": " BeautifulSoup([your markup], “html5lib”)" }, { "code": null, "e": 30463, "s": 30435, "text": " markup_type=markup_type))" }, { "code": null, "e": 30498, "s": 30463, "text": "Traceback (most recent call last):" }, { "code": null, "e": 30570, "s": 30498, "text": " File “/home/98e5f50281480cda5f5e31e3bcafb085.py”, line 9, in <module>" }, { "code": null, "e": 30608, "s": 30570, "text": " print(“Content :”,soup.h1.string)" }, { "code": null, "e": 30709, "s": 30608, "text": "UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not in range(128)" }, { "code": null, "e": 30881, "s": 30709, "text": "The editor in GeeksforGeeks tried to parse it with ASCII and ended up with an error. The output of executing the same code in the local machine gave the following output :" }, { "code": null, "e": 31085, "s": 30881, "text": "But the content actually corresponds to “ISO-8859-8” and the interpreted characters are not the desired ones. Thus by explicitly mentioning the encoding method if known, the correct output will be given." }, { "code": null, "e": 31093, "s": 31085, "text": "Python3" }, { "code": "from bs4 import BeautifulSoup # HTML elementinput = b\"<h1>\\xa2\\xf6`\\xe0</h1>\" # parsing contentsoup = BeautifulSoup(input, \"html.parser\", from_encoding=\"iso-8859-8\") print(\"Content :\",soup.h1.string) print(\"Encoding method :\",soup.original_encoding)", "e": 31343, "s": 31093, "text": null }, { "code": null, "e": 31351, "s": 31343, "text": "Output:" }, { "code": null, "e": 31626, "s": 31351, "text": "When the parsed HTML content has to be given as output, by default bs4 module delivers it as UTF-8 encoded document or sometimes with the mispredicted ones. If You want a document to be encoded by other methods without passing to the constructor, the following can be done :" }, { "code": null, "e": 31848, "s": 31626, "text": "prettify() : This method is used to print the HTML content with correct indentation. The encoding method to be used can be passed as a parameter to this method, so that while printing it modifies the encoding method also." }, { "code": null, "e": 31858, "s": 31848, "text": "Example :" }, { "code": null, "e": 31866, "s": 31858, "text": "Python3" }, { "code": "# import modulefrom bs4 import BeautifulSoup # HTML elementinput = b'''<html><meta charset=\"iso-8859-8\"/><body><h1>\\xa2\\xf6`\\xe0</h1></body></html>''' # parsing contentsoup = BeautifulSoup(input,\"html.parser\") print(soup.prettify())", "e": 32099, "s": 31866, "text": null }, { "code": null, "e": 32108, "s": 32099, "text": " Output:" }, { "code": null, "e": 32216, "s": 32110, "text": "Here, you can see the <meta> tag where encoding is set as UTF-8. To prevent this, one can write as below." }, { "code": null, "e": 32224, "s": 32216, "text": "Python3" }, { "code": "from bs4 import BeautifulSoup # HTML elementinput = b'''<html><meta charset=\"iso-8859-8\"/><body><h1>\\xa2\\xf6`\\xe0</h1></body></html>''' # parsing contentsoup = BeautifulSoup(input,\"html.parser\") print(soup.prettify(\"iso-8859-8\"))", "e": 32454, "s": 32224, "text": null }, { "code": null, "e": 32462, "s": 32454, "text": "Output:" }, { "code": null, "e": 32566, "s": 32462, "text": "b'<html>\\n <meta charset=\"iso-8859-8\"/>\\n <body>\\n <h1>\\n \\xa2\\xf6`\\xe0\\n </h1>\\n </body>\\n</html>'" }, { "code": null, "e": 32713, "s": 32566, "text": "encode() : The encoding method can be used to explicitly pass the required method. This replaces characters with the corresponding XML references." }, { "code": null, "e": 32723, "s": 32713, "text": "Example :" }, { "code": null, "e": 32731, "s": 32723, "text": "Python3" }, { "code": "from bs4 import BeautifulSoup # HTML elementinput = b\"<html><head></head><body><h1>\\xa2\\xf6`\\xe0</h1></body></html>\" # parsing contentsoup = BeautifulSoup(input) print(\"Content :\",soup.h1.string) print(\"Encoding method :\",soup.original_encoding) print(\"After explicit encoding :\",soup.html.encode(\"iso-8859-8\"))", "e": 33043, "s": 32731, "text": null }, { "code": null, "e": 33051, "s": 33043, "text": "Output:" }, { "code": null, "e": 33066, "s": 33051, "text": "kapoorsagar226" }, { "code": null, "e": 33073, "s": 33066, "text": "Picked" }, { "code": null, "e": 33094, "s": 33073, "text": "Python BeautifulSoup" }, { "code": null, "e": 33101, "s": 33094, "text": "Python" }, { "code": null, "e": 33199, "s": 33101, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33231, "s": 33199, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33273, "s": 33231, "text": "Check if element exists in list in Python" }, { "code": null, "e": 33315, "s": 33273, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 33371, "s": 33315, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 33398, "s": 33371, "text": "Python Classes and Objects" }, { "code": null, "e": 33429, "s": 33398, "text": "Python | os.path.join() method" }, { "code": null, "e": 33468, "s": 33429, "text": "Python | Get unique values from a list" }, { "code": null, "e": 33497, "s": 33468, "text": "Create a directory in Python" }, { "code": null, "e": 33519, "s": 33497, "text": "Defaultdict in Python" } ]
size of char datatype and char array in C - GeeksforGeeks
15 Oct, 2019 Given a char variable and a char array, the task is to write a program to find the size of this char variable and char array in C. Examples: Input: ch = 'G', arr[] = {'G', 'F', 'G'} Output: Size of char datatype is: 1 byte Size of char array is: 3 byte Input: ch = 'G', arr[] = {'G', 'F'} Output: Size of char datatype is: 1 byte Size of char array is: 2 byte Approach:In the below program, to find the size of the char variable and char array: first, the char variable is defined in charType and the char array in arr. Then, the size of the char variable is calculated using sizeof() operator. Then the size of the char array is find by dividing the size of the complete array by the size of the first variable. Below is the C program to find the size of the char variable and char array: // C program to find the size of// char data type and char array #include <stdio.h> int main(){ char charType = 'G'; char arr[] = { 'G', 'F', 'G' }; // Calculate and Print // the size of charType printf("Size of char datatype is: %ld byte\n", sizeof(charType)); // Calculate the size of char array size_t size = sizeof(arr) / sizeof(arr[0]); // Print the size of char array printf("Size of char array is: %ld byte", size); return 0;} Size of char datatype is: 1 byte Size of char array is: 3 byte C-Data Types C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ 'this' pointer in C++ Multithreading in C Arrow operator -> in C/C++ with Examples Strings in C Arrow operator -> in C/C++ with Examples Header files in C/C++ and its uses C Program to read contents of Whole File UDP Server-Client implementation in C
[ { "code": null, "e": 24330, "s": 24302, "text": "\n15 Oct, 2019" }, { "code": null, "e": 24461, "s": 24330, "text": "Given a char variable and a char array, the task is to write a program to find the size of this char variable and char array in C." }, { "code": null, "e": 24471, "s": 24461, "text": "Examples:" }, { "code": null, "e": 24694, "s": 24471, "text": "Input: ch = 'G', arr[] = {'G', 'F', 'G'}\nOutput: \nSize of char datatype is: 1 byte\nSize of char array is: 3 byte\n\nInput: ch = 'G', arr[] = {'G', 'F'}\nOutput: \nSize of char datatype is: 1 byte\nSize of char array is: 2 byte\n" }, { "code": null, "e": 24779, "s": 24694, "text": "Approach:In the below program, to find the size of the char variable and char array:" }, { "code": null, "e": 24854, "s": 24779, "text": "first, the char variable is defined in charType and the char array in arr." }, { "code": null, "e": 24929, "s": 24854, "text": "Then, the size of the char variable is calculated using sizeof() operator." }, { "code": null, "e": 25047, "s": 24929, "text": "Then the size of the char array is find by dividing the size of the complete array by the size of the first variable." }, { "code": null, "e": 25124, "s": 25047, "text": "Below is the C program to find the size of the char variable and char array:" }, { "code": "// C program to find the size of// char data type and char array #include <stdio.h> int main(){ char charType = 'G'; char arr[] = { 'G', 'F', 'G' }; // Calculate and Print // the size of charType printf(\"Size of char datatype is: %ld byte\\n\", sizeof(charType)); // Calculate the size of char array size_t size = sizeof(arr) / sizeof(arr[0]); // Print the size of char array printf(\"Size of char array is: %ld byte\", size); return 0;}", "e": 25620, "s": 25124, "text": null }, { "code": null, "e": 25684, "s": 25620, "text": "Size of char datatype is: 1 byte\nSize of char array is: 3 byte\n" }, { "code": null, "e": 25697, "s": 25684, "text": "C-Data Types" }, { "code": null, "e": 25708, "s": 25697, "text": "C Language" }, { "code": null, "e": 25719, "s": 25708, "text": "C Programs" }, { "code": null, "e": 25817, "s": 25719, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25855, "s": 25817, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 25881, "s": 25855, "text": "Exception Handling in C++" }, { "code": null, "e": 25903, "s": 25881, "text": "'this' pointer in C++" }, { "code": null, "e": 25923, "s": 25903, "text": "Multithreading in C" }, { "code": null, "e": 25964, "s": 25923, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 25977, "s": 25964, "text": "Strings in C" }, { "code": null, "e": 26018, "s": 25977, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26053, "s": 26018, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 26094, "s": 26053, "text": "C Program to read contents of Whole File" } ]
GATE | GATE CS 2008 | Question 32 - GeeksforGeeks
19 Nov, 2018 Which of the following is/are true of the auto-increment addressing mode? I. It is useful in creating self-relocating code. II. If it is included in an Instruction Set Architecture, then an additional ALU is required for effective address calculation. III.The amount of increment depends on the size of the data item accessed. (A) I only(B) II only(C) III Only(D) II and III onlyAnswer: (C)Explanation: In auto-increment addressing mode the address where next data block to be stored is generated automatically depending upon the size of single data item required to store. Self relocating code takes always some address in memory and statement says that this mode is used for self relocating code so option 1 is incorrect and no additional ALU is required So option (C) is correct option.Quiz of this Question GATE-CS-2008 GATE-GATE CS 2008 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25861, "s": 25833, "text": "\n19 Nov, 2018" }, { "code": null, "e": 25935, "s": 25861, "text": "Which of the following is/are true of the auto-increment addressing mode?" }, { "code": null, "e": 26204, "s": 25935, "text": "I. It is useful in creating self-relocating code.\nII. If it is included in an Instruction Set Architecture, \n then an additional ALU is required for effective address \n calculation.\nIII.The amount of increment depends on the size of the data\n item accessed." }, { "code": null, "e": 26451, "s": 26204, "text": "(A) I only(B) II only(C) III Only(D) II and III onlyAnswer: (C)Explanation: In auto-increment addressing mode the address where next data block to be stored is generated automatically depending upon the size of single data item required to store." }, { "code": null, "e": 26689, "s": 26451, "text": "Self relocating code takes always some address in memory and statement says that this mode is used for self relocating code so option 1 is incorrect and no additional ALU is required So option (C) is correct option.Quiz of this Question" }, { "code": null, "e": 26702, "s": 26689, "text": "GATE-CS-2008" }, { "code": null, "e": 26720, "s": 26702, "text": "GATE-GATE CS 2008" }, { "code": null, "e": 26725, "s": 26720, "text": "GATE" }, { "code": null, "e": 26823, "s": 26725, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26857, "s": 26823, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26891, "s": 26857, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26925, "s": 26891, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26958, "s": 26925, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26994, "s": 26958, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27028, "s": 26994, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27064, "s": 27028, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27098, "s": 27064, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27132, "s": 27098, "text": "GATE | GATE-CS-2009 | Question 38" } ]
String Literal Vs String Object in Java - GeeksforGeeks
23 Jan, 2018 Compare string initialization performance for String Literal and String object.String Literal String str = “GeeksForGeeks”; This is string literal. When you declare string like this, you are actually calling intern() method on String. This method references internal pool of string objects. If there already exists a string value “GeeksForGeeks”, then str will reference of that string and no new String object will be created. Please refer Initialize and Compare Strings in Java for details. String Object String str = new String(“GeeksForGeeks”); This is string object. In this method JVM is forced to create a new string reference, even if “GeeksForGeeks” is in the reference pool. Therefore, if we compare performance of string literal and string object, string object will always take more time to execute than string literal because it will construct a new string every time it is executed.Note: Execution time is compiler dependent. Below is the Java program to compare their performances. // Java program to compare performance // of string literal and string object class ComparePerformance { public static void main(String args[]) { // Initialization time for String // Literal long start1 = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { String s1 = "GeeksForGeeks"; String s2 = "Welcome"; } long end1 = System.currentTimeMillis(); long total_time = end1 - start1; System.out.println("Time taken to execute"+ " string literal = " + total_time); // Initialization time for String // object long start2 = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { String s3 = new String("GeeksForGeeks"); String s4 = new String("Welcome"); } long end2 = System.currentTimeMillis(); long total_time1 = end2 - start2; System.out.println("Time taken to execute"+ " string object=" + total_time1); }} Output: Time taken to execute string literal = 0 Time taken to execute string object = 2 Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java Stream In Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 24652, "s": 24624, "text": "\n23 Jan, 2018" }, { "code": null, "e": 24746, "s": 24652, "text": "Compare string initialization performance for String Literal and String object.String Literal" }, { "code": null, "e": 24776, "s": 24746, "text": "String str = “GeeksForGeeks”;" }, { "code": null, "e": 25145, "s": 24776, "text": "This is string literal. When you declare string like this, you are actually calling intern() method on String. This method references internal pool of string objects. If there already exists a string value “GeeksForGeeks”, then str will reference of that string and no new String object will be created. Please refer Initialize and Compare Strings in Java for details." }, { "code": null, "e": 25159, "s": 25145, "text": "String Object" }, { "code": null, "e": 25201, "s": 25159, "text": "String str = new String(“GeeksForGeeks”);" }, { "code": null, "e": 25337, "s": 25201, "text": "This is string object. In this method JVM is forced to create a new string reference, even if “GeeksForGeeks” is in the reference pool." }, { "code": null, "e": 25592, "s": 25337, "text": "Therefore, if we compare performance of string literal and string object, string object will always take more time to execute than string literal because it will construct a new string every time it is executed.Note: Execution time is compiler dependent." }, { "code": null, "e": 25649, "s": 25592, "text": "Below is the Java program to compare their performances." }, { "code": "// Java program to compare performance // of string literal and string object class ComparePerformance { public static void main(String args[]) { // Initialization time for String // Literal long start1 = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { String s1 = \"GeeksForGeeks\"; String s2 = \"Welcome\"; } long end1 = System.currentTimeMillis(); long total_time = end1 - start1; System.out.println(\"Time taken to execute\"+ \" string literal = \" + total_time); // Initialization time for String // object long start2 = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { String s3 = new String(\"GeeksForGeeks\"); String s4 = new String(\"Welcome\"); } long end2 = System.currentTimeMillis(); long total_time1 = end2 - start2; System.out.println(\"Time taken to execute\"+ \" string object=\" + total_time1); }}", "e": 26742, "s": 25649, "text": null }, { "code": null, "e": 26750, "s": 26742, "text": "Output:" }, { "code": null, "e": 26832, "s": 26750, "text": "Time taken to execute string literal = 0\nTime taken to execute string object = 2\n" }, { "code": null, "e": 26845, "s": 26832, "text": "Java-Strings" }, { "code": null, "e": 26850, "s": 26845, "text": "Java" }, { "code": null, "e": 26863, "s": 26850, "text": "Java-Strings" }, { "code": null, "e": 26868, "s": 26863, "text": "Java" }, { "code": null, "e": 26966, "s": 26868, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27017, "s": 26966, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27032, "s": 27017, "text": "Stream In Java" }, { "code": null, "e": 27062, "s": 27032, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27081, "s": 27062, "text": "Interfaces in Java" }, { "code": null, "e": 27112, "s": 27081, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27130, "s": 27112, "text": "ArrayList in Java" }, { "code": null, "e": 27162, "s": 27130, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27182, "s": 27162, "text": "Stack Class in Java" }, { "code": null, "e": 27206, "s": 27182, "text": "Singleton Class in Java" } ]
Scala Stack toMap() method with example - GeeksforGeeks
03 Nov, 2019 In Scala Stack class, the toMap() method is utilized to return a map consisting of all the elements of the stack. Method Definition: def toMap[T, U]: Map[T, U] Return Type: It returns a map consisting of all the elements of the stack. Example #1: // Scala program of toMap() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack((1, 2), (3, 4), (5, 6)) // Print the stack println(s1) // Applying toMap method val result = s1.toMap // Display output print("Elements in the map: " + result) } } Stack((1, 2), (3, 4), (5, 6)) Elements in the map: Map(1 -> 2, 3 -> 4, 5 -> 6) Example #2: // Scala program of toMap() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack((5, 2), (13, 7), (1, 3)) // Print the stack println(s1) // Applying toMap method val result = s1.toMap // Display output print("Elements in the map: " + result) } } Stack((5, 2), (13, 7), (1, 3)) Elements in the map: Map(5 -> 2, 13 -> 7, 1 -> 3) Scala scala-collection Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Type Casting in Scala Class and Object in Scala Scala Lists Scala Constructors Scala Tutorial – Learn Scala with Step By Step Guide Operators in Scala Scala | Arrays Scala String substring() method with example How to get the first element of List in Scala Scala String replace() method with example
[ { "code": null, "e": 25361, "s": 25333, "text": "\n03 Nov, 2019" }, { "code": null, "e": 25475, "s": 25361, "text": "In Scala Stack class, the toMap() method is utilized to return a map consisting of all the elements of the stack." }, { "code": null, "e": 25521, "s": 25475, "text": "Method Definition: def toMap[T, U]: Map[T, U]" }, { "code": null, "e": 25596, "s": 25521, "text": "Return Type: It returns a map consisting of all the elements of the stack." }, { "code": null, "e": 25608, "s": 25596, "text": "Example #1:" }, { "code": "// Scala program of toMap() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack((1, 2), (3, 4), (5, 6)) // Print the stack println(s1) // Applying toMap method val result = s1.toMap // Display output print(\"Elements in the map: \" + result) } } ", "e": 26103, "s": 25608, "text": null }, { "code": null, "e": 26183, "s": 26103, "text": "Stack((1, 2), (3, 4), (5, 6))\nElements in the map: Map(1 -> 2, 3 -> 4, 5 -> 6)\n" }, { "code": null, "e": 26195, "s": 26183, "text": "Example #2:" }, { "code": "// Scala program of toMap() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack((5, 2), (13, 7), (1, 3)) // Print the stack println(s1) // Applying toMap method val result = s1.toMap // Display output print(\"Elements in the map: \" + result) } } ", "e": 26691, "s": 26195, "text": null }, { "code": null, "e": 26773, "s": 26691, "text": "Stack((5, 2), (13, 7), (1, 3))\nElements in the map: Map(5 -> 2, 13 -> 7, 1 -> 3)\n" }, { "code": null, "e": 26779, "s": 26773, "text": "Scala" }, { "code": null, "e": 26796, "s": 26779, "text": "scala-collection" }, { "code": null, "e": 26809, "s": 26796, "text": "Scala-Method" }, { "code": null, "e": 26815, "s": 26809, "text": "Scala" }, { "code": null, "e": 26913, "s": 26815, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26935, "s": 26913, "text": "Type Casting in Scala" }, { "code": null, "e": 26961, "s": 26935, "text": "Class and Object in Scala" }, { "code": null, "e": 26973, "s": 26961, "text": "Scala Lists" }, { "code": null, "e": 26992, "s": 26973, "text": "Scala Constructors" }, { "code": null, "e": 27045, "s": 26992, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 27064, "s": 27045, "text": "Operators in Scala" }, { "code": null, "e": 27079, "s": 27064, "text": "Scala | Arrays" }, { "code": null, "e": 27124, "s": 27079, "text": "Scala String substring() method with example" }, { "code": null, "e": 27170, "s": 27124, "text": "How to get the first element of List in Scala" } ]
What is the Difference Between i++ and ++i in Java? - GeeksforGeeks
07 Jan, 2021 ++i and i++ both increment the value of i by 1 but in a different way. If ++ precedes the variable, it is called pre-increment operator and it comes after a variable, it is called post-increment operator. Increment in java is performed in two ways, 1) Post-Increment (i++): we use i++ in our statement if we want to use the current value, and then we want to increment the value of i by 1. 2) Pre-Increment(++i): We use ++i in our statement if we want to increment the value of i by 1 and then use it in our statement. Example int i = 3; int a = i++; // a = 3, i = 4 int b = ++a; // b = 4, a = 4 Example 1 Java // Java program to demonstrate pre and post increment// operators import java.io.*; class GFG { public static void main(String[] args) { // initialize i int i = 0; System.out.println("Post-Increment"); // i values is incremented to 1 after returning // current value i.e; 0 System.out.println(i++); // initialized to 0 int j = 0; System.out.println("Pre-Increment"); // j is incremented to 1 and then it's value is // returned System.out.println(++j); }} Post-Increment 0 Pre-Increment 1 Example 2: Cannot apply the increment operator (++) on a constant value Java // Applying increment operator on a constant value import java.io.*; class GFG { public static void main(String[] args) { int x = ++10; System.out.println("Hello"); }} Output prog.java:8: error: unexpected type int x = ++ 10; ^ required: variable found: value 1 error Picked Technical Scripter 2020 Difference Between Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java Arrays in Java Split() String method in Java with examples For-each loop in Java Stream In Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 26679, "s": 26651, "text": "\n07 Jan, 2021" }, { "code": null, "e": 26884, "s": 26679, "text": "++i and i++ both increment the value of i by 1 but in a different way. If ++ precedes the variable, it is called pre-increment operator and it comes after a variable, it is called post-increment operator." }, { "code": null, "e": 26928, "s": 26884, "text": "Increment in java is performed in two ways," }, { "code": null, "e": 27069, "s": 26928, "text": "1) Post-Increment (i++): we use i++ in our statement if we want to use the current value, and then we want to increment the value of i by 1." }, { "code": null, "e": 27198, "s": 27069, "text": "2) Pre-Increment(++i): We use ++i in our statement if we want to increment the value of i by 1 and then use it in our statement." }, { "code": null, "e": 27206, "s": 27198, "text": "Example" }, { "code": null, "e": 27275, "s": 27206, "text": "int i = 3;\nint a = i++; // a = 3, i = 4\nint b = ++a; // b = 4, a = 4" }, { "code": null, "e": 27285, "s": 27275, "text": "Example 1" }, { "code": null, "e": 27290, "s": 27285, "text": "Java" }, { "code": "// Java program to demonstrate pre and post increment// operators import java.io.*; class GFG { public static void main(String[] args) { // initialize i int i = 0; System.out.println(\"Post-Increment\"); // i values is incremented to 1 after returning // current value i.e; 0 System.out.println(i++); // initialized to 0 int j = 0; System.out.println(\"Pre-Increment\"); // j is incremented to 1 and then it's value is // returned System.out.println(++j); }}", "e": 27846, "s": 27290, "text": null }, { "code": null, "e": 27879, "s": 27846, "text": "Post-Increment\n0\nPre-Increment\n1" }, { "code": null, "e": 27951, "s": 27879, "text": "Example 2: Cannot apply the increment operator (++) on a constant value" }, { "code": null, "e": 27956, "s": 27951, "text": "Java" }, { "code": "// Applying increment operator on a constant value import java.io.*; class GFG { public static void main(String[] args) { int x = ++10; System.out.println(\"Hello\"); }}", "e": 28153, "s": 27956, "text": null }, { "code": null, "e": 28160, "s": 28153, "text": "Output" }, { "code": null, "e": 28291, "s": 28160, "text": "prog.java:8: error: unexpected type\n int x = ++ 10;\n ^\n required: variable\n found: value\n1 error" }, { "code": null, "e": 28298, "s": 28291, "text": "Picked" }, { "code": null, "e": 28322, "s": 28298, "text": "Technical Scripter 2020" }, { "code": null, "e": 28341, "s": 28322, "text": "Difference Between" }, { "code": null, "e": 28346, "s": 28341, "text": "Java" }, { "code": null, "e": 28365, "s": 28346, "text": "Technical Scripter" }, { "code": null, "e": 28370, "s": 28365, "text": "Java" }, { "code": null, "e": 28468, "s": 28370, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28529, "s": 28468, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28597, "s": 28529, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 28655, "s": 28597, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 28710, "s": 28655, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 28776, "s": 28710, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 28791, "s": 28776, "text": "Arrays in Java" }, { "code": null, "e": 28835, "s": 28791, "text": "Split() String method in Java with examples" }, { "code": null, "e": 28857, "s": 28835, "text": "For-each loop in Java" }, { "code": null, "e": 28872, "s": 28857, "text": "Stream In Java" } ]
Python | Basic Gantt chart using Matplotlib - GeeksforGeeks
16 Aug, 2021 Prerequisites : Matplotlib IntroductionIn this article, we will be discussing how to plot a Gantt Chart in Python using Matplotlib.A Gantt chart is a graphical depiction of a project schedule or task schedule (In OS). It’s is a type of bar chart that shows the start and finish dates of several elements of a project that include resources or deadline. The first Gantt chart was devised in the mid-1890s by Karol Adamiecki, a Polish engineer who ran a steelworks in southern Poland and had become interested in management ideas and techniques. Some 15 years after Adamiecki, Henry Gantt, an American engineer, and project management consultant, devised his own version of the chart which became famous as “Gantt Charts”.Some Uses of Gantt Charts : Project Scheduling. Task Scheduling on Processors A sample Gantt Chart for task scheduling is shown below: We will be using broken_barh types of graph available in matplotlib to draw gantt charts.Below is the code for generating the above ganntt chart : Python3 # Importing the matplotlib.pyplotimport matplotlib.pyplot as plt # Declaring a figure "gnt"fig, gnt = plt.subplots() # Setting Y-axis limitsgnt.set_ylim(0, 50) # Setting X-axis limitsgnt.set_xlim(0, 160) # Setting labels for x-axis and y-axisgnt.set_xlabel('seconds since start')gnt.set_ylabel('Processor') # Setting ticks on y-axisgnt.set_yticks([15, 25, 35])# Labelling tickes of y-axisgnt.set_yticklabels(['1', '2', '3']) # Setting graph attributegnt.grid(True) # Declaring a bar in schedulegnt.broken_barh([(40, 50)], (30, 9), facecolors =('tab:orange')) # Declaring multiple bars in at same level and same widthgnt.broken_barh([(110, 10), (150, 10)], (10, 9), facecolors ='tab:blue') gnt.broken_barh([(10, 50), (100, 20), (130, 10)], (20, 9), facecolors =('tab:red')) plt.savefig("gantt1.png") Lets’s understand the different pieces of codes one by one : fig, gnt = plt.subplots() Here, we declared a figure “gnt” for plotting the chart. gnt.set_ylim(0, 50) gnt.set_xlim(0, 160) Here, we declared the limits of X-axis and Y-axis of the chart. By default the lower X-axis and Y-axis limit is 0 and higher limits for both axis is 5 unit more the highest X-axis value and Y-axis value. gnt.set_xlabel('seconds since start') gnt.set_ylabel('Processor') Here, we added labels to the axes. By default, there is no labels. gnt.set_yticks([15, 25, 35]) gnt.set_yticklabels(['1', '2', '3']) Here, we added ticks in Y-axis. We can also label them. By default the axes is divides uniformly in the limits. gnt.grid(True) Here, we set grid() to True to show grids. By default, it is False. gnt.broken_barh([(40, 50)], (30, 9), facecolors=('tab:orange')) Here, we added a bar in the chart. In this example, this bar represent the operation going on for time 40 to (40+50)= 90 sec.The basic arguments : gnt.broken_barh([(start_time, duration)], (lower_yaxis, height), facecolors=('tab:colours')) By default color is set to Blue.We can declare multiple bars at the same time : gnt.broken_barh([(10, 50), (100, 20), (130, 10)], (20, 9), facecolors=('tab:red')) We can also add edge color by setting “edgecolor” attribute to any color. plt.savefig("gantt1.png") We saved the figure formed in the png file. Reference : Broken Barh Example Matplotlib Documentation saurabh1990aror surindertarika1234 Python-matplotlib python-utility Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25747, "s": 25719, "text": "\n16 Aug, 2021" }, { "code": null, "e": 26497, "s": 25747, "text": "Prerequisites : Matplotlib IntroductionIn this article, we will be discussing how to plot a Gantt Chart in Python using Matplotlib.A Gantt chart is a graphical depiction of a project schedule or task schedule (In OS). It’s is a type of bar chart that shows the start and finish dates of several elements of a project that include resources or deadline. The first Gantt chart was devised in the mid-1890s by Karol Adamiecki, a Polish engineer who ran a steelworks in southern Poland and had become interested in management ideas and techniques. Some 15 years after Adamiecki, Henry Gantt, an American engineer, and project management consultant, devised his own version of the chart which became famous as “Gantt Charts”.Some Uses of Gantt Charts : " }, { "code": null, "e": 26517, "s": 26497, "text": "Project Scheduling." }, { "code": null, "e": 26547, "s": 26517, "text": "Task Scheduling on Processors" }, { "code": null, "e": 26606, "s": 26547, "text": "A sample Gantt Chart for task scheduling is shown below: " }, { "code": null, "e": 26755, "s": 26606, "text": "We will be using broken_barh types of graph available in matplotlib to draw gantt charts.Below is the code for generating the above ganntt chart : " }, { "code": null, "e": 26763, "s": 26755, "text": "Python3" }, { "code": "# Importing the matplotlib.pyplotimport matplotlib.pyplot as plt # Declaring a figure \"gnt\"fig, gnt = plt.subplots() # Setting Y-axis limitsgnt.set_ylim(0, 50) # Setting X-axis limitsgnt.set_xlim(0, 160) # Setting labels for x-axis and y-axisgnt.set_xlabel('seconds since start')gnt.set_ylabel('Processor') # Setting ticks on y-axisgnt.set_yticks([15, 25, 35])# Labelling tickes of y-axisgnt.set_yticklabels(['1', '2', '3']) # Setting graph attributegnt.grid(True) # Declaring a bar in schedulegnt.broken_barh([(40, 50)], (30, 9), facecolors =('tab:orange')) # Declaring multiple bars in at same level and same widthgnt.broken_barh([(110, 10), (150, 10)], (10, 9), facecolors ='tab:blue') gnt.broken_barh([(10, 50), (100, 20), (130, 10)], (20, 9), facecolors =('tab:red')) plt.savefig(\"gantt1.png\")", "e": 27619, "s": 26763, "text": null }, { "code": null, "e": 27681, "s": 27619, "text": "Lets’s understand the different pieces of codes one by one : " }, { "code": null, "e": 27707, "s": 27681, "text": "fig, gnt = plt.subplots()" }, { "code": null, "e": 27765, "s": 27707, "text": "Here, we declared a figure “gnt” for plotting the chart. " }, { "code": null, "e": 27806, "s": 27765, "text": "gnt.set_ylim(0, 50)\ngnt.set_xlim(0, 160)" }, { "code": null, "e": 28011, "s": 27806, "text": "Here, we declared the limits of X-axis and Y-axis of the chart. By default the lower X-axis and Y-axis limit is 0 and higher limits for both axis is 5 unit more the highest X-axis value and Y-axis value. " }, { "code": null, "e": 28077, "s": 28011, "text": "gnt.set_xlabel('seconds since start')\ngnt.set_ylabel('Processor')" }, { "code": null, "e": 28145, "s": 28077, "text": "Here, we added labels to the axes. By default, there is no labels. " }, { "code": null, "e": 28211, "s": 28145, "text": "gnt.set_yticks([15, 25, 35])\ngnt.set_yticklabels(['1', '2', '3'])" }, { "code": null, "e": 28324, "s": 28211, "text": "Here, we added ticks in Y-axis. We can also label them. By default the axes is divides uniformly in the limits. " }, { "code": null, "e": 28339, "s": 28324, "text": "gnt.grid(True)" }, { "code": null, "e": 28408, "s": 28339, "text": "Here, we set grid() to True to show grids. By default, it is False. " }, { "code": null, "e": 28472, "s": 28408, "text": "gnt.broken_barh([(40, 50)], (30, 9), facecolors=('tab:orange'))" }, { "code": null, "e": 28620, "s": 28472, "text": "Here, we added a bar in the chart. In this example, this bar represent the operation going on for time 40 to (40+50)= 90 sec.The basic arguments : " }, { "code": null, "e": 28747, "s": 28620, "text": "gnt.broken_barh([(start_time, duration)],\n (lower_yaxis, height),\n facecolors=('tab:colours'))" }, { "code": null, "e": 28828, "s": 28747, "text": "By default color is set to Blue.We can declare multiple bars at the same time : " }, { "code": null, "e": 28945, "s": 28828, "text": "gnt.broken_barh([(10, 50), (100, 20), (130, 10)], (20, 9),\n facecolors=('tab:red'))" }, { "code": null, "e": 29020, "s": 28945, "text": "We can also add edge color by setting “edgecolor” attribute to any color. " }, { "code": null, "e": 29046, "s": 29020, "text": "plt.savefig(\"gantt1.png\")" }, { "code": null, "e": 29091, "s": 29046, "text": "We saved the figure formed in the png file. " }, { "code": null, "e": 29148, "s": 29091, "text": "Reference : Broken Barh Example Matplotlib Documentation" }, { "code": null, "e": 29164, "s": 29148, "text": "saurabh1990aror" }, { "code": null, "e": 29183, "s": 29164, "text": "surindertarika1234" }, { "code": null, "e": 29201, "s": 29183, "text": "Python-matplotlib" }, { "code": null, "e": 29216, "s": 29201, "text": "python-utility" }, { "code": null, "e": 29223, "s": 29216, "text": "Python" }, { "code": null, "e": 29239, "s": 29223, "text": "Python Programs" }, { "code": null, "e": 29337, "s": 29239, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29355, "s": 29337, "text": "Python Dictionary" }, { "code": null, "e": 29390, "s": 29355, "text": "Read a file line by line in Python" }, { "code": null, "e": 29422, "s": 29390, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29464, "s": 29422, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29490, "s": 29464, "text": "Python String | replace()" }, { "code": null, "e": 29533, "s": 29490, "text": "Python program to convert a list to string" }, { "code": null, "e": 29555, "s": 29533, "text": "Defaultdict in Python" }, { "code": null, "e": 29594, "s": 29555, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29640, "s": 29594, "text": "Python | Split string into list of characters" } ]
Babylonian method to find the square root
The Babylonian method to find square root is based on one of the numerical method, which is based on the Newton- Raphson method for solving non-linear equations. The idea is simple, starting from an arbitrary value of x, and y as 1, we can simply get next approximation of root by finding the average of x and y. Then the y value will be updated with number / x. Input: A number: 65 Output: The square root of 65 is: 8.06226 sqRoot(number) Input: The number in real. Output: Square root of given number. Begin x := number y := 1 precision := 0.000001 while relative error of x and y > precision, do x := (x+y) / 2 y := number / x done return x End #include<iostream> #include<cmath> using namespace std; float sqRoot(float number) { float x = number, y = 1; //initial guess as number and 1 float precision = 0.000001; //the result is correct upto 0.000001 while(abs(x - y)/abs(x) > precision) { x = (x + y)/2; y = number/x; } return x; } int main() { int n; cout << "Enter Number to find square root: "; cin >> n; cout << "The square root of " << n <<" is: " << sqRoot(n); } Enter Number to find square root: 65 The square root of 65 is: 8.06226
[ { "code": null, "e": 1224, "s": 1062, "text": "The Babylonian method to find square root is based on one of the numerical method, which is based on the Newton- Raphson method for solving non-linear equations." }, { "code": null, "e": 1426, "s": 1224, "text": "The idea is simple, starting from an arbitrary value of x, and y as 1, we can simply get next approximation of root by finding the average of x and y. Then the y value will be updated with number / x." }, { "code": null, "e": 1488, "s": 1426, "text": "Input:\nA number: 65\nOutput:\nThe square root of 65 is: 8.06226" }, { "code": null, "e": 1503, "s": 1488, "text": "sqRoot(number)" }, { "code": null, "e": 1530, "s": 1503, "text": "Input: The number in real." }, { "code": null, "e": 1567, "s": 1530, "text": "Output: Square root of given number." }, { "code": null, "e": 1741, "s": 1567, "text": "Begin\n x := number\n y := 1\n precision := 0.000001\n while relative error of x and y > precision, do\n x := (x+y) / 2\n y := number / x\n done\n return x\nEnd" }, { "code": null, "e": 2230, "s": 1741, "text": "#include<iostream>\n#include<cmath>\nusing namespace std;\n\nfloat sqRoot(float number) {\n float x = number, y = 1; //initial guess as number and 1\n float precision = 0.000001; //the result is correct upto 0.000001\n\n while(abs(x - y)/abs(x) > precision) {\n x = (x + y)/2;\n y = number/x;\n }\n return x;\n}\n\nint main() {\n int n;\n cout << \"Enter Number to find square root: \"; cin >> n;\n cout << \"The square root of \" << n <<\" is: \" << sqRoot(n);\n}" }, { "code": null, "e": 2301, "s": 2230, "text": "Enter Number to find square root: 65\nThe square root of 65 is: 8.06226" } ]
Cython to Wrap Existing C Code - GeeksforGeeks
29 Mar, 2019 What is Cython ?It is an optimizing static compiler for both the Python programming language and the extended Cython programming language. It is used to make it easy to write C extensions for Python as easy as Python itself. It comes up with many helpful features : Writing a Python code that calls back and forth from and to C/C++ code. Easily tuning of readable Python code into plain C performance by adding static type declarations. Use of combined source code level debugging to find bugs in given Python, Cython and C code. Efficient interaction with large data sets, e.g. using multi-dimensional NumPy arrays. Integration with existing code and data from low-level or high-performance libraries and applications. To make an extension with Cython is a tricky task to perform. Doing so, one needs to create a collection of wrapper functions. Assuming that the work code shown has been compiled into a C library called libwork. The code below will create a file named csample.pxd. Code #1 : # cwork.pxd## Declarations of "external" C # functions and structures cdef extern from "work.h": int gcd(int, int) int divide(int, int, int *) double avg(double *, int) nogil ctypedef struct Point: double x double y double distance(Point *, Point *) In Cython, the code above will work as a C header file. The initial declaration cdef extern from "work.h" declares the required C header file. Declarations that follow are taken from the header. The name of this file is cwork.pxd. Next target is to create a work.pyx file which will define wrappers that bridge the Python interpreter to the underlying C code declared in the cwork.pxd file. Code #2 : # work.pyx# Import the low-level C declarations cimport cwork# Importing functionalities from Python# and the C stdlibfrom cpython.pycapsule cimport * from libc.stdlib cimport malloc, free # Wrappersdef gcd(unsigned int x, unsigned int y): return cwork.gcd(x, y) def divide(x, y): cdef int rem quot = cwork.divide(x, y, &rem) return quot, rem def avg(double[:] a): cdef: int sz double result sz = a.size with nogil: result = cwork.avg(<double *> &a[0], sz) return result Code #3 : # Destructor for cleaning up Point objectscdef del_Point(object obj): pt = <csample.Point *> PyCapsule_GetPointer(obj, "Point") free(<void *> pt) # Create a Point object and return as a capsuledef Point(double x, double y): cdef csample.Point * p p = <csample.Point *> malloc(sizeof(csample.Point)) if p == NULL: raise MemoryError("No memory to make a Point") p.x = x p.y = y return PyCapsule_New(<void *>p, "Point", <PyCapsule_Destructor>del_Point) def distance(p1, p2): pt1 = <csample.Point *> PyCapsule_GetPointer(p1, "Point") pt2 = <csample.Point *> PyCapsule_GetPointer(p2, "Point") return csample.distance(pt1, pt2) Finally, to build the extension module, create a work.py file. Code #4: # importing librariesfrom distutils.core import setupfrom distutils.extension import Extensionfrom Cython.Distutils import build_ext ext_modules = [Extension('work', ['work.pyx'], libraries=['work'], library_dirs=['.'])] setup(name = 'work extension module', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules) Code #5 : Building resulting module for experimentation. bash % python3 setup.py build_ext --inplacerunning build_ext cythoning work.pyx to work.cbuilding 'work' extension gcc -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes-I/usr/local/include/python3.3m -c work.c-o build/temp.macosx-10.6-x86_64-3.3/work.o gcc -bundle -undefined dynamic_lookup build/temp.macosx-10.6-x86_64-3.3/work.o-L. -lwork -o work.sobash % Now, we have an extension module work.so. Let’s see how it works. Code #6 : import sampleprint ("GCD : ", sample.gcd(12, 8)) print ("\nDivision : ", sample.divide(42,10)) import arrayarr = array.array('d',[1,2,3])print ("\nAverage : ", sample.avg(a) pt1 = sample.Point(2,3)pt2 = sample.Point(4,5) print ("\npt1 : ", pt1)print ("\npt2 : ", pt2) print ("\nDistance between the two points : ", sample.distance(pt1, pt2)) Output : GCD : 4 Division : (4, 2) Average : 2.0 pt1 : <capsule object "Point" at 0x1005d1e70> pt2 : <capsule object "Point" at 0x1005d1ea0> Distance between the two points : 2.8284271247461903 At a high level, using Cython is modeled after C. The .pxd files merely contain C definitions (similar to .h files) and the .pyx files contain implementation (similar to a .c file). The cimport statement is used by Cython to import definitions from a .pxd file. This is different than using a normal Python import statement, which would load a regular Python module. Marketing Python-ctype Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Python | Get unique values from a list Python | Pandas dataframe.groupby() Defaultdict in Python
[ { "code": null, "e": 25555, "s": 25527, "text": "\n29 Mar, 2019" }, { "code": null, "e": 25780, "s": 25555, "text": "What is Cython ?It is an optimizing static compiler for both the Python programming language and the extended Cython programming language. It is used to make it easy to write C extensions for Python as easy as Python itself." }, { "code": null, "e": 25821, "s": 25780, "text": "It comes up with many helpful features :" }, { "code": null, "e": 25893, "s": 25821, "text": "Writing a Python code that calls back and forth from and to C/C++ code." }, { "code": null, "e": 25992, "s": 25893, "text": "Easily tuning of readable Python code into plain C performance by adding static type declarations." }, { "code": null, "e": 26085, "s": 25992, "text": "Use of combined source code level debugging to find bugs in given Python, Cython and C code." }, { "code": null, "e": 26172, "s": 26085, "text": "Efficient interaction with large data sets, e.g. using multi-dimensional NumPy arrays." }, { "code": null, "e": 26275, "s": 26172, "text": "Integration with existing code and data from low-level or high-performance libraries and applications." }, { "code": null, "e": 26540, "s": 26275, "text": "To make an extension with Cython is a tricky task to perform. Doing so, one needs to create a collection of wrapper functions. Assuming that the work code shown has been compiled into a C library called libwork. The code below will create a file named csample.pxd." }, { "code": null, "e": 26550, "s": 26540, "text": "Code #1 :" }, { "code": "# cwork.pxd## Declarations of \"external\" C # functions and structures cdef extern from \"work.h\": int gcd(int, int) int divide(int, int, int *) double avg(double *, int) nogil ctypedef struct Point: double x double y double distance(Point *, Point *)", "e": 26849, "s": 26550, "text": null }, { "code": null, "e": 27240, "s": 26849, "text": "In Cython, the code above will work as a C header file. The initial declaration cdef extern from \"work.h\" declares the required C header file. Declarations that follow are taken from the header. The name of this file is cwork.pxd. Next target is to create a work.pyx file which will define wrappers that bridge the Python interpreter to the underlying C code declared in the cwork.pxd file." }, { "code": null, "e": 27250, "s": 27240, "text": "Code #2 :" }, { "code": "# work.pyx# Import the low-level C declarations cimport cwork# Importing functionalities from Python# and the C stdlibfrom cpython.pycapsule cimport * from libc.stdlib cimport malloc, free # Wrappersdef gcd(unsigned int x, unsigned int y): return cwork.gcd(x, y) def divide(x, y): cdef int rem quot = cwork.divide(x, y, &rem) return quot, rem def avg(double[:] a): cdef: int sz double result sz = a.size with nogil: result = cwork.avg(<double *> &a[0], sz) return result", "e": 27782, "s": 27250, "text": null }, { "code": null, "e": 27793, "s": 27782, "text": " Code #3 :" }, { "code": "# Destructor for cleaning up Point objectscdef del_Point(object obj): pt = <csample.Point *> PyCapsule_GetPointer(obj, \"Point\") free(<void *> pt) # Create a Point object and return as a capsuledef Point(double x, double y): cdef csample.Point * p p = <csample.Point *> malloc(sizeof(csample.Point)) if p == NULL: raise MemoryError(\"No memory to make a Point\") p.x = x p.y = y return PyCapsule_New(<void *>p, \"Point\", <PyCapsule_Destructor>del_Point) def distance(p1, p2): pt1 = <csample.Point *> PyCapsule_GetPointer(p1, \"Point\") pt2 = <csample.Point *> PyCapsule_GetPointer(p2, \"Point\") return csample.distance(pt1, pt2)", "e": 28513, "s": 27793, "text": null }, { "code": null, "e": 28577, "s": 28513, "text": " Finally, to build the extension module, create a work.py file." }, { "code": null, "e": 28586, "s": 28577, "text": "Code #4:" }, { "code": "# importing librariesfrom distutils.core import setupfrom distutils.extension import Extensionfrom Cython.Distutils import build_ext ext_modules = [Extension('work', ['work.pyx'], libraries=['work'], library_dirs=['.'])] setup(name = 'work extension module', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules)", "e": 28996, "s": 28586, "text": null }, { "code": null, "e": 29054, "s": 28996, "text": " Code #5 : Building resulting module for experimentation." }, { "code": "bash % python3 setup.py build_ext --inplacerunning build_ext cythoning work.pyx to work.cbuilding 'work' extension gcc -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes-I/usr/local/include/python3.3m -c work.c-o build/temp.macosx-10.6-x86_64-3.3/work.o gcc -bundle -undefined dynamic_lookup build/temp.macosx-10.6-x86_64-3.3/work.o-L. -lwork -o work.sobash %", "e": 29437, "s": 29054, "text": null }, { "code": null, "e": 29503, "s": 29437, "text": "Now, we have an extension module work.so. Let’s see how it works." }, { "code": null, "e": 29513, "s": 29503, "text": "Code #6 :" }, { "code": "import sampleprint (\"GCD : \", sample.gcd(12, 8)) print (\"\\nDivision : \", sample.divide(42,10)) import arrayarr = array.array('d',[1,2,3])print (\"\\nAverage : \", sample.avg(a) pt1 = sample.Point(2,3)pt2 = sample.Point(4,5) print (\"\\npt1 : \", pt1)print (\"\\npt2 : \", pt2) print (\"\\nDistance between the two points : \", sample.distance(pt1, pt2))", "e": 29868, "s": 29513, "text": null }, { "code": null, "e": 29877, "s": 29868, "text": "Output :" }, { "code": null, "e": 30068, "s": 29877, "text": "GCD : 4\n\nDivision : (4, 2)\n\nAverage : 2.0\n\npt1 : <capsule object \"Point\" at 0x1005d1e70>\n\npt2 : <capsule object \"Point\" at 0x1005d1ea0>\n\nDistance between the two points : 2.8284271247461903\n" }, { "code": null, "e": 30435, "s": 30068, "text": "At a high level, using Cython is modeled after C. The .pxd files merely contain C definitions (similar to .h files) and the .pyx files contain implementation (similar to a .c file). The cimport statement is used by Cython to import definitions from a .pxd file. This is different than using a normal Python import statement, which would load a regular Python module." }, { "code": null, "e": 30445, "s": 30435, "text": "Marketing" }, { "code": null, "e": 30458, "s": 30445, "text": "Python-ctype" }, { "code": null, "e": 30465, "s": 30458, "text": "Python" }, { "code": null, "e": 30563, "s": 30465, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30595, "s": 30563, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30637, "s": 30595, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30679, "s": 30637, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30735, "s": 30679, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30762, "s": 30735, "text": "Python Classes and Objects" }, { "code": null, "e": 30793, "s": 30762, "text": "Python | os.path.join() method" }, { "code": null, "e": 30822, "s": 30793, "text": "Create a directory in Python" }, { "code": null, "e": 30861, "s": 30822, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30897, "s": 30861, "text": "Python | Pandas dataframe.groupby()" } ]
Comparing content of files using Perl - GeeksforGeeks
26 Jul, 2019 In Perl, we can easily compare the content of two files by using the File::Compare module. This module provides a function called compare, which helps in comparing the content of two files specified to it as arguments. If the data present in both the files comes out to be same, the function returns 0 as the output, if the data in the passed files is different, the return value is 1 and if there is any error occurred while accessing the specified/passed files, it returns the value as -1.Syntax: use File::Compare; $compare = compare('FILE_NAME_1', 'FILE_NAME_2'); Note: Same Content: Return Value [0] Different Content: Return Value [1] Error in Accessing Files: Return Value [-1] Example:Files Present in the Folder. When the content of the Files is same: #!/usr/bin/perlprint "Content-type: text/html\n\n"; # Module to use compare functionuse File::Compare; # compare function to access the passed files.$compare = compare("gfg_a.txt", "gfg_c.txt"); # checking if the files are sameif ($compare == 0){ print "Files are equal. \n";} # checking if the files are differentelsif ($compare == 1){ print "Files are not equal. \n";} # checking if the file is not accessibleelsif($compare == -1){ print "Error Occured. \n";} exit; Output: When the content of the Files is different: #!/usr/bin/perlprint "Content-type: text/html\n\n"; # Module to use compare functionuse File::Compare; # compare function to access the passed files.$compare = compare("gfg_a.txt", "gfg_b.txt"); # checking if the files are sameif ($compare == 0){ print "Files are equal. \n";} # checking if the files are differentelsif ($compare == 1){ print "Files are not equal. \n";} # checking if the file is not accessibleelsif($compare == -1){ print "Error Occured. \n";} exit; Output: When the file is not accessible: #!/usr/bin/perlprint "Content-type: text/html\n\n"; # Module to use compare functionuse File::Compare; # compare function to access the passed files.$compare = compare("gfg_a.txt", "gfg_d.txt"); # checking if the files are sameif ($compare == 0){ print "Files are equal. \n";} # checking if the files are differentelsif ($compare == 1){ print "Files are not equal. \n";} # checking if the file is not accessibleelsif($compare == -1){ print "Error occurred. The file is not accessible. \n";} exit; Output: Perl-files Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Perl | Writing to a File Perl Tutorial - Learn Perl With Examples Perl | Operators | Set - 1 Perl | Multidimensional Hashes Perl | Reading Excel Files Perl | File Handling Introduction Perl | index() Function Perl | Data Types Perl | shift() Function Perl | Appending to a File
[ { "code": null, "e": 23990, "s": 23962, "text": "\n26 Jul, 2019" }, { "code": null, "e": 24489, "s": 23990, "text": "In Perl, we can easily compare the content of two files by using the File::Compare module. This module provides a function called compare, which helps in comparing the content of two files specified to it as arguments. If the data present in both the files comes out to be same, the function returns 0 as the output, if the data in the passed files is different, the return value is 1 and if there is any error occurred while accessing the specified/passed files, it returns the value as -1.Syntax:" }, { "code": null, "e": 24559, "s": 24489, "text": "use File::Compare;\n$compare = compare('FILE_NAME_1', 'FILE_NAME_2');\n" }, { "code": null, "e": 24565, "s": 24559, "text": "Note:" }, { "code": null, "e": 24596, "s": 24565, "text": "Same Content: Return Value [0]" }, { "code": null, "e": 24632, "s": 24596, "text": "Different Content: Return Value [1]" }, { "code": null, "e": 24676, "s": 24632, "text": "Error in Accessing Files: Return Value [-1]" }, { "code": null, "e": 24752, "s": 24676, "text": "Example:Files Present in the Folder. When the content of the Files is same:" }, { "code": "#!/usr/bin/perlprint \"Content-type: text/html\\n\\n\"; # Module to use compare functionuse File::Compare; # compare function to access the passed files.$compare = compare(\"gfg_a.txt\", \"gfg_c.txt\"); # checking if the files are sameif ($compare == 0){ print \"Files are equal. \\n\";} # checking if the files are differentelsif ($compare == 1){ print \"Files are not equal. \\n\";} # checking if the file is not accessibleelsif($compare == -1){ print \"Error Occured. \\n\";} exit;", "e": 25235, "s": 24752, "text": null }, { "code": null, "e": 25287, "s": 25235, "text": "Output: When the content of the Files is different:" }, { "code": "#!/usr/bin/perlprint \"Content-type: text/html\\n\\n\"; # Module to use compare functionuse File::Compare; # compare function to access the passed files.$compare = compare(\"gfg_a.txt\", \"gfg_b.txt\"); # checking if the files are sameif ($compare == 0){ print \"Files are equal. \\n\";} # checking if the files are differentelsif ($compare == 1){ print \"Files are not equal. \\n\";} # checking if the file is not accessibleelsif($compare == -1){ print \"Error Occured. \\n\";} exit;", "e": 25770, "s": 25287, "text": null }, { "code": null, "e": 25811, "s": 25770, "text": "Output: When the file is not accessible:" }, { "code": "#!/usr/bin/perlprint \"Content-type: text/html\\n\\n\"; # Module to use compare functionuse File::Compare; # compare function to access the passed files.$compare = compare(\"gfg_a.txt\", \"gfg_d.txt\"); # checking if the files are sameif ($compare == 0){ print \"Files are equal. \\n\";} # checking if the files are differentelsif ($compare == 1){ print \"Files are not equal. \\n\";} # checking if the file is not accessibleelsif($compare == -1){ print \"Error occurred. The file is not accessible. \\n\";} exit;", "e": 26323, "s": 25811, "text": null }, { "code": null, "e": 26331, "s": 26323, "text": "Output:" }, { "code": null, "e": 26342, "s": 26331, "text": "Perl-files" }, { "code": null, "e": 26347, "s": 26342, "text": "Perl" }, { "code": null, "e": 26352, "s": 26347, "text": "Perl" }, { "code": null, "e": 26450, "s": 26352, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26459, "s": 26450, "text": "Comments" }, { "code": null, "e": 26472, "s": 26459, "text": "Old Comments" }, { "code": null, "e": 26497, "s": 26472, "text": "Perl | Writing to a File" }, { "code": null, "e": 26538, "s": 26497, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 26565, "s": 26538, "text": "Perl | Operators | Set - 1" }, { "code": null, "e": 26596, "s": 26565, "text": "Perl | Multidimensional Hashes" }, { "code": null, "e": 26623, "s": 26596, "text": "Perl | Reading Excel Files" }, { "code": null, "e": 26657, "s": 26623, "text": "Perl | File Handling Introduction" }, { "code": null, "e": 26681, "s": 26657, "text": "Perl | index() Function" }, { "code": null, "e": 26699, "s": 26681, "text": "Perl | Data Types" }, { "code": null, "e": 26723, "s": 26699, "text": "Perl | shift() Function" } ]