title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
How to maximize a plt.show() window using Python?
|
Using plt.get_current_fig_manager() and mng.full_screen_toggle() methods, we can maximise a plot.
Add a subplot to the current figure, where nrow = 1, ncols = 1 and index = 1.
Add a subplot to the current figure, where nrow = 1, ncols = 1 and index = 1.
Create a pie chart using list [1, 2, 3] and pie() method.
Create a pie chart using list [1, 2, 3] and pie() method.
Return the figure manager of the current figure, using get_current_fig_manager() method. The figure manager is a container for the actual backend-depended window that displays the figure on the screen.
Return the figure manager of the current figure, using get_current_fig_manager() method. The figure manager is a container for the actual backend-depended window that displays the figure on the screen.
Create an abstract base class to handle drawing/rendering operations using the full_screen_toggle() method.
Create an abstract base class to handle drawing/rendering operations using the full_screen_toggle() method.
Use plt.show() to show the figure.
Use plt.show() to show the figure.
import matplotlib.pyplot as plt
plt.subplot(1, 1, 1)
plt.pie([1, 2, 3])
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
plt.show()
|
[
{
"code": null,
"e": 1160,
"s": 1062,
"text": "Using plt.get_current_fig_manager() and mng.full_screen_toggle() methods, we can maximise a plot."
},
{
"code": null,
"e": 1238,
"s": 1160,
"text": "Add a subplot to the current figure, where nrow = 1, ncols = 1 and index = 1."
},
{
"code": null,
"e": 1316,
"s": 1238,
"text": "Add a subplot to the current figure, where nrow = 1, ncols = 1 and index = 1."
},
{
"code": null,
"e": 1374,
"s": 1316,
"text": "Create a pie chart using list [1, 2, 3] and pie() method."
},
{
"code": null,
"e": 1432,
"s": 1374,
"text": "Create a pie chart using list [1, 2, 3] and pie() method."
},
{
"code": null,
"e": 1634,
"s": 1432,
"text": "Return the figure manager of the current figure, using get_current_fig_manager() method. The figure manager is a container for the actual backend-depended window that displays the figure on the screen."
},
{
"code": null,
"e": 1836,
"s": 1634,
"text": "Return the figure manager of the current figure, using get_current_fig_manager() method. The figure manager is a container for the actual backend-depended window that displays the figure on the screen."
},
{
"code": null,
"e": 1944,
"s": 1836,
"text": "Create an abstract base class to handle drawing/rendering operations using the full_screen_toggle() method."
},
{
"code": null,
"e": 2052,
"s": 1944,
"text": "Create an abstract base class to handle drawing/rendering operations using the full_screen_toggle() method."
},
{
"code": null,
"e": 2087,
"s": 2052,
"text": "Use plt.show() to show the figure."
},
{
"code": null,
"e": 2122,
"s": 2087,
"text": "Use plt.show() to show the figure."
},
{
"code": null,
"e": 2268,
"s": 2122,
"text": "import matplotlib.pyplot as plt\n\nplt.subplot(1, 1, 1)\nplt.pie([1, 2, 3])\n\nmng = plt.get_current_fig_manager()\nmng.full_screen_toggle()\nplt.show()"
}
] |
How to make the corners of a button round in Android?
|
This example demonstrates how to make the corners of a button round in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#ffffff"
android:background="@drawable/mybutton"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="Buttons" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 3 − Add the following code to src/MainActivity.java
package com.app.sample;
import androidx.appcompat.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);
}
}
Step 4 − Add the following code to res/drawable/mybutton.xml.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#5e7974" />
<gradient android:angle="-90" android:startColor="#345953" android:endColor="#689a92" />
</shape>
</item>
<item android:state_focused="true">
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#5e7974" />
<solid android:color="#58857e"/>
</shape>
</item>
<item >
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#5e7974" />
<gradient android:angle="-90" android:startColor="#8dbab3" android:endColor="#58857e" />
</shape>
</item>
</selector>
Step 5 − Add the following code to Manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
|
[
{
"code": null,
"e": 1142,
"s": 1062,
"text": "This example demonstrates how to make the corners of a button round in Android."
},
{
"code": null,
"e": 1271,
"s": 1142,
"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": 1336,
"s": 1271,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2196,
"s": 1336,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n<Button\n android:id=\"@+id/button1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:padding=\"10dp\"\n android:textColor=\"#ffffff\"\n android:background=\"@drawable/mybutton\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\"\n android:text=\"Buttons\" />\n</androidx.constraintlayout.widget.ConstraintLayout>"
},
{
"code": null,
"e": 2253,
"s": 2196,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2570,
"s": 2253,
"text": "package com.app.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}"
},
{
"code": null,
"e": 2632,
"s": 2570,
"text": "Step 4 − Add the following code to res/drawable/mybutton.xml."
},
{
"code": null,
"e": 3606,
"s": 2632,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<selector xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <item android:state_pressed=\"true\" >\n <shape android:shape=\"rectangle\" >\n <corners android:radius=\"3dip\" />\n <stroke android:width=\"1dip\" android:color=\"#5e7974\" />\n <gradient android:angle=\"-90\" android:startColor=\"#345953\" android:endColor=\"#689a92\" />\n </shape>\n </item>\n <item android:state_focused=\"true\">\n <shape android:shape=\"rectangle\" >\n <corners android:radius=\"3dip\" />\n <stroke android:width=\"1dip\" android:color=\"#5e7974\" />\n <solid android:color=\"#58857e\"/>\n </shape>\n </item>\n <item >\n <shape android:shape=\"rectangle\" >\n <corners android:radius=\"3dip\" />\n <stroke android:width=\"1dip\" android:color=\"#5e7974\" />\n <gradient android:angle=\"-90\" android:startColor=\"#8dbab3\" android:endColor=\"#58857e\" />\n </shape>\n </item>\n</selector>"
},
{
"code": null,
"e": 3671,
"s": 3606,
"text": "Step 5 − Add the following code to Manifests/AndroidManifest.xml"
},
{
"code": null,
"e": 4341,
"s": 3671,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.app.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4692,
"s": 4341,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 4733,
"s": 4692,
"text": "Click here to download the project code."
}
] |
How to get the list of empty folders using PowerShell?
|
To get the list of empty folder on the windows OS using PowerShell, we can use the below method.
gci C:\Temp -Recurse | foreach {
if( $_.psiscontainer -eq $true){
if((gci $_.FullName) -eq $null){$_.FullName}
}
}
The above command checks the C:\Temp folder and its subfolders and if the content is empty it returns the Folder full path. The PSISContainer property stands for the folder and GCI is the alias of the Get-ChildItem command. We can alternatively use the below command, instead of using the PSISContainer property.
gci C:\Temp -Recurse -Directory | foreach {
if((gci $_.FullName) -eq $null){$_.FullName}
}
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "To get the list of empty folder on the windows OS using PowerShell, we can use the below method."
},
{
"code": null,
"e": 1286,
"s": 1159,
"text": "gci C:\\Temp -Recurse | foreach {\n if( $_.psiscontainer -eq $true){\n if((gci $_.FullName) -eq $null){$_.FullName}\n }\n}"
},
{
"code": null,
"e": 1599,
"s": 1286,
"text": "The above command checks the C:\\Temp folder and its subfolders and if the content is empty it returns the Folder full path. The PSISContainer property stands for the folder and GCI is the alias of the Get-ChildItem command. We can alternatively use the below command, instead of using the PSISContainer property."
},
{
"code": null,
"e": 1693,
"s": 1599,
"text": "gci C:\\Temp -Recurse -Directory | foreach {\n if((gci $_.FullName) -eq $null){$_.FullName}\n}"
}
] |
How to maximize the browser in Selenium?
|
We can maximize the browser in Selenium with the help of method maximize().
The present active window becomes maximized with this method.
Code implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class BrowserMax {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/index.htm";
driver.get(url);
// maximizing browser with maximize()
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.partialLinkText("Coding")).click();
driver.close();
}
}
|
[
{
"code": null,
"e": 1138,
"s": 1062,
"text": "We can maximize the browser in Selenium with the help of method maximize()."
},
{
"code": null,
"e": 1200,
"s": 1138,
"text": "The present active window becomes maximized with this method."
},
{
"code": null,
"e": 1221,
"s": 1200,
"text": "Code implementation."
},
{
"code": null,
"e": 2008,
"s": 1221,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class BrowserMax {\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n // maximizing browser with maximize()\n driver.manage().window().maximize();\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n driver.findElement(By.partialLinkText(\"Coding\")).click();\n driver.close();\n }\n}"
}
] |
Find last two digits of sum of N factorials - GeeksforGeeks
|
12 Apr, 2021
Given a number N, the task is to find unit and tens places digit of the first N natural numbers factorials, i.e last last two digit of 1!+2!+3!+....N! where N<=10e18.Examples:
Input : n = 2
Output :3
1! + 2! = 3
Last two digit is 3
Input :4
Output :33
1!+2!+3!+4!=33
Last two digit is 33
Naive Approach:In this approach, simply calculate factorial of each number and find sum of these. Finally get the unit and tens place digit of sum. This will take a lot of time and unnecessary calculations.Efficient Approach: In this approach, only unit’s and ten’s digit of N is to be calculated in the range [1, 10], because: 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8!=40320 9!=362880 10!=3628800 so on.As 10 != 3628800, and factorial of number greater than 10 have two trailing zeros. So, N>=10 doesn’t contribute in unit and tens place while doing sum.Therefore,
if (n < 10) ans = (1 ! + 2 ! +..+ n !) % 100; else ans = (1 ! + 2 ! + 3 ! + 4 !+ 5 ! + 6 ! + 7 ! + 8 ! + 9 ! + 10 !) % 100;Note : We know (1! + 2! + 3! + 4!+...+10!) % 100 = 13 So we always return 3 when n is greater than 4.
Below is the implementation of above approach.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the unit place digit// of the first N natural numbers factorials#include <iostream>using namespace std;#define ll long int// Function to find the unit's and ten's place digitint get_last_two_digit(long long int N){ // Let us write for cases when // N is smaller than or equal // to 10. if (N <= 10) { ll ans = 0, fac = 1; for (int i = 1; i <= N; i++) { fac = fac * i; ans += fac; } return ans % 100; } // We know following // (1! + 2! + 3! + 4!...+10!) % 100 = 13 else // (N >= 10) return 13;} // Driver codeint main(){ long long int N = 1; for (N = 1; N <= 10; N++) cout << "For N = " << N << " : " << get_last_two_digit(N) << endl; return 0;}
//Java program to find the unit place digit//of the first N natural numbers factorialspublic class AAA { //Function to find the unit's and ten's place digit static int get_last_two_digit(long N) { // Let us write for cases when // N is smaller than or equal // to 10. if (N <= 10) { long ans = 0, fac = 1; for (int i = 1; i <= N; i++) { fac = fac * i; ans += fac; } return (int)ans % 100; } // We know following // (1! + 2! + 3! + 4!...+10!) % 100 = 13 else // (N >= 10) return 13; } //Driver code public static void main(String[] args) { long N = 1; for (N = 1; N <= 10; N++) System.out.println( "For N = " + N + " : " + get_last_two_digit(N)); } }
# Python3 program to find the unit# place digit of the first N natural# numbers factorials # Function to find the unit's# and ten's place digitdef get_last_two_digit(N): # Let us write for cases when # N is smaller than or equal # to 10 if N <= 10: ans = 0 fac = 1 for i in range(1, N + 1): fac = fac * i ans += fac ans = ans % 100 return ans # We know following # (1! + 2! + 3! + 4!...+10!) % 100 = 13 # // (N >= 10) else: return 13 # Driver CodeN = 1for N in range(1, 11): print("For N = ", N, ": ", get_last_two_digit(N), sep = ' ') # This code is contributed# by sahilshelangia
// C# program to find the unit// place digit of the first N// natural numbers factorialsusing System; class GFG{ // Function to find the unit's// and ten's place digitstatic int get_last_two_digit(long N){ // Let us write for cases when// N is smaller than or equal// to 10.if (N <= 10){ long ans = 0, fac = 1; for (int i = 1; i <= N; i++) { fac = fac * i; ans += fac; } return (int)ans % 100;} // We know following// (1! + 2! + 3! + 4!...+10!) % 100 = 13else // (N >= 10) return 13;} // Driver codepublic static void Main(){ long N = 1; for (N = 1; N <= 10; N++) Console.WriteLine( "For N = " + N + " : " + get_last_two_digit(N));}} // This code is contributed// by Akanksha Rai(Abby_akku)
<?php// PHP program to find the unit place digit// of the first N natural numbers factorials // Function to find the unit's// and ten's place digitfunction get_last_two_digit($N){ // Let us write for cases when // N is smaller than or equal // to 10. if ($N <= 10) { $ans = 0; $fac = 1; for ($i = 1; $i <= $N; $i++) { $fac = $fac * $i; $ans += $fac; } return $ans % 100; } // We know following // (1! + 2! + 3! + 4!...+10!) % 100 = 13 else // (N >= 10) return 13;} // Driver code$N = 1;for ($N = 1; $N <= 10; $N++) echo "For N = " . $N . " : " . get_last_two_digit($N) . "\n"; // This code is contributed// by Akanksha Rai(Abby_akku)
<script> // Javascript program to find the unit place digit// of the first N natural numbers factorials // Function to find the unit's and ten's place digitfunction get_last_two_digit(N){ // Let us write for cases when // N is smaller than or equal // to 10. if (N <= 10) { let ans = 0, fac = 1; for (let i = 1; i <= N; i++) { fac = fac * i; ans += fac; } return ans % 100; } // We know following // (1! + 2! + 3! + 4!...+10!) % 100 = 13 else // (N >= 10) return 13;} // Driver code let N = 1; for (N = 1; N <= 10; N++) document.write("For N = " + N + " : " + get_last_two_digit(N) + "<br>"); // This code is contributed by Mayank Tyagi </script>
For N = 1 : 1
For N = 2 : 3
For N = 3 : 9
For N = 4 : 33
For N = 5 : 53
For N = 6 : 73
For N = 7 : 13
For N = 8 : 33
For N = 9 : 13
For N = 10 : 13
sahilshelangia
ukasp
Akanksha_Rai
mayanktyagi1709
factorial
Modular Arithmetic
number-digits
Mathematical
Mathematical
Modular Arithmetic
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
Program for Decimal to Binary Conversion
Euclidean algorithms (Basic and Extended)
Algorithm to solve Rubik's Cube
|
[
{
"code": null,
"e": 25076,
"s": 25048,
"text": "\n12 Apr, 2021"
},
{
"code": null,
"e": 25254,
"s": 25076,
"text": "Given a number N, the task is to find unit and tens places digit of the first N natural numbers factorials, i.e last last two digit of 1!+2!+3!+....N! where N<=10e18.Examples: "
},
{
"code": null,
"e": 25369,
"s": 25254,
"text": "Input : n = 2 \nOutput :3\n1! + 2! = 3\nLast two digit is 3\n\nInput :4\nOutput :33\n1!+2!+3!+4!=33\nLast two digit is 33"
},
{
"code": null,
"e": 25957,
"s": 25371,
"text": "Naive Approach:In this approach, simply calculate factorial of each number and find sum of these. Finally get the unit and tens place digit of sum. This will take a lot of time and unnecessary calculations.Efficient Approach: In this approach, only unit’s and ten’s digit of N is to be calculated in the range [1, 10], because: 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8!=40320 9!=362880 10!=3628800 so on.As 10 != 3628800, and factorial of number greater than 10 have two trailing zeros. So, N>=10 doesn’t contribute in unit and tens place while doing sum.Therefore, "
},
{
"code": null,
"e": 26182,
"s": 25957,
"text": "if (n < 10) ans = (1 ! + 2 ! +..+ n !) % 100; else ans = (1 ! + 2 ! + 3 ! + 4 !+ 5 ! + 6 ! + 7 ! + 8 ! + 9 ! + 10 !) % 100;Note : We know (1! + 2! + 3! + 4!+...+10!) % 100 = 13 So we always return 3 when n is greater than 4."
},
{
"code": null,
"e": 26230,
"s": 26182,
"text": "Below is the implementation of above approach. "
},
{
"code": null,
"e": 26234,
"s": 26230,
"text": "C++"
},
{
"code": null,
"e": 26239,
"s": 26234,
"text": "Java"
},
{
"code": null,
"e": 26247,
"s": 26239,
"text": "Python3"
},
{
"code": null,
"e": 26250,
"s": 26247,
"text": "C#"
},
{
"code": null,
"e": 26254,
"s": 26250,
"text": "PHP"
},
{
"code": null,
"e": 26265,
"s": 26254,
"text": "Javascript"
},
{
"code": "// C++ program to find the unit place digit// of the first N natural numbers factorials#include <iostream>using namespace std;#define ll long int// Function to find the unit's and ten's place digitint get_last_two_digit(long long int N){ // Let us write for cases when // N is smaller than or equal // to 10. if (N <= 10) { ll ans = 0, fac = 1; for (int i = 1; i <= N; i++) { fac = fac * i; ans += fac; } return ans % 100; } // We know following // (1! + 2! + 3! + 4!...+10!) % 100 = 13 else // (N >= 10) return 13;} // Driver codeint main(){ long long int N = 1; for (N = 1; N <= 10; N++) cout << \"For N = \" << N << \" : \" << get_last_two_digit(N) << endl; return 0;}",
"e": 27057,
"s": 26265,
"text": null
},
{
"code": "//Java program to find the unit place digit//of the first N natural numbers factorialspublic class AAA { //Function to find the unit's and ten's place digit static int get_last_two_digit(long N) { // Let us write for cases when // N is smaller than or equal // to 10. if (N <= 10) { long ans = 0, fac = 1; for (int i = 1; i <= N; i++) { fac = fac * i; ans += fac; } return (int)ans % 100; } // We know following // (1! + 2! + 3! + 4!...+10!) % 100 = 13 else // (N >= 10) return 13; } //Driver code public static void main(String[] args) { long N = 1; for (N = 1; N <= 10; N++) System.out.println( \"For N = \" + N + \" : \" + get_last_two_digit(N)); } }",
"e": 27881,
"s": 27057,
"text": null
},
{
"code": "# Python3 program to find the unit# place digit of the first N natural# numbers factorials # Function to find the unit's# and ten's place digitdef get_last_two_digit(N): # Let us write for cases when # N is smaller than or equal # to 10 if N <= 10: ans = 0 fac = 1 for i in range(1, N + 1): fac = fac * i ans += fac ans = ans % 100 return ans # We know following # (1! + 2! + 3! + 4!...+10!) % 100 = 13 # // (N >= 10) else: return 13 # Driver CodeN = 1for N in range(1, 11): print(\"For N = \", N, \": \", get_last_two_digit(N), sep = ' ') # This code is contributed# by sahilshelangia",
"e": 28578,
"s": 27881,
"text": null
},
{
"code": "// C# program to find the unit// place digit of the first N// natural numbers factorialsusing System; class GFG{ // Function to find the unit's// and ten's place digitstatic int get_last_two_digit(long N){ // Let us write for cases when// N is smaller than or equal// to 10.if (N <= 10){ long ans = 0, fac = 1; for (int i = 1; i <= N; i++) { fac = fac * i; ans += fac; } return (int)ans % 100;} // We know following// (1! + 2! + 3! + 4!...+10!) % 100 = 13else // (N >= 10) return 13;} // Driver codepublic static void Main(){ long N = 1; for (N = 1; N <= 10; N++) Console.WriteLine( \"For N = \" + N + \" : \" + get_last_two_digit(N));}} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 29325,
"s": 28578,
"text": null
},
{
"code": "<?php// PHP program to find the unit place digit// of the first N natural numbers factorials // Function to find the unit's// and ten's place digitfunction get_last_two_digit($N){ // Let us write for cases when // N is smaller than or equal // to 10. if ($N <= 10) { $ans = 0; $fac = 1; for ($i = 1; $i <= $N; $i++) { $fac = $fac * $i; $ans += $fac; } return $ans % 100; } // We know following // (1! + 2! + 3! + 4!...+10!) % 100 = 13 else // (N >= 10) return 13;} // Driver code$N = 1;for ($N = 1; $N <= 10; $N++) echo \"For N = \" . $N . \" : \" . get_last_two_digit($N) . \"\\n\"; // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 30064,
"s": 29325,
"text": null
},
{
"code": "<script> // Javascript program to find the unit place digit// of the first N natural numbers factorials // Function to find the unit's and ten's place digitfunction get_last_two_digit(N){ // Let us write for cases when // N is smaller than or equal // to 10. if (N <= 10) { let ans = 0, fac = 1; for (let i = 1; i <= N; i++) { fac = fac * i; ans += fac; } return ans % 100; } // We know following // (1! + 2! + 3! + 4!...+10!) % 100 = 13 else // (N >= 10) return 13;} // Driver code let N = 1; for (N = 1; N <= 10; N++) document.write(\"For N = \" + N + \" : \" + get_last_two_digit(N) + \"<br>\"); // This code is contributed by Mayank Tyagi </script>",
"e": 30830,
"s": 30064,
"text": null
},
{
"code": null,
"e": 30978,
"s": 30830,
"text": "For N = 1 : 1\nFor N = 2 : 3\nFor N = 3 : 9\nFor N = 4 : 33\nFor N = 5 : 53\nFor N = 6 : 73\nFor N = 7 : 13\nFor N = 8 : 33\nFor N = 9 : 13\nFor N = 10 : 13"
},
{
"code": null,
"e": 30995,
"s": 30980,
"text": "sahilshelangia"
},
{
"code": null,
"e": 31001,
"s": 30995,
"text": "ukasp"
},
{
"code": null,
"e": 31014,
"s": 31001,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 31030,
"s": 31014,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 31040,
"s": 31030,
"text": "factorial"
},
{
"code": null,
"e": 31059,
"s": 31040,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 31073,
"s": 31059,
"text": "number-digits"
},
{
"code": null,
"e": 31086,
"s": 31073,
"text": "Mathematical"
},
{
"code": null,
"e": 31099,
"s": 31086,
"text": "Mathematical"
},
{
"code": null,
"e": 31118,
"s": 31099,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 31128,
"s": 31118,
"text": "factorial"
},
{
"code": null,
"e": 31226,
"s": 31128,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31268,
"s": 31226,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 31311,
"s": 31268,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 31335,
"s": 31311,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 31349,
"s": 31335,
"text": "Prime Numbers"
},
{
"code": null,
"e": 31398,
"s": 31349,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 31432,
"s": 31398,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 31453,
"s": 31432,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 31494,
"s": 31453,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 31536,
"s": 31494,
"text": "Euclidean algorithms (Basic and Extended)"
}
] |
Arithmetic Number in C++
|
The arithmetic number is a number which has the average of all positive divisors is an integer i.e. for a number n if the number of divisors can divide the sum of divisors then n is an arithmetic number.
Let’s take an example to understand the concept better,
Input : n = 6
Output : YES
Explanation :
Divisors are 1 , 2 , 3 , 6
Sum = 1+2+3+6 = 12
Number of divisors = 4
Sum of divisors / number of divisor = 12 / 4 = 3
Step 1 : Calculate the sum of divisors and store into sum variable.
Step 2 : Find the total number of divisors.
Step 3 : Check if the remainder when sum of divisors is divided by the total number of divisors is equal to 0.
Step 4 : If remainder is equal 0. Print YES. Else print NO.
Live Demo
#include <bits/stdc++.h>
using namespace std;
void SieveOfEratosthenes(int n, bool prime[],bool primesquare[], int a[]);
int countDivisors(int n) ;
int sumofFactors(int n) ;
int main(){
int n = 46;
int divcount = countDivisors(n);
int divsum = sumofFactors(n);
if(divsum % divcount == 0 ){
cout<<"YES";
}
else
cout<<"NO";
return 0;
}
void SieveOfEratosthenes(int n, bool prime[],bool primesquare[], int a[]){
for (int i = 2; i <= n; i++)
prime[i] = true;
for (int i = 0; i <= (n * n + 1); i++)
primesquare[i] = false;
prime[1] = false;
for (int p = 2; p * p <= n; p++) {
if (prime[p] == true) {
for (int i = p * 2; i <= n; i += p)
prime[i] = false;
}
}
int j = 0;
for (int p = 2; p <= n; p++) {
if (prime[p]) {
a[j] = p;
primesquare[p * p] = true;
j++;
}
}
}
int countDivisors(int n){
if (n == 1)
return 1;
bool prime[n + 1], primesquare[n * n + 1];
int a[n];
SieveOfEratosthenes(n, prime, primesquare, a);
int ans = 1;
for (int i = 0;; i++) {
if (a[i] * a[i] * a[i] > n)
break;
int cnt = 1;
while (n % a[i] == 0){
n = n / a[i];
cnt = cnt + 1;
}
ans = ans * cnt;
}
if (prime[n])
ans = ans * 2;
else if (primesquare[n])
ans = ans * 3;
else if (n != 1)
ans = ans * 4;
return ans;
}
int sumofFactors(int n){
int res = 1;
for (int i = 2; i <= sqrt(n); i++) {
int count = 0, curr_sum = 1;
int curr_term = 1;
while (n % i == 0) {
count++;
n = n / i;
curr_term *= i;
curr_sum += curr_term;
}
res *= curr_sum;
}
if (n >= 2)
res *= (1 + n);
return res;
}
YES
|
[
{
"code": null,
"e": 1266,
"s": 1062,
"text": "The arithmetic number is a number which has the average of all positive divisors is an integer i.e. for a number n if the number of divisors can divide the sum of divisors then n is an arithmetic number."
},
{
"code": null,
"e": 1322,
"s": 1266,
"text": "Let’s take an example to understand the concept better,"
},
{
"code": null,
"e": 1481,
"s": 1322,
"text": "Input : n = 6\nOutput : YES\nExplanation :\nDivisors are 1 , 2 , 3 , 6\nSum = 1+2+3+6 = 12\nNumber of divisors = 4\nSum of divisors / number of divisor = 12 / 4 = 3"
},
{
"code": null,
"e": 1764,
"s": 1481,
"text": "Step 1 : Calculate the sum of divisors and store into sum variable.\nStep 2 : Find the total number of divisors.\nStep 3 : Check if the remainder when sum of divisors is divided by the total number of divisors is equal to 0.\nStep 4 : If remainder is equal 0. Print YES. Else print NO."
},
{
"code": null,
"e": 1775,
"s": 1764,
"text": " Live Demo"
},
{
"code": null,
"e": 3545,
"s": 1775,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid SieveOfEratosthenes(int n, bool prime[],bool primesquare[], int a[]);\nint countDivisors(int n) ;\nint sumofFactors(int n) ;\nint main(){\n int n = 46;\n int divcount = countDivisors(n);\n int divsum = sumofFactors(n);\n if(divsum % divcount == 0 ){\n cout<<\"YES\";\n }\n else\n cout<<\"NO\";\nreturn 0;\n}\nvoid SieveOfEratosthenes(int n, bool prime[],bool primesquare[], int a[]){\n for (int i = 2; i <= n; i++)\n prime[i] = true;\n for (int i = 0; i <= (n * n + 1); i++)\n primesquare[i] = false;\n prime[1] = false;\n for (int p = 2; p * p <= n; p++) {\n if (prime[p] == true) {\n for (int i = p * 2; i <= n; i += p)\n prime[i] = false;\n }\n }\n int j = 0;\n for (int p = 2; p <= n; p++) {\n if (prime[p]) {\n a[j] = p;\n primesquare[p * p] = true;\n j++;\n }\n }\n}\nint countDivisors(int n){\n if (n == 1)\n return 1;\n bool prime[n + 1], primesquare[n * n + 1];\n int a[n];\n SieveOfEratosthenes(n, prime, primesquare, a);\n int ans = 1;\n for (int i = 0;; i++) {\n if (a[i] * a[i] * a[i] > n)\n break;\n int cnt = 1;\n while (n % a[i] == 0){\n n = n / a[i];\n cnt = cnt + 1;\n }\n ans = ans * cnt;\n }\n if (prime[n])\n ans = ans * 2;\n else if (primesquare[n])\n ans = ans * 3;\n else if (n != 1)\n ans = ans * 4;\n return ans;\n}\nint sumofFactors(int n){\n int res = 1;\n for (int i = 2; i <= sqrt(n); i++) {\n int count = 0, curr_sum = 1;\n int curr_term = 1;\n while (n % i == 0) {\n count++;\n n = n / i;\n curr_term *= i;\n curr_sum += curr_term;\n }\n res *= curr_sum;\n }\n if (n >= 2)\n res *= (1 + n);\n return res;\n}"
},
{
"code": null,
"e": 3549,
"s": 3545,
"text": "YES"
}
] |
Timer in C++ using system calls
|
Here we will see how to design timer in C++ using a system call. We will not use any graphics or animations. Here timer means the stopwatch, that is up-counting the time. The used system calls are −
sleep(n) − This will help the program to sleep for n number of seconds
system() − This is used to execute the system command by passing command as an argument to this function.
Live Demo
#include <iomanip>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
int hrs = 0;
int mins = 0;
int sec = 0;
void showClk() {
system("cls");
cout << setfill(' ') << setw(55) << " TIMER \n";
cout << setfill(' ') << setw(66) << " --------------------------------------\n";
cout << setfill(' ') << setw(29);
cout << "| " << setfill('0') << setw(2) << hrs << " Hours | ";
cout << setfill('0') << setw(2) << mins << " Minutes | ";
cout << setfill('0') << setw(2) << sec << " Seconds |" << endl;
cout << setfill(' ') << setw(66) << " --------------------------------------\n";
}
void systemCallTimer() {
while (true) {
showClk();
sleep(1);
sec++;
if (sec == 60) {
mins++;
if (mins == 60) {
hrs++;
mins = 0;
}
sec = 0;
}
}
}
int main() {
systemCallTimer();
}
|
[
{
"code": null,
"e": 1261,
"s": 1062,
"text": "Here we will see how to design timer in C++ using a system call. We will not use any graphics or animations. Here timer means the stopwatch, that is up-counting the time. The used system calls are −"
},
{
"code": null,
"e": 1332,
"s": 1261,
"text": "sleep(n) − This will help the program to sleep for n number of seconds"
},
{
"code": null,
"e": 1438,
"s": 1332,
"text": "system() − This is used to execute the system command by passing command as an argument to this function."
},
{
"code": null,
"e": 1449,
"s": 1438,
"text": " Live Demo"
},
{
"code": null,
"e": 2355,
"s": 1449,
"text": "#include <iomanip>\n#include <iostream>\n#include <stdlib.h>\n#include <unistd.h>\nusing namespace std;\nint hrs = 0;\nint mins = 0;\nint sec = 0;\nvoid showClk() {\n system(\"cls\");\n cout << setfill(' ') << setw(55) << \" TIMER \\n\";\n cout << setfill(' ') << setw(66) << \" --------------------------------------\\n\";\n cout << setfill(' ') << setw(29);\n cout << \"| \" << setfill('0') << setw(2) << hrs << \" Hours | \";\n cout << setfill('0') << setw(2) << mins << \" Minutes | \";\n cout << setfill('0') << setw(2) << sec << \" Seconds |\" << endl;\n cout << setfill(' ') << setw(66) << \" --------------------------------------\\n\";\n}\nvoid systemCallTimer() {\n while (true) {\n showClk();\n sleep(1);\n sec++;\n if (sec == 60) {\n mins++;\n if (mins == 60) {\n hrs++;\n mins = 0;\n }\n sec = 0;\n }\n }\n}\nint main() {\n systemCallTimer();\n}"
}
] |
Cryptography GUI using python - GeeksforGeeks
|
29 Dec, 2020
Using cryptography techniques we can generate keys for a plain text which can not be predicted easily. We use Cryptography to ensure the safe and secure flow of data from one source to another without being accessed by a malicious user.
Prerequisites:
Language used – Python.Tkinter – This module is used to make GUIs using python language. To know more about tkinter click here.Basics of Cryptography – Cryptography is used for Secure Communication.
Encryption – The process of encoding a message or information in such a way that only authorized parties can access it.
Decryption – The process of taking encoded or encrypted text or other data and converting it back into text.
ONE-TIME PADThe one-time pad is a type of encryption which is unbreakable. A one-time pad will generate a key, this key is shared by both the user so it does encryption as well as decryption. The key used is generated randomly and this key is combined with the plain text in order to form the ciphertext. We can use different algorithms for the generation of the ciphertext such as modular addition, modular XOR, etc. Since the key generated every time is unique, it is impossible to break.
Examples:
In this example, we use a modular addition. Every letter of the message has it’s numerical value associated with it. This numerical value is mapped with the corresponding letter of the key and ciphertext is generated by doing modular addition operation. if the value exceeds 26, the result will be the mod of the value with 26. Here ‘GEEKS’ acts as a plain message and ‘DFSTL’ acts as the one-time pad key.
G E E K S message
6 (G) 4 (E) 4 (E) 10 (K) 18 (S) message
+ 3 (D) 5 (F) 18 (S) 19 (T) 11 (L) key
= 9 9 22 29 29 message + key
= 9 (J) 9 (J) 22 (W) 3 (D) 3 (D) (message + key) mod 26
J J W D D ? ciphertext
Since we used modular addition for the generation of the ciphertext. In order to get back the original message we have to perform modular subtraction. If the value comes out to be negative we will add 26 to the value, the resultant numerical value will result in the generation of the original message.
J J W D D ciphertext
9 (J) 9 (J) 22 (W) 3 (D) 3 (D) ciphertext
- 3 (D) 5 (F) 18 (S) 19 (T) 11 (L) key
= 6 4 4 -16 -8 ciphertext – key
= 6 (G) 4 (E) 4 (E) 10(K) 18 (S) ciphertext – key (mod 26)
G E E K S ? message
Below is the implementation.
# python module for one-timepadimport onetimepad # python module to create GUI from tkinter import * root = Tk()root.title("CRYPTOGRAPHY")root.geometry("800x600") def encryptMessage(): pt = e1.get() # inbuilt function to encrypt a message ct = onetimepad.encrypt(pt, 'random') e2.insert(0, ct) def decryptMessage(): ct1 = e3.get() # inbuilt function to decrypt a message pt1 = onetimepad.decrypt(ct1, 'random') e4.insert(0, pt1) # creating labels and positioning them on the gridlabel1 = Label(root, text ='plain text') label1.grid(row = 10, column = 1)label2 = Label(root, text ='encrypted text')label2.grid(row = 11, column = 1)l3 = Label(root, text ="cipher text")l3.grid(row = 10, column = 10)l4 = Label(root, text ="decrypted text")l4.grid(row = 11, column = 10) # creating entries and positioning them on the gride1 = Entry(root)e1.grid(row = 10, column = 2)e2 = Entry(root)e2.grid(row = 11, column = 2)e3 = Entry(root)e3.grid(row = 10, column = 11)e4 = Entry(root)e4.grid(row = 11, column = 11) # creating encryption button to produce the outputent = Button(root, text = "encrypt", bg ="red", fg ="white", command = encryptMessage)ent.grid(row = 13, column = 2) # creating decryption button to produce the outputb2 = Button(root, text = "decrypt", bg ="green", fg ="white", command = decryptMessage)b2.grid(row = 13, column = 11) root.mainloop()
OutputFor encryption:
For decryption:
Note: The default technique used by the module is not as same in the example given. We can apply different formulas for the generation of the ciphertext, however, the underlying principle remains the same.
Python Tkinter-exercises
Python-tkinter
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25598,
"s": 25570,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 25835,
"s": 25598,
"text": "Using cryptography techniques we can generate keys for a plain text which can not be predicted easily. We use Cryptography to ensure the safe and secure flow of data from one source to another without being accessed by a malicious user."
},
{
"code": null,
"e": 25850,
"s": 25835,
"text": "Prerequisites:"
},
{
"code": null,
"e": 26049,
"s": 25850,
"text": "Language used – Python.Tkinter – This module is used to make GUIs using python language. To know more about tkinter click here.Basics of Cryptography – Cryptography is used for Secure Communication."
},
{
"code": null,
"e": 26169,
"s": 26049,
"text": "Encryption – The process of encoding a message or information in such a way that only authorized parties can access it."
},
{
"code": null,
"e": 26278,
"s": 26169,
"text": "Decryption – The process of taking encoded or encrypted text or other data and converting it back into text."
},
{
"code": null,
"e": 26769,
"s": 26278,
"text": "ONE-TIME PADThe one-time pad is a type of encryption which is unbreakable. A one-time pad will generate a key, this key is shared by both the user so it does encryption as well as decryption. The key used is generated randomly and this key is combined with the plain text in order to form the ciphertext. We can use different algorithms for the generation of the ciphertext such as modular addition, modular XOR, etc. Since the key generated every time is unique, it is impossible to break."
},
{
"code": null,
"e": 26779,
"s": 26769,
"text": "Examples:"
},
{
"code": null,
"e": 27186,
"s": 26779,
"text": "In this example, we use a modular addition. Every letter of the message has it’s numerical value associated with it. This numerical value is mapped with the corresponding letter of the key and ciphertext is generated by doing modular addition operation. if the value exceeds 26, the result will be the mod of the value with 26. Here ‘GEEKS’ acts as a plain message and ‘DFSTL’ acts as the one-time pad key."
},
{
"code": null,
"e": 27501,
"s": 27186,
"text": " G E E K S message\n 6 (G) 4 (E) 4 (E) 10 (K) 18 (S) message\n+ 3 (D) 5 (F) 18 (S) 19 (T) 11 (L) key\n= 9 9 22 29 29 message + key\n= 9 (J) 9 (J) 22 (W) 3 (D) 3 (D) (message + key) mod 26\n J J W D D ? ciphertext\n"
},
{
"code": null,
"e": 27804,
"s": 27501,
"text": "Since we used modular addition for the generation of the ciphertext. In order to get back the original message we have to perform modular subtraction. If the value comes out to be negative we will add 26 to the value, the resultant numerical value will result in the generation of the original message."
},
{
"code": null,
"e": 28135,
"s": 27804,
"text": " J J W D D ciphertext\n 9 (J) 9 (J) 22 (W) 3 (D) 3 (D) ciphertext\n- 3 (D) 5 (F) 18 (S) 19 (T) 11 (L) key\n= 6 4 4 -16 -8 ciphertext – key\n= 6 (G) 4 (E) 4 (E) 10(K) 18 (S) ciphertext – key (mod 26)\n G E E K S ? message\n"
},
{
"code": null,
"e": 28164,
"s": 28135,
"text": "Below is the implementation."
},
{
"code": "# python module for one-timepadimport onetimepad # python module to create GUI from tkinter import * root = Tk()root.title(\"CRYPTOGRAPHY\")root.geometry(\"800x600\") def encryptMessage(): pt = e1.get() # inbuilt function to encrypt a message ct = onetimepad.encrypt(pt, 'random') e2.insert(0, ct) def decryptMessage(): ct1 = e3.get() # inbuilt function to decrypt a message pt1 = onetimepad.decrypt(ct1, 'random') e4.insert(0, pt1) # creating labels and positioning them on the gridlabel1 = Label(root, text ='plain text') label1.grid(row = 10, column = 1)label2 = Label(root, text ='encrypted text')label2.grid(row = 11, column = 1)l3 = Label(root, text =\"cipher text\")l3.grid(row = 10, column = 10)l4 = Label(root, text =\"decrypted text\")l4.grid(row = 11, column = 10) # creating entries and positioning them on the gride1 = Entry(root)e1.grid(row = 10, column = 2)e2 = Entry(root)e2.grid(row = 11, column = 2)e3 = Entry(root)e3.grid(row = 10, column = 11)e4 = Entry(root)e4.grid(row = 11, column = 11) # creating encryption button to produce the outputent = Button(root, text = \"encrypt\", bg =\"red\", fg =\"white\", command = encryptMessage)ent.grid(row = 13, column = 2) # creating decryption button to produce the outputb2 = Button(root, text = \"decrypt\", bg =\"green\", fg =\"white\", command = decryptMessage)b2.grid(row = 13, column = 11) root.mainloop()",
"e": 29635,
"s": 28164,
"text": null
},
{
"code": null,
"e": 29657,
"s": 29635,
"text": "OutputFor encryption:"
},
{
"code": null,
"e": 29673,
"s": 29657,
"text": "For decryption:"
},
{
"code": null,
"e": 29879,
"s": 29673,
"text": "Note: The default technique used by the module is not as same in the example given. We can apply different formulas for the generation of the ciphertext, however, the underlying principle remains the same."
},
{
"code": null,
"e": 29904,
"s": 29879,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 29919,
"s": 29904,
"text": "Python-tkinter"
},
{
"code": null,
"e": 29934,
"s": 29919,
"text": "python-utility"
},
{
"code": null,
"e": 29941,
"s": 29934,
"text": "Python"
},
{
"code": null,
"e": 30039,
"s": 29941,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30057,
"s": 30039,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30092,
"s": 30057,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30124,
"s": 30092,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30146,
"s": 30124,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30188,
"s": 30146,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30218,
"s": 30188,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 30244,
"s": 30218,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30273,
"s": 30244,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30317,
"s": 30273,
"text": "Reading and Writing to text files in Python"
}
] |
IMS DB - Data Retrieval
|
The various data retrieval methods used in IMS DL/I calls are as follows −
GU Call
GN Call
Using Command Codes
Multiple Processing
Let us consider the following IMS database structure to understand the data retrieval function calls −
The fundamentals of GU call are as follows −
GU call is known as Get Unique call. It is used for random processing.
GU call is known as Get Unique call. It is used for random processing.
If an application does not update the database regularly or if the number of database updates is less, then we use random processing.
If an application does not update the database regularly or if the number of database updates is less, then we use random processing.
GU call is used to place the pointer at a particular position for further sequential retrieval.
GU call is used to place the pointer at a particular position for further sequential retrieval.
GU calls are independent of the pointer position established by the previous calls.
GU calls are independent of the pointer position established by the previous calls.
GU call processing is based on the unique key fields supplied in the call statement.
GU call processing is based on the unique key fields supplied in the call statement.
If we supply a key field that is not unique, then DL/I returns the first segment occurrence of the key field.
If we supply a key field that is not unique, then DL/I returns the first segment occurrence of the key field.
CALL 'CBLTDLI' USING DLI-GU
PCB-NAME
IO-AREA
LIBRARY-SSA
BOOKS-SSA
ENGINEERING-SSA
IT-SSA
The above example shows we issue a GU call by providing a complete set of qualified SSAs. It includes all the key fields starting from the root level to the segment occurrence that we want to retrieve.
If we do not provide the complete set of qualified SSAs in the call, then DL/I works in the following way −
When we use an unqualified SSA in a GU call, DL/I accesses the first segment occurrence in the database that meets the criteria you specify.
When we use an unqualified SSA in a GU call, DL/I accesses the first segment occurrence in the database that meets the criteria you specify.
When we issue a GU call without any SSAs, DL/I returns the first occurrence of the root segment in the database.
When we issue a GU call without any SSAs, DL/I returns the first occurrence of the root segment in the database.
If some SSAs at intermediate levels are not mentioned in the call, then DL/I uses either the established position or the default value of an unqualified SSA for the segment.
If some SSAs at intermediate levels are not mentioned in the call, then DL/I uses either the established position or the default value of an unqualified SSA for the segment.
The following table shows the relevant status codes after a GU call −
Spaces
Successful call
GE
DL/I could not find a segment that met the criteria specified in the call
The fundamentals of GN call are as follows −
GN call is known as Get Next call. It is used for basic sequential processing.
GN call is known as Get Next call. It is used for basic sequential processing.
The initial position of the pointer in the database is before the root segment of the first database record.
The initial position of the pointer in the database is before the root segment of the first database record.
The database pointer position is before the next segment occurrence in the sequence, after a successful GN call.
The database pointer position is before the next segment occurrence in the sequence, after a successful GN call.
The GN call starts through the database from the position established by the previous call.
The GN call starts through the database from the position established by the previous call.
If a GN call is unqualified, it returns the next segment occurrence in the database regardless of its type, in hierarchical sequence.
If a GN call is unqualified, it returns the next segment occurrence in the database regardless of its type, in hierarchical sequence.
If a GN call includes SSAs, then DL/I retrieves only segments that meet the requirements of all specified SSAs.
If a GN call includes SSAs, then DL/I retrieves only segments that meet the requirements of all specified SSAs.
CALL 'CBLTDLI' USING DLI-GN
PCB-NAME
IO-AREA
BOOKS-SSA
The above example shows we issue a GN call providing the starting position to read the records sequentially. It fetches the first occurrence of the BOOKS segment.
The following table shows the relevant status codes after a GN call −
Spaces
Successful call
GE
DL/I could not find a segment that met the criteria specified in the call.
GA
An unqualified GN call moves up one level in the database hierarchy to fetch the segment.
GB
End of database is reached and segment not found.
GK
An unqualified GN call tries to fetch a segment of a particular type other than the one just retrieved but stays in the same hierarchical level.
Command codes are used with calls to fetch a segment occurrence. The various command codes used with calls are discussed below.
Points to note −
When an F command code is specified in a call, the call processes the first occurrence of the segment.
When an F command code is specified in a call, the call processes the first occurrence of the segment.
F command codes can be used when we want to process sequentially and it can be used with GN calls and GNP calls.
F command codes can be used when we want to process sequentially and it can be used with GN calls and GNP calls.
If we specify an F command code with a GU call, it does not have any significance, as GU calls fetch the first segment occurrence by default.
If we specify an F command code with a GU call, it does not have any significance, as GU calls fetch the first segment occurrence by default.
Points to note −
When an L command code is specified in a call, the call processes the last occurrence of the segment.
When an L command code is specified in a call, the call processes the last occurrence of the segment.
L command codes can be used when we want to process sequentially and it can be used with GN calls and GNP calls.
L command codes can be used when we want to process sequentially and it can be used with GN calls and GNP calls.
Points to note −
D command code is used to fetch more than one segment occurrences using just a single call.
D command code is used to fetch more than one segment occurrences using just a single call.
Normally DL/I operates on the lowest level segment specified in an SSA, but in many cases, we want data from other levels as well. In those cases, we can use the D command code.
Normally DL/I operates on the lowest level segment specified in an SSA, but in many cases, we want data from other levels as well. In those cases, we can use the D command code.
D command code makes easy retrieval of the entire path of segments.
D command code makes easy retrieval of the entire path of segments.
Points to note −
C command code is used to concatenate keys.
C command code is used to concatenate keys.
Using relational operators is a bit complex, as we need to specify a field name, a relational operator, and a search value. Instead, we can use a C command code to provide a concatenated key.
Using relational operators is a bit complex, as we need to specify a field name, a relational operator, and a search value. Instead, we can use a C command code to provide a concatenated key.
The following example shows the use of C command code −
01 LOCATION-SSA.
05 FILLER PIC X(11) VALUE ‘INLOCSEG*C(‘.
05 LIBRARY-SSA PIC X(5).
05 BOOKS-SSA PIC X(4).
05 ENGINEERING-SSA PIC X(6).
05 IT-SSA PIC X(3)
05 FILLER PIC X VALUE ‘)’.
CALL 'CBLTDLI' USING DLI-GU
PCB-NAME
IO-AREA
LOCATION-SSA
Points to note −
When we issue a GU or GN call, the DL/I establishes its parentage at the lowest level segment that is retrieved.
When we issue a GU or GN call, the DL/I establishes its parentage at the lowest level segment that is retrieved.
If we include a P command code, then the DL/I establishes its parentage at a higher level segment in the hierarchical path.
If we include a P command code, then the DL/I establishes its parentage at a higher level segment in the hierarchical path.
Points to note −
When a U command code is specified in an unqualified SSA in a GN call, the DL/I restricts the search for the segment.
When a U command code is specified in an unqualified SSA in a GN call, the DL/I restricts the search for the segment.
U command code is ignored if it is used with a qualified SSA.
U command code is ignored if it is used with a qualified SSA.
Points to note −
V command code works similar to the U command code, but it restricts the search of a segment at a particular level and all levels above the hierarchy.
V command code works similar to the U command code, but it restricts the search of a segment at a particular level and all levels above the hierarchy.
V command code is ignored when used with a qualified SSA.
V command code is ignored when used with a qualified SSA.
Points to note −
Q command code is used to enqueue or reserve a segment for exclusive use of your application program.
Q command code is used to enqueue or reserve a segment for exclusive use of your application program.
Q command code is used in an interactive environment where another program might make a change to a segment.
Q command code is used in an interactive environment where another program might make a change to a segment.
A program can have multiple positions in the IMS database which is known as multiple processing. Multiple processing can be done in two ways −
Multiple PCBs
Multiple Positioning
Multiple PCBs can be defined for a single database. If there are multiple PCBs, then an application program can have different views of it. This method for implementing multiple processing is inefficient because of the overheads imposed by the extra PCBs.
A program can maintain multiple positions in a database using a single PCB. This is achieved by maintaining a distinct position for each hierarchical path. Multiple positioning is used to access segments of two or more types sequentially at the same time.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2021,
"s": 1946,
"text": "The various data retrieval methods used in IMS DL/I calls are as follows −"
},
{
"code": null,
"e": 2029,
"s": 2021,
"text": "GU Call"
},
{
"code": null,
"e": 2037,
"s": 2029,
"text": "GN Call"
},
{
"code": null,
"e": 2057,
"s": 2037,
"text": "Using Command Codes"
},
{
"code": null,
"e": 2077,
"s": 2057,
"text": "Multiple Processing"
},
{
"code": null,
"e": 2180,
"s": 2077,
"text": "Let us consider the following IMS database structure to understand the data retrieval function calls −"
},
{
"code": null,
"e": 2225,
"s": 2180,
"text": "The fundamentals of GU call are as follows −"
},
{
"code": null,
"e": 2296,
"s": 2225,
"text": "GU call is known as Get Unique call. It is used for random processing."
},
{
"code": null,
"e": 2367,
"s": 2296,
"text": "GU call is known as Get Unique call. It is used for random processing."
},
{
"code": null,
"e": 2501,
"s": 2367,
"text": "If an application does not update the database regularly or if the number of database updates is less, then we use random processing."
},
{
"code": null,
"e": 2635,
"s": 2501,
"text": "If an application does not update the database regularly or if the number of database updates is less, then we use random processing."
},
{
"code": null,
"e": 2731,
"s": 2635,
"text": "GU call is used to place the pointer at a particular position for further sequential retrieval."
},
{
"code": null,
"e": 2827,
"s": 2731,
"text": "GU call is used to place the pointer at a particular position for further sequential retrieval."
},
{
"code": null,
"e": 2911,
"s": 2827,
"text": "GU calls are independent of the pointer position established by the previous calls."
},
{
"code": null,
"e": 2995,
"s": 2911,
"text": "GU calls are independent of the pointer position established by the previous calls."
},
{
"code": null,
"e": 3080,
"s": 2995,
"text": "GU call processing is based on the unique key fields supplied in the call statement."
},
{
"code": null,
"e": 3165,
"s": 3080,
"text": "GU call processing is based on the unique key fields supplied in the call statement."
},
{
"code": null,
"e": 3275,
"s": 3165,
"text": "If we supply a key field that is not unique, then DL/I returns the first segment occurrence of the key field."
},
{
"code": null,
"e": 3385,
"s": 3275,
"text": "If we supply a key field that is not unique, then DL/I returns the first segment occurrence of the key field."
},
{
"code": null,
"e": 3601,
"s": 3385,
"text": "CALL 'CBLTDLI' USING DLI-GU\n PCB-NAME\n IO-AREA\n LIBRARY-SSA\n BOOKS-SSA\n ENGINEERING-SSA\n IT-SSA"
},
{
"code": null,
"e": 3803,
"s": 3601,
"text": "The above example shows we issue a GU call by providing a complete set of qualified SSAs. It includes all the key fields starting from the root level to the segment occurrence that we want to retrieve."
},
{
"code": null,
"e": 3911,
"s": 3803,
"text": "If we do not provide the complete set of qualified SSAs in the call, then DL/I works in the following way −"
},
{
"code": null,
"e": 4052,
"s": 3911,
"text": "When we use an unqualified SSA in a GU call, DL/I accesses the first segment occurrence in the database that meets the criteria you specify."
},
{
"code": null,
"e": 4193,
"s": 4052,
"text": "When we use an unqualified SSA in a GU call, DL/I accesses the first segment occurrence in the database that meets the criteria you specify."
},
{
"code": null,
"e": 4306,
"s": 4193,
"text": "When we issue a GU call without any SSAs, DL/I returns the first occurrence of the root segment in the database."
},
{
"code": null,
"e": 4419,
"s": 4306,
"text": "When we issue a GU call without any SSAs, DL/I returns the first occurrence of the root segment in the database."
},
{
"code": null,
"e": 4593,
"s": 4419,
"text": "If some SSAs at intermediate levels are not mentioned in the call, then DL/I uses either the established position or the default value of an unqualified SSA for the segment."
},
{
"code": null,
"e": 4767,
"s": 4593,
"text": "If some SSAs at intermediate levels are not mentioned in the call, then DL/I uses either the established position or the default value of an unqualified SSA for the segment."
},
{
"code": null,
"e": 4837,
"s": 4767,
"text": "The following table shows the relevant status codes after a GU call −"
},
{
"code": null,
"e": 4844,
"s": 4837,
"text": "Spaces"
},
{
"code": null,
"e": 4860,
"s": 4844,
"text": "Successful call"
},
{
"code": null,
"e": 4863,
"s": 4860,
"text": "GE"
},
{
"code": null,
"e": 4937,
"s": 4863,
"text": "DL/I could not find a segment that met the criteria specified in the call"
},
{
"code": null,
"e": 4982,
"s": 4937,
"text": "The fundamentals of GN call are as follows −"
},
{
"code": null,
"e": 5061,
"s": 4982,
"text": "GN call is known as Get Next call. It is used for basic sequential processing."
},
{
"code": null,
"e": 5140,
"s": 5061,
"text": "GN call is known as Get Next call. It is used for basic sequential processing."
},
{
"code": null,
"e": 5249,
"s": 5140,
"text": "The initial position of the pointer in the database is before the root segment of the first database record."
},
{
"code": null,
"e": 5358,
"s": 5249,
"text": "The initial position of the pointer in the database is before the root segment of the first database record."
},
{
"code": null,
"e": 5471,
"s": 5358,
"text": "The database pointer position is before the next segment occurrence in the sequence, after a successful GN call."
},
{
"code": null,
"e": 5584,
"s": 5471,
"text": "The database pointer position is before the next segment occurrence in the sequence, after a successful GN call."
},
{
"code": null,
"e": 5676,
"s": 5584,
"text": "The GN call starts through the database from the position established by the previous call."
},
{
"code": null,
"e": 5768,
"s": 5676,
"text": "The GN call starts through the database from the position established by the previous call."
},
{
"code": null,
"e": 5902,
"s": 5768,
"text": "If a GN call is unqualified, it returns the next segment occurrence in the database regardless of its type, in hierarchical sequence."
},
{
"code": null,
"e": 6036,
"s": 5902,
"text": "If a GN call is unqualified, it returns the next segment occurrence in the database regardless of its type, in hierarchical sequence."
},
{
"code": null,
"e": 6148,
"s": 6036,
"text": "If a GN call includes SSAs, then DL/I retrieves only segments that meet the requirements of all specified SSAs."
},
{
"code": null,
"e": 6260,
"s": 6148,
"text": "If a GN call includes SSAs, then DL/I retrieves only segments that meet the requirements of all specified SSAs."
},
{
"code": null,
"e": 6378,
"s": 6260,
"text": "CALL 'CBLTDLI' USING DLI-GN\n PCB-NAME\n IO-AREA\n BOOKS-SSA"
},
{
"code": null,
"e": 6541,
"s": 6378,
"text": "The above example shows we issue a GN call providing the starting position to read the records sequentially. It fetches the first occurrence of the BOOKS segment."
},
{
"code": null,
"e": 6611,
"s": 6541,
"text": "The following table shows the relevant status codes after a GN call −"
},
{
"code": null,
"e": 6618,
"s": 6611,
"text": "Spaces"
},
{
"code": null,
"e": 6634,
"s": 6618,
"text": "Successful call"
},
{
"code": null,
"e": 6637,
"s": 6634,
"text": "GE"
},
{
"code": null,
"e": 6712,
"s": 6637,
"text": "DL/I could not find a segment that met the criteria specified in the call."
},
{
"code": null,
"e": 6715,
"s": 6712,
"text": "GA"
},
{
"code": null,
"e": 6805,
"s": 6715,
"text": "An unqualified GN call moves up one level in the database hierarchy to fetch the segment."
},
{
"code": null,
"e": 6808,
"s": 6805,
"text": "GB"
},
{
"code": null,
"e": 6858,
"s": 6808,
"text": "End of database is reached and segment not found."
},
{
"code": null,
"e": 6861,
"s": 6858,
"text": "GK"
},
{
"code": null,
"e": 7006,
"s": 6861,
"text": "An unqualified GN call tries to fetch a segment of a particular type other than the one just retrieved but stays in the same hierarchical level."
},
{
"code": null,
"e": 7134,
"s": 7006,
"text": "Command codes are used with calls to fetch a segment occurrence. The various command codes used with calls are discussed below."
},
{
"code": null,
"e": 7151,
"s": 7134,
"text": "Points to note −"
},
{
"code": null,
"e": 7254,
"s": 7151,
"text": "When an F command code is specified in a call, the call processes the first occurrence of the segment."
},
{
"code": null,
"e": 7357,
"s": 7254,
"text": "When an F command code is specified in a call, the call processes the first occurrence of the segment."
},
{
"code": null,
"e": 7470,
"s": 7357,
"text": "F command codes can be used when we want to process sequentially and it can be used with GN calls and GNP calls."
},
{
"code": null,
"e": 7583,
"s": 7470,
"text": "F command codes can be used when we want to process sequentially and it can be used with GN calls and GNP calls."
},
{
"code": null,
"e": 7725,
"s": 7583,
"text": "If we specify an F command code with a GU call, it does not have any significance, as GU calls fetch the first segment occurrence by default."
},
{
"code": null,
"e": 7867,
"s": 7725,
"text": "If we specify an F command code with a GU call, it does not have any significance, as GU calls fetch the first segment occurrence by default."
},
{
"code": null,
"e": 7884,
"s": 7867,
"text": "Points to note −"
},
{
"code": null,
"e": 7986,
"s": 7884,
"text": "When an L command code is specified in a call, the call processes the last occurrence of the segment."
},
{
"code": null,
"e": 8088,
"s": 7986,
"text": "When an L command code is specified in a call, the call processes the last occurrence of the segment."
},
{
"code": null,
"e": 8201,
"s": 8088,
"text": "L command codes can be used when we want to process sequentially and it can be used with GN calls and GNP calls."
},
{
"code": null,
"e": 8314,
"s": 8201,
"text": "L command codes can be used when we want to process sequentially and it can be used with GN calls and GNP calls."
},
{
"code": null,
"e": 8331,
"s": 8314,
"text": "Points to note −"
},
{
"code": null,
"e": 8423,
"s": 8331,
"text": "D command code is used to fetch more than one segment occurrences using just a single call."
},
{
"code": null,
"e": 8515,
"s": 8423,
"text": "D command code is used to fetch more than one segment occurrences using just a single call."
},
{
"code": null,
"e": 8693,
"s": 8515,
"text": "Normally DL/I operates on the lowest level segment specified in an SSA, but in many cases, we want data from other levels as well. In those cases, we can use the D command code."
},
{
"code": null,
"e": 8871,
"s": 8693,
"text": "Normally DL/I operates on the lowest level segment specified in an SSA, but in many cases, we want data from other levels as well. In those cases, we can use the D command code."
},
{
"code": null,
"e": 8939,
"s": 8871,
"text": "D command code makes easy retrieval of the entire path of segments."
},
{
"code": null,
"e": 9007,
"s": 8939,
"text": "D command code makes easy retrieval of the entire path of segments."
},
{
"code": null,
"e": 9024,
"s": 9007,
"text": "Points to note −"
},
{
"code": null,
"e": 9068,
"s": 9024,
"text": "C command code is used to concatenate keys."
},
{
"code": null,
"e": 9112,
"s": 9068,
"text": "C command code is used to concatenate keys."
},
{
"code": null,
"e": 9304,
"s": 9112,
"text": "Using relational operators is a bit complex, as we need to specify a field name, a relational operator, and a search value. Instead, we can use a C command code to provide a concatenated key."
},
{
"code": null,
"e": 9496,
"s": 9304,
"text": "Using relational operators is a bit complex, as we need to specify a field name, a relational operator, and a search value. Instead, we can use a C command code to provide a concatenated key."
},
{
"code": null,
"e": 9552,
"s": 9496,
"text": "The following example shows the use of C command code −"
},
{
"code": null,
"e": 9908,
"s": 9552,
"text": "01 LOCATION-SSA.\n 05 FILLER\t\t PIC X(11) VALUE ‘INLOCSEG*C(‘.\n 05 LIBRARY-SSA PIC X(5).\n 05 BOOKS-SSA PIC X(4).\n 05 ENGINEERING-SSA PIC X(6).\n 05 IT-SSA PIC X(3)\n 05 FILLER\t\t PIC X\tVALUE ‘)’.\n\nCALL 'CBLTDLI' USING DLI-GU\n PCB-NAME\n IO-AREA\n LOCATION-SSA"
},
{
"code": null,
"e": 9925,
"s": 9908,
"text": "Points to note −"
},
{
"code": null,
"e": 10038,
"s": 9925,
"text": "When we issue a GU or GN call, the DL/I establishes its parentage at the lowest level segment that is retrieved."
},
{
"code": null,
"e": 10151,
"s": 10038,
"text": "When we issue a GU or GN call, the DL/I establishes its parentage at the lowest level segment that is retrieved."
},
{
"code": null,
"e": 10275,
"s": 10151,
"text": "If we include a P command code, then the DL/I establishes its parentage at a higher level segment in the hierarchical path."
},
{
"code": null,
"e": 10399,
"s": 10275,
"text": "If we include a P command code, then the DL/I establishes its parentage at a higher level segment in the hierarchical path."
},
{
"code": null,
"e": 10416,
"s": 10399,
"text": "Points to note −"
},
{
"code": null,
"e": 10534,
"s": 10416,
"text": "When a U command code is specified in an unqualified SSA in a GN call, the DL/I restricts the search for the segment."
},
{
"code": null,
"e": 10652,
"s": 10534,
"text": "When a U command code is specified in an unqualified SSA in a GN call, the DL/I restricts the search for the segment."
},
{
"code": null,
"e": 10714,
"s": 10652,
"text": "U command code is ignored if it is used with a qualified SSA."
},
{
"code": null,
"e": 10776,
"s": 10714,
"text": "U command code is ignored if it is used with a qualified SSA."
},
{
"code": null,
"e": 10793,
"s": 10776,
"text": "Points to note −"
},
{
"code": null,
"e": 10944,
"s": 10793,
"text": "V command code works similar to the U command code, but it restricts the search of a segment at a particular level and all levels above the hierarchy."
},
{
"code": null,
"e": 11095,
"s": 10944,
"text": "V command code works similar to the U command code, but it restricts the search of a segment at a particular level and all levels above the hierarchy."
},
{
"code": null,
"e": 11153,
"s": 11095,
"text": "V command code is ignored when used with a qualified SSA."
},
{
"code": null,
"e": 11211,
"s": 11153,
"text": "V command code is ignored when used with a qualified SSA."
},
{
"code": null,
"e": 11228,
"s": 11211,
"text": "Points to note −"
},
{
"code": null,
"e": 11330,
"s": 11228,
"text": "Q command code is used to enqueue or reserve a segment for exclusive use of your application program."
},
{
"code": null,
"e": 11432,
"s": 11330,
"text": "Q command code is used to enqueue or reserve a segment for exclusive use of your application program."
},
{
"code": null,
"e": 11541,
"s": 11432,
"text": "Q command code is used in an interactive environment where another program might make a change to a segment."
},
{
"code": null,
"e": 11650,
"s": 11541,
"text": "Q command code is used in an interactive environment where another program might make a change to a segment."
},
{
"code": null,
"e": 11793,
"s": 11650,
"text": "A program can have multiple positions in the IMS database which is known as multiple processing. Multiple processing can be done in two ways −"
},
{
"code": null,
"e": 11807,
"s": 11793,
"text": "Multiple PCBs"
},
{
"code": null,
"e": 11828,
"s": 11807,
"text": "Multiple Positioning"
},
{
"code": null,
"e": 12084,
"s": 11828,
"text": "Multiple PCBs can be defined for a single database. If there are multiple PCBs, then an application program can have different views of it. This method for implementing multiple processing is inefficient because of the overheads imposed by the extra PCBs."
},
{
"code": null,
"e": 12340,
"s": 12084,
"text": "A program can maintain multiple positions in a database using a single PCB. This is achieved by maintaining a distinct position for each hierarchical path. Multiple positioning is used to access segments of two or more types sequentially at the same time."
},
{
"code": null,
"e": 12347,
"s": 12340,
"text": " Print"
},
{
"code": null,
"e": 12358,
"s": 12347,
"text": " Add Notes"
}
] |
Check if a number is Palindrome in PL/SQLs
|
In this section we will see how to check whether a number is Palindrome or not using the PL/SQL. In PL/SQL code, some group of commands are arranged within a block of related declaration of statements.
A number is palindrome if the number, and the reverse of that number are same. Suppose a number 12321, this is palindrome, but 12345 is not a palindrome.
DECLARE
n number;
m number;
temp number:=0;
rem number;
BEGIN
n :=12321;
m :=n;
while n>0
loop
rem := mod(n,10);
temp := (temp*10)+rem;
n := trunc(n/10);
end loop;
if m = temp
then
dbms_output.put_line('Palindrome');
else
dbms_output.put_line('Not Palindrome');
end if;
END;
Palindrome
|
[
{
"code": null,
"e": 1264,
"s": 1062,
"text": "In this section we will see how to check whether a number is Palindrome or not using the PL/SQL. In PL/SQL code, some group of commands are arranged within a block of related declaration of statements."
},
{
"code": null,
"e": 1418,
"s": 1264,
"text": "A number is palindrome if the number, and the reverse of that number are same. Suppose a number 12321, this is palindrome, but 12345 is not a palindrome."
},
{
"code": null,
"e": 1762,
"s": 1418,
"text": "DECLARE\n n number;\n m number;\n temp number:=0;\n rem number;\nBEGIN\n n :=12321;\n m :=n;\n while n>0\n loop\n rem := mod(n,10);\n temp := (temp*10)+rem;\n n := trunc(n/10);\n end loop;\n if m = temp\n then\n dbms_output.put_line('Palindrome');\n else\n dbms_output.put_line('Not Palindrome');\n end if;\nEND;"
},
{
"code": null,
"e": 1773,
"s": 1762,
"text": "Palindrome"
}
] |
Line Separator in Java
|
Strings have no newlines. We can form them into two lines by concatenating a newline string. Use System lineSeparator to get a platform-dependent newline string.
The following is an example.
Live Demo
public class Demo {
public static void main(String[] args) {
String str = "one" + System.lineSeparator() + "two";
System.out.println(str);
}
}
one
two
Let us see another example. On Linux based system, the program will work correctly.
Live Demo
public class Demo {
public static void main(String[] args) {
String str = System.lineSeparator();
System.out.println((int) str.charAt(0));
}
}
10
|
[
{
"code": null,
"e": 1224,
"s": 1062,
"text": "Strings have no newlines. We can form them into two lines by concatenating a newline string. Use System lineSeparator to get a platform-dependent newline string."
},
{
"code": null,
"e": 1253,
"s": 1224,
"text": "The following is an example."
},
{
"code": null,
"e": 1264,
"s": 1253,
"text": " Live Demo"
},
{
"code": null,
"e": 1425,
"s": 1264,
"text": "public class Demo {\n public static void main(String[] args) {\n String str = \"one\" + System.lineSeparator() + \"two\";\n System.out.println(str);\n }\n}"
},
{
"code": null,
"e": 1433,
"s": 1425,
"text": "one\ntwo"
},
{
"code": null,
"e": 1517,
"s": 1433,
"text": "Let us see another example. On Linux based system, the program will work correctly."
},
{
"code": null,
"e": 1528,
"s": 1517,
"text": " Live Demo"
},
{
"code": null,
"e": 1689,
"s": 1528,
"text": "public class Demo {\n public static void main(String[] args) {\n String str = System.lineSeparator();\n System.out.println((int) str.charAt(0));\n }\n}"
},
{
"code": null,
"e": 1692,
"s": 1689,
"text": "10"
}
] |
Python | os.kill() method - GeeksforGeeks
|
03 Jul, 2021
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.os.kill() method in Python is used to send specified signal to the process with specified process id. Constants for the specific signals available on the host platform are defined in the signal module.
Syntax: os.kill(pid, sig)Parameters: pid: An integer value representing process id to which signal is to be sent. sig An integer representing signal number or the signal constant available on the host platform defined in the signal module to be sent.Return type: This method does not return any value.
Code: Use of os.kill() method
Python3
# Python program to explain os.kill() method # importing os and signal module import os, signal # Create a child process# using os.fork() methodpid = os.fork() # pid greater than 0# indicates the parent processif pid : print("\nIn parent process") # send signal 'SIGSTOP' # to the child process # using os.kill() method # 'SIGSTOP' signal will # cause the process to stop os.kill(pid, signal.SIGSTOP) print("Signal sent, child stopped.") info = os.waitpid(pid, os.WSTOPPED) # waitpid() method returns a # tuple whose first attribute # represents child's pid # and second attribute # representing child's status indication # os.WSTOPSIG() returns the signal number # which caused the process to stop stopSignal = os.WSTOPSIG(info[1]) print("Child stopped due to signal no:", stopSignal) print("Signal name:", signal.Signals(stopSignal).name) # send signal 'SIGCONT' # to the child process # using os.kill() method # 'SIGCONT' signal will # cause the process to continue os.kill(pid, signal.SIGCONT) print("\nSignal sent, child continued.") else : print("\nIn child process") print("Process ID:", os.getpid()) print("Hello ! Geeks") print("Exiting")
In child process
In parent process
Signal sent, child stopped.
Child stopped due to signal no: 19
Signal name: SIGSTOP
Signal sent, child continued.
Process ID: 5166
Hello! Geeks
Exiting
References: https://docs.python.org/3/library/os.html#os.kill
rajeev0719singh
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24732,
"s": 24704,
"text": "\n03 Jul, 2021"
},
{
"code": null,
"e": 25152,
"s": 24732,
"text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.os.kill() method in Python is used to send specified signal to the process with specified process id. Constants for the specific signals available on the host platform are defined in the signal module."
},
{
"code": null,
"e": 25456,
"s": 25152,
"text": "Syntax: os.kill(pid, sig)Parameters: pid: An integer value representing process id to which signal is to be sent. sig An integer representing signal number or the signal constant available on the host platform defined in the signal module to be sent.Return type: This method does not return any value. "
},
{
"code": null,
"e": 25488,
"s": 25456,
"text": "Code: Use of os.kill() method "
},
{
"code": null,
"e": 25496,
"s": 25488,
"text": "Python3"
},
{
"code": "# Python program to explain os.kill() method # importing os and signal module import os, signal # Create a child process# using os.fork() methodpid = os.fork() # pid greater than 0# indicates the parent processif pid : print(\"\\nIn parent process\") # send signal 'SIGSTOP' # to the child process # using os.kill() method # 'SIGSTOP' signal will # cause the process to stop os.kill(pid, signal.SIGSTOP) print(\"Signal sent, child stopped.\") info = os.waitpid(pid, os.WSTOPPED) # waitpid() method returns a # tuple whose first attribute # represents child's pid # and second attribute # representing child's status indication # os.WSTOPSIG() returns the signal number # which caused the process to stop stopSignal = os.WSTOPSIG(info[1]) print(\"Child stopped due to signal no:\", stopSignal) print(\"Signal name:\", signal.Signals(stopSignal).name) # send signal 'SIGCONT' # to the child process # using os.kill() method # 'SIGCONT' signal will # cause the process to continue os.kill(pid, signal.SIGCONT) print(\"\\nSignal sent, child continued.\") else : print(\"\\nIn child process\") print(\"Process ID:\", os.getpid()) print(\"Hello ! Geeks\") print(\"Exiting\")",
"e": 26778,
"s": 25496,
"text": null
},
{
"code": null,
"e": 26968,
"s": 26778,
"text": "In child process\n\nIn parent process\nSignal sent, child stopped.\nChild stopped due to signal no: 19\nSignal name: SIGSTOP\n\nSignal sent, child continued.\n\nProcess ID: 5166\nHello! Geeks\nExiting"
},
{
"code": null,
"e": 27033,
"s": 26970,
"text": "References: https://docs.python.org/3/library/os.html#os.kill "
},
{
"code": null,
"e": 27049,
"s": 27033,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 27066,
"s": 27049,
"text": "python-os-module"
},
{
"code": null,
"e": 27073,
"s": 27066,
"text": "Python"
},
{
"code": null,
"e": 27171,
"s": 27073,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27189,
"s": 27171,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27224,
"s": 27189,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27246,
"s": 27224,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27278,
"s": 27246,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27308,
"s": 27278,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27350,
"s": 27308,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27376,
"s": 27350,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27419,
"s": 27376,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27456,
"s": 27419,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Degree of an Array in C++
|
Suppose we have an array of non-negative integers called nums, the degree of this array is actually the maximum frequency of any one of its elements. We have to find the smallest possible length of a contiguous subarray of nums, that has the same degree as nums.
So, if the input is like [1,2,2,3,1], then the output will be 2, this is because the input array has a degree of 2 because both elements 1 and 2 appear twice. The subarrays that have the same degree − [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is 2. So
answer will be 2.
To solve this, we will follow these steps −
Define an array freq of size 50000 and fill this with 0
max_ := 0
for each n in nums(increase freq[n] by 1)max_ := maximum of max_ and freq[n]
(increase freq[n] by 1)
max_ := maximum of max_ and freq[n]
fill freq array with 0.
min_ := size of nums
for initialize i := 0, j := -1, size := size of nums, when j < size, do −if j >= 0 and freq[nums[j]] is same as max_, then −min_ := minimum of min_ and j - i + 1otherwise when j < size - 1, then −increase j by 1increase freq[nums[j]] by 1OtherwiseCome out from the loop
if j >= 0 and freq[nums[j]] is same as max_, then −min_ := minimum of min_ and j - i + 1
min_ := minimum of min_ and j - i + 1
otherwise when j < size - 1, then −increase j by 1increase freq[nums[j]] by 1
increase j by 1
increase freq[nums[j]] by 1
OtherwiseCome out from the loop
Come out from the loop
return min_
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
vector<int> freq(50000, 0);
int max_ = 0;
for (const int n : nums)
max_ = max(max_, ++freq[n]);
fill(freq.begin(), freq.end(), 0);
int min_ = nums.size();
for (int i = 0, j = -1, size = nums.size(); j < size;) {
if (j >= 0 && freq[nums[j]] == max_)
min_ = min(min_, j - i + 1), --freq[nums[i++]];
else if (j < size - 1)
++freq[nums[++j]];
else
break;
}
return min_;
}
};
main(){
Solution ob;
vector<int> v = {1, 2, 2, 3, 1};
cout << (ob.findShortestSubArray(v));
}
{1, 2, 2, 3, 1}
2
|
[
{
"code": null,
"e": 1325,
"s": 1062,
"text": "Suppose we have an array of non-negative integers called nums, the degree of this array is actually the maximum frequency of any one of its elements. We have to find the smallest possible length of a contiguous subarray of nums, that has the same degree as nums."
},
{
"code": null,
"e": 1647,
"s": 1325,
"text": "So, if the input is like [1,2,2,3,1], then the output will be 2, this is because the input array has a degree of 2 because both elements 1 and 2 appear twice. The subarrays that have the same degree − [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is 2. So\nanswer will be 2."
},
{
"code": null,
"e": 1691,
"s": 1647,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1747,
"s": 1691,
"text": "Define an array freq of size 50000 and fill this with 0"
},
{
"code": null,
"e": 1757,
"s": 1747,
"text": "max_ := 0"
},
{
"code": null,
"e": 1834,
"s": 1757,
"text": "for each n in nums(increase freq[n] by 1)max_ := maximum of max_ and freq[n]"
},
{
"code": null,
"e": 1858,
"s": 1834,
"text": "(increase freq[n] by 1)"
},
{
"code": null,
"e": 1894,
"s": 1858,
"text": "max_ := maximum of max_ and freq[n]"
},
{
"code": null,
"e": 1918,
"s": 1894,
"text": "fill freq array with 0."
},
{
"code": null,
"e": 1939,
"s": 1918,
"text": "min_ := size of nums"
},
{
"code": null,
"e": 2209,
"s": 1939,
"text": "for initialize i := 0, j := -1, size := size of nums, when j < size, do −if j >= 0 and freq[nums[j]] is same as max_, then −min_ := minimum of min_ and j - i + 1otherwise when j < size - 1, then −increase j by 1increase freq[nums[j]] by 1OtherwiseCome out from the loop"
},
{
"code": null,
"e": 2298,
"s": 2209,
"text": "if j >= 0 and freq[nums[j]] is same as max_, then −min_ := minimum of min_ and j - i + 1"
},
{
"code": null,
"e": 2336,
"s": 2298,
"text": "min_ := minimum of min_ and j - i + 1"
},
{
"code": null,
"e": 2414,
"s": 2336,
"text": "otherwise when j < size - 1, then −increase j by 1increase freq[nums[j]] by 1"
},
{
"code": null,
"e": 2430,
"s": 2414,
"text": "increase j by 1"
},
{
"code": null,
"e": 2458,
"s": 2430,
"text": "increase freq[nums[j]] by 1"
},
{
"code": null,
"e": 2490,
"s": 2458,
"text": "OtherwiseCome out from the loop"
},
{
"code": null,
"e": 2513,
"s": 2490,
"text": "Come out from the loop"
},
{
"code": null,
"e": 2525,
"s": 2513,
"text": "return min_"
},
{
"code": null,
"e": 2595,
"s": 2525,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2606,
"s": 2595,
"text": " Live Demo"
},
{
"code": null,
"e": 3320,
"s": 2606,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int findShortestSubArray(vector<int>& nums) {\n vector<int> freq(50000, 0);\n int max_ = 0;\n for (const int n : nums)\n max_ = max(max_, ++freq[n]);\n fill(freq.begin(), freq.end(), 0);\n int min_ = nums.size();\n for (int i = 0, j = -1, size = nums.size(); j < size;) {\n if (j >= 0 && freq[nums[j]] == max_)\n min_ = min(min_, j - i + 1), --freq[nums[i++]];\n else if (j < size - 1)\n ++freq[nums[++j]];\n else\n break;\n }\n return min_;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {1, 2, 2, 3, 1};\n cout << (ob.findShortestSubArray(v));\n}"
},
{
"code": null,
"e": 3336,
"s": 3320,
"text": "{1, 2, 2, 3, 1}"
},
{
"code": null,
"e": 3338,
"s": 3336,
"text": "2"
}
] |
Dynamically split/create multiple datasets from single dataset in SAS | by Pramod K | Towards Data Science
|
Splitting a dataset into multiple datasets is a challenge often faced by SAS programmers. For example, splitting data collected from all over the world into unique country-wise datasets, where each datsaset contains data specific only to that country. In such scenarios, programmers are often forced to hard code the program and use multiple loops to get the job done, which is not a good practice. SAS, however, provides a beautiful, one-time, reusable solution to this problem. Let’s get straight into it.
We have the following worldwide sales dataset with us (Worldwide_Sales.xls):
All datasets and code files can be found at GitHub ( https://github.com/pramodkumavat/createMultipleDatasets/ ).
Let’s first import this dataset into our SAS environment.
P.S : Please copy the dataset file Worldwide_Sales.xls into your SAS working directory myfolders.
proc import out=work.salesdatafile='/folders/myfolders/Worldwide_Sales.xls'dbms=xls replace;getnames=yes;run;
Running the above code will load our dataset as work.sales library in SAS.
To understand the various options used in the import code, this FAQ is all you need.
The business requirement says that we must create country-wise unique datasets from the worldwide dataset. Each dataset thus created will have sales data for that specific country. To achieve this, we will first need to extract the unique country names from the dataset.
proc sort data=work.sales out=work.unique (keep=Country)nodupkey;by country;run;
Running the above code will give us the unique country names from the dataset.
Once we have extracted the country names, let’s now create our magic code to dynamically create country-wise datasets inside single data statement.
data _null_;set work.unique;call execute('data ' !! compress(Country) !! '; set work.sales; where Country = "' !! Country !! '"; run;');run;
As you can see in the above output, on the left-hand side, we see country-wise unique datasets have been created.
Let’s understand each aspect of the code line by line that makes this magic possible.
data _null_;
We set the output data as _null_ because we don’t want to create a single dataset, but multiple datasets at once, which we we’ll see in some time.
set work.unique;
We set the input dataset as work.unique, which contains unique country names. We do this because we will want unique country-wise datasets to be created on each iteration.
call execute('data ' !! compress(Country) !! '; set work.sales; where Country = "' !! Country !! '"; run;');run;
This is the real deal! You might have noticed that we have written a nested query inside the call execute() statement. As mentioned earlier, SAS provides this beautiful solution to create multiple datasets without using multiple loops.
Inside the execute() call, we start with the data statement and then append it with our unique country name. Country here is nothing but the variable from our work.unique dataset. The compress function is applied to the Country variable because we have country names with whitespaces in them (for example, New Zealand, United Kingdom). This compress function removes the whitespace from the country names when creating unique datasets.
Then we put semicolon(;) to end our data step and then set the input dataset as work.sales. It is obvious that we set input as our parent dataset work.sales using which we will create unique datasets. Then, we put the where condition so that it picks country-wise data from the parent dataset. Then we end the nested query with the run statement and close the execute() call. The last run statement of the code is to end the outer query.
I’m pasting the full SAS code here for your reference. This SAS code (dynamicMultipleDatasets.sas) along with the dataset used (Worldwide_Sales.xls) can be download from GitHub here.
* Importing the dataset in SAS;proc import out=work.salesdatafile='/folders/myfolders/Worldwide_Sales.xls'dbms=xls replace;getnames=yes;run;* Extracting country names from the dataset;proc sort data=work.sales out=work.unique (keep=Country)nodupkey;by country;run;* Creating multiple datasets from the parent dataset;data _null_;set work.unique;call execute('data ' !! compress(Country) !! '; set work.sales; where Country = "' !! Country !! '"; run;');run;
Hope this was helpful. Please comment your feedback/suggestions. Cheers!
|
[
{
"code": null,
"e": 680,
"s": 172,
"text": "Splitting a dataset into multiple datasets is a challenge often faced by SAS programmers. For example, splitting data collected from all over the world into unique country-wise datasets, where each datsaset contains data specific only to that country. In such scenarios, programmers are often forced to hard code the program and use multiple loops to get the job done, which is not a good practice. SAS, however, provides a beautiful, one-time, reusable solution to this problem. Let’s get straight into it."
},
{
"code": null,
"e": 757,
"s": 680,
"text": "We have the following worldwide sales dataset with us (Worldwide_Sales.xls):"
},
{
"code": null,
"e": 870,
"s": 757,
"text": "All datasets and code files can be found at GitHub ( https://github.com/pramodkumavat/createMultipleDatasets/ )."
},
{
"code": null,
"e": 928,
"s": 870,
"text": "Let’s first import this dataset into our SAS environment."
},
{
"code": null,
"e": 1026,
"s": 928,
"text": "P.S : Please copy the dataset file Worldwide_Sales.xls into your SAS working directory myfolders."
},
{
"code": null,
"e": 1136,
"s": 1026,
"text": "proc import out=work.salesdatafile='/folders/myfolders/Worldwide_Sales.xls'dbms=xls replace;getnames=yes;run;"
},
{
"code": null,
"e": 1211,
"s": 1136,
"text": "Running the above code will load our dataset as work.sales library in SAS."
},
{
"code": null,
"e": 1296,
"s": 1211,
"text": "To understand the various options used in the import code, this FAQ is all you need."
},
{
"code": null,
"e": 1567,
"s": 1296,
"text": "The business requirement says that we must create country-wise unique datasets from the worldwide dataset. Each dataset thus created will have sales data for that specific country. To achieve this, we will first need to extract the unique country names from the dataset."
},
{
"code": null,
"e": 1648,
"s": 1567,
"text": "proc sort data=work.sales out=work.unique (keep=Country)nodupkey;by country;run;"
},
{
"code": null,
"e": 1727,
"s": 1648,
"text": "Running the above code will give us the unique country names from the dataset."
},
{
"code": null,
"e": 1875,
"s": 1727,
"text": "Once we have extracted the country names, let’s now create our magic code to dynamically create country-wise datasets inside single data statement."
},
{
"code": null,
"e": 2016,
"s": 1875,
"text": "data _null_;set work.unique;call execute('data ' !! compress(Country) !! '; set work.sales; where Country = \"' !! Country !! '\"; run;');run;"
},
{
"code": null,
"e": 2130,
"s": 2016,
"text": "As you can see in the above output, on the left-hand side, we see country-wise unique datasets have been created."
},
{
"code": null,
"e": 2216,
"s": 2130,
"text": "Let’s understand each aspect of the code line by line that makes this magic possible."
},
{
"code": null,
"e": 2229,
"s": 2216,
"text": "data _null_;"
},
{
"code": null,
"e": 2376,
"s": 2229,
"text": "We set the output data as _null_ because we don’t want to create a single dataset, but multiple datasets at once, which we we’ll see in some time."
},
{
"code": null,
"e": 2393,
"s": 2376,
"text": "set work.unique;"
},
{
"code": null,
"e": 2565,
"s": 2393,
"text": "We set the input dataset as work.unique, which contains unique country names. We do this because we will want unique country-wise datasets to be created on each iteration."
},
{
"code": null,
"e": 2678,
"s": 2565,
"text": "call execute('data ' !! compress(Country) !! '; set work.sales; where Country = \"' !! Country !! '\"; run;');run;"
},
{
"code": null,
"e": 2914,
"s": 2678,
"text": "This is the real deal! You might have noticed that we have written a nested query inside the call execute() statement. As mentioned earlier, SAS provides this beautiful solution to create multiple datasets without using multiple loops."
},
{
"code": null,
"e": 3350,
"s": 2914,
"text": "Inside the execute() call, we start with the data statement and then append it with our unique country name. Country here is nothing but the variable from our work.unique dataset. The compress function is applied to the Country variable because we have country names with whitespaces in them (for example, New Zealand, United Kingdom). This compress function removes the whitespace from the country names when creating unique datasets."
},
{
"code": null,
"e": 3788,
"s": 3350,
"text": "Then we put semicolon(;) to end our data step and then set the input dataset as work.sales. It is obvious that we set input as our parent dataset work.sales using which we will create unique datasets. Then, we put the where condition so that it picks country-wise data from the parent dataset. Then we end the nested query with the run statement and close the execute() call. The last run statement of the code is to end the outer query."
},
{
"code": null,
"e": 3971,
"s": 3788,
"text": "I’m pasting the full SAS code here for your reference. This SAS code (dynamicMultipleDatasets.sas) along with the dataset used (Worldwide_Sales.xls) can be download from GitHub here."
},
{
"code": null,
"e": 4429,
"s": 3971,
"text": "* Importing the dataset in SAS;proc import out=work.salesdatafile='/folders/myfolders/Worldwide_Sales.xls'dbms=xls replace;getnames=yes;run;* Extracting country names from the dataset;proc sort data=work.sales out=work.unique (keep=Country)nodupkey;by country;run;* Creating multiple datasets from the parent dataset;data _null_;set work.unique;call execute('data ' !! compress(Country) !! '; set work.sales; where Country = \"' !! Country !! '\"; run;');run;"
}
] |
How can we get the client's IP address in ASP.NET MVC C#?
|
Every machine on a network has a unique identifier. Just as you would address a letter
to send in the mail, computers use the unique identifier to send data to specific
computers on a network. Most networks today, including all computers on the
internet, use the TCP/IP protocol as the standard for how to communicate on the
network. In the TCP/IP protocol, the unique identifier for a computer is called its IP
address.
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers{
public class HomeController : Controller{
public string Index(){
string ipAddress = Request.UserHostAddress;
return ipAddress;
}
}
}
If we want to fetch IP address outside the controller i.e. in a normal class, we can do
like below.
using System.Web;
namespace DemoMvcApplication.Helpers{
public static class DemoHelperClass{
public static string GetIPAddress(){
string ipAddress = HttpContext.Current.Request.UserHostAddress;
return ipAddress;
}
}
}
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers{
public class HomeController : Controller{
public string Index(){
string ipAddress = Request.ServerVariables["REMOTE_ADDR"];
return ipAddress;
}
}
}
Since we are running the application locally, the ip address for the localhost is ::1.
The name localhost normally resolves to the IPv4 loopback address 127.0.0.1, and to
the IPv6 loopback address ::1
|
[
{
"code": null,
"e": 1483,
"s": 1062,
"text": "Every machine on a network has a unique identifier. Just as you would address a letter\nto send in the mail, computers use the unique identifier to send data to specific\ncomputers on a network. Most networks today, including all computers on the\ninternet, use the TCP/IP protocol as the standard for how to communicate on the\nnetwork. In the TCP/IP protocol, the unique identifier for a computer is called its IP\naddress."
},
{
"code": null,
"e": 1716,
"s": 1483,
"text": "using System.Web.Mvc;\nnamespace DemoMvcApplication.Controllers{\n public class HomeController : Controller{\n public string Index(){\n string ipAddress = Request.UserHostAddress;\n return ipAddress;\n }\n }\n}"
},
{
"code": null,
"e": 1816,
"s": 1716,
"text": "If we want to fetch IP address outside the controller i.e. in a normal class, we can do\nlike below."
},
{
"code": null,
"e": 2070,
"s": 1816,
"text": "using System.Web;\nnamespace DemoMvcApplication.Helpers{\n public static class DemoHelperClass{\n public static string GetIPAddress(){\n string ipAddress = HttpContext.Current.Request.UserHostAddress;\n return ipAddress;\n }\n }\n}"
},
{
"code": null,
"e": 2318,
"s": 2070,
"text": "using System.Web.Mvc;\nnamespace DemoMvcApplication.Controllers{\n public class HomeController : Controller{\n public string Index(){\n string ipAddress = Request.ServerVariables[\"REMOTE_ADDR\"];\n return ipAddress;\n }\n }\n}"
},
{
"code": null,
"e": 2519,
"s": 2318,
"text": "Since we are running the application locally, the ip address for the localhost is ::1.\nThe name localhost normally resolves to the IPv4 loopback address 127.0.0.1, and to\nthe IPv6 loopback address ::1"
}
] |
Python | How to copy data from one excel sheet to another - GeeksforGeeks
|
03 Oct, 2019
In this article, we will learn how to copy data from one excel sheet to destination excel workbook using openpyxl module in Python.
For working with excel files, we require openpyxl, which is a Python library that is used for reading, writing and modifying excel (with extension xlsx/xlsm/xltx/xltm) files. It can be installed using the following command:
Sudo pip3 install openpyxl
For copying one excel file to another, we first open both the source and destination excel files. Then we calculate the total number of rows and columns in the source excel file and read a single cell value and store it in a variable and then write that value to the destination excel file at a cell position similar to that of the cell in source file. The destination file is saved.
Procedure –
1) Import openpyxl library as xl.2) Open the source excel file using the path in which it is located.
Note: The path should be a string and have double backslashes (\\) instead of single backslash (\). Eg: Path should be C:\\Users\\Desktop\\source.xlsx Instead of C:\Users\Admin\Desktop\source.xlsx
3) Open the required worksheet to copy using the index of it. The index of worksheet ‘n’ is ‘n-1’. For example, the index of worksheet 1 is 0.4) Open the destination excel file and the active worksheet in it.5) Calculate the total number of rows and columns in source excel file.6) Use two for loops (one for iterating through rows and another for iterating through columns of the excel file) to read the cell value in source file to a variable and then write it to a cell in destination file from that variable.7) Save the destination file.
# importing openpyxl moduleimport openpyxl as xl; # opening the source excel filefilename ="C:\\Users\\Admin\\Desktop\\trading.xlsx"wb1 = xl.load_workbook(filename)ws1 = wb1.worksheets[0] # opening the destination excel file filename1 ="C:\\Users\\Admin\\Desktop\\test.xlsx"wb2 = xl.load_workbook(filename1)ws2 = wb2.active # calculate total number of rows and # columns in source excel filemr = ws1.max_rowmc = ws1.max_column # copying the cell values from source # excel file to destination excel filefor i in range (1, mr + 1): for j in range (1, mc + 1): # reading cell value from source excel file c = ws1.cell(row = i, column = j) # writing the read value to destination excel file ws2.cell(row = i, column = j).value = c.value # saving the destination excel filewb2.save(str(filename1))
Source File:
Output:
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
|
[
{
"code": null,
"e": 24930,
"s": 24902,
"text": "\n03 Oct, 2019"
},
{
"code": null,
"e": 25062,
"s": 24930,
"text": "In this article, we will learn how to copy data from one excel sheet to destination excel workbook using openpyxl module in Python."
},
{
"code": null,
"e": 25286,
"s": 25062,
"text": "For working with excel files, we require openpyxl, which is a Python library that is used for reading, writing and modifying excel (with extension xlsx/xlsm/xltx/xltm) files. It can be installed using the following command:"
},
{
"code": null,
"e": 25313,
"s": 25286,
"text": "Sudo pip3 install openpyxl"
},
{
"code": null,
"e": 25697,
"s": 25313,
"text": "For copying one excel file to another, we first open both the source and destination excel files. Then we calculate the total number of rows and columns in the source excel file and read a single cell value and store it in a variable and then write that value to the destination excel file at a cell position similar to that of the cell in source file. The destination file is saved."
},
{
"code": null,
"e": 25709,
"s": 25697,
"text": "Procedure –"
},
{
"code": null,
"e": 25811,
"s": 25709,
"text": "1) Import openpyxl library as xl.2) Open the source excel file using the path in which it is located."
},
{
"code": null,
"e": 26008,
"s": 25811,
"text": "Note: The path should be a string and have double backslashes (\\\\) instead of single backslash (\\). Eg: Path should be C:\\\\Users\\\\Desktop\\\\source.xlsx Instead of C:\\Users\\Admin\\Desktop\\source.xlsx"
},
{
"code": null,
"e": 26550,
"s": 26008,
"text": "3) Open the required worksheet to copy using the index of it. The index of worksheet ‘n’ is ‘n-1’. For example, the index of worksheet 1 is 0.4) Open the destination excel file and the active worksheet in it.5) Calculate the total number of rows and columns in source excel file.6) Use two for loops (one for iterating through rows and another for iterating through columns of the excel file) to read the cell value in source file to a variable and then write it to a cell in destination file from that variable.7) Save the destination file."
},
{
"code": "# importing openpyxl moduleimport openpyxl as xl; # opening the source excel filefilename =\"C:\\\\Users\\\\Admin\\\\Desktop\\\\trading.xlsx\"wb1 = xl.load_workbook(filename)ws1 = wb1.worksheets[0] # opening the destination excel file filename1 =\"C:\\\\Users\\\\Admin\\\\Desktop\\\\test.xlsx\"wb2 = xl.load_workbook(filename1)ws2 = wb2.active # calculate total number of rows and # columns in source excel filemr = ws1.max_rowmc = ws1.max_column # copying the cell values from source # excel file to destination excel filefor i in range (1, mr + 1): for j in range (1, mc + 1): # reading cell value from source excel file c = ws1.cell(row = i, column = j) # writing the read value to destination excel file ws2.cell(row = i, column = j).value = c.value # saving the destination excel filewb2.save(str(filename1))",
"e": 27382,
"s": 26550,
"text": null
},
{
"code": null,
"e": 27395,
"s": 27382,
"text": "Source File:"
},
{
"code": null,
"e": 27403,
"s": 27395,
"text": "Output:"
},
{
"code": null,
"e": 27418,
"s": 27403,
"text": "python-utility"
},
{
"code": null,
"e": 27425,
"s": 27418,
"text": "Python"
},
{
"code": null,
"e": 27523,
"s": 27425,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27541,
"s": 27523,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27563,
"s": 27541,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27595,
"s": 27563,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27625,
"s": 27595,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27667,
"s": 27625,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27693,
"s": 27667,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27730,
"s": 27693,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27774,
"s": 27730,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27803,
"s": 27774,
"text": "*args and **kwargs in Python"
}
] |
Python - tensorflow.math.square() - GeeksforGeeks
|
16 Jun, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks.
square() is used to compute element wise square of x i.e x*x.
Syntax: tensorflow.math.square(x, name)
Parameters:
x: It’s a tensor. Allowed dtypes are bfloat16, half, float32, float64, complex64, complex128.
name(optional): It defines the name for the operation.
Returns: It returns a tensor.
Example 1:
Python3
# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([ -5, -7, 2, 5, 7], dtype = tf.float64) # Printing the input tensorprint('a: ', a) # Calculating resultres = tf.math.square(a) # Printing the resultprint('Result: ', res)
Output:
a: tf.Tensor([-5. -7. 2. 5. 7.], shape=(5, ), dtype=float64)
Result: tf.Tensor([25. 49. 4. 25. 49.], shape=(5, ), dtype=float64)
Example 2: Visualization
Python3
# import tensorflow as tfimport matplotlib.pyplot as plt # Initializing the input tensora = tf.constant([ -7, -5, 2, 5, 7], dtype = tf.float64) # Calculating tangentres = tf.math.square(a) # Plotting the graphplt.plot(a, res, color ='green')plt.title('tensorflow.math.square')plt.xlabel('Input')plt.ylabel('Result')plt.show()
Output:
Python Tensorflow-math-functions
Python-Tensorflow
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": "\n16 Jun, 2020"
},
{
"code": null,
"e": 24423,
"s": 24292,
"text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks."
},
{
"code": null,
"e": 24485,
"s": 24423,
"text": "square() is used to compute element wise square of x i.e x*x."
},
{
"code": null,
"e": 24525,
"s": 24485,
"text": "Syntax: tensorflow.math.square(x, name)"
},
{
"code": null,
"e": 24537,
"s": 24525,
"text": "Parameters:"
},
{
"code": null,
"e": 24631,
"s": 24537,
"text": "x: It’s a tensor. Allowed dtypes are bfloat16, half, float32, float64, complex64, complex128."
},
{
"code": null,
"e": 24686,
"s": 24631,
"text": "name(optional): It defines the name for the operation."
},
{
"code": null,
"e": 24716,
"s": 24686,
"text": "Returns: It returns a tensor."
},
{
"code": null,
"e": 24727,
"s": 24716,
"text": "Example 1:"
},
{
"code": null,
"e": 24735,
"s": 24727,
"text": "Python3"
},
{
"code": "# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([ -5, -7, 2, 5, 7], dtype = tf.float64) # Printing the input tensorprint('a: ', a) # Calculating resultres = tf.math.square(a) # Printing the resultprint('Result: ', res)",
"e": 25004,
"s": 24735,
"text": null
},
{
"code": null,
"e": 25012,
"s": 25004,
"text": "Output:"
},
{
"code": null,
"e": 25151,
"s": 25012,
"text": "a: tf.Tensor([-5. -7. 2. 5. 7.], shape=(5, ), dtype=float64)\nResult: tf.Tensor([25. 49. 4. 25. 49.], shape=(5, ), dtype=float64)\n\n\n\n"
},
{
"code": null,
"e": 25176,
"s": 25151,
"text": "Example 2: Visualization"
},
{
"code": null,
"e": 25184,
"s": 25176,
"text": "Python3"
},
{
"code": "# import tensorflow as tfimport matplotlib.pyplot as plt # Initializing the input tensora = tf.constant([ -7, -5, 2, 5, 7], dtype = tf.float64) # Calculating tangentres = tf.math.square(a) # Plotting the graphplt.plot(a, res, color ='green')plt.title('tensorflow.math.square')plt.xlabel('Input')plt.ylabel('Result')plt.show()",
"e": 25513,
"s": 25184,
"text": null
},
{
"code": null,
"e": 25521,
"s": 25513,
"text": "Output:"
},
{
"code": null,
"e": 25554,
"s": 25521,
"text": "Python Tensorflow-math-functions"
},
{
"code": null,
"e": 25572,
"s": 25554,
"text": "Python-Tensorflow"
},
{
"code": null,
"e": 25579,
"s": 25572,
"text": "Python"
},
{
"code": null,
"e": 25677,
"s": 25579,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25709,
"s": 25677,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25765,
"s": 25709,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25807,
"s": 25765,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25849,
"s": 25807,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25904,
"s": 25849,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 25926,
"s": 25904,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25965,
"s": 25926,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25996,
"s": 25965,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26025,
"s": 25996,
"text": "Create a directory in Python"
}
] |
How to install and configure prometheus using docker on centos 7
|
In this article, we will learn how to install Prometheus server to collect the metrics and query them and also install Grafana – a web based graphical dashboard builder. Prometheus is an open source monitoring tool with time series database. It addresses many aspects for monitoring and generating a collection of metrics and graphs for resulting the data on the dashboards along with alerting.
To complete this article we needed these resources CentOS 7 installed, a user with sudo access and Dockers installed.
We are installing the Prometheus using the Dockers, so make sure that we already installed Docker on the CentOS 7 machine. Dockers container images for Prometheus components are located under the prom organization from the Dockers Hub. We can start the Docker image without using any options using the demo configuration which is located at /etc/Prometheus/Prometheus.yml.
We have multiple ways of overriding the default config files. A custom configuration file may be used into the container from the host system as a Docker data volume or we can choose a build Docker container with our own configuration, her for demo purpose we will choose to pass in the config file from the host system.
$ nano ~/prometheus.yml
# A scrape configuration scraping a Node Exporter and the Prometheus server
# itself.
scrape_configs:
# Scrape Prometheus itself every 5 seconds.
- job_name: 'prometheus'
scrape_interval: 5s
target_groups:
- targets: ['localhost:9090']
# Scrape the Node Exporter every 5 seconds.
- job_name: 'node'
scrape_interval: 5s
target_groups:
- targets: ['192.168.1.100:9100']
Start the Prometheus Docker container with this external configuration file using the below command
$ docker run -d -p 9090:9090 -v ~/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus -config.file=/etc/prometheus/prometheus.yml -storage.local.path=/prometheus -storage.local.memory-chunks=10000
This command is quite long and contains many commands in one line with many options.
We will see each and every option used in the above command
The -d option starts the Prometheus container to start in detached mode, meaning that the container will be started in the background and will not be terminated by pressing CTRL+C.
The -p 9090:9090 option allows the Prometheus's web port (9090) and makes it reachable via the external IP address of the host system.
The -v [...] option mounts the prometheus.yml configuration file from the host filesystem from the location within the container where Prometheus expects it (/etc/prometheus/prometheus.yml)
The -config.file option is instruct the Dockers accordingly to the location of the Prometheus configuration file within the container.
The -storage.local.path option configures the metrics storage location within the container.
Finally, the -storage.local.memory-chunks option adjusts Prometheus's memory usage to the host system's very small amount of RAM (only 512MB) and small number of stored time series in this tutorial (just under 1000)
It instructs Prometheus to keep only 10000 sample chunks in memory (roughly 10 chunks per series), instead of the default of 1048576. This is a value you will definitely need to tune when running Prometheus on a machine with more RAM and when storing more time serie
Refer to Prometheus's storage documentation for detailed usage.
As this is the first time we have run the command this will download the contents from Dockers hub.
We can use the docker ps command to see the Docker containers available in local machine.
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
55e31548c9a0 prom/prometheus "/bin/prometheus -con" 26 seconds ago Up 24 seconds 0.0.0.0:9090->9090/tcp cocky_fermat
We can use the container ID which we get from the docker ps command to see the logs for the Prometheus server, below is the command to see the logs
$ docker logs 55e31548c9a0
time="2016-07-11T19:56:44Z" level=info msg="Starting prometheus (version=0.20.0, branch=master, revision=aeab25c)" source="main.go:73"
time="2016-07-11T19:56:44Z" level=info msg="Build context (go=go1.6.2, user=root@77050118f904, date=20160616-08:38:14)" source="main.go:74"
time="2016-07-11T19:56:44Z" level=info msg="Loading configuration file /etc/prometheus/prometheus.yml" source="main.go:206"
time="2016-07-11T19:56:44Z" level=warning msg="The 'target_groups' option for scrape configurations is deprecated, use 'static_configs' instead" source="config.go:468"
time="2016-07-11T19:56:44Z" level=warning msg="The 'target_groups' option for scrape configurations is deprecated, use 'static_configs' instead" source="config.go:468"
time="2016-07-11T19:56:44Z" level=info msg="Loading series map and head chunks..." source="storage.go:341"
time="2016-07-11T19:56:44Z" level=info msg="0 series loaded." source="storage.go:346"
time="2016-07-11T19:56:44Z" level=info msg="Starting target manager..." source="targetmanager.go:74"
time="2016-07-11T19:56:44Z" level=warning msg="No AlertManagers configured, not dispatching any alerts" source="notifier.go:174"
time="2016-07-11T19:56:44Z" level=info msg="Listening on :9090" source="web.go:241"
To find out the storage volumes stored, we can run the below command
$ docker inspect 55e31548c9a0
[
{
"Id": "55e31548c9a0273bd91340bf08f5eb55996c8fe9a648b819b348d1a5af08990b",
"Created": "2016-07-11T19:56:43.814310728Z",
"Path": "/bin/prometheus",
"Args": [
"-config.file=/etc/prometheus/prometheus.yml",
"-storage.local.path=/prometheus",
"-storage.local.memory-chunks=10000"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 4803,
"ExitCode": 0,
...
...
"Gateway": "172.17.0.1",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"MacAddress": "02:42:ac:11:00:02",
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "4bbd72d2b2defe67b5223fe7f89919b9dd952e13f1d273ac871e8af1486b92c4",
"EndpointID": "b35f6fe49c02b8a6593e4e8549f1ab46a6bdc3b94f0279315f49a30725832e74",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:02"
}
}
}
}
]
...
...
We can find that in the section
"Mounts": [
{
"Source": "/root/prometheus.yml",
"Destination": "/etc/prometheus/prometheus.yml",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
},
{
"Name": "1dd33b889f2fe804ceceb90d4100767a14a21b09ba880972f25a2bf452d31150",
"Source": "/var/lib/docker/volumes/1dd33b889f2fe804ceceb90d4100767a14a21b09ba880972f25a2bf452d31150/_data",
"Destination": "/prometheus",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
}
...
...
From the output, we can observe that the metrics are stored in the following – “
/var/lib/docker/volumes/1dd33b889f2fe804ceceb90d4100767
a14a21b09ba880972f25a2bf452d31150/_data”
The directory was automatically created and mapped to /Prometheus directory in the container.
As we can see that, the container is up and running and we can now check the Prometheus server at http://your_ip:9090/ or http://192.168.1.226:9090/status (Note: The IP Address may differ from this demo to your setup so use your host IP address).
We have to click on the status and click on the targets. We can See UNHEALTHY as the node and see that the node exporter has not yet started.
Here we will install the Prometheus Node Exporter. The Node Exporter is the server that exposes the Prometheus metrics of the host machine and it is running in which, it show the machine’s file system, networking devices, processor, memory usages and others too.
As our requirement is to manage all the process using the Docker, we will have the workaround to provide an approximation of metrics from Docker.
To start the Node Exporter on the port 9100, use the below command using the Docker.
$ docker run -d -p 9100:9100 -v "/proc:/host/proc" -v "/sys:/host/sys" -v "/:/rootfs" --net="host" prom/node-exporter -collector.procfs /host/proc -collector.sysfs /host/proc -collector.filesystem.ignored-mount-points "^/(sys|proc|dev|host|etc)($|/)"
Unable to find image 'prom/node-exporter:latest' locally
latest: Pulling from prom/node-exporter
385e281300cc: Already exists
a3ed95caeb02: Pull complete
e418e02f5f37: Already exists
061d745f0f4c: Pull complete
Digest: sha256:a2ae701df7f3ace9f60b890415db9310dd8c28b5446002c4e8ebd102242d076e
Status: Downloaded newer image for prom/node-exporter:latest
49c08ad640f10556fedc517532386d11fbf9a9b49fcf4c14c463ef5dab4a0737
As most of the metircs are gathered from /proc and /sys from the Linux file system, and the /host dircotory using the Docker’s –v option
-collector.procfs and –collector.sysfs. They are used to instruct the Node Exporter to look for the /proc and /sys folders for a non-standard location
Dockers –v flag is used to mount the entire root (/) file system into the contain as (/rootfs)
-collector.filesystem.ignored-mount-points is used to ignore any other filesystem container which are belong to the host system.
--net=host is used to place the container in the same network as the host so that it can read the /proc/net/dev
As we can see, the Prometheus server will automatically start the scraping of the Node Exporter.
http://192.168.1.226:9090/status
http://192.168.1.226:9100/metrics
As the Prometheus server is installed and ready, we will now set-up Grafana. Grafana is a graphic interface with a dashboard which supports Promethus as a back-end to query for the data to generate the graph.
Grafana stores the data in SQL based database, Grafana supports SQLite3, MySQL or PostgreSQL for this. In this tutorial we are using the SQLite3 Database for storing the database.
Launching Grafana as a Docker container with an administrator password
$ docker run -d -p 3000:3000 -e "GF_SECURITY_ADMIN_PASSWORD=password" -v ~/grafana_db:/var/lib/grafana grafana/grafana
Unable to find image 'grafana/grafana:latest' locally
latest: Pulling from grafana/grafana
5c90d4a2d1a8: Pull complete
b1a9a0b6158e: Pull complete
acb23b0d58de: Pull complete
Digest: sha256:34ca2f9c7986cb2d115eea373083f7150a2b9b753210546d14477e2276074ae1
Status: Downloaded newer image for grafana/grafana:latest
5a2041049010fa0be8b23906cb2d864de7ff9a71e4930f686bc07eff24667d5a
The above command will download the Grafana Docker image from Docker Hub and stores at ~/grafana_db on the local system this will automatically create and initialize the SQLite3 database at /var/lib/grafana/grafana.db
The –e option will pass the environment variables to process the Docker container and GF-SERCURITY_ADMIN_PASSWORD variable to the desired dashboard administrator password for admin user. The Grafana is currently running on port 3000
To login into the Grafana, open the link http://192.168.1.226:3000 . The IP address may differ from one system to another.
As there is no system added for monitoring, we will add http://192.168.1.226:9090 from Grafana icon Datasource and add the Prometheus server
As we have configured the Prometheus server, a Node Exporter and Grafana all using the Docker, as they are all running the same machine and this is for the demo purpose only. We can learn more about Prometheus and Grafana from the respective documentation.
|
[
{
"code": null,
"e": 1457,
"s": 1062,
"text": "In this article, we will learn how to install Prometheus server to collect the metrics and query them and also install Grafana – a web based graphical dashboard builder. Prometheus is an open source monitoring tool with time series database. It addresses many aspects for monitoring and generating a collection of metrics and graphs for resulting the data on the dashboards along with alerting."
},
{
"code": null,
"e": 1575,
"s": 1457,
"text": "To complete this article we needed these resources CentOS 7 installed, a user with sudo access and Dockers installed."
},
{
"code": null,
"e": 1948,
"s": 1575,
"text": "We are installing the Prometheus using the Dockers, so make sure that we already installed Docker on the CentOS 7 machine. Dockers container images for Prometheus components are located under the prom organization from the Dockers Hub. We can start the Docker image without using any options using the demo configuration which is located at /etc/Prometheus/Prometheus.yml."
},
{
"code": null,
"e": 2269,
"s": 1948,
"text": "We have multiple ways of overriding the default config files. A custom configuration file may be used into the container from the host system as a Docker data volume or we can choose a build Docker container with our own configuration, her for demo purpose we will choose to pass in the config file from the host system."
},
{
"code": null,
"e": 2661,
"s": 2269,
"text": "$ nano ~/prometheus.yml\n# A scrape configuration scraping a Node Exporter and the Prometheus server\n# itself.\nscrape_configs:\n# Scrape Prometheus itself every 5 seconds.\n- job_name: 'prometheus'\nscrape_interval: 5s\ntarget_groups:\n- targets: ['localhost:9090']\n# Scrape the Node Exporter every 5 seconds.\n- job_name: 'node'\nscrape_interval: 5s\ntarget_groups:\n- targets: ['192.168.1.100:9100']"
},
{
"code": null,
"e": 2761,
"s": 2661,
"text": "Start the Prometheus Docker container with this external configuration file using the below command"
},
{
"code": null,
"e": 2968,
"s": 2761,
"text": "$ docker run -d -p 9090:9090 -v ~/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus -config.file=/etc/prometheus/prometheus.yml -storage.local.path=/prometheus -storage.local.memory-chunks=10000"
},
{
"code": null,
"e": 3053,
"s": 2968,
"text": "This command is quite long and contains many commands in one line with many options."
},
{
"code": null,
"e": 3113,
"s": 3053,
"text": "We will see each and every option used in the above command"
},
{
"code": null,
"e": 4394,
"s": 3113,
"text": "The -d option starts the Prometheus container to start in detached mode, meaning that the container will be started in the background and will not be terminated by pressing CTRL+C.\nThe -p 9090:9090 option allows the Prometheus's web port (9090) and makes it reachable via the external IP address of the host system.\nThe -v [...] option mounts the prometheus.yml configuration file from the host filesystem from the location within the container where Prometheus expects it (/etc/prometheus/prometheus.yml)\nThe -config.file option is instruct the Dockers accordingly to the location of the Prometheus configuration file within the container.\nThe -storage.local.path option configures the metrics storage location within the container.\nFinally, the -storage.local.memory-chunks option adjusts Prometheus's memory usage to the host system's very small amount of RAM (only 512MB) and small number of stored time series in this tutorial (just under 1000)\nIt instructs Prometheus to keep only 10000 sample chunks in memory (roughly 10 chunks per series), instead of the default of 1048576. This is a value you will definitely need to tune when running Prometheus on a machine with more RAM and when storing more time serie\nRefer to Prometheus's storage documentation for detailed usage."
},
{
"code": null,
"e": 4494,
"s": 4394,
"text": "As this is the first time we have run the command this will download the contents from Dockers hub."
},
{
"code": null,
"e": 4584,
"s": 4494,
"text": "We can use the docker ps command to see the Docker containers available in local machine."
},
{
"code": null,
"e": 4767,
"s": 4584,
"text": "$ docker ps\nCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES\n55e31548c9a0 prom/prometheus \"/bin/prometheus -con\" 26 seconds ago Up 24 seconds 0.0.0.0:9090->9090/tcp cocky_fermat"
},
{
"code": null,
"e": 4915,
"s": 4767,
"text": "We can use the container ID which we get from the docker ps command to see the logs for the Prometheus server, below is the command to see the logs"
},
{
"code": null,
"e": 6184,
"s": 4915,
"text": "$ docker logs 55e31548c9a0\ntime=\"2016-07-11T19:56:44Z\" level=info msg=\"Starting prometheus (version=0.20.0, branch=master, revision=aeab25c)\" source=\"main.go:73\"\ntime=\"2016-07-11T19:56:44Z\" level=info msg=\"Build context (go=go1.6.2, user=root@77050118f904, date=20160616-08:38:14)\" source=\"main.go:74\"\ntime=\"2016-07-11T19:56:44Z\" level=info msg=\"Loading configuration file /etc/prometheus/prometheus.yml\" source=\"main.go:206\"\ntime=\"2016-07-11T19:56:44Z\" level=warning msg=\"The 'target_groups' option for scrape configurations is deprecated, use 'static_configs' instead\" source=\"config.go:468\"\ntime=\"2016-07-11T19:56:44Z\" level=warning msg=\"The 'target_groups' option for scrape configurations is deprecated, use 'static_configs' instead\" source=\"config.go:468\"\ntime=\"2016-07-11T19:56:44Z\" level=info msg=\"Loading series map and head chunks...\" source=\"storage.go:341\"\ntime=\"2016-07-11T19:56:44Z\" level=info msg=\"0 series loaded.\" source=\"storage.go:346\"\ntime=\"2016-07-11T19:56:44Z\" level=info msg=\"Starting target manager...\" source=\"targetmanager.go:74\"\ntime=\"2016-07-11T19:56:44Z\" level=warning msg=\"No AlertManagers configured, not dispatching any alerts\" source=\"notifier.go:174\"\ntime=\"2016-07-11T19:56:44Z\" level=info msg=\"Listening on :9090\" source=\"web.go:241\""
},
{
"code": null,
"e": 6253,
"s": 6184,
"text": "To find out the storage volumes stored, we can run the below command"
},
{
"code": null,
"e": 8345,
"s": 6253,
"text": "$ docker inspect 55e31548c9a0\n[\n {\n \"Id\": \"55e31548c9a0273bd91340bf08f5eb55996c8fe9a648b819b348d1a5af08990b\",\n \"Created\": \"2016-07-11T19:56:43.814310728Z\",\n \"Path\": \"/bin/prometheus\",\n \"Args\": [\n \"-config.file=/etc/prometheus/prometheus.yml\",\n \"-storage.local.path=/prometheus\",\n \"-storage.local.memory-chunks=10000\"\n ],\n \"State\": {\n \"Status\": \"running\",\n \"Running\": true,\n \"Paused\": false,\n \"Restarting\": false,\n \"OOMKilled\": false,\n \"Dead\": false,\n \"Pid\": 4803,\n \"ExitCode\": 0,\n ...\n ...\n \"Gateway\": \"172.17.0.1\",\n \"GlobalIPv6Address\": \"\",\n \"GlobalIPv6PrefixLen\": 0,\n \"IPAddress\": \"172.17.0.2\",\n \"IPPrefixLen\": 16,\n \"IPv6Gateway\": \"\",\n \"MacAddress\": \"02:42:ac:11:00:02\",\n \"Networks\": {\n \"bridge\": {\n \"IPAMConfig\": null,\n \"Links\": null,\n \"Aliases\": null,\n \"NetworkID\": \"4bbd72d2b2defe67b5223fe7f89919b9dd952e13f1d273ac871e8af1486b92c4\",\n \"EndpointID\": \"b35f6fe49c02b8a6593e4e8549f1ab46a6bdc3b94f0279315f49a30725832e74\",\n \"Gateway\": \"172.17.0.1\",\n \"IPAddress\": \"172.17.0.2\",\n \"IPPrefixLen\": 16,\n \"IPv6Gateway\": \"\",\n \"GlobalIPv6Address\": \"\",\n \"GlobalIPv6PrefixLen\": 0,\n \"MacAddress\": \"02:42:ac:11:00:02\"\n }\n }\n }\n }\n]\n...\n...\nWe can find that in the section\n\"Mounts\": [\n {\n \"Source\": \"/root/prometheus.yml\",\n \"Destination\": \"/etc/prometheus/prometheus.yml\",\n \"Mode\": \"\",\n \"RW\": true,\n \"Propagation\": \"rprivate\"\n },\n {\n \"Name\": \"1dd33b889f2fe804ceceb90d4100767a14a21b09ba880972f25a2bf452d31150\",\n \"Source\": \"/var/lib/docker/volumes/1dd33b889f2fe804ceceb90d4100767a14a21b09ba880972f25a2bf452d31150/_data\",\n \"Destination\": \"/prometheus\",\n \"Driver\": \"local\",\n \"Mode\": \"\",\n \"RW\": true,\n \"Propagation\": \"\"\n }\n ...\n..."
},
{
"code": null,
"e": 8426,
"s": 8345,
"text": "From the output, we can observe that the metrics are stored in the following – “"
},
{
"code": null,
"e": 8523,
"s": 8426,
"text": "/var/lib/docker/volumes/1dd33b889f2fe804ceceb90d4100767\na14a21b09ba880972f25a2bf452d31150/_data”"
},
{
"code": null,
"e": 8617,
"s": 8523,
"text": "The directory was automatically created and mapped to /Prometheus directory in the container."
},
{
"code": null,
"e": 8864,
"s": 8617,
"text": "As we can see that, the container is up and running and we can now check the Prometheus server at http://your_ip:9090/ or http://192.168.1.226:9090/status (Note: The IP Address may differ from this demo to your setup so use your host IP address)."
},
{
"code": null,
"e": 9006,
"s": 8864,
"text": "We have to click on the status and click on the targets. We can See UNHEALTHY as the node and see that the node exporter has not yet started."
},
{
"code": null,
"e": 9269,
"s": 9006,
"text": "Here we will install the Prometheus Node Exporter. The Node Exporter is the server that exposes the Prometheus metrics of the host machine and it is running in which, it show the machine’s file system, networking devices, processor, memory usages and others too."
},
{
"code": null,
"e": 9415,
"s": 9269,
"text": "As our requirement is to manage all the process using the Docker, we will have the workaround to provide an approximation of metrics from Docker."
},
{
"code": null,
"e": 9500,
"s": 9415,
"text": "To start the Node Exporter on the port 9100, use the below command using the Docker."
},
{
"code": null,
"e": 10168,
"s": 9500,
"text": "$ docker run -d -p 9100:9100 -v \"/proc:/host/proc\" -v \"/sys:/host/sys\" -v \"/:/rootfs\" --net=\"host\" prom/node-exporter -collector.procfs /host/proc -collector.sysfs /host/proc -collector.filesystem.ignored-mount-points \"^/(sys|proc|dev|host|etc)($|/)\"\nUnable to find image 'prom/node-exporter:latest' locally\nlatest: Pulling from prom/node-exporter\n385e281300cc: Already exists\na3ed95caeb02: Pull complete\ne418e02f5f37: Already exists\n061d745f0f4c: Pull complete\nDigest: sha256:a2ae701df7f3ace9f60b890415db9310dd8c28b5446002c4e8ebd102242d076e\nStatus: Downloaded newer image for prom/node-exporter:latest\n49c08ad640f10556fedc517532386d11fbf9a9b49fcf4c14c463ef5dab4a0737"
},
{
"code": null,
"e": 10792,
"s": 10168,
"text": "As most of the metircs are gathered from /proc and /sys from the Linux file system, and the /host dircotory using the Docker’s –v option\n-collector.procfs and –collector.sysfs. They are used to instruct the Node Exporter to look for the /proc and /sys folders for a non-standard location\nDockers –v flag is used to mount the entire root (/) file system into the contain as (/rootfs)\n-collector.filesystem.ignored-mount-points is used to ignore any other filesystem container which are belong to the host system.\n--net=host is used to place the container in the same network as the host so that it can read the /proc/net/dev"
},
{
"code": null,
"e": 10889,
"s": 10792,
"text": "As we can see, the Prometheus server will automatically start the scraping of the Node Exporter."
},
{
"code": null,
"e": 10922,
"s": 10889,
"text": "http://192.168.1.226:9090/status"
},
{
"code": null,
"e": 10956,
"s": 10922,
"text": "http://192.168.1.226:9100/metrics"
},
{
"code": null,
"e": 11165,
"s": 10956,
"text": "As the Prometheus server is installed and ready, we will now set-up Grafana. Grafana is a graphic interface with a dashboard which supports Promethus as a back-end to query for the data to generate the graph."
},
{
"code": null,
"e": 11345,
"s": 11165,
"text": "Grafana stores the data in SQL based database, Grafana supports SQLite3, MySQL or PostgreSQL for this. In this tutorial we are using the SQLite3 Database for storing the database."
},
{
"code": null,
"e": 11416,
"s": 11345,
"text": "Launching Grafana as a Docker container with an administrator password"
},
{
"code": null,
"e": 11913,
"s": 11416,
"text": "$ docker run -d -p 3000:3000 -e \"GF_SECURITY_ADMIN_PASSWORD=password\" -v ~/grafana_db:/var/lib/grafana grafana/grafana\nUnable to find image 'grafana/grafana:latest' locally\nlatest: Pulling from grafana/grafana\n5c90d4a2d1a8: Pull complete\nb1a9a0b6158e: Pull complete\nacb23b0d58de: Pull complete\nDigest: sha256:34ca2f9c7986cb2d115eea373083f7150a2b9b753210546d14477e2276074ae1\nStatus: Downloaded newer image for grafana/grafana:latest\n5a2041049010fa0be8b23906cb2d864de7ff9a71e4930f686bc07eff24667d5a"
},
{
"code": null,
"e": 12131,
"s": 11913,
"text": "The above command will download the Grafana Docker image from Docker Hub and stores at ~/grafana_db on the local system this will automatically create and initialize the SQLite3 database at /var/lib/grafana/grafana.db"
},
{
"code": null,
"e": 12364,
"s": 12131,
"text": "The –e option will pass the environment variables to process the Docker container and GF-SERCURITY_ADMIN_PASSWORD variable to the desired dashboard administrator password for admin user. The Grafana is currently running on port 3000"
},
{
"code": null,
"e": 12487,
"s": 12364,
"text": "To login into the Grafana, open the link http://192.168.1.226:3000 . The IP address may differ from one system to another."
},
{
"code": null,
"e": 12628,
"s": 12487,
"text": "As there is no system added for monitoring, we will add http://192.168.1.226:9090 from Grafana icon Datasource and add the Prometheus server"
},
{
"code": null,
"e": 12885,
"s": 12628,
"text": "As we have configured the Prometheus server, a Node Exporter and Grafana all using the Docker, as they are all running the same machine and this is for the demo purpose only. We can learn more about Prometheus and Grafana from the respective documentation."
}
] |
Two Step Facial Recognition With Colab | by Dev Dash MD MPH | Towards Data Science
|
It’s Monday morning and I’m channeling my inner Jeremy Howard (again). Over the last few months, I have seen plenty of facial recognition guides and some of them are really quite good.
The problem is, each student of deep learning or machine vision becomes interested through different venues. Maybe you’re a musician interested in sounds, or a statistics student interested in tabular data.
I know I personally became interested when started reading about TensorFlow and image classification — this idea that if I have a well curated dataset, I might be able to train an architecture to classify images with high accuracy.
Google Colab didn’t exist then and I recently ported something similar over to Colab and I’m in the process of a walkthrough. Check out Part 1 here:
towardsdatascience.com
My initial foray was done on my iMac using Anaconda, Spyder, no GPU usage, just letting my Core i5 trudge through thousands of images while I left to do other things (read: study for emergency medicine boards). Of course, before I could train, I had to read through two dozen articles of people using different styles to write code. What resulted was a chimeric hodge-podge of code that was difficult to understand when I looked at it weeks later.
Then Colab entered the scene and while I still use Jupyter and Spyder on my machine, I use Colab to speak to you and efficiently share my code. It’s not perfect but they’ve done a great job in making high end computing available to the masses and all you need is a Google account.
Enough rambling. Let’s walk through the notebook:
I’m being a bit facetious here — the two steps are “Run All” and uploading your picture of faces.
The notebook is designed to hide most of the code so you can cleanly look at the results. Look at the output first and convince yourself that we can not only pick out (hopefully most) the faces in the picture and later on, assign an emotion using an emotion detector function.
I’ve also left in some code to try to time the calculation process.
This one uses the ‘face_recognition’ library, found here. We will be timing how long this takes, too.
This line in particular does all the heavy lifting:
face_locations = face_recognition.face_locations(image)
The rest of the code uses a for loop to iterate through the number of faces, and draw a box around the faces using these two lines:
rect = patches.Rectangle((left,top), (right - left), (bottom-top),linewidth=3,edgecolor='r',facecolor='none')ax.add_patch(rect)
Note: Not all faces are detected; hats and sunglasses throw the detection off.
Number of faces detected: 24
Time taken: 2.43 seconds
The code is almost identical to above except for one line (if block at line 11):
There’s a reason the ‘if’ statement is present as we’ll see in the image below. The ‘detect_emotions’ line doesn’t work with all the faces.
Here’s the result:
Note: Emotion detection mostly works. Not all faces register an emotion and it thinks the baby is angry. I will let you take a closer look to see if you feel the labels match up perfectly — I don’t think they do.
Number of faces detected: 24
Time taken: 2.83 seconds (slightly longer to add emotion detection)
Haar cascade based recognition is another way of doing facial recognition. Discussion of how these work is beyond this post. There are plenty of technical resources available online that discuss this method.
Here’s the result:
Again, using Haar cascades is another method and there are some missteps here as well. In particular, it misses some faces and thinks the combination of a pant leg, ankle, top of a shoe is a face.
However, in every iteration I have run, using Haar cascades and OpenCV is much faster than using the face_recognition library — almost 20–30% faster at times. This kind of speed benefit is significant, especially if going through hundreds of images (e.g. video). It also speaks to a process that might be computationally less expensive and likely runs on less expensive hardware that requires less power.
Of course, these are not the only two facial detection methods and proprietary ones are likely much better. If you had to pick between the two, I don’t think there’s a clear answer — one is better at detection (face_recognition) but the other is much faster (Haar cascades).
Number of faces detected: 24
Time taken: 1.95 seconds (faster)
[1] Wikipedia-Jeremy Howard, Accessed October 2020
[2] Facial Recognition Library, PyPi, Accessed October 2020
[3] Open CV Haar Cascades, Accessed October 2020
|
[
{
"code": null,
"e": 357,
"s": 172,
"text": "It’s Monday morning and I’m channeling my inner Jeremy Howard (again). Over the last few months, I have seen plenty of facial recognition guides and some of them are really quite good."
},
{
"code": null,
"e": 564,
"s": 357,
"text": "The problem is, each student of deep learning or machine vision becomes interested through different venues. Maybe you’re a musician interested in sounds, or a statistics student interested in tabular data."
},
{
"code": null,
"e": 796,
"s": 564,
"text": "I know I personally became interested when started reading about TensorFlow and image classification — this idea that if I have a well curated dataset, I might be able to train an architecture to classify images with high accuracy."
},
{
"code": null,
"e": 945,
"s": 796,
"text": "Google Colab didn’t exist then and I recently ported something similar over to Colab and I’m in the process of a walkthrough. Check out Part 1 here:"
},
{
"code": null,
"e": 968,
"s": 945,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1416,
"s": 968,
"text": "My initial foray was done on my iMac using Anaconda, Spyder, no GPU usage, just letting my Core i5 trudge through thousands of images while I left to do other things (read: study for emergency medicine boards). Of course, before I could train, I had to read through two dozen articles of people using different styles to write code. What resulted was a chimeric hodge-podge of code that was difficult to understand when I looked at it weeks later."
},
{
"code": null,
"e": 1697,
"s": 1416,
"text": "Then Colab entered the scene and while I still use Jupyter and Spyder on my machine, I use Colab to speak to you and efficiently share my code. It’s not perfect but they’ve done a great job in making high end computing available to the masses and all you need is a Google account."
},
{
"code": null,
"e": 1747,
"s": 1697,
"text": "Enough rambling. Let’s walk through the notebook:"
},
{
"code": null,
"e": 1845,
"s": 1747,
"text": "I’m being a bit facetious here — the two steps are “Run All” and uploading your picture of faces."
},
{
"code": null,
"e": 2122,
"s": 1845,
"text": "The notebook is designed to hide most of the code so you can cleanly look at the results. Look at the output first and convince yourself that we can not only pick out (hopefully most) the faces in the picture and later on, assign an emotion using an emotion detector function."
},
{
"code": null,
"e": 2190,
"s": 2122,
"text": "I’ve also left in some code to try to time the calculation process."
},
{
"code": null,
"e": 2292,
"s": 2190,
"text": "This one uses the ‘face_recognition’ library, found here. We will be timing how long this takes, too."
},
{
"code": null,
"e": 2344,
"s": 2292,
"text": "This line in particular does all the heavy lifting:"
},
{
"code": null,
"e": 2400,
"s": 2344,
"text": "face_locations = face_recognition.face_locations(image)"
},
{
"code": null,
"e": 2532,
"s": 2400,
"text": "The rest of the code uses a for loop to iterate through the number of faces, and draw a box around the faces using these two lines:"
},
{
"code": null,
"e": 2664,
"s": 2532,
"text": "rect = patches.Rectangle((left,top), (right - left), (bottom-top),linewidth=3,edgecolor='r',facecolor='none')ax.add_patch(rect)"
},
{
"code": null,
"e": 2743,
"s": 2664,
"text": "Note: Not all faces are detected; hats and sunglasses throw the detection off."
},
{
"code": null,
"e": 2772,
"s": 2743,
"text": "Number of faces detected: 24"
},
{
"code": null,
"e": 2797,
"s": 2772,
"text": "Time taken: 2.43 seconds"
},
{
"code": null,
"e": 2878,
"s": 2797,
"text": "The code is almost identical to above except for one line (if block at line 11):"
},
{
"code": null,
"e": 3018,
"s": 2878,
"text": "There’s a reason the ‘if’ statement is present as we’ll see in the image below. The ‘detect_emotions’ line doesn’t work with all the faces."
},
{
"code": null,
"e": 3037,
"s": 3018,
"text": "Here’s the result:"
},
{
"code": null,
"e": 3250,
"s": 3037,
"text": "Note: Emotion detection mostly works. Not all faces register an emotion and it thinks the baby is angry. I will let you take a closer look to see if you feel the labels match up perfectly — I don’t think they do."
},
{
"code": null,
"e": 3279,
"s": 3250,
"text": "Number of faces detected: 24"
},
{
"code": null,
"e": 3347,
"s": 3279,
"text": "Time taken: 2.83 seconds (slightly longer to add emotion detection)"
},
{
"code": null,
"e": 3555,
"s": 3347,
"text": "Haar cascade based recognition is another way of doing facial recognition. Discussion of how these work is beyond this post. There are plenty of technical resources available online that discuss this method."
},
{
"code": null,
"e": 3574,
"s": 3555,
"text": "Here’s the result:"
},
{
"code": null,
"e": 3771,
"s": 3574,
"text": "Again, using Haar cascades is another method and there are some missteps here as well. In particular, it misses some faces and thinks the combination of a pant leg, ankle, top of a shoe is a face."
},
{
"code": null,
"e": 4176,
"s": 3771,
"text": "However, in every iteration I have run, using Haar cascades and OpenCV is much faster than using the face_recognition library — almost 20–30% faster at times. This kind of speed benefit is significant, especially if going through hundreds of images (e.g. video). It also speaks to a process that might be computationally less expensive and likely runs on less expensive hardware that requires less power."
},
{
"code": null,
"e": 4451,
"s": 4176,
"text": "Of course, these are not the only two facial detection methods and proprietary ones are likely much better. If you had to pick between the two, I don’t think there’s a clear answer — one is better at detection (face_recognition) but the other is much faster (Haar cascades)."
},
{
"code": null,
"e": 4480,
"s": 4451,
"text": "Number of faces detected: 24"
},
{
"code": null,
"e": 4514,
"s": 4480,
"text": "Time taken: 1.95 seconds (faster)"
},
{
"code": null,
"e": 4565,
"s": 4514,
"text": "[1] Wikipedia-Jeremy Howard, Accessed October 2020"
},
{
"code": null,
"e": 4625,
"s": 4565,
"text": "[2] Facial Recognition Library, PyPi, Accessed October 2020"
}
] |
How to query a key having space in its name with MongoDB?
|
To query a key having space in its name, you can use dot(.) notation.
Step 1: First, you need to create a set in which a key has space in its name. Following is the
query:
> myValues["Details"] = {}
{ }
> myValues["Details"]["Student Name"]="John";
John
> myValues["Details"]["StudentAge"]=26;
26
Step 2: Now you need to create a collection and store the above set as a document. Following
is the query
> db.keyHavingSpaceDemo.insertOne( myValues);
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca27e3b6304881c5ce84ba4")
}
Following is the query to display all documents from a collection with the help of find() method
> db.keyHavingSpaceDemo.find().pretty();
This will produce the following output
{
"_id" : ObjectId("5ca27e3b6304881c5ce84ba4"),
"Details" : {
"Student Name" : "John",
"StudentAge" : 26
}
}
Here is how you can query a key having space in its name i.e. “Student Name”. Following is the
query
> db.keyHavingSpaceDemo.find({ "Details.Student Name": "John"} ).pretty();
This will produce the following output
{
"_id" : ObjectId("5ca27e3b6304881c5ce84ba4"),
"Details" : {
"Student Name" : "John",
"StudentAge" : 26
}
}
|
[
{
"code": null,
"e": 1132,
"s": 1062,
"text": "To query a key having space in its name, you can use dot(.) notation."
},
{
"code": null,
"e": 1234,
"s": 1132,
"text": "Step 1: First, you need to create a set in which a key has space in its name. Following is the\nquery:"
},
{
"code": null,
"e": 1359,
"s": 1234,
"text": "> myValues[\"Details\"] = {}\n{ }\n> myValues[\"Details\"][\"Student Name\"]=\"John\";\nJohn\n> myValues[\"Details\"][\"StudentAge\"]=26;\n26"
},
{
"code": null,
"e": 1465,
"s": 1359,
"text": "Step 2: Now you need to create a collection and store the above set as a document. Following\nis the query"
},
{
"code": null,
"e": 1596,
"s": 1465,
"text": "> db.keyHavingSpaceDemo.insertOne( myValues);\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ca27e3b6304881c5ce84ba4\")\n}"
},
{
"code": null,
"e": 1693,
"s": 1596,
"text": "Following is the query to display all documents from a collection with the help of find() method"
},
{
"code": null,
"e": 1734,
"s": 1693,
"text": "> db.keyHavingSpaceDemo.find().pretty();"
},
{
"code": null,
"e": 1773,
"s": 1734,
"text": "This will produce the following output"
},
{
"code": null,
"e": 1903,
"s": 1773,
"text": "{\n \"_id\" : ObjectId(\"5ca27e3b6304881c5ce84ba4\"),\n \"Details\" : {\n \"Student Name\" : \"John\",\n \"StudentAge\" : 26\n }\n}"
},
{
"code": null,
"e": 2004,
"s": 1903,
"text": "Here is how you can query a key having space in its name i.e. “Student Name”. Following is the\nquery"
},
{
"code": null,
"e": 2079,
"s": 2004,
"text": "> db.keyHavingSpaceDemo.find({ \"Details.Student Name\": \"John\"} ).pretty();"
},
{
"code": null,
"e": 2118,
"s": 2079,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2248,
"s": 2118,
"text": "{\n \"_id\" : ObjectId(\"5ca27e3b6304881c5ce84ba4\"),\n \"Details\" : {\n \"Student Name\" : \"John\",\n \"StudentAge\" : 26\n }\n}"
}
] |
C++ Program to Subtract Complex Number using Operator Overloading
|
Operator overloading can be done with most of the built-in operators in C++. The overloaded operators are functions with the keyword operator followed by the operator symbol that is defined. The overloaded operators have a return type and a parameter list like any function.
A program that subtracts complex numbers using operator overloading is as follows −
Live Demo
#include<iostream>
using namespace std;
class ComplexNum {
private:
int real, imag;
public:
ComplexNum(int r = 0, int i =0) {
real = r;
imag = i;
}
ComplexNum operator - (ComplexNum const &obj1) {
ComplexNum obj2;
obj2.real = real - obj1.real;
obj2.imag = imag - obj1.imag;
return obj2;
}
void print() {
if(imag>=0)
cout << real << " + i" << imag <<endl;
else
cout << real << " + i(" << imag <<")"<<endl;
}
};
int main() {
ComplexNum comp1(15, -2), comp2(5, 10);
cout<<"The two comple numbers are:"<<endl;
comp1.print();
comp2.print();
cout<<"The result of the subtraction is: ";
ComplexNum comp3 = comp1 - comp2;
comp3.print();
}
The two comple numbers are:
15 + i(-2)
5 + i10
The result of the subtraction is: 10 + i(-12)
In the above program, the class ComplexNum is defined which has variables real and imag for the real and imaginary part of a complex number respectively. The constructor ComplexNum is used to initialize the values of real and imag. It also contains the default values as 0. This is shown in the following code snippet −
class ComplexNum {
private:
int real, imag;
public:
ComplexNum(int r = 0, int i =0) {
real = r;
imag = i;
}
}
The function that is the overloaded operator contains the keyword operator followed by - as that is the operator being overloaded. The function subtracts the two complex numbers and the result is stored in the object obj2. Then this value is returned to the ComplexNum object comp3.
The following code snippet demonstrates this −
ComplexNum operator - (ComplexNum const &obj1) {
ComplexNum obj2;
obj2.real = real - obj1.real;
obj2.imag = imag - obj1.imag;
return obj2;
}
The print() function prints the real and imaginary part of the complex number. This is shown as follows.
void print() {
if(imag>=0)
cout << real << " + i" << imag <<endl;
else
cout << real << " + i(" << imag <<")"<<endl;
}
|
[
{
"code": null,
"e": 1337,
"s": 1062,
"text": "Operator overloading can be done with most of the built-in operators in C++. The overloaded operators are functions with the keyword operator followed by the operator symbol that is defined. The overloaded operators have a return type and a parameter list like any function."
},
{
"code": null,
"e": 1421,
"s": 1337,
"text": "A program that subtracts complex numbers using operator overloading is as follows −"
},
{
"code": null,
"e": 1432,
"s": 1421,
"text": " Live Demo"
},
{
"code": null,
"e": 2171,
"s": 1432,
"text": "#include<iostream>\nusing namespace std;\nclass ComplexNum {\n private:\n int real, imag;\n public:\n ComplexNum(int r = 0, int i =0) {\n real = r;\n imag = i;\n }\n ComplexNum operator - (ComplexNum const &obj1) {\n ComplexNum obj2;\n obj2.real = real - obj1.real;\n obj2.imag = imag - obj1.imag;\n return obj2;\n }\n void print() {\n if(imag>=0)\n cout << real << \" + i\" << imag <<endl;\n else\n cout << real << \" + i(\" << imag <<\")\"<<endl;\n }\n};\nint main() {\n ComplexNum comp1(15, -2), comp2(5, 10);\n cout<<\"The two comple numbers are:\"<<endl;\n comp1.print();\n comp2.print();\n cout<<\"The result of the subtraction is: \";\n ComplexNum comp3 = comp1 - comp2;\n comp3.print();\n}"
},
{
"code": null,
"e": 2264,
"s": 2171,
"text": "The two comple numbers are:\n15 + i(-2)\n5 + i10\nThe result of the subtraction is: 10 + i(-12)"
},
{
"code": null,
"e": 2584,
"s": 2264,
"text": "In the above program, the class ComplexNum is defined which has variables real and imag for the real and imaginary part of a complex number respectively. The constructor ComplexNum is used to initialize the values of real and imag. It also contains the default values as 0. This is shown in the following code snippet −"
},
{
"code": null,
"e": 2721,
"s": 2584,
"text": "class ComplexNum {\n private:\n int real, imag;\n public:\n ComplexNum(int r = 0, int i =0) {\n real = r;\n imag = i;\n }\n}"
},
{
"code": null,
"e": 3004,
"s": 2721,
"text": "The function that is the overloaded operator contains the keyword operator followed by - as that is the operator being overloaded. The function subtracts the two complex numbers and the result is stored in the object obj2. Then this value is returned to the ComplexNum object comp3."
},
{
"code": null,
"e": 3051,
"s": 3004,
"text": "The following code snippet demonstrates this −"
},
{
"code": null,
"e": 3204,
"s": 3051,
"text": "ComplexNum operator - (ComplexNum const &obj1) {\n ComplexNum obj2;\n obj2.real = real - obj1.real;\n obj2.imag = imag - obj1.imag;\n return obj2;\n}"
},
{
"code": null,
"e": 3309,
"s": 3204,
"text": "The print() function prints the real and imaginary part of the complex number. This is shown as follows."
},
{
"code": null,
"e": 3439,
"s": 3309,
"text": "void print() {\n if(imag>=0)\n cout << real << \" + i\" << imag <<endl;\n else\n cout << real << \" + i(\" << imag <<\")\"<<endl;\n}"
}
] |
MongoDB - Replication
|
Replication is the process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability with multiple copies of data on different database servers. Replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions. With additional copies of the data, you can dedicate one to disaster recovery, reporting, or backup.
To keep your data safe
High (24*7) availability of data
Disaster recovery
No downtime for maintenance (like backups, index rebuilds, compaction)
Read scaling (extra copies to read from)
Replica set is transparent to the application
MongoDB achieves replication by the use of replica set. A replica set is a group of mongod instances that host the same data set. In a replica, one node is primary node that receives all write operations. All other instances, such as secondaries, apply operations from the primary so that they have the same data set. Replica set can have only one primary node.
Replica set is a group of two or more nodes (generally minimum 3 nodes are required).
Replica set is a group of two or more nodes (generally minimum 3 nodes are required).
In a replica set, one node is primary node and remaining nodes are secondary.
In a replica set, one node is primary node and remaining nodes are secondary.
All data replicates from primary to secondary node.
All data replicates from primary to secondary node.
At the time of automatic failover or maintenance, election establishes for primary and a new primary node is elected.
At the time of automatic failover or maintenance, election establishes for primary and a new primary node is elected.
After the recovery of failed node, it again join the replica set and works as a secondary node.
After the recovery of failed node, it again join the replica set and works as a secondary node.
A typical diagram of MongoDB replication is shown in which client application always interact with the primary node and the primary node then replicates the data to the secondary nodes.
A cluster of N nodes
Any one node can be primary
All write operations go to primary
Automatic failover
Automatic recovery
Consensus election of primary
In this tutorial, we will convert standalone MongoDB instance to a replica set. To convert to replica set, following are the steps −
Shutdown already running MongoDB server.
Shutdown already running MongoDB server.
Start the MongoDB server by specifying -- replSet option. Following is the basic syntax of --replSet −
Start the MongoDB server by specifying -- replSet option. Following is the basic syntax of --replSet −
mongod --port "PORT" --dbpath "YOUR_DB_DATA_PATH" --replSet "REPLICA_SET_INSTANCE_NAME"
mongod --port 27017 --dbpath "D:\set up\mongodb\data" --replSet rs0
It will start a mongod instance with the name rs0, on port 27017.
It will start a mongod instance with the name rs0, on port 27017.
Now start the command prompt and connect to this mongod instance.
Now start the command prompt and connect to this mongod instance.
In Mongo client, issue the command rs.initiate() to initiate a new replica set.
In Mongo client, issue the command rs.initiate() to initiate a new replica set.
To check the replica set configuration, issue the command rs.conf(). To check the status of replica set issue the command rs.status().
To check the replica set configuration, issue the command rs.conf(). To check the status of replica set issue the command rs.status().
To add members to replica set, start mongod instances on multiple machines. Now start a mongo client and issue a command rs.add().
The basic syntax of rs.add() command is as follows −
>rs.add(HOST_NAME:PORT)
Suppose your mongod instance name is mongod1.net and it is running on port 27017. To add this instance to replica set, issue the command rs.add() in Mongo client.
>rs.add("mongod1.net:27017")
>
You can add mongod instance to replica set only when you are connected to primary node. To check whether you are connected to primary or not, issue the command db.isMaster() in mongo client.
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": 3006,
"s": 2553,
"text": "Replication is the process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability with multiple copies of data on different database servers. Replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions. With additional copies of the data, you can dedicate one to disaster recovery, reporting, or backup."
},
{
"code": null,
"e": 3029,
"s": 3006,
"text": "To keep your data safe"
},
{
"code": null,
"e": 3062,
"s": 3029,
"text": "High (24*7) availability of data"
},
{
"code": null,
"e": 3080,
"s": 3062,
"text": "Disaster recovery"
},
{
"code": null,
"e": 3151,
"s": 3080,
"text": "No downtime for maintenance (like backups, index rebuilds, compaction)"
},
{
"code": null,
"e": 3192,
"s": 3151,
"text": "Read scaling (extra copies to read from)"
},
{
"code": null,
"e": 3238,
"s": 3192,
"text": "Replica set is transparent to the application"
},
{
"code": null,
"e": 3600,
"s": 3238,
"text": "MongoDB achieves replication by the use of replica set. A replica set is a group of mongod instances that host the same data set. In a replica, one node is primary node that receives all write operations. All other instances, such as secondaries, apply operations from the primary so that they have the same data set. Replica set can have only one primary node."
},
{
"code": null,
"e": 3686,
"s": 3600,
"text": "Replica set is a group of two or more nodes (generally minimum 3 nodes are required)."
},
{
"code": null,
"e": 3772,
"s": 3686,
"text": "Replica set is a group of two or more nodes (generally minimum 3 nodes are required)."
},
{
"code": null,
"e": 3850,
"s": 3772,
"text": "In a replica set, one node is primary node and remaining nodes are secondary."
},
{
"code": null,
"e": 3928,
"s": 3850,
"text": "In a replica set, one node is primary node and remaining nodes are secondary."
},
{
"code": null,
"e": 3980,
"s": 3928,
"text": "All data replicates from primary to secondary node."
},
{
"code": null,
"e": 4032,
"s": 3980,
"text": "All data replicates from primary to secondary node."
},
{
"code": null,
"e": 4150,
"s": 4032,
"text": "At the time of automatic failover or maintenance, election establishes for primary and a new primary node is elected."
},
{
"code": null,
"e": 4268,
"s": 4150,
"text": "At the time of automatic failover or maintenance, election establishes for primary and a new primary node is elected."
},
{
"code": null,
"e": 4364,
"s": 4268,
"text": "After the recovery of failed node, it again join the replica set and works as a secondary node."
},
{
"code": null,
"e": 4460,
"s": 4364,
"text": "After the recovery of failed node, it again join the replica set and works as a secondary node."
},
{
"code": null,
"e": 4646,
"s": 4460,
"text": "A typical diagram of MongoDB replication is shown in which client application always interact with the primary node and the primary node then replicates the data to the secondary nodes."
},
{
"code": null,
"e": 4667,
"s": 4646,
"text": "A cluster of N nodes"
},
{
"code": null,
"e": 4695,
"s": 4667,
"text": "Any one node can be primary"
},
{
"code": null,
"e": 4730,
"s": 4695,
"text": "All write operations go to primary"
},
{
"code": null,
"e": 4749,
"s": 4730,
"text": "Automatic failover"
},
{
"code": null,
"e": 4768,
"s": 4749,
"text": "Automatic recovery"
},
{
"code": null,
"e": 4798,
"s": 4768,
"text": "Consensus election of primary"
},
{
"code": null,
"e": 4931,
"s": 4798,
"text": "In this tutorial, we will convert standalone MongoDB instance to a replica set. To convert to replica set, following are the steps −"
},
{
"code": null,
"e": 4972,
"s": 4931,
"text": "Shutdown already running MongoDB server."
},
{
"code": null,
"e": 5013,
"s": 4972,
"text": "Shutdown already running MongoDB server."
},
{
"code": null,
"e": 5118,
"s": 5015,
"text": "Start the MongoDB server by specifying -- replSet option. Following is the basic syntax of --replSet −"
},
{
"code": null,
"e": 5221,
"s": 5118,
"text": "Start the MongoDB server by specifying -- replSet option. Following is the basic syntax of --replSet −"
},
{
"code": null,
"e": 5310,
"s": 5221,
"text": "mongod --port \"PORT\" --dbpath \"YOUR_DB_DATA_PATH\" --replSet \"REPLICA_SET_INSTANCE_NAME\"\n"
},
{
"code": null,
"e": 5378,
"s": 5310,
"text": "mongod --port 27017 --dbpath \"D:\\set up\\mongodb\\data\" --replSet rs0"
},
{
"code": null,
"e": 5444,
"s": 5378,
"text": "It will start a mongod instance with the name rs0, on port 27017."
},
{
"code": null,
"e": 5510,
"s": 5444,
"text": "It will start a mongod instance with the name rs0, on port 27017."
},
{
"code": null,
"e": 5576,
"s": 5510,
"text": "Now start the command prompt and connect to this mongod instance."
},
{
"code": null,
"e": 5642,
"s": 5576,
"text": "Now start the command prompt and connect to this mongod instance."
},
{
"code": null,
"e": 5722,
"s": 5642,
"text": "In Mongo client, issue the command rs.initiate() to initiate a new replica set."
},
{
"code": null,
"e": 5802,
"s": 5722,
"text": "In Mongo client, issue the command rs.initiate() to initiate a new replica set."
},
{
"code": null,
"e": 5937,
"s": 5802,
"text": "To check the replica set configuration, issue the command rs.conf(). To check the status of replica set issue the command rs.status()."
},
{
"code": null,
"e": 6072,
"s": 5937,
"text": "To check the replica set configuration, issue the command rs.conf(). To check the status of replica set issue the command rs.status()."
},
{
"code": null,
"e": 6203,
"s": 6072,
"text": "To add members to replica set, start mongod instances on multiple machines. Now start a mongo client and issue a command rs.add()."
},
{
"code": null,
"e": 6256,
"s": 6203,
"text": "The basic syntax of rs.add() command is as follows −"
},
{
"code": null,
"e": 6280,
"s": 6256,
"text": ">rs.add(HOST_NAME:PORT)"
},
{
"code": null,
"e": 6443,
"s": 6280,
"text": "Suppose your mongod instance name is mongod1.net and it is running on port 27017. To add this instance to replica set, issue the command rs.add() in Mongo client."
},
{
"code": null,
"e": 6474,
"s": 6443,
"text": ">rs.add(\"mongod1.net:27017\")\n>"
},
{
"code": null,
"e": 6665,
"s": 6474,
"text": "You can add mongod instance to replica set only when you are connected to primary node. To check whether you are connected to primary or not, issue the command db.isMaster() in mongo client."
},
{
"code": null,
"e": 6698,
"s": 6665,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6717,
"s": 6698,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6752,
"s": 6717,
"text": "\n 54 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6780,
"s": 6752,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6815,
"s": 6780,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6838,
"s": 6815,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 6873,
"s": 6838,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6890,
"s": 6873,
"text": " University Code"
},
{
"code": null,
"e": 6923,
"s": 6890,
"text": "\n 26 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6942,
"s": 6923,
"text": " Bassir Jafarzadeh"
},
{
"code": null,
"e": 6977,
"s": 6942,
"text": "\n 70 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6997,
"s": 6977,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 7004,
"s": 6997,
"text": " Print"
},
{
"code": null,
"e": 7015,
"s": 7004,
"text": " Add Notes"
}
] |
How to resolve the ERROR 1115 (42000): Unknown character set: 'utf8mb4'?
|
You will get this type of error when your MySQL version is below 5.5.3. This is because “utf8mb4” introduced in MySQL version 5.5.3.
Firstly, you need to check the current version. If its less than 5.5.3, then you need to upgrade to solve the above error.
Check the current version −
mysql> select version();
Here, our MySQL version is over 5.5.3 −
+-----------+
| version() |
+-----------+
| 8.0.12 |
+-----------+
1 row in set (0.00 sec)
Now the same query that gave an error 1115, will display correct result. To check all character set in MySQL now, use the below query.
mysql> show character set;
The following is the output displaying “utf8mb4” correctly displayed;
+----------+---------------------------------+---------------------+--------+
| Charset | Description | Default collation | Maxlen |
+----------+---------------------------------+---------------------+--------+
| armscii8 | ARMSCII-8 Armenian | armscii8_general_ci | 1 |
| ascii | US ASCII | ascii_general_ci | 1 |
| big5 | Big5 Traditional Chinese | big5_chinese_ci | 2 |
| binary | Binary pseudo charset | binary | 1 |
| cp1250 | Windows Central European | cp1250_general_ci | 1 |
| cp1251 | Windows Cyrillic | cp1251_general_ci | 1 |
| cp1256 | Windows Arabic | cp1256_general_ci | 1 |
| cp1257 | Windows Baltic | cp1257_general_ci | 1 |
| cp850 | DOS West European | cp850_general_ci | 1 |
| cp852 | DOS Central European | cp852_general_ci | 1 |
| cp866 | DOS Russian | cp866_general_ci | 1 |
| cp932 | SJIS for Windows Japanese | cp932_japanese_ci | 2 |
| dec8 | DEC West European | dec8_swedish_ci | 1 |
| eucjpms | UJIS for Windows Japanese | eucjpms_japanese_ci | 3 |
| euckr | EUC-KR Korean | euckr_korean_ci | 2 |
| gb18030 | China National Standard GB18030 | gb18030_chinese_ci | 4 |
| gb2312 | GB2312 Simplified Chinese | gb2312_chinese_ci | 2 |
| gbk | GBK Simplified Chinese | gbk_chinese_ci | 2 |
| geostd8 | GEOSTD8 Georgian | geostd8_general_ci | 1 |
| greek | ISO 8859-7 Greek | greek_general_ci | 1 |
| hebrew | ISO 8859-8 Hebrew | hebrew_general_ci | 1 |
| hp8 | HP West European | hp8_english_ci | 1 |
| keybcs2 | DOS Kamenicky Czech-Slovak | keybcs2_general_ci | 1 |
| koi8r | KOI8-R Relcom Russian | koi8r_general_ci | 1 |
| koi8u | KOI8-U Ukrainian | koi8u_general_ci | 1 |
| latin1 | cp1252 West European | latin1_swedish_ci | 1 |
| latin2 | ISO 8859-2 Central European | latin2_general_ci | 1 |
| latin5 | ISO 8859-9 Turkish | latin5_turkish_ci | 1 |
| latin7 | ISO 8859-13 Baltic | latin7_general_ci | 1 |
| macce | Mac Central European | macce_general_ci | 1 |
| macroman | Mac West European | macroman_general_ci | 1 |
| sjis | Shift-JIS Japanese | sjis_japanese_ci | 2 |
| swe7 | 7bit Swedish | swe7_swedish_ci | 1 |
| tis620 | TIS620 Thai | tis620_thai_ci | 1 |
| ucs2 | UCS-2 Unicode | ucs2_general_ci | 2 |
| ujis | EUC-JP Japanese | ujis_japanese_ci | 3 |
| utf16 | UTF-16 Unicode | utf16_general_ci | 4 |
| utf16le | UTF-16LE Unicode | utf16le_general_ci | 4 |
| utf32 | UTF-32 Unicode | utf32_general_ci | 4 |
| utf8 | UTF-8 Unicode | utf8_general_ci | 3 |
| utf8mb4 | UTF-8 Unicode | utf8mb4_0900_ai_ci | 4 |
+----------+---------------------------------+---------------------+--------+
41 rows in set (0.01 sec)
|
[
{
"code": null,
"e": 1195,
"s": 1062,
"text": "You will get this type of error when your MySQL version is below 5.5.3. This is because “utf8mb4” introduced in MySQL version 5.5.3."
},
{
"code": null,
"e": 1318,
"s": 1195,
"text": "Firstly, you need to check the current version. If its less than 5.5.3, then you need to upgrade to solve the above error."
},
{
"code": null,
"e": 1346,
"s": 1318,
"text": "Check the current version −"
},
{
"code": null,
"e": 1371,
"s": 1346,
"text": "mysql> select version();"
},
{
"code": null,
"e": 1411,
"s": 1371,
"text": "Here, our MySQL version is over 5.5.3 −"
},
{
"code": null,
"e": 1505,
"s": 1411,
"text": "+-----------+\n| version() |\n+-----------+\n| 8.0.12 |\n+-----------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 1640,
"s": 1505,
"text": "Now the same query that gave an error 1115, will display correct result. To check all character set in MySQL now, use the below query."
},
{
"code": null,
"e": 1667,
"s": 1640,
"text": "mysql> show character set;"
},
{
"code": null,
"e": 1737,
"s": 1667,
"text": "The following is the output displaying “utf8mb4” correctly displayed;"
},
{
"code": null,
"e": 5273,
"s": 1737,
"text": "+----------+---------------------------------+---------------------+--------+\n| Charset | Description | Default collation | Maxlen |\n+----------+---------------------------------+---------------------+--------+\n| armscii8 | ARMSCII-8 Armenian | armscii8_general_ci | 1 |\n| ascii | US ASCII | ascii_general_ci | 1 |\n| big5 | Big5 Traditional Chinese | big5_chinese_ci | 2 |\n| binary | Binary pseudo charset | binary | 1 |\n| cp1250 | Windows Central European | cp1250_general_ci | 1 |\n| cp1251 | Windows Cyrillic | cp1251_general_ci | 1 |\n| cp1256 | Windows Arabic | cp1256_general_ci | 1 |\n| cp1257 | Windows Baltic | cp1257_general_ci | 1 |\n| cp850 | DOS West European | cp850_general_ci | 1 |\n| cp852 | DOS Central European | cp852_general_ci | 1 |\n| cp866 | DOS Russian | cp866_general_ci | 1 |\n| cp932 | SJIS for Windows Japanese | cp932_japanese_ci | 2 |\n| dec8 | DEC West European | dec8_swedish_ci | 1 |\n| eucjpms | UJIS for Windows Japanese | eucjpms_japanese_ci | 3 |\n| euckr | EUC-KR Korean | euckr_korean_ci | 2 |\n| gb18030 | China National Standard GB18030 | gb18030_chinese_ci | 4 |\n| gb2312 | GB2312 Simplified Chinese | gb2312_chinese_ci | 2 |\n| gbk | GBK Simplified Chinese | gbk_chinese_ci | 2 |\n| geostd8 | GEOSTD8 Georgian | geostd8_general_ci | 1 |\n| greek | ISO 8859-7 Greek | greek_general_ci | 1 |\n| hebrew | ISO 8859-8 Hebrew | hebrew_general_ci | 1 |\n| hp8 | HP West European | hp8_english_ci | 1 |\n| keybcs2 | DOS Kamenicky Czech-Slovak | keybcs2_general_ci | 1 |\n| koi8r | KOI8-R Relcom Russian | koi8r_general_ci | 1 |\n| koi8u | KOI8-U Ukrainian | koi8u_general_ci | 1 |\n| latin1 | cp1252 West European | latin1_swedish_ci | 1 |\n| latin2 | ISO 8859-2 Central European | latin2_general_ci | 1 |\n| latin5 | ISO 8859-9 Turkish | latin5_turkish_ci | 1 |\n| latin7 | ISO 8859-13 Baltic | latin7_general_ci | 1 |\n| macce | Mac Central European | macce_general_ci | 1 |\n| macroman | Mac West European | macroman_general_ci | 1 |\n| sjis | Shift-JIS Japanese | sjis_japanese_ci | 2 |\n| swe7 | 7bit Swedish | swe7_swedish_ci | 1 |\n| tis620 | TIS620 Thai | tis620_thai_ci | 1 |\n| ucs2 | UCS-2 Unicode | ucs2_general_ci | 2 |\n| ujis | EUC-JP Japanese | ujis_japanese_ci | 3 |\n| utf16 | UTF-16 Unicode | utf16_general_ci | 4 |\n| utf16le | UTF-16LE Unicode | utf16le_general_ci | 4 |\n| utf32 | UTF-32 Unicode | utf32_general_ci | 4 |\n| utf8 | UTF-8 Unicode | utf8_general_ci | 3 |\n| utf8mb4 | UTF-8 Unicode | utf8mb4_0900_ai_ci | 4 |\n+----------+---------------------------------+---------------------+--------+\n41 rows in set (0.01 sec)"
}
] |
Python - Data Wrangling
|
Data wrangling involves processing the data in various formats like - merging, grouping, concatenating etc. for the purpose of analysing or getting them ready to be used with another set of data.
Python has built-in features to apply these wrangling methods to various data sets to achieve the analytical goal. In this chapter we will look at few examples describing these methods.
The Pandas library in python provides a single function, merge, as the entry point for all standard database join operations between DataFrame objects −
pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None,
left_index=False, right_index=False, sort=True)
Let us now create two different DataFrames and perform the merging operations on it.
# import the pandas library
import pandas as pd
left = pd.DataFrame({
'id':[1,2,3,4,5],
'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],
'subject_id':['sub1','sub2','sub4','sub6','sub5']})
right = pd.DataFrame(
{'id':[1,2,3,4,5],
'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],
'subject_id':['sub2','sub4','sub3','sub6','sub5']})
print left
print right
Its output is as follows −
Name id subject_id
0 Alex 1 sub1
1 Amy 2 sub2
2 Allen 3 sub4
3 Alice 4 sub6
4 Ayoung 5 sub5
Name id subject_id
0 Billy 1 sub2
1 Brian 2 sub4
2 Bran 3 sub3
3 Bryce 4 sub6
4 Betty 5 sub5
Grouping data sets is a frequent need in data analysis where we need the result in terms of various groups present in the data set. Panadas has in-built methods
which can roll the data into various groups.
In the below example we group the data by year and then get the result for a specific year.
# import the pandas library
import pandas as pd
ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',
'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],
'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],
'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],
'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}
df = pd.DataFrame(ipl_data)
grouped = df.groupby('Year')
print grouped.get_group(2014)
Its output is as follows −
Points Rank Team Year
0 876 1 Riders 2014
2 863 2 Devils 2014
4 741 3 Kings 2014
9 701 4 Royals 2014
Pandas provides various facilities for easily combining together Series, DataFrame, and Panel objects. In the below example
the concat function performs concatenation operations along an axis. Let us create different objects and do concatenation.
import pandas as pd
one = pd.DataFrame({
'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],
'subject_id':['sub1','sub2','sub4','sub6','sub5'],
'Marks_scored':[98,90,87,69,78]},
index=[1,2,3,4,5])
two = pd.DataFrame({
'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],
'subject_id':['sub2','sub4','sub3','sub6','sub5'],
'Marks_scored':[89,80,79,97,88]},
index=[1,2,3,4,5])
print pd.concat([one,two])
Its output is as follows −
Marks_scored Name subject_id
1 98 Alex sub1
2 90 Amy sub2
3 87 Allen sub4
4 69 Alice sub6
5 78 Ayoung sub5
1 89 Billy sub2
2 80 Brian sub4
3 79 Bran sub3
4 97 Bryce sub6
5 88 Betty sub5
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": 2912,
"s": 2529,
"text": "Data wrangling involves processing the data in various formats like - merging, grouping, concatenating etc. for the purpose of analysing or getting them ready to be used with another set of data.\nPython has built-in features to apply these wrangling methods to various data sets to achieve the analytical goal. In this chapter we will look at few examples describing these methods. "
},
{
"code": null,
"e": 3065,
"s": 2912,
"text": "The Pandas library in python provides a single function, merge, as the entry point for all standard database join operations between DataFrame objects −"
},
{
"code": null,
"e": 3187,
"s": 3065,
"text": "pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None,\nleft_index=False, right_index=False, sort=True)\n"
},
{
"code": null,
"e": 3272,
"s": 3187,
"text": "Let us now create two different DataFrames and perform the merging operations on it."
},
{
"code": null,
"e": 3689,
"s": 3272,
"text": "# import the pandas library\nimport pandas as pd\nleft = pd.DataFrame({\n 'id':[1,2,3,4,5],\n 'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],\n 'subject_id':['sub1','sub2','sub4','sub6','sub5']})\nright = pd.DataFrame(\n {'id':[1,2,3,4,5],\n 'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],\n 'subject_id':['sub2','sub4','sub3','sub6','sub5']})\nprint left\nprint right"
},
{
"code": null,
"e": 3716,
"s": 3689,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4030,
"s": 3716,
"text": " Name id subject_id\n0 Alex 1 sub1\n1 Amy 2 sub2\n2 Allen 3 sub4\n3 Alice 4 sub6\n4 Ayoung 5 sub5\n\n Name id subject_id\n0 Billy 1 sub2\n1 Brian 2 sub4\n2 Bran 3 sub3\n3 Bryce 4 sub6\n4 Betty 5 sub5\n"
},
{
"code": null,
"e": 4236,
"s": 4030,
"text": "Grouping data sets is a frequent need in data analysis where we need the result in terms of various groups present in the data set. Panadas has in-built methods\nwhich can roll the data into various groups."
},
{
"code": null,
"e": 4328,
"s": 4236,
"text": "In the below example we group the data by year and then get the result for a specific year."
},
{
"code": null,
"e": 4813,
"s": 4328,
"text": "# import the pandas library\nimport pandas as pd\n\nipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',\n 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],\n 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],\n 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],\n 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}\ndf = pd.DataFrame(ipl_data)\n\ngrouped = df.groupby('Year')\nprint grouped.get_group(2014)"
},
{
"code": null,
"e": 4840,
"s": 4813,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5006,
"s": 4840,
"text": " Points Rank Team Year\n0 876 1 Riders 2014\n2 863 2 Devils 2014\n4 741 3 Kings 2014\n9 701 4 Royals 2014\n"
},
{
"code": null,
"e": 5253,
"s": 5006,
"text": "Pandas provides various facilities for easily combining together Series, DataFrame, and Panel objects. In the below example\nthe concat function performs concatenation operations along an axis. Let us create different objects and do concatenation."
},
{
"code": null,
"e": 5729,
"s": 5253,
"text": "import pandas as pd\none = pd.DataFrame({\n 'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],\n 'subject_id':['sub1','sub2','sub4','sub6','sub5'],\n 'Marks_scored':[98,90,87,69,78]},\n index=[1,2,3,4,5])\ntwo = pd.DataFrame({\n 'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],\n 'subject_id':['sub2','sub4','sub3','sub6','sub5'],\n 'Marks_scored':[89,80,79,97,88]},\n index=[1,2,3,4,5])\nprint pd.concat([one,two])"
},
{
"code": null,
"e": 5756,
"s": 5729,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 6186,
"s": 5756,
"text": " Marks_scored Name subject_id\n1 98 Alex sub1\n2 90 Amy sub2\n3 87 Allen sub4\n4 69 Alice sub6\n5 78 Ayoung sub5\n1 89 Billy sub2\n2 80 Brian sub4\n3 79 Bran sub3\n4 97 Bryce sub6\n5 88 Betty sub5\n"
},
{
"code": null,
"e": 6223,
"s": 6186,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6239,
"s": 6223,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6272,
"s": 6239,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6291,
"s": 6272,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6326,
"s": 6291,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 6348,
"s": 6326,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 6382,
"s": 6348,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6410,
"s": 6382,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6445,
"s": 6410,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6459,
"s": 6445,
"text": " Lets Kode It"
},
{
"code": null,
"e": 6492,
"s": 6459,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6509,
"s": 6492,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6516,
"s": 6509,
"text": " Print"
},
{
"code": null,
"e": 6527,
"s": 6516,
"text": " Add Notes"
}
] |
Maximum height of the binary search tree created from the given array - GeeksforGeeks
|
30 Jun, 2021
Given an array arr[] of N integers, the task is to make two binary search trees. One while traversing from the left side of the array and another while traversing from the right and find which tree has a greater height.Examples:
Input: arr[] = {2, 1, 3, 4}
Output: 0
BST starting from first index BST starting from last index
2 4
/ \ /
1 3 3
\ /
4 1
\
2
Input: arr[] = {1, 2, 6, 3, 5}
Output: 1
Prerequisites: Inserting a node in a Binary Search tree and Finding the height of a binary tree.Approach:
Create a binary search tree while inserting the nodes starting from the first element of the array till the last and find the height of this created tree say leftHeight.
Create another binary search tree while inserting the nodes starting from the last element of the array till the first and find the height of this created tree say rightHeight.
Print the maximum of these calculated heights i.e. max(leftHeight, rightHeight)
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; struct node { int key; struct node *left, *right;}; // A utility function to create a new BST nodestruct node* newNode(int item){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp;} /* A utility function to insert a new node with given key in BST */struct node* insert(struct node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} /* Compute the "maxDepth" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/int maxDepth(node* node){ if (node == NULL) return 0; else { /* compute the depth of each subtree */ int lDepth = maxDepth(node->left); int rDepth = maxDepth(node->right); /* use the larger one */ if (lDepth > rDepth) return (lDepth + 1); else return (rDepth + 1); }} // Function to return the maximum// heights among the BSTsint maxHeight(int a[], int n){ // Create a BST starting from // the first element struct node* rootA = NULL; rootA = insert(rootA, a[0]); for (int i = 1; i < n; i++) insert(rootA, a[i]); // Create another BST starting // from the last element struct node* rootB = NULL; rootB = insert(rootB, a[n - 1]); for (int i = n - 2; i >= 0; i--) insert(rootB, a[i]); // Find the heights of both the trees int A = maxDepth(rootA) - 1; int B = maxDepth(rootB) - 1; return max(A, B);} // Driver codeint main(){ int a[] = { 2, 1, 3, 4 }; int n = sizeof(a) / sizeof(a[0]); cout << maxHeight(a, n); return 0;}
// Java implementation of the approachclass GFG{ static class node{ int key; node left, right;}; // A utility function to create a new BST nodestatic node newNode(int item){ node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp;} /* A utility function to inserta new node with given key in BST */static node insert(node node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} /* Compute the "maxDepth" of a tree --the number of nodes along the longest pathfrom the root node down to the farthest leaf node.*/static int maxDepth(node node){ if (node == null) return 0; else { /* compute the depth of each subtree */ int lDepth = maxDepth(node.left); int rDepth = maxDepth(node.right); /* use the larger one */ if (lDepth > rDepth) return (lDepth + 1); else return (rDepth + 1); }} // Function to return the maximum// heights among the BSTsstatic int maxHeight(int a[], int n){ // Create a BST starting from // the first element node rootA = null; rootA = insert(rootA, a[0]); for (int i = 1; i < n; i++) rootA = insert(rootA, a[i]); // Create another BST starting // from the last element node rootB = null; rootB = insert(rootB, a[n - 1]); for (int i = n - 2; i >= 0; i--) rootB =insert(rootB, a[i]); // Find the heights of both the trees int A = maxDepth(rootA) - 1; int B = maxDepth(rootB) - 1; return Math.max(A, B);} // Driver codepublic static void main(String args[]){ int a[] = { 2, 1, 3, 4 }; int n = a.length; System.out.println(maxHeight(a, n));}} // This code is contributed by Arnab Kundu
# Python implementation of the approach class Node: def __init__(self, key): self.key = key self.left = None self.right = None # A utility function to insert# a new node with given key in BST */def insert(node: Node, key: int) -> Node: # If the tree is empty, # return a new node */ if node is None: return Node(key) # Otherwise, recur down the tree if key < node.key: node.left = insert(node.left, key) elif key > node.key: node.right = insert(node.right, key) # return the (unchanged) node pointer return node # Compute the "maxDepth" of a tree --# the number of nodes along the longest path# from the root node down to the farthest leaf node.*/def maxDepth(node: Node) -> int: if node is None: return 0 else: # compute the depth of each subtree lDepth = maxDepth(node.left) rDepth = maxDepth(node.right) # use the larger one if lDepth > rDepth: return lDepth + 1 else: return rDepth + 1 # Function to return the maximum# heights among the BSTsdef maxHeight(a: list, n: int) -> int: # Create a BST starting from # the first element rootA = Node(a[0]) for i in range(1, n): rootA = insert(rootA, a[i]) # Create another BST starting # from the last element rootB = Node(a[n - 1]) for i in range(n - 2, -1, -1): rootB = insert(rootB, a[i]) # Find the heights of both the trees A = maxDepth(rootA) - 1 B = maxDepth(rootB) - 1 return max(A, B) # Driver Codeif __name__ == "__main__": a = [2, 1, 3, 4] n = len(a) print(maxHeight(a, n)) # This code is contributed by# sanjeev2552
// C# implementation of the approachusing System; class GFG{ public class node { public int key; public node left, right; }; // A utility function to create a new BST node static node newNode(int item) { node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp; } /* A utility function to insert a new node with given key in BST */ static node insert(node node, int key) { /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node; } /* Compute the "maxDepth" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ static int maxDepth(node node) { if (node == null) return 0; else { /* compute the depth of each subtree */ int lDepth = maxDepth(node.left); int rDepth = maxDepth(node.right); /* use the larger one */ if (lDepth > rDepth) return (lDepth + 1); else return (rDepth + 1); } } // Function to return the maximum // heights among the BSTs static int maxHeight(int []a, int n) { // Create a BST starting from // the first element node rootA = null; rootA = insert(rootA, a[0]); for (int i = 1; i < n; i++) rootA = insert(rootA, a[i]); // Create another BST starting // from the last element node rootB = null; rootB = insert(rootB, a[n - 1]); for (int i = n - 2; i >= 0; i--) rootB =insert(rootB, a[i]); // Find the heights of both the trees int A = maxDepth(rootA) - 1; int B = maxDepth(rootB) - 1; return Math.Max(A, B); } // Driver code public static void Main() { int []a = { 2, 1, 3, 4 }; int n = a.Length; Console.WriteLine(maxHeight(a, n)); }} // This code is contributed by AnkitRai01
<script> // Javascript implementation of the approachclass node{ constructor() { this.key = 0; this.left = null; this.right = null; }}; // A utility function to create a new BST nodefunction newNode(item){ var temp = new node(); temp.key = item; temp.left = temp.right = null; return temp;} /* A utility function to inserta new node with given key in BST */function insert(node, key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} /* Compute the "maxDepth" of a tree --the number of nodes along the longest pathfrom the root node down to the farthest leaf node.*/function maxDepth(node){ if (node == null) return 0; else { /* compute the depth of each subtree */ var lDepth = maxDepth(node.left); var rDepth = maxDepth(node.right); /* use the larger one */ if (lDepth > rDepth) return (lDepth + 1); else return (rDepth + 1); }} // Function to return the maximum// heights among the BSTsfunction maxHeight(a, n){ // Create a BST starting from // the first element var rootA = null; rootA = insert(rootA, a[0]); for (var i = 1; i < n; i++) rootA = insert(rootA, a[i]); // Create another BST starting // from the last element var rootB = null; rootB = insert(rootB, a[n - 1]); for (var i = n - 2; i >= 0; i--) rootB =insert(rootB, a[i]); // Find the heights of both the trees var A = maxDepth(rootA) - 1; var B = maxDepth(rootB) - 1; return Math.max(A, B);} // Driver codevar a = [2, 1, 3, 4];var n = a.length;document.write(maxHeight(a, n)); // This code is contributed by rrrtnx.</script>
3
andrew1234
ankthon
sanjeev2552
rrrtnx
Arrays
Binary Search Tree
Recursion
Arrays
Recursion
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Binary Search Tree | Set 1 (Search and Insertion)
AVL Tree | Set 1 (Insertion)
Binary Search Tree | Set 2 (Delete)
A program to check if a binary tree is BST or not
Construct BST from given preorder traversal | Set 1
|
[
{
"code": null,
"e": 26041,
"s": 26013,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 26272,
"s": 26041,
"text": "Given an array arr[] of N integers, the task is to make two binary search trees. One while traversing from the left side of the array and another while traversing from the right and find which tree has a greater height.Examples: "
},
{
"code": null,
"e": 26771,
"s": 26272,
"text": "Input: arr[] = {2, 1, 3, 4}\nOutput: 0\nBST starting from first index BST starting from last index \n 2 4\n / \\ /\n 1 3 3\n \\ /\n 4 1\n \\\n 2\n\nInput: arr[] = {1, 2, 6, 3, 5}\nOutput: 1"
},
{
"code": null,
"e": 26881,
"s": 26773,
"text": "Prerequisites: Inserting a node in a Binary Search tree and Finding the height of a binary tree.Approach: "
},
{
"code": null,
"e": 27051,
"s": 26881,
"text": "Create a binary search tree while inserting the nodes starting from the first element of the array till the last and find the height of this created tree say leftHeight."
},
{
"code": null,
"e": 27228,
"s": 27051,
"text": "Create another binary search tree while inserting the nodes starting from the last element of the array till the first and find the height of this created tree say rightHeight."
},
{
"code": null,
"e": 27308,
"s": 27228,
"text": "Print the maximum of these calculated heights i.e. max(leftHeight, rightHeight)"
},
{
"code": null,
"e": 27361,
"s": 27308,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27365,
"s": 27361,
"text": "C++"
},
{
"code": null,
"e": 27370,
"s": 27365,
"text": "Java"
},
{
"code": null,
"e": 27378,
"s": 27370,
"text": "Python3"
},
{
"code": null,
"e": 27381,
"s": 27378,
"text": "C#"
},
{
"code": null,
"e": 27392,
"s": 27381,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; struct node { int key; struct node *left, *right;}; // A utility function to create a new BST nodestruct node* newNode(int item){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp;} /* A utility function to insert a new node with given key in BST */struct node* insert(struct node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} /* Compute the \"maxDepth\" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/int maxDepth(node* node){ if (node == NULL) return 0; else { /* compute the depth of each subtree */ int lDepth = maxDepth(node->left); int rDepth = maxDepth(node->right); /* use the larger one */ if (lDepth > rDepth) return (lDepth + 1); else return (rDepth + 1); }} // Function to return the maximum// heights among the BSTsint maxHeight(int a[], int n){ // Create a BST starting from // the first element struct node* rootA = NULL; rootA = insert(rootA, a[0]); for (int i = 1; i < n; i++) insert(rootA, a[i]); // Create another BST starting // from the last element struct node* rootB = NULL; rootB = insert(rootB, a[n - 1]); for (int i = n - 2; i >= 0; i--) insert(rootB, a[i]); // Find the heights of both the trees int A = maxDepth(rootA) - 1; int B = maxDepth(rootB) - 1; return max(A, B);} // Driver codeint main(){ int a[] = { 2, 1, 3, 4 }; int n = sizeof(a) / sizeof(a[0]); cout << maxHeight(a, n); return 0;}",
"e": 29427,
"s": 27392,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ static class node{ int key; node left, right;}; // A utility function to create a new BST nodestatic node newNode(int item){ node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp;} /* A utility function to inserta new node with given key in BST */static node insert(node node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} /* Compute the \"maxDepth\" of a tree --the number of nodes along the longest pathfrom the root node down to the farthest leaf node.*/static int maxDepth(node node){ if (node == null) return 0; else { /* compute the depth of each subtree */ int lDepth = maxDepth(node.left); int rDepth = maxDepth(node.right); /* use the larger one */ if (lDepth > rDepth) return (lDepth + 1); else return (rDepth + 1); }} // Function to return the maximum// heights among the BSTsstatic int maxHeight(int a[], int n){ // Create a BST starting from // the first element node rootA = null; rootA = insert(rootA, a[0]); for (int i = 1; i < n; i++) rootA = insert(rootA, a[i]); // Create another BST starting // from the last element node rootB = null; rootB = insert(rootB, a[n - 1]); for (int i = n - 2; i >= 0; i--) rootB =insert(rootB, a[i]); // Find the heights of both the trees int A = maxDepth(rootA) - 1; int B = maxDepth(rootB) - 1; return Math.max(A, B);} // Driver codepublic static void main(String args[]){ int a[] = { 2, 1, 3, 4 }; int n = a.length; System.out.println(maxHeight(a, n));}} // This code is contributed by Arnab Kundu",
"e": 31442,
"s": 29427,
"text": null
},
{
"code": "# Python implementation of the approach class Node: def __init__(self, key): self.key = key self.left = None self.right = None # A utility function to insert# a new node with given key in BST */def insert(node: Node, key: int) -> Node: # If the tree is empty, # return a new node */ if node is None: return Node(key) # Otherwise, recur down the tree if key < node.key: node.left = insert(node.left, key) elif key > node.key: node.right = insert(node.right, key) # return the (unchanged) node pointer return node # Compute the \"maxDepth\" of a tree --# the number of nodes along the longest path# from the root node down to the farthest leaf node.*/def maxDepth(node: Node) -> int: if node is None: return 0 else: # compute the depth of each subtree lDepth = maxDepth(node.left) rDepth = maxDepth(node.right) # use the larger one if lDepth > rDepth: return lDepth + 1 else: return rDepth + 1 # Function to return the maximum# heights among the BSTsdef maxHeight(a: list, n: int) -> int: # Create a BST starting from # the first element rootA = Node(a[0]) for i in range(1, n): rootA = insert(rootA, a[i]) # Create another BST starting # from the last element rootB = Node(a[n - 1]) for i in range(n - 2, -1, -1): rootB = insert(rootB, a[i]) # Find the heights of both the trees A = maxDepth(rootA) - 1 B = maxDepth(rootB) - 1 return max(A, B) # Driver Codeif __name__ == \"__main__\": a = [2, 1, 3, 4] n = len(a) print(maxHeight(a, n)) # This code is contributed by# sanjeev2552",
"e": 33131,
"s": 31442,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ public class node { public int key; public node left, right; }; // A utility function to create a new BST node static node newNode(int item) { node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp; } /* A utility function to insert a new node with given key in BST */ static node insert(node node, int key) { /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node; } /* Compute the \"maxDepth\" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ static int maxDepth(node node) { if (node == null) return 0; else { /* compute the depth of each subtree */ int lDepth = maxDepth(node.left); int rDepth = maxDepth(node.right); /* use the larger one */ if (lDepth > rDepth) return (lDepth + 1); else return (rDepth + 1); } } // Function to return the maximum // heights among the BSTs static int maxHeight(int []a, int n) { // Create a BST starting from // the first element node rootA = null; rootA = insert(rootA, a[0]); for (int i = 1; i < n; i++) rootA = insert(rootA, a[i]); // Create another BST starting // from the last element node rootB = null; rootB = insert(rootB, a[n - 1]); for (int i = n - 2; i >= 0; i--) rootB =insert(rootB, a[i]); // Find the heights of both the trees int A = maxDepth(rootA) - 1; int B = maxDepth(rootB) - 1; return Math.Max(A, B); } // Driver code public static void Main() { int []a = { 2, 1, 3, 4 }; int n = a.Length; Console.WriteLine(maxHeight(a, n)); }} // This code is contributed by AnkitRai01",
"e": 35512,
"s": 33131,
"text": null
},
{
"code": "<script> // Javascript implementation of the approachclass node{ constructor() { this.key = 0; this.left = null; this.right = null; }}; // A utility function to create a new BST nodefunction newNode(item){ var temp = new node(); temp.key = item; temp.left = temp.right = null; return temp;} /* A utility function to inserta new node with given key in BST */function insert(node, key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} /* Compute the \"maxDepth\" of a tree --the number of nodes along the longest pathfrom the root node down to the farthest leaf node.*/function maxDepth(node){ if (node == null) return 0; else { /* compute the depth of each subtree */ var lDepth = maxDepth(node.left); var rDepth = maxDepth(node.right); /* use the larger one */ if (lDepth > rDepth) return (lDepth + 1); else return (rDepth + 1); }} // Function to return the maximum// heights among the BSTsfunction maxHeight(a, n){ // Create a BST starting from // the first element var rootA = null; rootA = insert(rootA, a[0]); for (var i = 1; i < n; i++) rootA = insert(rootA, a[i]); // Create another BST starting // from the last element var rootB = null; rootB = insert(rootB, a[n - 1]); for (var i = n - 2; i >= 0; i--) rootB =insert(rootB, a[i]); // Find the heights of both the trees var A = maxDepth(rootA) - 1; var B = maxDepth(rootB) - 1; return Math.max(A, B);} // Driver codevar a = [2, 1, 3, 4];var n = a.length;document.write(maxHeight(a, n)); // This code is contributed by rrrtnx.</script>",
"e": 37493,
"s": 35512,
"text": null
},
{
"code": null,
"e": 37495,
"s": 37493,
"text": "3"
},
{
"code": null,
"e": 37508,
"s": 37497,
"text": "andrew1234"
},
{
"code": null,
"e": 37516,
"s": 37508,
"text": "ankthon"
},
{
"code": null,
"e": 37528,
"s": 37516,
"text": "sanjeev2552"
},
{
"code": null,
"e": 37535,
"s": 37528,
"text": "rrrtnx"
},
{
"code": null,
"e": 37542,
"s": 37535,
"text": "Arrays"
},
{
"code": null,
"e": 37561,
"s": 37542,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 37571,
"s": 37561,
"text": "Recursion"
},
{
"code": null,
"e": 37578,
"s": 37571,
"text": "Arrays"
},
{
"code": null,
"e": 37588,
"s": 37578,
"text": "Recursion"
},
{
"code": null,
"e": 37607,
"s": 37588,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 37705,
"s": 37607,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37732,
"s": 37705,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 37763,
"s": 37732,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 37788,
"s": 37763,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 37826,
"s": 37788,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 37847,
"s": 37826,
"text": "Next Greater Element"
},
{
"code": null,
"e": 37897,
"s": 37847,
"text": "Binary Search Tree | Set 1 (Search and Insertion)"
},
{
"code": null,
"e": 37926,
"s": 37897,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 37962,
"s": 37926,
"text": "Binary Search Tree | Set 2 (Delete)"
},
{
"code": null,
"e": 38012,
"s": 37962,
"text": "A program to check if a binary tree is BST or not"
}
] |
Calculate difference between dataframe rows by group in R - GeeksforGeeks
|
16 Dec, 2021
In this article, we will see how to find the difference between rows by the group in dataframe in R programming language.
The group_by method is used to divide and segregate date based on groups contained within the specific columns. The required column to group by is specified as an argument of this function. It may contain multiple column names.
Syntax:
group_by(col1, col2, ...)
This is followed by the application of mutate() method which is used to shift orientations and perform manipulations in the data. The new column name can be specified using the new column name. The difference from the previous row can be calculated using the lag() method of this library. This method finds the previous values in a vector.
Syntax:
lag(x, n = 1L, default = NA)
Parameter:
x – A vector of values
n – Number of positions to lag by
default (Default : NA)- the value used for non-existent rows.
A mutation is introduced in the data frame by using the lag of the column value subtracted from the specified column’s particular row. The default value is the first value of that particular group using the first(col-name).
Example:
R
# installing required librarieslibrary("dplyr") # creating a data framedata_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE), col2 = letters[1:3], col3 = c(1,4,5,1,NA,NA,2,NA,2)) print ("Original DataFrame")print (data_frame) print ("Modified DataFrame") # computing difference of each groupdata_frame%>%group_by(col1)%>%mutate(diff=col3-lag( col3,default=first(col3)))
Output
[1] "Original DataFrame"
col1 col2 col3
1 6 a 1
2 9 b 4
3 7 c 5
4 6 a 1
5 6 b NA
6 9 c NA
7 6 a 2
8 8 b NA
9 7 c 2
[1] "Modified DataFrame"
# A tibble: 9 x 4
# Groups: col1 [4]
col1 col2 col3 diff
<int> <chr> <dbl> <dbl>
1 6 a 1 0
2 9 b 4 0
3 7 c 5 0
4 6 a 1 0
5 6 b NA NA
6 9 c NA NA
7 6 a 2 NA
8 8 b NA NA
9 7 c 2 -3
The data frame indexing methods can be used to calculate the difference of rows by group in R. The ‘by’ attribute is to specify the column to group the data by. All the rows are retained, while a new column is added in the set of columns, using the column to take to compute the difference of rows by the group. The difference is calculated by using the particular row of the specified column and subtracting from it the previous value computed using the shift() method. The shift method is used to lag vectors or lists.
Syntax:
data_frame[ , new-col-name := reqd-col – shift(reqd-col), by = grouping-col]
The first instance of that particular group is replaced by NA in that particular column.
Example:
R
# installing required librarieslibrary("data.table") # creating a data framedata_frame <- data.table(col1 = sample(6:9, 9 , replace = TRUE), col2 = letters[1:3], col3 = c(1,4,5,1,9,11,2,7,2)) print ("Original DataFrame")print (data_frame) # computing difference of each groupdata_frame[ , diff := col3 - shift(col3), by = col1]print ("Modified DataFrame")print (data_frame)
Output
[1] "Original DataFrame"
col1 col2 col3
1: 8 a 1
2: 8 b 4
3: 7 c 5
4: 6 a 1
5: 6 b 9
6: 8 c 11
7: 8 a 2
8: 9 b 7
9: 7 c 2
[1] "Modified DataFrame"
col1 col2 col3 diff
1: 8 a 1 NA
2: 8 b 4 3
3: 7 c 5 NA
4: 6 a 1 NA
5: 6 b 9 8
6: 8 c 11 7
7: 8 a 2 -9
8: 9 b 7 NA
9: 7 c 2 -3
The ave() method in base R is used to group averages over the level combinations of factors.
Syntax:
ave(x, group , FUN = mean)
Parameter :
x – the required data frame column
group – the grouping variables
FUN – The function to apply for each factor level combination.
The function here is to compute the difference of a particular column in that row and the difference of the previous row with it. The first instance of that particular group is replaced by NA in that particular column.
Example:
R
# creating a data framedata_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE), col2 = letters[1:3], col3 = c(1,4,5,1,9,11,2,7,2)) print ("Original DataFrame")print (data_frame) # computing difference of each groupdata_frame$diff <- ave(data_frame$col3, factor(data_frame$col1), FUN=function(x) c(NA,diff(x))) print ("Modified DataFrame")print (data_frame)
Output
[1] "Original DataFrame"
col1 col2 col3
1 9 a 1
2 9 b 4
3 6 c 5
4 7 a 1
5 6 b 9
6 7 c 11
7 9 a 2
8 9 b 7
9 9 c 2
[1] "Modified DataFrame"
col1 col2 col3 diff
1 9 a 1 NA
2 9 b 4 3
3 6 c 5 NA
4 7 a 1 NA
5 6 b 9 4
6 7 c 11 10
7 9 a 2 -2
8 9 b 7 5
9 9 c 2 -5
sagar0719kumar
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 26609,
"s": 26487,
"text": "In this article, we will see how to find the difference between rows by the group in dataframe in R programming language."
},
{
"code": null,
"e": 26838,
"s": 26609,
"text": "The group_by method is used to divide and segregate date based on groups contained within the specific columns. The required column to group by is specified as an argument of this function. It may contain multiple column names. "
},
{
"code": null,
"e": 26846,
"s": 26838,
"text": "Syntax:"
},
{
"code": null,
"e": 26872,
"s": 26846,
"text": "group_by(col1, col2, ...)"
},
{
"code": null,
"e": 27213,
"s": 26872,
"text": "This is followed by the application of mutate() method which is used to shift orientations and perform manipulations in the data. The new column name can be specified using the new column name. The difference from the previous row can be calculated using the lag() method of this library. This method finds the previous values in a vector. "
},
{
"code": null,
"e": 27221,
"s": 27213,
"text": "Syntax:"
},
{
"code": null,
"e": 27250,
"s": 27221,
"text": "lag(x, n = 1L, default = NA)"
},
{
"code": null,
"e": 27262,
"s": 27250,
"text": "Parameter: "
},
{
"code": null,
"e": 27286,
"s": 27262,
"text": "x – A vector of values"
},
{
"code": null,
"e": 27320,
"s": 27286,
"text": "n – Number of positions to lag by"
},
{
"code": null,
"e": 27382,
"s": 27320,
"text": "default (Default : NA)- the value used for non-existent rows."
},
{
"code": null,
"e": 27606,
"s": 27382,
"text": "A mutation is introduced in the data frame by using the lag of the column value subtracted from the specified column’s particular row. The default value is the first value of that particular group using the first(col-name)."
},
{
"code": null,
"e": 27615,
"s": 27606,
"text": "Example:"
},
{
"code": null,
"e": 27617,
"s": 27615,
"text": "R"
},
{
"code": "# installing required librarieslibrary(\"dplyr\") # creating a data framedata_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE), col2 = letters[1:3], col3 = c(1,4,5,1,NA,NA,2,NA,2)) print (\"Original DataFrame\")print (data_frame) print (\"Modified DataFrame\") # computing difference of each groupdata_frame%>%group_by(col1)%>%mutate(diff=col3-lag( col3,default=first(col3)))",
"e": 28046,
"s": 27617,
"text": null
},
{
"code": null,
"e": 28055,
"s": 28046,
"text": " Output "
},
{
"code": null,
"e": 28634,
"s": 28055,
"text": "[1] \"Original DataFrame\" \n col1 col2 col3 \n1 6 a 1 \n2 9 b 4 \n3 7 c 5 \n4 6 a 1 \n5 6 b NA \n6 9 c NA \n7 6 a 2 \n8 8 b NA \n9 7 c 2 \n[1] \"Modified DataFrame\" \n # A tibble: 9 x 4 \n # Groups: col1 [4] \n col1 col2 col3 diff \n <int> <chr> <dbl> <dbl> \n1 6 a 1 0 \n2 9 b 4 0 \n3 7 c 5 0 \n4 6 a 1 0 \n5 6 b NA NA \n6 9 c NA NA \n7 6 a 2 NA \n8 8 b NA NA\n9 7 c 2 -3"
},
{
"code": null,
"e": 29156,
"s": 28634,
"text": "The data frame indexing methods can be used to calculate the difference of rows by group in R. The ‘by’ attribute is to specify the column to group the data by. All the rows are retained, while a new column is added in the set of columns, using the column to take to compute the difference of rows by the group. The difference is calculated by using the particular row of the specified column and subtracting from it the previous value computed using the shift() method. The shift method is used to lag vectors or lists. "
},
{
"code": null,
"e": 29165,
"s": 29156,
"text": "Syntax: "
},
{
"code": null,
"e": 29242,
"s": 29165,
"text": "data_frame[ , new-col-name := reqd-col – shift(reqd-col), by = grouping-col]"
},
{
"code": null,
"e": 29332,
"s": 29242,
"text": "The first instance of that particular group is replaced by NA in that particular column. "
},
{
"code": null,
"e": 29342,
"s": 29332,
"text": "Example: "
},
{
"code": null,
"e": 29344,
"s": 29342,
"text": "R"
},
{
"code": "# installing required librarieslibrary(\"data.table\") # creating a data framedata_frame <- data.table(col1 = sample(6:9, 9 , replace = TRUE), col2 = letters[1:3], col3 = c(1,4,5,1,9,11,2,7,2)) print (\"Original DataFrame\")print (data_frame) # computing difference of each groupdata_frame[ , diff := col3 - shift(col3), by = col1]print (\"Modified DataFrame\")print (data_frame)",
"e": 29766,
"s": 29344,
"text": null
},
{
"code": null,
"e": 29775,
"s": 29766,
"text": " Output "
},
{
"code": null,
"e": 30253,
"s": 29775,
"text": "[1] \"Original DataFrame\" \ncol1 col2 col3 \n1: 8 a 1 \n2: 8 b 4 \n3: 7 c 5 \n4: 6 a 1 \n5: 6 b 9 \n6: 8 c 11 \n7: 8 a 2 \n8: 9 b 7 \n9: 7 c 2 \n[1] \"Modified DataFrame\" \n col1 col2 col3 diff \n1: 8 a 1 NA \n2: 8 b 4 3 \n3: 7 c 5 NA \n4: 6 a 1 NA \n5: 6 b 9 8 \n6: 8 c 11 7 \n7: 8 a 2 -9 \n8: 9 b 7 NA \n9: 7 c 2 -3"
},
{
"code": null,
"e": 30348,
"s": 30253,
"text": "The ave() method in base R is used to group averages over the level combinations of factors. "
},
{
"code": null,
"e": 30356,
"s": 30348,
"text": "Syntax:"
},
{
"code": null,
"e": 30383,
"s": 30356,
"text": "ave(x, group , FUN = mean)"
},
{
"code": null,
"e": 30396,
"s": 30383,
"text": "Parameter : "
},
{
"code": null,
"e": 30431,
"s": 30396,
"text": "x – the required data frame column"
},
{
"code": null,
"e": 30462,
"s": 30431,
"text": "group – the grouping variables"
},
{
"code": null,
"e": 30525,
"s": 30462,
"text": "FUN – The function to apply for each factor level combination."
},
{
"code": null,
"e": 30746,
"s": 30525,
"text": "The function here is to compute the difference of a particular column in that row and the difference of the previous row with it. The first instance of that particular group is replaced by NA in that particular column. "
},
{
"code": null,
"e": 30756,
"s": 30746,
"text": "Example: "
},
{
"code": null,
"e": 30758,
"s": 30756,
"text": "R"
},
{
"code": "# creating a data framedata_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE), col2 = letters[1:3], col3 = c(1,4,5,1,9,11,2,7,2)) print (\"Original DataFrame\")print (data_frame) # computing difference of each groupdata_frame$diff <- ave(data_frame$col3, factor(data_frame$col1), FUN=function(x) c(NA,diff(x))) print (\"Modified DataFrame\")print (data_frame)",
"e": 31216,
"s": 30758,
"text": null
},
{
"code": null,
"e": 31225,
"s": 31216,
"text": " Output "
},
{
"code": null,
"e": 31680,
"s": 31225,
"text": "[1] \"Original DataFrame\" \ncol1 col2 col3 \n1 9 a 1 \n2 9 b 4 \n3 6 c 5 \n4 7 a 1 \n5 6 b 9 \n6 7 c 11\n7 9 a 2 \n8 9 b 7 \n9 9 c 2\n[1] \"Modified DataFrame\" \ncol1 col2 col3 diff \n1 9 a 1 NA \n2 9 b 4 3 \n3 6 c 5 NA \n4 7 a 1 NA \n5 6 b 9 4 \n6 7 c 11 10 \n7 9 a 2 -2 \n8 9 b 7 5 \n9 9 c 2 -5"
},
{
"code": null,
"e": 31697,
"s": 31682,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 31704,
"s": 31697,
"text": "Picked"
},
{
"code": null,
"e": 31725,
"s": 31704,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 31737,
"s": 31725,
"text": "R-DataFrame"
},
{
"code": null,
"e": 31748,
"s": 31737,
"text": "R Language"
},
{
"code": null,
"e": 31759,
"s": 31748,
"text": "R Programs"
},
{
"code": null,
"e": 31857,
"s": 31759,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31909,
"s": 31857,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 31944,
"s": 31909,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 31982,
"s": 31944,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 32040,
"s": 31982,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 32083,
"s": 32040,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 32141,
"s": 32083,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 32184,
"s": 32141,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 32233,
"s": 32184,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 32283,
"s": 32233,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
Lodash _.update() Method - GeeksforGeeks
|
16 Sep, 2020
The _.update() method accepts updater to produce the value to set. This method use _.updateWith() function to customize path creation. It is almost the same as _.set() function.
Syntax:
_.update(object, path, updater)
Parameters: This method accepts three parameters as mentioned above and described below:
object: This parameter holds the object to modify.
path: This parameter holds the path of the property to set. It will be array or string.
updater: This is the function to produce the updated value.
Return Value: This method returns the new object.
Note: Here, const _ = require(‘lodash’) is used to import the lodash library into the file.
Example 1:
Javascript
// Requiring the lodash library const _ = require("lodash"); // The source object var obj = { 'cpp': [{ 'java': { 'python': 3 } }] }; // Use of _.update() method _.update(obj, 'cpp[0].java.python', function(n) { return n * n; }); // return the new objectconsole.log(obj.cpp[0].java.python);
Output:
9
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); // The source object var obj = { 'cpp': [{ 'java': { 'python': 3 } }] }; // Use of _.update() method _.update(obj, 'html[0].css.javascript', function(n) { return n ? n + 1 : 0; }); // return the new objectconsole.log(obj.html[0].css.javascript);
Output:
0
Note: This will not work in normal JavaScript because it requires the library lodash to be installed.
Reference: https://lodash.com/docs/4.17.15#update
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n16 Sep, 2020"
},
{
"code": null,
"e": 26723,
"s": 26545,
"text": "The _.update() method accepts updater to produce the value to set. This method use _.updateWith() function to customize path creation. It is almost the same as _.set() function."
},
{
"code": null,
"e": 26731,
"s": 26723,
"text": "Syntax:"
},
{
"code": null,
"e": 26764,
"s": 26731,
"text": "_.update(object, path, updater)\n"
},
{
"code": null,
"e": 26853,
"s": 26764,
"text": "Parameters: This method accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 26904,
"s": 26853,
"text": "object: This parameter holds the object to modify."
},
{
"code": null,
"e": 26992,
"s": 26904,
"text": "path: This parameter holds the path of the property to set. It will be array or string."
},
{
"code": null,
"e": 27052,
"s": 26992,
"text": "updater: This is the function to produce the updated value."
},
{
"code": null,
"e": 27102,
"s": 27052,
"text": "Return Value: This method returns the new object."
},
{
"code": null,
"e": 27196,
"s": 27102,
"text": "Note: Here, const _ = require(‘lodash’) is used to import the lodash library into the file. "
},
{
"code": null,
"e": 27207,
"s": 27196,
"text": "Example 1:"
},
{
"code": null,
"e": 27218,
"s": 27207,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // The source object var obj = { 'cpp': [{ 'java': { 'python': 3 } }] }; // Use of _.update() method _.update(obj, 'cpp[0].java.python', function(n) { return n * n; }); // return the new objectconsole.log(obj.cpp[0].java.python);",
"e": 27519,
"s": 27218,
"text": null
},
{
"code": null,
"e": 27527,
"s": 27519,
"text": "Output:"
},
{
"code": null,
"e": 27530,
"s": 27527,
"text": "9\n"
},
{
"code": null,
"e": 27543,
"s": 27530,
"text": "Example 2: "
},
{
"code": null,
"e": 27554,
"s": 27543,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // The source object var obj = { 'cpp': [{ 'java': { 'python': 3 } }] }; // Use of _.update() method _.update(obj, 'html[0].css.javascript', function(n) { return n ? n + 1 : 0; }); // return the new objectconsole.log(obj.html[0].css.javascript);",
"e": 27871,
"s": 27554,
"text": null
},
{
"code": null,
"e": 27879,
"s": 27871,
"text": "Output:"
},
{
"code": null,
"e": 27882,
"s": 27879,
"text": "0\n"
},
{
"code": null,
"e": 27985,
"s": 27882,
"text": "Note: This will not work in normal JavaScript because it requires the library lodash to be installed. "
},
{
"code": null,
"e": 28035,
"s": 27985,
"text": "Reference: https://lodash.com/docs/4.17.15#update"
},
{
"code": null,
"e": 28053,
"s": 28035,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 28064,
"s": 28053,
"text": "JavaScript"
},
{
"code": null,
"e": 28081,
"s": 28064,
"text": "Web Technologies"
},
{
"code": null,
"e": 28179,
"s": 28081,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28219,
"s": 28179,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28280,
"s": 28219,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28321,
"s": 28280,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28343,
"s": 28321,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28397,
"s": 28343,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28437,
"s": 28397,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28470,
"s": 28437,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28513,
"s": 28470,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28563,
"s": 28513,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Find number of unique triangles among given N triangles - GeeksforGeeks
|
05 Aug, 2021
Given three arrays a[], b[] and c[] of N elements representing the three sides of N triangles. The task is to find the number of triangles that are unique out of given triangles. A triangle is non-unique if all of its sides match with all the sides of some other triangle in length.Examples:
Input: a[] = {1, 2}, b[] = {2, 3}, c[] = {3, 5} Output: 2 The triangles have sides 1, 2, 3 and 2, 3, 5 respectively. None of them have same sides. Thus both are unique.Input: a[] = {7, 5, 8, 2, 2}, b[] = {6, 7, 2, 3, 4}, c[] = {5, 6, 9, 4, 3} Output: 1 Only triangle with sides 8, 2 and 9 is unique.
Approach: The idea is, for each triangle, sort all of its sides and then store it in a map, if all those three sides are already present in the map then increase the frequency by 1, else its frequency will be 1. The count of elements of the map which have frequency 1 in the end will be the answer.Below is the implementation of the above approach:
C++
Python3
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of unique trianglesint UniqueTriangles(int a[], int b[], int c[], int n){ vector<int> sides[n]; // Map to store the frequency of triangles // with same sides map<vector<int>, int> m; for (int i = 0; i < n; i++) { // Push all the sides of the current triangle sides[i].push_back(a[i]); sides[i].push_back(b[i]); sides[i].push_back(c[i]); // Sort the three sides sort(sides[i].begin(), sides[i].end()); // Store the frequency of the sides // of the triangle m[sides[i]] = m[sides[i]] + 1; } map<vector<int>, int>::iterator i; // To store the count of unique triangles int count = 0; for (i = m.begin(); i != m.end(); i++) { // If current triangle has unique sides if (i->second == 1) count++; } return count;} // Driver codeint main(){ int a[] = { 7, 5, 8, 2, 2 }; int b[] = { 6, 7, 2, 3, 4 }; int c[] = { 5, 6, 9, 4, 3 }; int n = sizeof(a) / sizeof(int); cout << UniqueTriangles(a, b, c, n); return 0;}
# Python3 implementation of the approachfrom collections import defaultdict # Function to return the number# of unique trianglesdef UniqueTriangles(a, b, c, n): sides = [None for i in range(n)] # Map to store the frequency of # triangles with same sides m = defaultdict(lambda:0) for i in range(0, n): # Push all the sides of the current triangle sides[i] = (a[i], b[i], c[i]) # Sort the three sides sides[i] = tuple(sorted(sides[i])) # Store the frequency of the sides # of the triangle m[sides[i]] += 1 # To store the count of unique triangles count = 0 for i in m: # If current triangle has unique sides if m[i] == 1: count += 1 return count # Driver codeif __name__ == "__main__": a = [7, 5, 8, 2, 2] b = [6, 7, 2, 3, 4] c = [5, 6, 9, 4, 3] n = len(a) print(UniqueTriangles(a, b, c, n)) # This code is contributed by Rituraj Jain
1
Time Complexity : O(N * log(N))Auxiliary Space: O(N)
rituraj_jain
pankajsharmagfg
cpp-map
Arrays
Data Structures
Hash
Data Structures
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
Introduction to Algorithms
How to Start Learning DSA?
|
[
{
"code": null,
"e": 26041,
"s": 26013,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 26335,
"s": 26041,
"text": "Given three arrays a[], b[] and c[] of N elements representing the three sides of N triangles. The task is to find the number of triangles that are unique out of given triangles. A triangle is non-unique if all of its sides match with all the sides of some other triangle in length.Examples: "
},
{
"code": null,
"e": 26637,
"s": 26335,
"text": "Input: a[] = {1, 2}, b[] = {2, 3}, c[] = {3, 5} Output: 2 The triangles have sides 1, 2, 3 and 2, 3, 5 respectively. None of them have same sides. Thus both are unique.Input: a[] = {7, 5, 8, 2, 2}, b[] = {6, 7, 2, 3, 4}, c[] = {5, 6, 9, 4, 3} Output: 1 Only triangle with sides 8, 2 and 9 is unique. "
},
{
"code": null,
"e": 26989,
"s": 26639,
"text": "Approach: The idea is, for each triangle, sort all of its sides and then store it in a map, if all those three sides are already present in the map then increase the frequency by 1, else its frequency will be 1. The count of elements of the map which have frequency 1 in the end will be the answer.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26993,
"s": 26989,
"text": "C++"
},
{
"code": null,
"e": 27001,
"s": 26993,
"text": "Python3"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of unique trianglesint UniqueTriangles(int a[], int b[], int c[], int n){ vector<int> sides[n]; // Map to store the frequency of triangles // with same sides map<vector<int>, int> m; for (int i = 0; i < n; i++) { // Push all the sides of the current triangle sides[i].push_back(a[i]); sides[i].push_back(b[i]); sides[i].push_back(c[i]); // Sort the three sides sort(sides[i].begin(), sides[i].end()); // Store the frequency of the sides // of the triangle m[sides[i]] = m[sides[i]] + 1; } map<vector<int>, int>::iterator i; // To store the count of unique triangles int count = 0; for (i = m.begin(); i != m.end(); i++) { // If current triangle has unique sides if (i->second == 1) count++; } return count;} // Driver codeint main(){ int a[] = { 7, 5, 8, 2, 2 }; int b[] = { 6, 7, 2, 3, 4 }; int c[] = { 5, 6, 9, 4, 3 }; int n = sizeof(a) / sizeof(int); cout << UniqueTriangles(a, b, c, n); return 0;}",
"e": 28172,
"s": 27001,
"text": null
},
{
"code": "# Python3 implementation of the approachfrom collections import defaultdict # Function to return the number# of unique trianglesdef UniqueTriangles(a, b, c, n): sides = [None for i in range(n)] # Map to store the frequency of # triangles with same sides m = defaultdict(lambda:0) for i in range(0, n): # Push all the sides of the current triangle sides[i] = (a[i], b[i], c[i]) # Sort the three sides sides[i] = tuple(sorted(sides[i])) # Store the frequency of the sides # of the triangle m[sides[i]] += 1 # To store the count of unique triangles count = 0 for i in m: # If current triangle has unique sides if m[i] == 1: count += 1 return count # Driver codeif __name__ == \"__main__\": a = [7, 5, 8, 2, 2] b = [6, 7, 2, 3, 4] c = [5, 6, 9, 4, 3] n = len(a) print(UniqueTriangles(a, b, c, n)) # This code is contributed by Rituraj Jain",
"e": 29138,
"s": 28172,
"text": null
},
{
"code": null,
"e": 29140,
"s": 29138,
"text": "1"
},
{
"code": null,
"e": 29196,
"s": 29142,
"text": "Time Complexity : O(N * log(N))Auxiliary Space: O(N) "
},
{
"code": null,
"e": 29209,
"s": 29196,
"text": "rituraj_jain"
},
{
"code": null,
"e": 29225,
"s": 29209,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 29233,
"s": 29225,
"text": "cpp-map"
},
{
"code": null,
"e": 29240,
"s": 29233,
"text": "Arrays"
},
{
"code": null,
"e": 29256,
"s": 29240,
"text": "Data Structures"
},
{
"code": null,
"e": 29261,
"s": 29256,
"text": "Hash"
},
{
"code": null,
"e": 29277,
"s": 29261,
"text": "Data Structures"
},
{
"code": null,
"e": 29284,
"s": 29277,
"text": "Arrays"
},
{
"code": null,
"e": 29289,
"s": 29284,
"text": "Hash"
},
{
"code": null,
"e": 29387,
"s": 29289,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29414,
"s": 29387,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 29445,
"s": 29414,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 29470,
"s": 29445,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 29508,
"s": 29470,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 29529,
"s": 29508,
"text": "Next Greater Element"
},
{
"code": null,
"e": 29578,
"s": 29529,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 29603,
"s": 29578,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 29659,
"s": 29603,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 29686,
"s": 29659,
"text": "Introduction to Algorithms"
}
] |
Data Structures | Heap | Question 3 - GeeksforGeeks
|
28 Jun, 2021
A 3-ary max heap is like a binary max heap, but instead of 2 children, nodes have 3 children. A 3-ary heap can be represented by an array as follows: The root is stored in the first location, a[0], nodes in the next level, from left to right, is stored from a[1] to a[3]. The nodes from the second level of the tree from left to right are stored from a[4] location onward. An item x can be inserted into a 3-ary heap containing n items by placing x in the location a[n] and pushing it up the tree to satisfy the heap property.
Which one of the following is a valid sequence of elements in an array representing 3-ary max heap?(A) 1, 3, 5, 6, 8, 9(B) 9, 6, 3, 1, 8, 5(C) 9, 3, 6, 8, 5, 1(D) 9, 5, 6, 8, 3, 1Answer: (D)Explanation: Following 3-ary Max Heap can be constructed from sequence given option (D)
9
/ | \
/ | \
5 6 8
/ |
/ |
3 1
Quiz of this Question
Data Structures
Data Structures-Heap
Heap Quizzes
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count number of times each Edge appears in all possible paths of a given Tree
Difference between Singly linked list and Doubly linked list
Program to create Custom Vector Class in C++
Introduction to Data Structures
Data Structures | Stack | Question 2
Data Structures | Queue | Question 2
Advantages and Disadvantages of Linked List
Advantages of vector over array in C++
Data Structures | Queue | Question 11
Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
|
[
{
"code": null,
"e": 26061,
"s": 26033,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 26588,
"s": 26061,
"text": "A 3-ary max heap is like a binary max heap, but instead of 2 children, nodes have 3 children. A 3-ary heap can be represented by an array as follows: The root is stored in the first location, a[0], nodes in the next level, from left to right, is stored from a[1] to a[3]. The nodes from the second level of the tree from left to right are stored from a[4] location onward. An item x can be inserted into a 3-ary heap containing n items by placing x in the location a[n] and pushing it up the tree to satisfy the heap property."
},
{
"code": null,
"e": 26866,
"s": 26588,
"text": "Which one of the following is a valid sequence of elements in an array representing 3-ary max heap?(A) 1, 3, 5, 6, 8, 9(B) 9, 6, 3, 1, 8, 5(C) 9, 3, 6, 8, 5, 1(D) 9, 5, 6, 8, 3, 1Answer: (D)Explanation: Following 3-ary Max Heap can be constructed from sequence given option (D)"
},
{
"code": null,
"e": 27140,
"s": 26866,
"text": " 9\n / | \\\n / | \\\n 5 6 8\n / |\n / |\n 3 1\n"
},
{
"code": null,
"e": 27162,
"s": 27140,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 27178,
"s": 27162,
"text": "Data Structures"
},
{
"code": null,
"e": 27199,
"s": 27178,
"text": "Data Structures-Heap"
},
{
"code": null,
"e": 27212,
"s": 27199,
"text": "Heap Quizzes"
},
{
"code": null,
"e": 27228,
"s": 27212,
"text": "Data Structures"
},
{
"code": null,
"e": 27244,
"s": 27228,
"text": "Data Structures"
},
{
"code": null,
"e": 27342,
"s": 27244,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27420,
"s": 27342,
"text": "Count number of times each Edge appears in all possible paths of a given Tree"
},
{
"code": null,
"e": 27481,
"s": 27420,
"text": "Difference between Singly linked list and Doubly linked list"
},
{
"code": null,
"e": 27526,
"s": 27481,
"text": "Program to create Custom Vector Class in C++"
},
{
"code": null,
"e": 27558,
"s": 27526,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 27595,
"s": 27558,
"text": "Data Structures | Stack | Question 2"
},
{
"code": null,
"e": 27632,
"s": 27595,
"text": "Data Structures | Queue | Question 2"
},
{
"code": null,
"e": 27676,
"s": 27632,
"text": "Advantages and Disadvantages of Linked List"
},
{
"code": null,
"e": 27715,
"s": 27676,
"text": "Advantages of vector over array in C++"
},
{
"code": null,
"e": 27753,
"s": 27715,
"text": "Data Structures | Queue | Question 11"
}
] |
Select DataFrame Rows where Column Values are in Range in R - GeeksforGeeks
|
23 Sep, 2021
In this article, we will discuss how to select dataframe rows where column values are in a range in R programming language.
Data frame indexing can be used to extract rows or columns from the dataframe. The condition can be applied to the specific columns of the dataframe and combined using the logical operator. The logical values in terms of TRUE or FALSE are returned where the TRUE values indicate the rows satisfying the condition. The selected rows are then extracted using the returned row indexes.
Syntax:
dataframe[condition to define range]
Example: Select rows where column values are in the range
R
# create first dataframedata_frame1 < -data.frame(col1=c(rep('Grp1', 2), rep('Grp2', 2), rep('Grp3', 2)), col2=rep(1: 3, 2), col3=rep(1: 2, 3), col4=letters[1:6] ) print("Original DataFrame")print(data_frame1) filtered_rows < - data_frame1$col2 >= 2 & data_frame1$col2 < 4data_frame_mod < - data_frame1[filtered_rows, ] print("Extracted DataFrame")print(data_frame_mod)
Output:
[1] "Original DataFrame"
col1 col2 col3 col4
1 Grp1 1 1 a
2 Grp1 2 2 b
3 Grp2 3 1 c
4 Grp2 1 2 d
5 Grp3 2 1 e
6 Grp3 3 2 f
[1] "Extracted DataFrame"
col1 col2 col3 col4
2 Grp1 2 2 b
3 Grp2 3 1 c
5 Grp3 2 1 e
6 Grp3 3 2 f
Conditions can also be applied over multiple columns of the dataframe and connected using a logical operator.
Example: Selecting columns by applying conditions over multiple columns.
R
# create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1:3,2), col3=rep(1:2,3), col4 = letters[1:6] ) print("Original DataFrame")print(data_frame1) filtered_rows <- data_frame1$col4 == 'a' | data_frame1$col3==2data_frame_mod <- data_frame1[filtered_rows ,] print("Extracted DataFrame")print(data_frame_mod)
Output:
[1] "Original DataFrame"
col1 col2 col3 col4
1 Grp1 1 1 a
2 Grp1 2 2 b
3 Grp2 3 1 c
4 Grp2 1 2 d
5 Grp3 2 1 e
6 Grp3 3 2 f
[1] "Extracted DataFrame"
col1 col2 col3 col4
1 Grp1 1 1 a
2 Grp1 2 2 b
4 Grp2 1 2 d
6 Grp3 3 2 f
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 26611,
"s": 26487,
"text": "In this article, we will discuss how to select dataframe rows where column values are in a range in R programming language."
},
{
"code": null,
"e": 26996,
"s": 26611,
"text": "Data frame indexing can be used to extract rows or columns from the dataframe. The condition can be applied to the specific columns of the dataframe and combined using the logical operator. The logical values in terms of TRUE or FALSE are returned where the TRUE values indicate the rows satisfying the condition. The selected rows are then extracted using the returned row indexes. "
},
{
"code": null,
"e": 27004,
"s": 26996,
"text": "Syntax:"
},
{
"code": null,
"e": 27041,
"s": 27004,
"text": "dataframe[condition to define range]"
},
{
"code": null,
"e": 27099,
"s": 27041,
"text": "Example: Select rows where column values are in the range"
},
{
"code": null,
"e": 27101,
"s": 27099,
"text": "R"
},
{
"code": "# create first dataframedata_frame1 < -data.frame(col1=c(rep('Grp1', 2), rep('Grp2', 2), rep('Grp3', 2)), col2=rep(1: 3, 2), col3=rep(1: 2, 3), col4=letters[1:6] ) print(\"Original DataFrame\")print(data_frame1) filtered_rows < - data_frame1$col2 >= 2 & data_frame1$col2 < 4data_frame_mod < - data_frame1[filtered_rows, ] print(\"Extracted DataFrame\")print(data_frame_mod)",
"e": 27638,
"s": 27101,
"text": null
},
{
"code": null,
"e": 27646,
"s": 27638,
"text": "Output:"
},
{
"code": null,
"e": 27970,
"s": 27646,
"text": "[1] \"Original DataFrame\" \ncol1 col2 col3 col4 \n1 Grp1 1 1 a \n2 Grp1 2 2 b \n3 Grp2 3 1 c \n4 Grp2 1 2 d \n5 Grp3 2 1 e \n6 Grp3 3 2 f \n[1] \"Extracted DataFrame\" \ncol1 col2 col3 col4 \n2 Grp1 2 2 b \n3 Grp2 3 1 c \n5 Grp3 2 1 e \n6 Grp3 3 2 f"
},
{
"code": null,
"e": 28081,
"s": 27970,
"text": "Conditions can also be applied over multiple columns of the dataframe and connected using a logical operator. "
},
{
"code": null,
"e": 28155,
"s": 28081,
"text": "Example: Selecting columns by applying conditions over multiple columns. "
},
{
"code": null,
"e": 28157,
"s": 28155,
"text": "R"
},
{
"code": "# create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1:3,2), col3=rep(1:2,3), col4 = letters[1:6] ) print(\"Original DataFrame\")print(data_frame1) filtered_rows <- data_frame1$col4 == 'a' | data_frame1$col3==2data_frame_mod <- data_frame1[filtered_rows ,] print(\"Extracted DataFrame\")print(data_frame_mod)",
"e": 28675,
"s": 28157,
"text": null
},
{
"code": null,
"e": 28683,
"s": 28675,
"text": "Output:"
},
{
"code": null,
"e": 29008,
"s": 28683,
"text": "[1] \"Original DataFrame\" \ncol1 col2 col3 col4 \n1 Grp1 1 1 a \n2 Grp1 2 2 b \n3 Grp2 3 1 c \n4 Grp2 1 2 d \n5 Grp3 2 1 e \n6 Grp3 3 2 f \n[1] \"Extracted DataFrame\" \n col1 col2 col3 col4 \n1 Grp1 1 1 a \n2 Grp1 2 2 b \n4 Grp2 1 2 d \n6 Grp3 3 2 f"
},
{
"code": null,
"e": 29015,
"s": 29008,
"text": "Picked"
},
{
"code": null,
"e": 29036,
"s": 29015,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 29048,
"s": 29036,
"text": "R-DataFrame"
},
{
"code": null,
"e": 29059,
"s": 29048,
"text": "R Language"
},
{
"code": null,
"e": 29070,
"s": 29059,
"text": "R Programs"
},
{
"code": null,
"e": 29168,
"s": 29070,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29220,
"s": 29168,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29255,
"s": 29220,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29293,
"s": 29255,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29351,
"s": 29293,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29394,
"s": 29351,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29452,
"s": 29394,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29495,
"s": 29452,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29544,
"s": 29495,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29594,
"s": 29544,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
Maximum sum of pairs with specific difference - GeeksforGeeks
|
12 May, 2022
Given an array of integers and a number k. We can pair two numbers of the array if the difference between them is strictly less than k. The task is to find the maximum possible sum of disjoint pairs. Sum of P pairs is the sum of all 2P numbers of pairs.
Examples:
Input : arr[] = {3, 5, 10, 15, 17, 12, 9}, K = 4Output : 62Explanation:Then disjoint pairs with difference less than K are, (3, 5), (10, 12), (15, 17) So maximum sum which we can get is 3 + 5 + 12 + 10 + 15 + 17 = 62Note that an alternate way to form disjoint pairs is, (3, 5), (9, 12), (15, 17), but this pairing produces lesser sum.
Input : arr[] = {5, 15, 10, 300}, k = 12Output : 25
Approach:First, we sort the given array in increasing order. Once array is sorted, we traverse the array. For every element, we try to pair it with its previous element first. Why do we prefer previous element? Let arr[i] can be paired with arr[i-1] and arr[i-2] (i.e. arr[i] – arr[i-1] < K and arr[i]-arr[i-2] < K). Since the array is sorted, value of arr[i-1] would be more than arr[i-2]. Also, we need to pair with difference less than k, it means if arr[i-2] can be paired, then arr[i-1] can also be paired in a sorted array. Now observing the above facts, we can formulate our dynamic programming solution as below, Let dp[i] denotes the maximum disjoint pair sum we can achieve using first i elements of the array. Assume currently, we are at i’th position, then there are two possibilities for us.
Pair up i with (i-1)th element, i.e.
dp[i] = dp[i-2] + arr[i] + arr[i-1]
Don't pair up, i.e.
dp[i] = dp[i-1]
Above iteration takes O(N) time and sorting of array will take O(N log N) time so total time complexity of the solution will be O(N log N)
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find maximum pair sum whose// difference is less than K#include <bits/stdc++.h>using namespace std; // method to return maximum sum we can get by// finding less than K difference pairint maxSumPairWithDifferenceLessThanK(int arr[], int N, int K){ // Sort input array in ascending order. sort(arr, arr+N); // dp[i] denotes the maximum disjoint pair sum // we can achieve using first i elements int dp[N]; // if no element then dp value will be 0 dp[0] = 0; for (int i = 1; i < N; i++) { // first give previous value to dp[i] i.e. // no pairing with (i-1)th element dp[i] = dp[i-1]; // if current and previous element can form a pair if (arr[i] - arr[i-1] < K) { // update dp[i] by choosing maximum between // pairing and not pairing if (i >= 2) dp[i] = max(dp[i], dp[i-2] + arr[i] + arr[i-1]); else dp[i] = max(dp[i], arr[i] + arr[i-1]); } } // last index will have the result return dp[N - 1];} // Driver code to test above methodsint main(){ int arr[] = {3, 5, 10, 15, 17, 12, 9}; int N = sizeof(arr)/sizeof(int); int K = 4; cout << maxSumPairWithDifferenceLessThanK(arr, N, K); return 0;}
// Java program to find maximum pair sum whose// difference is less than K import java.io.*;import java.util.*; class GFG { // method to return maximum sum we can get by // finding less than K difference pair static int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K) { // Sort input array in ascending order. Arrays.sort(arr); // dp[i] denotes the maximum disjoint pair sum // we can achieve using first i elements int dp[] = new int[N]; // if no element then dp value will be 0 dp[0] = 0; for (int i = 1; i < N; i++) { // first give previous value to dp[i] i.e. // no pairing with (i-1)th element dp[i] = dp[i-1]; // if current and previous element can form a pair if (arr[i] - arr[i-1] < K) { // update dp[i] by choosing maximum between // pairing and not pairing if (i >= 2) dp[i] = Math.max(dp[i], dp[i-2] + arr[i] + arr[i-1]); else dp[i] = Math.max(dp[i], arr[i] + arr[i-1]); } } // last index will have the result return dp[N - 1]; } // Driver code to test above methods public static void main (String[] args) { int arr[] = {3, 5, 10, 15, 17, 12, 9}; int N = arr.length; int K = 4; System.out.println ( maxSumPairWithDifferenceLessThanK( arr, N, K)); }} //This code is contributed by vt_m.
# Python3 program to find maximum pair# sum whose difference is less than K # method to return maximum sum we can# get by get by finding less than K# difference pairdef maxSumPairWithDifferenceLessThanK(arr, N, K): # Sort input array in ascending order. arr.sort() # dp[i] denotes the maximum disjoint # pair sum we can achieve using first # i elements dp = [0] * N # if no element then dp value will be 0 dp[0] = 0 for i in range(1, N): # first give previous value to # dp[i] i.e. no pairing with # (i-1)th element dp[i] = dp[i-1] # if current and previous element # can form a pair if (arr[i] - arr[i-1] < K): # update dp[i] by choosing # maximum between pairing # and not pairing if (i >= 2): dp[i] = max(dp[i], dp[i-2] + arr[i] + arr[i-1]); else: dp[i] = max(dp[i], arr[i] + arr[i-1]); # last index will have the result return dp[N - 1] # Driver code to test above methodsarr = [3, 5, 10, 15, 17, 12, 9]N = len(arr)K = 4print(maxSumPairWithDifferenceLessThanK(arr, N, K)) # This code is contributed by Smitha Dinesh Semwal
// C# program to find maximum pair sum whose// difference is less than Kusing System; class GFG { // method to return maximum sum we can get by // finding less than K difference pair static int maxSumPairWithDifferenceLessThanK(int []arr, int N, int K) { // Sort input array in ascending order. Array.Sort(arr); // dp[i] denotes the maximum disjoint pair sum // we can achieve using first i elements int []dp = new int[N]; // if no element then dp value will be 0 dp[0] = 0; for (int i = 1; i < N; i++) { // first give previous value to dp[i] i.e. // no pairing with (i-1)th element dp[i] = dp[i-1]; // if current and previous element can form // a pair if (arr[i] - arr[i-1] < K) { // update dp[i] by choosing maximum // between pairing and not pairing if (i >= 2) dp[i] = Math.Max(dp[i], dp[i-2] + arr[i] + arr[i-1]); else dp[i] = Math.Max(dp[i], arr[i] + arr[i-1]); } } // last index will have the result return dp[N - 1]; } // Driver code to test above methods public static void Main () { int []arr = {3, 5, 10, 15, 17, 12, 9}; int N = arr.Length; int K = 4; Console.WriteLine( maxSumPairWithDifferenceLessThanK(arr, N, K)); }} // This code is contributed by anuj_67.
<?php// Php program to find maximum pair sum whose// difference is less than K // method to return maximum sum we can get by// finding less than K difference pairfunction maxSumPairWithDifferenceLessThanK($arr, $N, $K){ // Sort input array in ascending order. sort($arr) ; // dp[i] denotes the maximum disjoint pair sum // we can achieve using first i elements $dp = array() ; // if no element then dp value will be 0 $dp[0] = 0; for ($i = 1; $i < $N; $i++) { // first give previous value to dp[i] i.e. // no pairing with (i-1)th element $dp[$i] = $dp[$i-1]; // if current and previous element can form a pair if ($arr[$i] - $arr[$i-1] < $K) { // update dp[i] by choosing maximum between // pairing and not pairing if ($i >= 2) $dp[$i] = max($dp[$i], $dp[$i-2] + $arr[$i] + $arr[$i-1]); else $dp[$i] = max($dp[$i], $arr[$i] + $arr[$i-1]); } } // last index will have the result return $dp[$N - 1];} // Driver code $arr = array(3, 5, 10, 15, 17, 12, 9); $N = sizeof($arr) ; $K = 4; echo maxSumPairWithDifferenceLessThanK($arr, $N, $K); // This code is contributed by Ryuga?>
<script> // Javascript program to find maximum pair sum whose// difference is less than K // method to return maximum sum we can get by // finding less than K difference pair function maxSumPairWithDifferenceLessThanK(arr, N, K) { // Sort input array in ascending order. arr.sort(); // dp[i] denotes the maximum disjoint pair sum // we can achieve using first i elements let dp = []; // if no element then dp value will be 0 dp[0] = 0; for (let i = 1; i < N; i++) { // first give previous value to dp[i] i.e. // no pairing with (i-1)th element dp[i] = dp[i-1]; // if current and previous element can form a pair if (arr[i] - arr[i-1] < K) { // update dp[i] by choosing maximum between // pairing and not pairing if (i >= 2) dp[i] = Math.max(dp[i], dp[i-2] + arr[i] + arr[i-1]); else dp[i] = Math.max(dp[i], arr[i] + arr[i-1]); } } // last index will have the result return dp[N - 1]; } // Driver code to test above methods let arr = [3, 5, 10, 15, 17, 12, 9]; let N = arr.length; let K = 4; document.write( maxSumPairWithDifferenceLessThanK( arr, N, K));// This code is contributed by avijitmondal1998.</script>
62
Time complexity: O(N Log N) Auxiliary Space: O(N)
An optimised solution contributed by Amit Sane is given below,
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find maximum pair sum whose// difference is less than K#include <bits/stdc++.h>using namespace std; // Method to return maximum sum we can get by// finding less than K difference pairsint maxSumPair(int arr[], int N, int k){ int maxSum = 0; // Sort elements to ensure every i and i-1 is closest // possible pair sort(arr, arr + N); // To get maximum possible sum, // iterate from largest to // smallest, giving larger // numbers priority over smaller // numbers. for (int i = N - 1; i > 0; --i) { // Case I: Diff of arr[i] and arr[i-1] // is less than K,add to maxSum // Case II: Diff between arr[i] and arr[i-1] is not // less than K, move to next i since with // sorting we know, arr[i]-arr[i-1] < // rr[i]-arr[i-2] and so on. if (arr[i] - arr[i - 1] < k) { // Assuming only positive numbers. maxSum += arr[i]; maxSum += arr[i - 1]; // When a match is found skip this pair --i; } } return maxSum;} // Driver codeint main(){ int arr[] = { 3, 5, 10, 15, 17, 12, 9 }; int N = sizeof(arr) / sizeof(int); int K = 4; cout << maxSumPair(arr, N, K); return 0;}
// Java program to find maximum pair sum whose// difference is less than K import java.io.*;import java.util.*; class GFG { // Method to return maximum sum we can get by // finding less than K difference pairs static int maxSumPairWithDifferenceLessThanK(int arr[], int N, int k) { int maxSum = 0; // Sort elements to ensure every i and i-1 is // closest possible pair Arrays.sort(arr); // To get maximum possible sum, // iterate from largest // to smallest, giving larger // numbers priority over // smaller numbers. for (int i = N - 1; i > 0; --i) { // Case I: Diff of arr[i] and arr[i-1] is less // than K, add to maxSum // Case II: Diff between arr[i] and arr[i-1] is // not less than K, move to next i // since with sorting we know, arr[i]-arr[i-1] < // arr[i]-arr[i-2] and so on. if (arr[i] - arr[i - 1] < k) { // Assuming only positive numbers. maxSum += arr[i]; maxSum += arr[i - 1]; // When a match is found skip this pair --i; } } return maxSum; } // Driver code public static void main(String[] args) { int arr[] = { 3, 5, 10, 15, 17, 12, 9 }; int N = arr.length; int K = 4; System.out.println( maxSumPairWithDifferenceLessThanK(arr, N, K)); }} // This code is contributed by vt_m.
# Python3 program to find maximum pair sum# whose difference is less than K # Method to return maximum sum we can# get by finding less than K difference# pairs def maxSumPairWithDifferenceLessThanK(arr, N, k): maxSum = 0 # Sort elements to ensure every i and # i-1 is closest possible pair arr.sort() # To get maximum possible sum, iterate # from largest to smallest, giving larger # numbers priority over smaller numbers. i = N - 1 while (i > 0): # Case I: Diff of arr[i] and arr[i-1] # is less than K, add to maxSum # Case II: Diff between arr[i] and # arr[i-1] is not less than K, # move to next i since with sorting # we know, arr[i]-arr[i-1] < arr[i]-arr[i-2] # and so on. if (arr[i] - arr[i - 1] < k): # Assuming only positive numbers. maxSum += arr[i] maxSum += arr[i - 1] # When a match is found skip this pair i -= 1 i -= 1 return maxSum # Driver Codearr = [3, 5, 10, 15, 17, 12, 9]N = len(arr) K = 4print(maxSumPairWithDifferenceLessThanK(arr, N, K)) # This code is contributed by mits
// C# program to find maximum pair sum whose// difference is less than Kusing System;class GFG { // Method to return maximum sum we can get by // finding less than K difference pairs static int maxSumPairWithDifferenceLessThanK(int []arr, int N, int k) { int maxSum = 0; // Sort elements to ensure // every i and i-1 is closest // possible pair Array.Sort(arr); // To get maximum possible sum, // iterate from largest // to smallest, giving larger // numbers priority over // smaller numbers. for (int i = N-1; i > 0; --i) { /* Case I: Diff of arr[i] and arr[i-1] is less than K, add to maxSum Case II: Diff between arr[i] and arr[i-1] is not less than K, move to next i since with sorting we know, arr[i]-arr[i-1] < arr[i]-arr[i-2] and so on.*/ if (arr[i] - arr[i-1] < k) { // Assuming only positive numbers. maxSum += arr[i]; maxSum += arr[i - 1]; // When a match is found // skip this pair --i; } } return maxSum; } // Driver Code public static void Main () { int []arr = {3, 5, 10, 15, 17, 12, 9}; int N = arr.Length; int K = 4; Console.Write( maxSumPairWithDifferenceLessThanK(arr, N, K)); }} // This code is contributed by nitin mittal.
<?php// PHP program to find maximum pair sum // whose difference is less than K // Method to return maximum sum we can // get by finding less than K difference// pairsfunction maxSumPairWithDifferenceLessThanK($arr, $N, $k){ $maxSum = 0; // Sort elements to ensure every i and // i-1 is closest possible pair sort($arr); // To get maximum possible sum, iterate // from largest to smallest, giving larger // numbers priority over smaller numbers. for ($i = $N - 1; $i > 0; --$i) { // Case I: Diff of arr[i] and arr[i-1] // is less than K, add to maxSum // Case II: Diff between arr[i] and // arr[i-1] is not less than K, // move to next i since with sorting // we know, arr[i]-arr[i-1] < arr[i]-arr[i-2] // and so on. if ($arr[$i] - $arr[$i - 1] < $k) { // Assuming only positive numbers. $maxSum += $arr[$i]; $maxSum += $arr[$i - 1]; // When a match is found skip this pair --$i; } } return $maxSum;} // Driver Code$arr = array(3, 5, 10, 15, 17, 12, 9);$N = sizeof($arr); $K = 4;echo maxSumPairWithDifferenceLessThanK($arr, $N, $K); // This code is contributed// by Sach_Code ?>
<script> // Javascript program to find// maximum pair sum whose// difference is less than K// Method to return maximum sum we can get by// finding less than K difference pairsfunction maxSumPairWithDifferenceLessThanK(arr, N, k){ var maxSum = 0; // Sort elements to ensure every i and i-1 is // closest possible pair arr.sort((a,b)=>a-b); // To get maximum possible sum, // iterate from largest // to smallest, giving larger // numbers priority over // smaller numbers. for (i = N - 1; i > 0; --i) { // Case I: Diff of arr[i] and arr[i-1] is less // than K, add to maxSum // Case II: Diff between arr[i] and arr[i-1] is // not less than K, move to next i // since with sorting we know, arr[i]-arr[i-1] < // arr[i]-arr[i-2] and so on. if (arr[i] - arr[i - 1] < k) { // Assuming only positive numbers. maxSum += arr[i]; maxSum += arr[i - 1]; // When a match is found skip this pair --i; } } return maxSum;} // Driver codevar arr = [ 3, 5, 10, 15, 17, 12, 9 ];var N = arr.length;var K = 4; document.write(maxSumPairWithDifferenceLessThanK(arr, N, K)); // This code is contributed by 29AjayKumar </script>
62
Time complexity: O(N Log N) Auxiliary Space: O(1)
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
vt_m
ankthon
Sach_Code
Mithun Kumar
ashsihpal7861
avijitmondal1998
29AjayKumar
surinderdawra388
Arrays
Dynamic Programming
Arrays
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Count pairs with given sum
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
|
[
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 26321,
"s": 26067,
"text": "Given an array of integers and a number k. We can pair two numbers of the array if the difference between them is strictly less than k. The task is to find the maximum possible sum of disjoint pairs. Sum of P pairs is the sum of all 2P numbers of pairs."
},
{
"code": null,
"e": 26331,
"s": 26321,
"text": "Examples:"
},
{
"code": null,
"e": 26668,
"s": 26331,
"text": "Input : arr[] = {3, 5, 10, 15, 17, 12, 9}, K = 4Output : 62Explanation:Then disjoint pairs with difference less than K are, (3, 5), (10, 12), (15, 17) So maximum sum which we can get is 3 + 5 + 12 + 10 + 15 + 17 = 62Note that an alternate way to form disjoint pairs is, (3, 5), (9, 12), (15, 17), but this pairing produces lesser sum."
},
{
"code": null,
"e": 26721,
"s": 26668,
"text": "Input : arr[] = {5, 15, 10, 300}, k = 12Output : 25"
},
{
"code": null,
"e": 27527,
"s": 26721,
"text": "Approach:First, we sort the given array in increasing order. Once array is sorted, we traverse the array. For every element, we try to pair it with its previous element first. Why do we prefer previous element? Let arr[i] can be paired with arr[i-1] and arr[i-2] (i.e. arr[i] – arr[i-1] < K and arr[i]-arr[i-2] < K). Since the array is sorted, value of arr[i-1] would be more than arr[i-2]. Also, we need to pair with difference less than k, it means if arr[i-2] can be paired, then arr[i-1] can also be paired in a sorted array. Now observing the above facts, we can formulate our dynamic programming solution as below, Let dp[i] denotes the maximum disjoint pair sum we can achieve using first i elements of the array. Assume currently, we are at i’th position, then there are two possibilities for us. "
},
{
"code": null,
"e": 27655,
"s": 27527,
"text": " Pair up i with (i-1)th element, i.e. \n dp[i] = dp[i-2] + arr[i] + arr[i-1]\n Don't pair up, i.e. \n dp[i] = dp[i-1] "
},
{
"code": null,
"e": 27795,
"s": 27655,
"text": "Above iteration takes O(N) time and sorting of array will take O(N log N) time so total time complexity of the solution will be O(N log N) "
},
{
"code": null,
"e": 27799,
"s": 27795,
"text": "C++"
},
{
"code": null,
"e": 27804,
"s": 27799,
"text": "Java"
},
{
"code": null,
"e": 27812,
"s": 27804,
"text": "Python3"
},
{
"code": null,
"e": 27815,
"s": 27812,
"text": "C#"
},
{
"code": null,
"e": 27819,
"s": 27815,
"text": "PHP"
},
{
"code": null,
"e": 27830,
"s": 27819,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum pair sum whose// difference is less than K#include <bits/stdc++.h>using namespace std; // method to return maximum sum we can get by// finding less than K difference pairint maxSumPairWithDifferenceLessThanK(int arr[], int N, int K){ // Sort input array in ascending order. sort(arr, arr+N); // dp[i] denotes the maximum disjoint pair sum // we can achieve using first i elements int dp[N]; // if no element then dp value will be 0 dp[0] = 0; for (int i = 1; i < N; i++) { // first give previous value to dp[i] i.e. // no pairing with (i-1)th element dp[i] = dp[i-1]; // if current and previous element can form a pair if (arr[i] - arr[i-1] < K) { // update dp[i] by choosing maximum between // pairing and not pairing if (i >= 2) dp[i] = max(dp[i], dp[i-2] + arr[i] + arr[i-1]); else dp[i] = max(dp[i], arr[i] + arr[i-1]); } } // last index will have the result return dp[N - 1];} // Driver code to test above methodsint main(){ int arr[] = {3, 5, 10, 15, 17, 12, 9}; int N = sizeof(arr)/sizeof(int); int K = 4; cout << maxSumPairWithDifferenceLessThanK(arr, N, K); return 0;}",
"e": 29122,
"s": 27830,
"text": null
},
{
"code": "// Java program to find maximum pair sum whose// difference is less than K import java.io.*;import java.util.*; class GFG { // method to return maximum sum we can get by // finding less than K difference pair static int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K) { // Sort input array in ascending order. Arrays.sort(arr); // dp[i] denotes the maximum disjoint pair sum // we can achieve using first i elements int dp[] = new int[N]; // if no element then dp value will be 0 dp[0] = 0; for (int i = 1; i < N; i++) { // first give previous value to dp[i] i.e. // no pairing with (i-1)th element dp[i] = dp[i-1]; // if current and previous element can form a pair if (arr[i] - arr[i-1] < K) { // update dp[i] by choosing maximum between // pairing and not pairing if (i >= 2) dp[i] = Math.max(dp[i], dp[i-2] + arr[i] + arr[i-1]); else dp[i] = Math.max(dp[i], arr[i] + arr[i-1]); } } // last index will have the result return dp[N - 1]; } // Driver code to test above methods public static void main (String[] args) { int arr[] = {3, 5, 10, 15, 17, 12, 9}; int N = arr.length; int K = 4; System.out.println ( maxSumPairWithDifferenceLessThanK( arr, N, K)); }} //This code is contributed by vt_m.",
"e": 30874,
"s": 29122,
"text": null
},
{
"code": "# Python3 program to find maximum pair# sum whose difference is less than K # method to return maximum sum we can# get by get by finding less than K# difference pairdef maxSumPairWithDifferenceLessThanK(arr, N, K): # Sort input array in ascending order. arr.sort() # dp[i] denotes the maximum disjoint # pair sum we can achieve using first # i elements dp = [0] * N # if no element then dp value will be 0 dp[0] = 0 for i in range(1, N): # first give previous value to # dp[i] i.e. no pairing with # (i-1)th element dp[i] = dp[i-1] # if current and previous element # can form a pair if (arr[i] - arr[i-1] < K): # update dp[i] by choosing # maximum between pairing # and not pairing if (i >= 2): dp[i] = max(dp[i], dp[i-2] + arr[i] + arr[i-1]); else: dp[i] = max(dp[i], arr[i] + arr[i-1]); # last index will have the result return dp[N - 1] # Driver code to test above methodsarr = [3, 5, 10, 15, 17, 12, 9]N = len(arr)K = 4print(maxSumPairWithDifferenceLessThanK(arr, N, K)) # This code is contributed by Smitha Dinesh Semwal",
"e": 32096,
"s": 30874,
"text": null
},
{
"code": "// C# program to find maximum pair sum whose// difference is less than Kusing System; class GFG { // method to return maximum sum we can get by // finding less than K difference pair static int maxSumPairWithDifferenceLessThanK(int []arr, int N, int K) { // Sort input array in ascending order. Array.Sort(arr); // dp[i] denotes the maximum disjoint pair sum // we can achieve using first i elements int []dp = new int[N]; // if no element then dp value will be 0 dp[0] = 0; for (int i = 1; i < N; i++) { // first give previous value to dp[i] i.e. // no pairing with (i-1)th element dp[i] = dp[i-1]; // if current and previous element can form // a pair if (arr[i] - arr[i-1] < K) { // update dp[i] by choosing maximum // between pairing and not pairing if (i >= 2) dp[i] = Math.Max(dp[i], dp[i-2] + arr[i] + arr[i-1]); else dp[i] = Math.Max(dp[i], arr[i] + arr[i-1]); } } // last index will have the result return dp[N - 1]; } // Driver code to test above methods public static void Main () { int []arr = {3, 5, 10, 15, 17, 12, 9}; int N = arr.Length; int K = 4; Console.WriteLine( maxSumPairWithDifferenceLessThanK(arr, N, K)); }} // This code is contributed by anuj_67.",
"e": 33799,
"s": 32096,
"text": null
},
{
"code": "<?php// Php program to find maximum pair sum whose// difference is less than K // method to return maximum sum we can get by// finding less than K difference pairfunction maxSumPairWithDifferenceLessThanK($arr, $N, $K){ // Sort input array in ascending order. sort($arr) ; // dp[i] denotes the maximum disjoint pair sum // we can achieve using first i elements $dp = array() ; // if no element then dp value will be 0 $dp[0] = 0; for ($i = 1; $i < $N; $i++) { // first give previous value to dp[i] i.e. // no pairing with (i-1)th element $dp[$i] = $dp[$i-1]; // if current and previous element can form a pair if ($arr[$i] - $arr[$i-1] < $K) { // update dp[i] by choosing maximum between // pairing and not pairing if ($i >= 2) $dp[$i] = max($dp[$i], $dp[$i-2] + $arr[$i] + $arr[$i-1]); else $dp[$i] = max($dp[$i], $arr[$i] + $arr[$i-1]); } } // last index will have the result return $dp[$N - 1];} // Driver code $arr = array(3, 5, 10, 15, 17, 12, 9); $N = sizeof($arr) ; $K = 4; echo maxSumPairWithDifferenceLessThanK($arr, $N, $K); // This code is contributed by Ryuga?>",
"e": 35060,
"s": 33799,
"text": null
},
{
"code": "<script> // Javascript program to find maximum pair sum whose// difference is less than K // method to return maximum sum we can get by // finding less than K difference pair function maxSumPairWithDifferenceLessThanK(arr, N, K) { // Sort input array in ascending order. arr.sort(); // dp[i] denotes the maximum disjoint pair sum // we can achieve using first i elements let dp = []; // if no element then dp value will be 0 dp[0] = 0; for (let i = 1; i < N; i++) { // first give previous value to dp[i] i.e. // no pairing with (i-1)th element dp[i] = dp[i-1]; // if current and previous element can form a pair if (arr[i] - arr[i-1] < K) { // update dp[i] by choosing maximum between // pairing and not pairing if (i >= 2) dp[i] = Math.max(dp[i], dp[i-2] + arr[i] + arr[i-1]); else dp[i] = Math.max(dp[i], arr[i] + arr[i-1]); } } // last index will have the result return dp[N - 1]; } // Driver code to test above methods let arr = [3, 5, 10, 15, 17, 12, 9]; let N = arr.length; let K = 4; document.write( maxSumPairWithDifferenceLessThanK( arr, N, K));// This code is contributed by avijitmondal1998.</script>",
"e": 36692,
"s": 35060,
"text": null
},
{
"code": null,
"e": 36695,
"s": 36692,
"text": "62"
},
{
"code": null,
"e": 36745,
"s": 36695,
"text": "Time complexity: O(N Log N) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 36809,
"s": 36745,
"text": "An optimised solution contributed by Amit Sane is given below, "
},
{
"code": null,
"e": 36813,
"s": 36809,
"text": "C++"
},
{
"code": null,
"e": 36818,
"s": 36813,
"text": "Java"
},
{
"code": null,
"e": 36826,
"s": 36818,
"text": "Python3"
},
{
"code": null,
"e": 36829,
"s": 36826,
"text": "C#"
},
{
"code": null,
"e": 36833,
"s": 36829,
"text": "PHP"
},
{
"code": null,
"e": 36844,
"s": 36833,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum pair sum whose// difference is less than K#include <bits/stdc++.h>using namespace std; // Method to return maximum sum we can get by// finding less than K difference pairsint maxSumPair(int arr[], int N, int k){ int maxSum = 0; // Sort elements to ensure every i and i-1 is closest // possible pair sort(arr, arr + N); // To get maximum possible sum, // iterate from largest to // smallest, giving larger // numbers priority over smaller // numbers. for (int i = N - 1; i > 0; --i) { // Case I: Diff of arr[i] and arr[i-1] // is less than K,add to maxSum // Case II: Diff between arr[i] and arr[i-1] is not // less than K, move to next i since with // sorting we know, arr[i]-arr[i-1] < // rr[i]-arr[i-2] and so on. if (arr[i] - arr[i - 1] < k) { // Assuming only positive numbers. maxSum += arr[i]; maxSum += arr[i - 1]; // When a match is found skip this pair --i; } } return maxSum;} // Driver codeint main(){ int arr[] = { 3, 5, 10, 15, 17, 12, 9 }; int N = sizeof(arr) / sizeof(int); int K = 4; cout << maxSumPair(arr, N, K); return 0;}",
"e": 38101,
"s": 36844,
"text": null
},
{
"code": "// Java program to find maximum pair sum whose// difference is less than K import java.io.*;import java.util.*; class GFG { // Method to return maximum sum we can get by // finding less than K difference pairs static int maxSumPairWithDifferenceLessThanK(int arr[], int N, int k) { int maxSum = 0; // Sort elements to ensure every i and i-1 is // closest possible pair Arrays.sort(arr); // To get maximum possible sum, // iterate from largest // to smallest, giving larger // numbers priority over // smaller numbers. for (int i = N - 1; i > 0; --i) { // Case I: Diff of arr[i] and arr[i-1] is less // than K, add to maxSum // Case II: Diff between arr[i] and arr[i-1] is // not less than K, move to next i // since with sorting we know, arr[i]-arr[i-1] < // arr[i]-arr[i-2] and so on. if (arr[i] - arr[i - 1] < k) { // Assuming only positive numbers. maxSum += arr[i]; maxSum += arr[i - 1]; // When a match is found skip this pair --i; } } return maxSum; } // Driver code public static void main(String[] args) { int arr[] = { 3, 5, 10, 15, 17, 12, 9 }; int N = arr.length; int K = 4; System.out.println( maxSumPairWithDifferenceLessThanK(arr, N, K)); }} // This code is contributed by vt_m.",
"e": 39729,
"s": 38101,
"text": null
},
{
"code": "# Python3 program to find maximum pair sum# whose difference is less than K # Method to return maximum sum we can# get by finding less than K difference# pairs def maxSumPairWithDifferenceLessThanK(arr, N, k): maxSum = 0 # Sort elements to ensure every i and # i-1 is closest possible pair arr.sort() # To get maximum possible sum, iterate # from largest to smallest, giving larger # numbers priority over smaller numbers. i = N - 1 while (i > 0): # Case I: Diff of arr[i] and arr[i-1] # is less than K, add to maxSum # Case II: Diff between arr[i] and # arr[i-1] is not less than K, # move to next i since with sorting # we know, arr[i]-arr[i-1] < arr[i]-arr[i-2] # and so on. if (arr[i] - arr[i - 1] < k): # Assuming only positive numbers. maxSum += arr[i] maxSum += arr[i - 1] # When a match is found skip this pair i -= 1 i -= 1 return maxSum # Driver Codearr = [3, 5, 10, 15, 17, 12, 9]N = len(arr) K = 4print(maxSumPairWithDifferenceLessThanK(arr, N, K)) # This code is contributed by mits",
"e": 40902,
"s": 39729,
"text": null
},
{
"code": "// C# program to find maximum pair sum whose// difference is less than Kusing System;class GFG { // Method to return maximum sum we can get by // finding less than K difference pairs static int maxSumPairWithDifferenceLessThanK(int []arr, int N, int k) { int maxSum = 0; // Sort elements to ensure // every i and i-1 is closest // possible pair Array.Sort(arr); // To get maximum possible sum, // iterate from largest // to smallest, giving larger // numbers priority over // smaller numbers. for (int i = N-1; i > 0; --i) { /* Case I: Diff of arr[i] and arr[i-1] is less than K, add to maxSum Case II: Diff between arr[i] and arr[i-1] is not less than K, move to next i since with sorting we know, arr[i]-arr[i-1] < arr[i]-arr[i-2] and so on.*/ if (arr[i] - arr[i-1] < k) { // Assuming only positive numbers. maxSum += arr[i]; maxSum += arr[i - 1]; // When a match is found // skip this pair --i; } } return maxSum; } // Driver Code public static void Main () { int []arr = {3, 5, 10, 15, 17, 12, 9}; int N = arr.Length; int K = 4; Console.Write( maxSumPairWithDifferenceLessThanK(arr, N, K)); }} // This code is contributed by nitin mittal.",
"e": 42695,
"s": 40902,
"text": null
},
{
"code": "<?php// PHP program to find maximum pair sum // whose difference is less than K // Method to return maximum sum we can // get by finding less than K difference// pairsfunction maxSumPairWithDifferenceLessThanK($arr, $N, $k){ $maxSum = 0; // Sort elements to ensure every i and // i-1 is closest possible pair sort($arr); // To get maximum possible sum, iterate // from largest to smallest, giving larger // numbers priority over smaller numbers. for ($i = $N - 1; $i > 0; --$i) { // Case I: Diff of arr[i] and arr[i-1] // is less than K, add to maxSum // Case II: Diff between arr[i] and // arr[i-1] is not less than K, // move to next i since with sorting // we know, arr[i]-arr[i-1] < arr[i]-arr[i-2] // and so on. if ($arr[$i] - $arr[$i - 1] < $k) { // Assuming only positive numbers. $maxSum += $arr[$i]; $maxSum += $arr[$i - 1]; // When a match is found skip this pair --$i; } } return $maxSum;} // Driver Code$arr = array(3, 5, 10, 15, 17, 12, 9);$N = sizeof($arr); $K = 4;echo maxSumPairWithDifferenceLessThanK($arr, $N, $K); // This code is contributed// by Sach_Code ?>",
"e": 43988,
"s": 42695,
"text": null
},
{
"code": "<script> // Javascript program to find// maximum pair sum whose// difference is less than K// Method to return maximum sum we can get by// finding less than K difference pairsfunction maxSumPairWithDifferenceLessThanK(arr, N, k){ var maxSum = 0; // Sort elements to ensure every i and i-1 is // closest possible pair arr.sort((a,b)=>a-b); // To get maximum possible sum, // iterate from largest // to smallest, giving larger // numbers priority over // smaller numbers. for (i = N - 1; i > 0; --i) { // Case I: Diff of arr[i] and arr[i-1] is less // than K, add to maxSum // Case II: Diff between arr[i] and arr[i-1] is // not less than K, move to next i // since with sorting we know, arr[i]-arr[i-1] < // arr[i]-arr[i-2] and so on. if (arr[i] - arr[i - 1] < k) { // Assuming only positive numbers. maxSum += arr[i]; maxSum += arr[i - 1]; // When a match is found skip this pair --i; } } return maxSum;} // Driver codevar arr = [ 3, 5, 10, 15, 17, 12, 9 ];var N = arr.length;var K = 4; document.write(maxSumPairWithDifferenceLessThanK(arr, N, K)); // This code is contributed by 29AjayKumar </script>",
"e": 45251,
"s": 43988,
"text": null
},
{
"code": null,
"e": 45254,
"s": 45251,
"text": "62"
},
{
"code": null,
"e": 45304,
"s": 45254,
"text": "Time complexity: O(N Log N) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 45728,
"s": 45304,
"text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 45741,
"s": 45728,
"text": "nitin mittal"
},
{
"code": null,
"e": 45746,
"s": 45741,
"text": "vt_m"
},
{
"code": null,
"e": 45754,
"s": 45746,
"text": "ankthon"
},
{
"code": null,
"e": 45764,
"s": 45754,
"text": "Sach_Code"
},
{
"code": null,
"e": 45777,
"s": 45764,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 45791,
"s": 45777,
"text": "ashsihpal7861"
},
{
"code": null,
"e": 45808,
"s": 45791,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 45820,
"s": 45808,
"text": "29AjayKumar"
},
{
"code": null,
"e": 45837,
"s": 45820,
"text": "surinderdawra388"
},
{
"code": null,
"e": 45844,
"s": 45837,
"text": "Arrays"
},
{
"code": null,
"e": 45864,
"s": 45844,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 45871,
"s": 45864,
"text": "Arrays"
},
{
"code": null,
"e": 45891,
"s": 45871,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 45989,
"s": 45891,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46020,
"s": 45989,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 46047,
"s": 46020,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 46072,
"s": 46047,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 46110,
"s": 46072,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 46131,
"s": 46110,
"text": "Next Greater Element"
},
{
"code": null,
"e": 46160,
"s": 46131,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 46190,
"s": 46160,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 46224,
"s": 46190,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 46255,
"s": 46224,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
PyQt5 – How to make semi-transparent label ? - GeeksforGeeks
|
26 Mar, 2020
While designing a GUI (Graphical User Interface) application we tend to make lot of labels, but sometimes some labels overlaps each other and only label which is on top is visible, that’s why semi transparent label is needed.
Normal label vs Semi-transparent label –
In order to create semi-transparent labels setStyleSheet() method is used.
Syntax : label.setStyleSheet(“background-color: rgba(255, 255, 255, 10);”)Here we are setting color using RGBA i.e transparency factor, 255 is completely opaque, and an alpha of 0 is completely transparent.
Argument: It takes string as argument.
Action performed : It makes the color of the label transparent.
Code :
# importing the required libraries from PyQt5.QtWidgets import * from PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Label") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget # by default label will display at top left corner self.label_1 = QLabel('back', self) # moving position self.label_1.move(100, 100) # setting up border and background color self.label_1.setStyleSheet("background-color: lightgreen; border: 3px solid green") # creating a label widget # by default label will display at top left corner self.label_2 = QLabel('front', self) # moving position self.label_2.move(140, 100) # setting up border and background # color with transparency factor self.label_2.setStyleSheet("border: 3px solid blue; background-color: rgba(0, 255, 255, 90);") # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window()# start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 26225,
"s": 26197,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 26451,
"s": 26225,
"text": "While designing a GUI (Graphical User Interface) application we tend to make lot of labels, but sometimes some labels overlaps each other and only label which is on top is visible, that’s why semi transparent label is needed."
},
{
"code": null,
"e": 26500,
"s": 26451,
"text": "Normal label vs Semi-transparent label – "
},
{
"code": null,
"e": 26575,
"s": 26500,
"text": "In order to create semi-transparent labels setStyleSheet() method is used."
},
{
"code": null,
"e": 26782,
"s": 26575,
"text": "Syntax : label.setStyleSheet(“background-color: rgba(255, 255, 255, 10);”)Here we are setting color using RGBA i.e transparency factor, 255 is completely opaque, and an alpha of 0 is completely transparent."
},
{
"code": null,
"e": 26821,
"s": 26782,
"text": "Argument: It takes string as argument."
},
{
"code": null,
"e": 26885,
"s": 26821,
"text": "Action performed : It makes the color of the label transparent."
},
{
"code": null,
"e": 26892,
"s": 26885,
"text": "Code :"
},
{
"code": "# importing the required libraries from PyQt5.QtWidgets import * from PyQt5.QtGui import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Label\") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget # by default label will display at top left corner self.label_1 = QLabel('back', self) # moving position self.label_1.move(100, 100) # setting up border and background color self.label_1.setStyleSheet(\"background-color: lightgreen; border: 3px solid green\") # creating a label widget # by default label will display at top left corner self.label_2 = QLabel('front', self) # moving position self.label_2.move(140, 100) # setting up border and background # color with transparency factor self.label_2.setStyleSheet(\"border: 3px solid blue; background-color: rgba(0, 255, 255, 90);\") # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window()# start the appsys.exit(App.exec())",
"e": 28196,
"s": 26892,
"text": null
},
{
"code": null,
"e": 28205,
"s": 28196,
"text": "Output :"
},
{
"code": null,
"e": 28216,
"s": 28205,
"text": "Python-gui"
},
{
"code": null,
"e": 28228,
"s": 28216,
"text": "Python-PyQt"
},
{
"code": null,
"e": 28235,
"s": 28228,
"text": "Python"
},
{
"code": null,
"e": 28333,
"s": 28235,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28351,
"s": 28333,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28386,
"s": 28351,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28418,
"s": 28386,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28440,
"s": 28418,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28482,
"s": 28440,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28512,
"s": 28482,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28538,
"s": 28512,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28582,
"s": 28538,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28611,
"s": 28582,
"text": "*args and **kwargs in Python"
}
] |
aplaymidi Command in Linux with Examples - GeeksforGeeks
|
24 Jun, 2019
aplaymidi command in Linux is used to play standard MIDI(Musical Instrument Digital Interface) files, by sending the content of a MIDI file to an ALSA(Advanced Linux Sound Architecture) MIDI port, sound renderer like timidity or a hardware MIDI device are required to play MIDI files.
Syntax:
aplaymidi [options] [MIDIfile]
Options:
-h or –help: This is used to show all the options and syntax of the command.$ aplaymidi -h
$ aplaymidi -h
-V or –version: It is used to display the current version of the SW.$ aplaymidi -V
$ aplaymidi -V
-l or –list: It is used to display the list of all possible MIDI output ports.$ aplaymidi -l
$ aplaymidi -l
-p or –port=client:port : It specifies ports(s) to play MIDI to.$ aplaymidi -p 14:0 test1.mid
$ aplaymidi -p 14:0 test1.mid
-d or –delay=seconds : It delay once MIDI sound ends.$ aplaymidi -p 14:0 -d 10 test1.mid
$ aplaymidi -p 14:0 -d 10 test1.mid
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
UDP Server-Client implementation in C
Tail command in Linux with examples
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
|
[
{
"code": null,
"e": 25331,
"s": 25303,
"text": "\n24 Jun, 2019"
},
{
"code": null,
"e": 25616,
"s": 25331,
"text": "aplaymidi command in Linux is used to play standard MIDI(Musical Instrument Digital Interface) files, by sending the content of a MIDI file to an ALSA(Advanced Linux Sound Architecture) MIDI port, sound renderer like timidity or a hardware MIDI device are required to play MIDI files."
},
{
"code": null,
"e": 25624,
"s": 25616,
"text": "Syntax:"
},
{
"code": null,
"e": 25655,
"s": 25624,
"text": "aplaymidi [options] [MIDIfile]"
},
{
"code": null,
"e": 25664,
"s": 25655,
"text": "Options:"
},
{
"code": null,
"e": 25755,
"s": 25664,
"text": "-h or –help: This is used to show all the options and syntax of the command.$ aplaymidi -h"
},
{
"code": null,
"e": 25770,
"s": 25755,
"text": "$ aplaymidi -h"
},
{
"code": null,
"e": 25853,
"s": 25770,
"text": "-V or –version: It is used to display the current version of the SW.$ aplaymidi -V"
},
{
"code": null,
"e": 25868,
"s": 25853,
"text": "$ aplaymidi -V"
},
{
"code": null,
"e": 25961,
"s": 25868,
"text": "-l or –list: It is used to display the list of all possible MIDI output ports.$ aplaymidi -l"
},
{
"code": null,
"e": 25976,
"s": 25961,
"text": "$ aplaymidi -l"
},
{
"code": null,
"e": 26070,
"s": 25976,
"text": "-p or –port=client:port : It specifies ports(s) to play MIDI to.$ aplaymidi -p 14:0 test1.mid"
},
{
"code": null,
"e": 26100,
"s": 26070,
"text": "$ aplaymidi -p 14:0 test1.mid"
},
{
"code": null,
"e": 26189,
"s": 26100,
"text": "-d or –delay=seconds : It delay once MIDI sound ends.$ aplaymidi -p 14:0 -d 10 test1.mid"
},
{
"code": null,
"e": 26225,
"s": 26189,
"text": "$ aplaymidi -p 14:0 -d 10 test1.mid"
},
{
"code": null,
"e": 26239,
"s": 26225,
"text": "linux-command"
},
{
"code": null,
"e": 26259,
"s": 26239,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 26266,
"s": 26259,
"text": "Picked"
},
{
"code": null,
"e": 26277,
"s": 26266,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26375,
"s": 26277,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26413,
"s": 26375,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 26448,
"s": 26413,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 26484,
"s": 26448,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 26522,
"s": 26484,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 26560,
"s": 26522,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 26596,
"s": 26560,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 26631,
"s": 26596,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 26668,
"s": 26631,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 26704,
"s": 26668,
"text": "echo command in Linux with Examples"
}
] |
Things You Should Know About React Hooks - GeeksforGeeks
|
18 Jul, 2021
React...We all know the importance of this library in the tech industry. Most of the applications are switching to React because of its advantages and features. There are many features of React. React hooks is one of them. React hooks was first released in October 2018. In React a lot of developers use the lifecycle method which is nothing, but just a series of components. It is used from the birth of React component to its death.
render(), componentDidMount(), componentDidUpdate() componentWillUnmount() all these are the lifecycle method. React hooks is the alternative approach of state management and lifecycle method. There are many hooks used for different purposes. Some of them are useReducer, useState, useCallBack, useMemo, useRef, useDispatcher etc.
In this blog, we will discuss the common hooks, the benefits of React hooks, the rules of React hooks along some examples.
Hooks provide a lot of benefits to the developers. It makes your component better, and it helps in writing clear, concise, and maintainable code. It just cut all the unnecessary code from your component and makes your code more readable. But the question is when to use React hooks?
Use Hooks when you’re writing a function component, and you want to add some state to it. Earlier this job was done by using a Class, but now you can write the hooks inside a function component.
Below are the main rules of using React hooks...
1. Always call hooks at the top level. Do not call it inside loops, conditions, or nested functions. You will be ensured that hooks can be called in the same order each time component renders.
2. Hooks can not be called from regular JavaScript functions. You can call it from React function components. One hook can call another hook.
Hooks effect allows you to perform a side effect in function components. Hooks effect has no use of function components available in-class components. Hooks effects are similar to the lifecycle method componentDidMount(), componentDidUpdate(), and componentWillUnmount().
Hooks effect has the common features given below...
Updating the DOM
Fetching and Consuming data from server API
Setting up subscription
Below is one of the examples of React hooks.
Javascript
import React, { useState, useEffect } from 'react'; function CounterExample() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0); const incerementCount = () =>setCount(count+1); useEffect(() => { // Update the document title using the browser API document.title = `You clicked ${count} times`; }); return ( <div> <p>You clicked {count} times</p> <button onClick={incrementCount}> Click me </button> </div> ); } export default CounterExample;
There is a concept of Context hook in React. Context hook is used in Context API. You create the context in React and this hook is used to interact with created context. An example is given below...
Javascript
import React, { useContext } from 'react';const ExampleContext = React.createContext();function Display() { const Examplevalue = useContext(ExampleContext); return <div>{Examplevalue}, This value is from context.</div>;}function App() { return ( <ExampleContext.Provider value={"Tamil"}> <Display /> </ExampleContext.Provider> );}
You might have listened to this word if you have worked with Redux. Reducer hook works as an alternative for a state hook. When a state is changed it gets bundled in a central function called Reducer. After that state will be updated depending on the action and existing state. One of the examples is given below... You can rewrite the state hook example as given below...
Javascript
import React, { useReducer } from 'react';const initialState = {count: 0}; function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: throw new Error(); }} function App() { const [state, dispatch] = useReducer(reducer, initialState); return ( <> <h2>Count: {state.count}</h2> <button onClick={() => dispatch({type: 'increment'})}>+</button> <button onClick={() => dispatch({type: 'decrement'})}>-</button> </> );}
Reference hook refers to the React element created by the render method. An example is given below...
Javascript
import React, { useRef } from 'react';function App() { const newElement = useRef(null); const onButtonClick = () => { newElement.current.focus(); }; return ( <> <input ref={newElement} type="text" /> <button onClick={onButtonClick}>Focus to Element</button> </> );}
We have discussed the major hooks and their usage with code examples. These hooks are not limited here. Once you will have experience in React, you will be using many more hooks such as useDispatch, useSelect, etc. Each one of them has its own application.
bunnyram19
GBlog
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Introduction to Recurrent Neural Network
12 pip Commands For Python Developers
A Freshers Guide To Programming
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
|
[
{
"code": null,
"e": 26313,
"s": 26285,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 26749,
"s": 26313,
"text": "React...We all know the importance of this library in the tech industry. Most of the applications are switching to React because of its advantages and features. There are many features of React. React hooks is one of them. React hooks was first released in October 2018. In React a lot of developers use the lifecycle method which is nothing, but just a series of components. It is used from the birth of React component to its death. "
},
{
"code": null,
"e": 27081,
"s": 26749,
"text": "render(), componentDidMount(), componentDidUpdate() componentWillUnmount() all these are the lifecycle method. React hooks is the alternative approach of state management and lifecycle method. There are many hooks used for different purposes. Some of them are useReducer, useState, useCallBack, useMemo, useRef, useDispatcher etc. "
},
{
"code": null,
"e": 27204,
"s": 27081,
"text": "In this blog, we will discuss the common hooks, the benefits of React hooks, the rules of React hooks along some examples."
},
{
"code": null,
"e": 27487,
"s": 27204,
"text": "Hooks provide a lot of benefits to the developers. It makes your component better, and it helps in writing clear, concise, and maintainable code. It just cut all the unnecessary code from your component and makes your code more readable. But the question is when to use React hooks?"
},
{
"code": null,
"e": 27683,
"s": 27487,
"text": "Use Hooks when you’re writing a function component, and you want to add some state to it. Earlier this job was done by using a Class, but now you can write the hooks inside a function component. "
},
{
"code": null,
"e": 27732,
"s": 27683,
"text": "Below are the main rules of using React hooks..."
},
{
"code": null,
"e": 27926,
"s": 27732,
"text": "1. Always call hooks at the top level. Do not call it inside loops, conditions, or nested functions. You will be ensured that hooks can be called in the same order each time component renders. "
},
{
"code": null,
"e": 28069,
"s": 27926,
"text": "2. Hooks can not be called from regular JavaScript functions. You can call it from React function components. One hook can call another hook. "
},
{
"code": null,
"e": 28342,
"s": 28069,
"text": "Hooks effect allows you to perform a side effect in function components. Hooks effect has no use of function components available in-class components. Hooks effects are similar to the lifecycle method componentDidMount(), componentDidUpdate(), and componentWillUnmount(). "
},
{
"code": null,
"e": 28394,
"s": 28342,
"text": "Hooks effect has the common features given below..."
},
{
"code": null,
"e": 28411,
"s": 28394,
"text": "Updating the DOM"
},
{
"code": null,
"e": 28455,
"s": 28411,
"text": "Fetching and Consuming data from server API"
},
{
"code": null,
"e": 28479,
"s": 28455,
"text": "Setting up subscription"
},
{
"code": null,
"e": 28524,
"s": 28479,
"text": "Below is one of the examples of React hooks."
},
{
"code": null,
"e": 28535,
"s": 28524,
"text": "Javascript"
},
{
"code": "import React, { useState, useEffect } from 'react'; function CounterExample() { // Declare a new state variable, which we'll call \"count\" const [count, setCount] = useState(0); const incerementCount = () =>setCount(count+1); useEffect(() => { // Update the document title using the browser API document.title = `You clicked ${count} times`; }); return ( <div> <p>You clicked {count} times</p> <button onClick={incrementCount}> Click me </button> </div> ); } export default CounterExample;",
"e": 29114,
"s": 28535,
"text": null
},
{
"code": null,
"e": 29318,
"s": 29119,
"text": "There is a concept of Context hook in React. Context hook is used in Context API. You create the context in React and this hook is used to interact with created context. An example is given below..."
},
{
"code": null,
"e": 29331,
"s": 29320,
"text": "Javascript"
},
{
"code": "import React, { useContext } from 'react';const ExampleContext = React.createContext();function Display() { const Examplevalue = useContext(ExampleContext); return <div>{Examplevalue}, This value is from context.</div>;}function App() { return ( <ExampleContext.Provider value={\"Tamil\"}> <Display /> </ExampleContext.Provider> );}",
"e": 29688,
"s": 29331,
"text": null
},
{
"code": null,
"e": 30066,
"s": 29693,
"text": "You might have listened to this word if you have worked with Redux. Reducer hook works as an alternative for a state hook. When a state is changed it gets bundled in a central function called Reducer. After that state will be updated depending on the action and existing state. One of the examples is given below... You can rewrite the state hook example as given below..."
},
{
"code": null,
"e": 30079,
"s": 30068,
"text": "Javascript"
},
{
"code": "import React, { useReducer } from 'react';const initialState = {count: 0}; function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: throw new Error(); }} function App() { const [state, dispatch] = useReducer(reducer, initialState); return ( <> <h2>Count: {state.count}</h2> <button onClick={() => dispatch({type: 'increment'})}>+</button> <button onClick={() => dispatch({type: 'decrement'})}>-</button> </> );}",
"e": 30643,
"s": 30079,
"text": null
},
{
"code": null,
"e": 30750,
"s": 30648,
"text": "Reference hook refers to the React element created by the render method. An example is given below..."
},
{
"code": null,
"e": 30763,
"s": 30752,
"text": "Javascript"
},
{
"code": "import React, { useRef } from 'react';function App() { const newElement = useRef(null); const onButtonClick = () => { newElement.current.focus(); }; return ( <> <input ref={newElement} type=\"text\" /> <button onClick={onButtonClick}>Focus to Element</button> </> );}",
"e": 31053,
"s": 30763,
"text": null
},
{
"code": null,
"e": 31313,
"s": 31056,
"text": "We have discussed the major hooks and their usage with code examples. These hooks are not limited here. Once you will have experience in React, you will be using many more hooks such as useDispatch, useSelect, etc. Each one of them has its own application."
},
{
"code": null,
"e": 31326,
"s": 31315,
"text": "bunnyram19"
},
{
"code": null,
"e": 31332,
"s": 31326,
"text": "GBlog"
},
{
"code": null,
"e": 31340,
"s": 31332,
"text": "ReactJS"
},
{
"code": null,
"e": 31357,
"s": 31340,
"text": "Web Technologies"
},
{
"code": null,
"e": 31455,
"s": 31357,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31480,
"s": 31455,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 31507,
"s": 31480,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 31548,
"s": 31507,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 31586,
"s": 31548,
"text": "12 pip Commands For Python Developers"
},
{
"code": null,
"e": 31618,
"s": 31586,
"text": "A Freshers Guide To Programming"
},
{
"code": null,
"e": 31661,
"s": 31618,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31706,
"s": 31661,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 31771,
"s": 31706,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 31839,
"s": 31771,
"text": "How to pass data from one component to other component in ReactJS ?"
}
] |
Three address code in Compiler - GeeksforGeeks
|
11 Sep, 2019
Prerequisite – Intermediate Code Generation
Three address code is a type of intermediate code which is easy to generate and can be easily converted to machine code.It makes use of at most three addresses and one operator to represent an expression and the value computed at each instruction is stored in temporary variable generated by compiler. The compiler decides the order of operation given by three address code.
General representation –
a = b op c
Where a, b or c represents operands like names, constants or compiler generated temporaries and op represents the operator
Example-1: Convert the expression a * – (b + c) into three address code.
Example-2: Write three address code for following code
for(i = 1; i<=10; i++)
{
a[i] = x * 5;
}
Implementation of Three Address Code –There are 3 representations of three address code namely
QuadrupleTriplesIndirect Triples
Quadruple
Triples
Indirect Triples
1. Quadruple –It is structure with consist of 4 fields namely op, arg1, arg2 and result. op denotes the operator and arg1 and arg2 denotes the two operands and result is used to store the result of the expression.
Advantage –
Easy to rearrange code for global optimization.
One can quickly access value of temporary variables using symbol table.
Disadvantage –
Contain lot of temporaries.
Temporary variable creation increases time and space complexity.
Example – Consider expression a = b * – c + b * – c.The three address code is:
t1 = uminus c
t2 = b * t1
t3 = uminus c
t4 = b * t3
t5 = t2 + t4
a = t5
2. Triples –This representation doesn’t make use of extra temporary variable to represent a single operation instead when a reference to another triple’s value is needed, a pointer to that triple is used. So, it consist of only three fields namely op, arg1 and arg2.
Disadvantage –
Temporaries are implicit and difficult to rearrange code.
It is difficult to optimize because optimization involves moving intermediate code. When a triple is moved, any other triple referring to it must be updated also. With help of pointer one can directly access symbol table entry.
Example – Consider expression a = b * – c + b * – c
3. Indirect Triples –This representation makes use of pointer to the listing of all references to computations which is made separately and stored. Its similar in utility as compared to quadruple representation but requires less space than it. Temporaries are implicit and easier to rearrange code.
Example – Consider expression a = b * – c + b * – c
Question – Write quadruple, triples and indirect triples for following expression : (x + y) * (y + z) + (x + y + z)
Explanation – The three address code is:
t1 = x + y
t2 = y + z
t3 = t1 * t2
t4 = t1 + z
t5 = t3 + t4
pradeepgangwar
sayuj
Compiler Design
GATE CS
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Construction of LL(1) Parsing Table
Directed Acyclic graph in Compiler Design (with examples)
Types of Parsers in Compiler Design
Difference between Compiler and Interpreter
Peephole Optimization in Compiler Design
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
|
[
{
"code": null,
"e": 26488,
"s": 26460,
"text": "\n11 Sep, 2019"
},
{
"code": null,
"e": 26532,
"s": 26488,
"text": "Prerequisite – Intermediate Code Generation"
},
{
"code": null,
"e": 26907,
"s": 26532,
"text": "Three address code is a type of intermediate code which is easy to generate and can be easily converted to machine code.It makes use of at most three addresses and one operator to represent an expression and the value computed at each instruction is stored in temporary variable generated by compiler. The compiler decides the order of operation given by three address code."
},
{
"code": null,
"e": 26932,
"s": 26907,
"text": "General representation –"
},
{
"code": null,
"e": 26945,
"s": 26932,
"text": " a = b op c "
},
{
"code": null,
"e": 27068,
"s": 26945,
"text": "Where a, b or c represents operands like names, constants or compiler generated temporaries and op represents the operator"
},
{
"code": null,
"e": 27141,
"s": 27068,
"text": "Example-1: Convert the expression a * – (b + c) into three address code."
},
{
"code": null,
"e": 27196,
"s": 27141,
"text": "Example-2: Write three address code for following code"
},
{
"code": null,
"e": 27281,
"s": 27196,
"text": "for(i = 1; i<=10; i++)\n {\n a[i] = x * 5; \n } "
},
{
"code": null,
"e": 27376,
"s": 27281,
"text": "Implementation of Three Address Code –There are 3 representations of three address code namely"
},
{
"code": null,
"e": 27409,
"s": 27376,
"text": "QuadrupleTriplesIndirect Triples"
},
{
"code": null,
"e": 27419,
"s": 27409,
"text": "Quadruple"
},
{
"code": null,
"e": 27427,
"s": 27419,
"text": "Triples"
},
{
"code": null,
"e": 27444,
"s": 27427,
"text": "Indirect Triples"
},
{
"code": null,
"e": 27658,
"s": 27444,
"text": "1. Quadruple –It is structure with consist of 4 fields namely op, arg1, arg2 and result. op denotes the operator and arg1 and arg2 denotes the two operands and result is used to store the result of the expression."
},
{
"code": null,
"e": 27670,
"s": 27658,
"text": "Advantage –"
},
{
"code": null,
"e": 27718,
"s": 27670,
"text": "Easy to rearrange code for global optimization."
},
{
"code": null,
"e": 27790,
"s": 27718,
"text": "One can quickly access value of temporary variables using symbol table."
},
{
"code": null,
"e": 27805,
"s": 27790,
"text": "Disadvantage –"
},
{
"code": null,
"e": 27833,
"s": 27805,
"text": "Contain lot of temporaries."
},
{
"code": null,
"e": 27898,
"s": 27833,
"text": "Temporary variable creation increases time and space complexity."
},
{
"code": null,
"e": 27977,
"s": 27898,
"text": "Example – Consider expression a = b * – c + b * – c.The three address code is:"
},
{
"code": null,
"e": 28052,
"s": 27977,
"text": "t1 = uminus c\nt2 = b * t1\nt3 = uminus c\nt4 = b * t3 \nt5 = t2 + t4\na = t5 "
},
{
"code": null,
"e": 28319,
"s": 28052,
"text": "2. Triples –This representation doesn’t make use of extra temporary variable to represent a single operation instead when a reference to another triple’s value is needed, a pointer to that triple is used. So, it consist of only three fields namely op, arg1 and arg2."
},
{
"code": null,
"e": 28334,
"s": 28319,
"text": "Disadvantage –"
},
{
"code": null,
"e": 28392,
"s": 28334,
"text": "Temporaries are implicit and difficult to rearrange code."
},
{
"code": null,
"e": 28620,
"s": 28392,
"text": "It is difficult to optimize because optimization involves moving intermediate code. When a triple is moved, any other triple referring to it must be updated also. With help of pointer one can directly access symbol table entry."
},
{
"code": null,
"e": 28672,
"s": 28620,
"text": "Example – Consider expression a = b * – c + b * – c"
},
{
"code": null,
"e": 28971,
"s": 28672,
"text": "3. Indirect Triples –This representation makes use of pointer to the listing of all references to computations which is made separately and stored. Its similar in utility as compared to quadruple representation but requires less space than it. Temporaries are implicit and easier to rearrange code."
},
{
"code": null,
"e": 29023,
"s": 28971,
"text": "Example – Consider expression a = b * – c + b * – c"
},
{
"code": null,
"e": 29139,
"s": 29023,
"text": "Question – Write quadruple, triples and indirect triples for following expression : (x + y) * (y + z) + (x + y + z)"
},
{
"code": null,
"e": 29180,
"s": 29139,
"text": "Explanation – The three address code is:"
},
{
"code": null,
"e": 29242,
"s": 29180,
"text": "t1 = x + y\nt2 = y + z\nt3 = t1 * t2\nt4 = t1 + z\nt5 = t3 + t4 "
},
{
"code": null,
"e": 29261,
"s": 29246,
"text": "pradeepgangwar"
},
{
"code": null,
"e": 29267,
"s": 29261,
"text": "sayuj"
},
{
"code": null,
"e": 29283,
"s": 29267,
"text": "Compiler Design"
},
{
"code": null,
"e": 29291,
"s": 29283,
"text": "GATE CS"
},
{
"code": null,
"e": 29310,
"s": 29291,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29408,
"s": 29310,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29444,
"s": 29408,
"text": "Construction of LL(1) Parsing Table"
},
{
"code": null,
"e": 29502,
"s": 29444,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 29538,
"s": 29502,
"text": "Types of Parsers in Compiler Design"
},
{
"code": null,
"e": 29582,
"s": 29538,
"text": "Difference between Compiler and Interpreter"
},
{
"code": null,
"e": 29623,
"s": 29582,
"text": "Peephole Optimization in Compiler Design"
},
{
"code": null,
"e": 29643,
"s": 29623,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 29667,
"s": 29643,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 29680,
"s": 29667,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 29707,
"s": 29680,
"text": "Types of Operating Systems"
}
] |
Itertools in Python3 - GeeksforGeeks
|
22 Sep, 2021
Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.
This module incorporates functions that utilize computational resources efficiently. Using this module also tends to enhance the readability and maintainability of the code.
The grouper() function can be found in the Recipes section of the itertools docs. The recipes are an excellent source of inspiration for ways to use itertools to your advantage.Example
python3
# Python code to demonstrate the# grouper Recipeimport itertools as it # defining the grouper functiondef grouper(inputs, n, fillvalue = None): iters = [iter(inputs)] * n return it.zip_longest(*iters, fillvalue = fillvalue) alpha = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's']print(list(grouper(alpha, 3)))
Output :
[(‘g’, ‘e’, ‘e’), (‘k’, ‘s’, ‘f’), (‘o’, ‘r’, ‘g’), (‘e’, ‘e’, ‘k’), (‘s’, None, None)]
Brute force is a straightforward method of solving a problem that relies on sheer computing power and trying every possibility rather than advanced techniques to improve efficiency. There are different Brute force itertools function such as:
combinations()
combinations_with_replacement()
permutations()
The itertools.combinations() function takes two arguments—an iterable inputs and a positive integer n—and produces an iterator over tuples of all combinations of n elements in inputs.Example
python3
# Python code to demonstrate combinationsimport itertools as it print(list(it.combinations([1, 2], 2)))
Output :
[(1, 2)]
combinations_with_replacement() works just like combinations(), accepting an iterable inputs and a positive integer n, and returns an iterator over n-tuples of elements from inputs. The difference is that combinations_with_replacement() allows elements to be repeated in the tuples it returns. Example
python3
# Python code to demonstrate combinations_with_replacementimport itertools as it print(list(it.combinations_with_replacement([1, 2], 2)))
Output :
[(1, 1), (1, 2), (2, 2)]
A permutation is a collection or a combination of objects from a set where the order or the arrangement of the chosen objects does matter. permutations() accepts a single iterable and produces all possible permutations (rearrangements) of its elements. Example
python3
# Python code to demonstrate permutationsimport itertools as it print(list(it.permutations(['g', 'e', 'k'])))
Output :
[(‘g’, ‘e’, ‘k’), (‘g’, ‘k’, ‘e’), (‘e’, ‘g’, ‘k’), (‘e’, ‘k’, ‘g’), (‘k’, ‘g’, ‘e’), (‘k’, ‘e’, ‘g’)]
Converting a list of lists (2D), into a list (1D) is called flattening. Flattening a list of lists merges all the sublists into one unified list. Example
python3
# Python code to demonstrate flattening a list of listsimport itertools as it list_of_lists = [[1, 2], [3, 4]]chain_object = it.chain.from_iterable(list_of_lists) # Return chain object with nested lists separated# Convert to list to flattenflattened_list = list(chain_object) print(flattened_list)
Output :
[1, 2, 3, 4]
adnanirshad158
Python-itertools
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Defaultdict in Python
Enumerate() in Python
sum() function in Python
Python String | replace()
Read a file line by line in Python
How to Install PIP on Windows ?
Deque in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
|
[
{
"code": null,
"e": 26049,
"s": 26021,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 26348,
"s": 26049,
"text": "Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. "
},
{
"code": null,
"e": 26523,
"s": 26348,
"text": "This module incorporates functions that utilize computational resources efficiently. Using this module also tends to enhance the readability and maintainability of the code. "
},
{
"code": null,
"e": 26710,
"s": 26523,
"text": "The grouper() function can be found in the Recipes section of the itertools docs. The recipes are an excellent source of inspiration for ways to use itertools to your advantage.Example "
},
{
"code": null,
"e": 26718,
"s": 26710,
"text": "python3"
},
{
"code": "# Python code to demonstrate the# grouper Recipeimport itertools as it # defining the grouper functiondef grouper(inputs, n, fillvalue = None): iters = [iter(inputs)] * n return it.zip_longest(*iters, fillvalue = fillvalue) alpha = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's']print(list(grouper(alpha, 3)))",
"e": 27060,
"s": 26718,
"text": null
},
{
"code": null,
"e": 27070,
"s": 27060,
"text": "Output : "
},
{
"code": null,
"e": 27160,
"s": 27070,
"text": "[(‘g’, ‘e’, ‘e’), (‘k’, ‘s’, ‘f’), (‘o’, ‘r’, ‘g’), (‘e’, ‘e’, ‘k’), (‘s’, None, None)] "
},
{
"code": null,
"e": 27406,
"s": 27162,
"text": "Brute force is a straightforward method of solving a problem that relies on sheer computing power and trying every possibility rather than advanced techniques to improve efficiency. There are different Brute force itertools function such as: "
},
{
"code": null,
"e": 27423,
"s": 27406,
"text": "combinations() "
},
{
"code": null,
"e": 27457,
"s": 27423,
"text": "combinations_with_replacement() "
},
{
"code": null,
"e": 27474,
"s": 27457,
"text": "permutations() "
},
{
"code": null,
"e": 27669,
"s": 27476,
"text": "The itertools.combinations() function takes two arguments—an iterable inputs and a positive integer n—and produces an iterator over tuples of all combinations of n elements in inputs.Example "
},
{
"code": null,
"e": 27677,
"s": 27669,
"text": "python3"
},
{
"code": "# Python code to demonstrate combinationsimport itertools as it print(list(it.combinations([1, 2], 2)))",
"e": 27781,
"s": 27677,
"text": null
},
{
"code": null,
"e": 27792,
"s": 27781,
"text": "Output : "
},
{
"code": null,
"e": 27801,
"s": 27792,
"text": "[(1, 2)]"
},
{
"code": null,
"e": 28107,
"s": 27803,
"text": "combinations_with_replacement() works just like combinations(), accepting an iterable inputs and a positive integer n, and returns an iterator over n-tuples of elements from inputs. The difference is that combinations_with_replacement() allows elements to be repeated in the tuples it returns. Example "
},
{
"code": null,
"e": 28115,
"s": 28107,
"text": "python3"
},
{
"code": "# Python code to demonstrate combinations_with_replacementimport itertools as it print(list(it.combinations_with_replacement([1, 2], 2)))",
"e": 28253,
"s": 28115,
"text": null
},
{
"code": null,
"e": 28264,
"s": 28253,
"text": "Output : "
},
{
"code": null,
"e": 28290,
"s": 28264,
"text": "[(1, 1), (1, 2), (2, 2)] "
},
{
"code": null,
"e": 28555,
"s": 28292,
"text": "A permutation is a collection or a combination of objects from a set where the order or the arrangement of the chosen objects does matter. permutations() accepts a single iterable and produces all possible permutations (rearrangements) of its elements. Example "
},
{
"code": null,
"e": 28563,
"s": 28555,
"text": "python3"
},
{
"code": "# Python code to demonstrate permutationsimport itertools as it print(list(it.permutations(['g', 'e', 'k'])))",
"e": 28673,
"s": 28563,
"text": null
},
{
"code": null,
"e": 28683,
"s": 28673,
"text": "Output : "
},
{
"code": null,
"e": 28786,
"s": 28683,
"text": "[(‘g’, ‘e’, ‘k’), (‘g’, ‘k’, ‘e’), (‘e’, ‘g’, ‘k’), (‘e’, ‘k’, ‘g’), (‘k’, ‘g’, ‘e’), (‘k’, ‘e’, ‘g’)]"
},
{
"code": null,
"e": 28944,
"s": 28788,
"text": "Converting a list of lists (2D), into a list (1D) is called flattening. Flattening a list of lists merges all the sublists into one unified list. Example "
},
{
"code": null,
"e": 28952,
"s": 28944,
"text": "python3"
},
{
"code": "# Python code to demonstrate flattening a list of listsimport itertools as it list_of_lists = [[1, 2], [3, 4]]chain_object = it.chain.from_iterable(list_of_lists) # Return chain object with nested lists separated# Convert to list to flattenflattened_list = list(chain_object) print(flattened_list)",
"e": 29250,
"s": 28952,
"text": null
},
{
"code": null,
"e": 29261,
"s": 29250,
"text": "Output : "
},
{
"code": null,
"e": 29275,
"s": 29261,
"text": "[1, 2, 3, 4] "
},
{
"code": null,
"e": 29292,
"s": 29277,
"text": "adnanirshad158"
},
{
"code": null,
"e": 29309,
"s": 29292,
"text": "Python-itertools"
},
{
"code": null,
"e": 29316,
"s": 29309,
"text": "Python"
},
{
"code": null,
"e": 29414,
"s": 29316,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29432,
"s": 29414,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29454,
"s": 29432,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29476,
"s": 29454,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29501,
"s": 29476,
"text": "sum() function in Python"
},
{
"code": null,
"e": 29527,
"s": 29501,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29562,
"s": 29527,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29594,
"s": 29562,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29610,
"s": 29594,
"text": "Deque in Python"
},
{
"code": null,
"e": 29652,
"s": 29610,
"text": "Different ways to create Pandas Dataframe"
}
] |
Optimal Strategy for the Divisor game using Dynamic Programming - GeeksforGeeks
|
25 May, 2021
Given an integer N and two players, A and B are playing a game. On each player’s turn, that player makes a move by subtracting a divisor of current N (which is less than N) from current N, thus forming a new N for the next turn. The player who does not have any divisor left to subtract loses the game. The task is to tell which player wins the game if player A takes the first turn, assuming both players play optimally.Examples:
Input : N = 2 Output : Player A wins Explanation : Player A chooses 1, and B has no more moves.Input : N = 3 Output : Player B wins Explanation : Player A chooses 1, player B chooses 1, and A has no more moves.
Approach :This problem mentioned above can be solved using Dynamic Programming.
We will take a DP having 2 states i.e.
N -> current number left A -> boolean value to decide if it’s player A’s turn or not
At each state, we will try to find all the divisors of N and will try to find the next state where the current player is winning. For player A, we will try to find the next state where the return value is true while for player B, we will try to find the next state where the return value is false (as false represents the loss of player A).
The base cases will be for N=1 where always the player A will lose and N=2 where always the player B will lose.
To find the answer, we just need to find the value of DP[ N ][ 1 ].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for implementation of// Optimal Strategy for the Divisor// Game using Dynamic Programming#include <bits/stdc++.h>using namespace std; // Recursive function to find the winnerbool divisorGame(int N, bool A, int dp[][2]){ // check if N=1 or N=3 then player B wins if (N == 1 or N == 3) return false; // check if N=2 then player A wins if (N == 2) return true; // check if current state already visited // then return the previously obtained ans if (dp[N][A] != -1) return dp[N][A]; // check if currently it is player A's turn // then initialise the ans to 0 int ans = (A == 1) ? 0 : 1; // Traversing across all the divisors of N // which are less than N for (int i = 1; i * i <= N; i++) { // check if current value of // i is a divisor of N if (N % i == 0) { // check if it is player A's turn // then we need at least one true if (A) ans |= divisorGame(N - i, 0, dp); // Else if it is player B's turn // then we need at least one false else ans &= divisorGame(N - i, 1, dp); } } // Return the current ans return dp[N][A] = ans;} // Driver codeint main(){ // initialise N int N = 3; int dp[N + 1][2]; memset(dp, -1, sizeof(dp)); if (divisorGame(N, 1, dp) == true) cout << "Player A wins"; else cout << "Player B wins"; return 0;}
// Java program for implementation of// optimal strategy for the divisor// game using dynamic programming import java.util.*; class GFG { // Recursive function to find the winner static int divisorGame(int N, int A, int dp[][]) { // Check if N = 1 or N = 3 then player B wins if (N == 1 || N == 3) return 0; // Check if N = 2 then player A wins if (N == 2) return 1; // Check if current state already visited // then return the previously obtained ans if (dp[N][A] != -1) return dp[N][A]; // Check if currently it is player A's turn // then initialise the ans to 0 int ans = (A == 1) ? 0 : 1; // Traversing across all the divisors of N // which are less than N for (int i = 1; i * i <= N; i++) { // Check if current value of // i is a divisor of N if (N % i == 0) { // Check if it is player A's turn // then we need at least one true if (A == 1) ans |= divisorGame(N - i, 0, dp); // Else if it is player B's turn // then we need at least one false else ans &= divisorGame(N - i, 1, dp); } } // Return the current ans return dp[N][A] = ans; } // Driver code public static void main(String[] args) { // Initialise N int N = 3; int[][] dp = new int[N + 1][2]; for (int i = 0; i < N + 1; i++) { for (int j = 0; j < 2; j++) { dp[i][j] = -1; } } if (divisorGame(N, 1, dp) == 1) System.out.print("Player A wins"); else System.out.print("Player B wins"); }} // This code contributed by sapnasingh4991
# Python3 program for implementation of# Optimal Strategy for the Divisor# Game using Dynamic Programming from math import sqrt # Recursive function to find the winnerdef divisorGame(N,A,dp): # check if N=1 or N=3 then player B wins if (N == 1 or N == 3): return False # check if N=2 then player A wins if (N == 2): return True # check if current state already visited # then return the previously obtained ans if (dp[N][A] != -1): return dp[N][A] # check if currently it is player A's turn # then initialise the ans to 0 if(A == 1): ans = 0 else: ans = 1 # Traversing across all the divisors of N # which are less than N for i in range(1,int(sqrt(N))+1,1): # check if current value of # i is a divisor of N if (N % i == 0): # check if it is player A's turn # then we need at least one true if (A): ans |= divisorGame(N - i, 0, dp) # Else if it is player B's turn # then we need at least one false else: ans &= divisorGame(N - i, 1, dp) dp[N][A] = ans # Return the current ans return dp[N][A] # Driver codeif __name__ == '__main__': # initialise N N = 3 dp = [[-1 for i in range(2)] for j in range(N+1)] if (divisorGame(N, 1, dp) == True): print("Player A wins") else: print("Player B wins") # This code is contributed by Surendra_Gangwar
// C# program for implementation of// optimal strategy for the divisor// game using dynamic programmingusing System; class GFG { // Recursive function to find the winnerstatic int divisorGame(int N, int A, int [,]dp){ // Check if N = 1 or N = 3 // then player B wins if (N == 1 || N == 3) return 0; // Check if N = 2 then player A wins if (N == 2) return 1; // Check if current state already visited // then return the previously obtained ans if (dp[N, A] != -1) return dp[N, A]; // Check if currently it is player A's turn // then initialise the ans to 0 int ans = (A == 1) ? 0 : 1; // Traversing across all the divisors of N // which are less than N for(int i = 1; i * i <= N; i++) { // Check if current value of // i is a divisor of N if (N % i == 0) { // Check if it is player A's turn // then we need at least one true if (A == 1) ans |= divisorGame(N - i, 0, dp); // Else if it is player B's turn // then we need at least one false else ans &= divisorGame(N - i, 1, dp); } } // Return the current ans return dp[N, A] = ans;} // Driver codepublic static void Main(String[] args){ // Initialise N int N = 3; int[,] dp = new int[N + 1, 2]; for(int i = 0; i < N + 1; i++) { for(int j = 0; j < 2; j++) { dp[i, j] = -1; } } if (divisorGame(N, 1, dp) == 1) { Console.Write("Player A wins"); } else { Console.Write("Player B wins"); }}} // This code is contributed by amal kumar choubey
<script>// Javascript program for implementation of// Optimal Strategy for the Divisor// Game using Dynamic Programming // Recursive function to find the winnerfunction divisorGame(N, A, dp) { // check if N=1 or N=3 then player B wins if (N == 1 || N == 3) return false; // check if N=2 then player A wins if (N == 2) return true; // check if current state already visited // then return the previously obtained ans if (dp[N][A] != -1) return dp[N][A]; // check if currently it is player A's turn // then initialise the ans to 0 let ans = (A == 1) ? 0 : 1; // Traversing across all the divisors of N // which are less than N for (let i = 1; i * i <= N; i++) { // check if current value of // i is a divisor of N if (N % i == 0) { // check if it is player A's turn // then we need at least one true if (A) ans |= divisorGame(N - i, 0, dp); // Else if it is player B's turn // then we need at least one false else ans &= divisorGame(N - i, 1, dp); } } // Return the current ans return dp[N][A] = ans;} // Driver code // initialise Nlet N = 3; let dp = []; for (let i = 0; i < N + 1; i++) { let temp = [-1] for (let j = 0; j < 2; j++) { temp.push([-1]) } dp.push(temp)} // memset(dp, -1, sizeof(dp)); if (divisorGame(N, 1, dp) == true) document.write("Player A wins");else document.write("Player B wins"); // This code is contributed by gfgking</script>
Player B wins
SURENDRA_GANGWAR
sapnasingh4991
Amal Kumar Choubey
gfgking
Arrays
Competitive Programming
Dynamic Programming
Game Theory
Write From Home
Arrays
Dynamic Programming
Game Theory
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Fast I/O for Competitive Programming
|
[
{
"code": null,
"e": 26065,
"s": 26037,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 26497,
"s": 26065,
"text": "Given an integer N and two players, A and B are playing a game. On each player’s turn, that player makes a move by subtracting a divisor of current N (which is less than N) from current N, thus forming a new N for the next turn. The player who does not have any divisor left to subtract loses the game. The task is to tell which player wins the game if player A takes the first turn, assuming both players play optimally.Examples: "
},
{
"code": null,
"e": 26710,
"s": 26497,
"text": "Input : N = 2 Output : Player A wins Explanation : Player A chooses 1, and B has no more moves.Input : N = 3 Output : Player B wins Explanation : Player A chooses 1, player B chooses 1, and A has no more moves. "
},
{
"code": null,
"e": 26794,
"s": 26712,
"text": "Approach :This problem mentioned above can be solved using Dynamic Programming. "
},
{
"code": null,
"e": 26835,
"s": 26794,
"text": "We will take a DP having 2 states i.e. "
},
{
"code": null,
"e": 26920,
"s": 26835,
"text": "N -> current number left A -> boolean value to decide if it’s player A’s turn or not"
},
{
"code": null,
"e": 27265,
"s": 26924,
"text": "At each state, we will try to find all the divisors of N and will try to find the next state where the current player is winning. For player A, we will try to find the next state where the return value is true while for player B, we will try to find the next state where the return value is false (as false represents the loss of player A)."
},
{
"code": null,
"e": 27377,
"s": 27265,
"text": "The base cases will be for N=1 where always the player A will lose and N=2 where always the player B will lose."
},
{
"code": null,
"e": 27445,
"s": 27377,
"text": "To find the answer, we just need to find the value of DP[ N ][ 1 ]."
},
{
"code": null,
"e": 27498,
"s": 27445,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27502,
"s": 27498,
"text": "C++"
},
{
"code": null,
"e": 27507,
"s": 27502,
"text": "Java"
},
{
"code": null,
"e": 27515,
"s": 27507,
"text": "Python3"
},
{
"code": null,
"e": 27518,
"s": 27515,
"text": "C#"
},
{
"code": null,
"e": 27529,
"s": 27518,
"text": "Javascript"
},
{
"code": "// C++ program for implementation of// Optimal Strategy for the Divisor// Game using Dynamic Programming#include <bits/stdc++.h>using namespace std; // Recursive function to find the winnerbool divisorGame(int N, bool A, int dp[][2]){ // check if N=1 or N=3 then player B wins if (N == 1 or N == 3) return false; // check if N=2 then player A wins if (N == 2) return true; // check if current state already visited // then return the previously obtained ans if (dp[N][A] != -1) return dp[N][A]; // check if currently it is player A's turn // then initialise the ans to 0 int ans = (A == 1) ? 0 : 1; // Traversing across all the divisors of N // which are less than N for (int i = 1; i * i <= N; i++) { // check if current value of // i is a divisor of N if (N % i == 0) { // check if it is player A's turn // then we need at least one true if (A) ans |= divisorGame(N - i, 0, dp); // Else if it is player B's turn // then we need at least one false else ans &= divisorGame(N - i, 1, dp); } } // Return the current ans return dp[N][A] = ans;} // Driver codeint main(){ // initialise N int N = 3; int dp[N + 1][2]; memset(dp, -1, sizeof(dp)); if (divisorGame(N, 1, dp) == true) cout << \"Player A wins\"; else cout << \"Player B wins\"; return 0;}",
"e": 29012,
"s": 27529,
"text": null
},
{
"code": "// Java program for implementation of// optimal strategy for the divisor// game using dynamic programming import java.util.*; class GFG { // Recursive function to find the winner static int divisorGame(int N, int A, int dp[][]) { // Check if N = 1 or N = 3 then player B wins if (N == 1 || N == 3) return 0; // Check if N = 2 then player A wins if (N == 2) return 1; // Check if current state already visited // then return the previously obtained ans if (dp[N][A] != -1) return dp[N][A]; // Check if currently it is player A's turn // then initialise the ans to 0 int ans = (A == 1) ? 0 : 1; // Traversing across all the divisors of N // which are less than N for (int i = 1; i * i <= N; i++) { // Check if current value of // i is a divisor of N if (N % i == 0) { // Check if it is player A's turn // then we need at least one true if (A == 1) ans |= divisorGame(N - i, 0, dp); // Else if it is player B's turn // then we need at least one false else ans &= divisorGame(N - i, 1, dp); } } // Return the current ans return dp[N][A] = ans; } // Driver code public static void main(String[] args) { // Initialise N int N = 3; int[][] dp = new int[N + 1][2]; for (int i = 0; i < N + 1; i++) { for (int j = 0; j < 2; j++) { dp[i][j] = -1; } } if (divisorGame(N, 1, dp) == 1) System.out.print(\"Player A wins\"); else System.out.print(\"Player B wins\"); }} // This code contributed by sapnasingh4991",
"e": 30874,
"s": 29012,
"text": null
},
{
"code": "# Python3 program for implementation of# Optimal Strategy for the Divisor# Game using Dynamic Programming from math import sqrt # Recursive function to find the winnerdef divisorGame(N,A,dp): # check if N=1 or N=3 then player B wins if (N == 1 or N == 3): return False # check if N=2 then player A wins if (N == 2): return True # check if current state already visited # then return the previously obtained ans if (dp[N][A] != -1): return dp[N][A] # check if currently it is player A's turn # then initialise the ans to 0 if(A == 1): ans = 0 else: ans = 1 # Traversing across all the divisors of N # which are less than N for i in range(1,int(sqrt(N))+1,1): # check if current value of # i is a divisor of N if (N % i == 0): # check if it is player A's turn # then we need at least one true if (A): ans |= divisorGame(N - i, 0, dp) # Else if it is player B's turn # then we need at least one false else: ans &= divisorGame(N - i, 1, dp) dp[N][A] = ans # Return the current ans return dp[N][A] # Driver codeif __name__ == '__main__': # initialise N N = 3 dp = [[-1 for i in range(2)] for j in range(N+1)] if (divisorGame(N, 1, dp) == True): print(\"Player A wins\") else: print(\"Player B wins\") # This code is contributed by Surendra_Gangwar",
"e": 32355,
"s": 30874,
"text": null
},
{
"code": "// C# program for implementation of// optimal strategy for the divisor// game using dynamic programmingusing System; class GFG { // Recursive function to find the winnerstatic int divisorGame(int N, int A, int [,]dp){ // Check if N = 1 or N = 3 // then player B wins if (N == 1 || N == 3) return 0; // Check if N = 2 then player A wins if (N == 2) return 1; // Check if current state already visited // then return the previously obtained ans if (dp[N, A] != -1) return dp[N, A]; // Check if currently it is player A's turn // then initialise the ans to 0 int ans = (A == 1) ? 0 : 1; // Traversing across all the divisors of N // which are less than N for(int i = 1; i * i <= N; i++) { // Check if current value of // i is a divisor of N if (N % i == 0) { // Check if it is player A's turn // then we need at least one true if (A == 1) ans |= divisorGame(N - i, 0, dp); // Else if it is player B's turn // then we need at least one false else ans &= divisorGame(N - i, 1, dp); } } // Return the current ans return dp[N, A] = ans;} // Driver codepublic static void Main(String[] args){ // Initialise N int N = 3; int[,] dp = new int[N + 1, 2]; for(int i = 0; i < N + 1; i++) { for(int j = 0; j < 2; j++) { dp[i, j] = -1; } } if (divisorGame(N, 1, dp) == 1) { Console.Write(\"Player A wins\"); } else { Console.Write(\"Player B wins\"); }}} // This code is contributed by amal kumar choubey",
"e": 34093,
"s": 32355,
"text": null
},
{
"code": "<script>// Javascript program for implementation of// Optimal Strategy for the Divisor// Game using Dynamic Programming // Recursive function to find the winnerfunction divisorGame(N, A, dp) { // check if N=1 or N=3 then player B wins if (N == 1 || N == 3) return false; // check if N=2 then player A wins if (N == 2) return true; // check if current state already visited // then return the previously obtained ans if (dp[N][A] != -1) return dp[N][A]; // check if currently it is player A's turn // then initialise the ans to 0 let ans = (A == 1) ? 0 : 1; // Traversing across all the divisors of N // which are less than N for (let i = 1; i * i <= N; i++) { // check if current value of // i is a divisor of N if (N % i == 0) { // check if it is player A's turn // then we need at least one true if (A) ans |= divisorGame(N - i, 0, dp); // Else if it is player B's turn // then we need at least one false else ans &= divisorGame(N - i, 1, dp); } } // Return the current ans return dp[N][A] = ans;} // Driver code // initialise Nlet N = 3; let dp = []; for (let i = 0; i < N + 1; i++) { let temp = [-1] for (let j = 0; j < 2; j++) { temp.push([-1]) } dp.push(temp)} // memset(dp, -1, sizeof(dp)); if (divisorGame(N, 1, dp) == true) document.write(\"Player A wins\");else document.write(\"Player B wins\"); // This code is contributed by gfgking</script>",
"e": 35672,
"s": 34093,
"text": null
},
{
"code": null,
"e": 35686,
"s": 35672,
"text": "Player B wins"
},
{
"code": null,
"e": 35705,
"s": 35688,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 35720,
"s": 35705,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 35739,
"s": 35720,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 35747,
"s": 35739,
"text": "gfgking"
},
{
"code": null,
"e": 35754,
"s": 35747,
"text": "Arrays"
},
{
"code": null,
"e": 35778,
"s": 35754,
"text": "Competitive Programming"
},
{
"code": null,
"e": 35798,
"s": 35778,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 35810,
"s": 35798,
"text": "Game Theory"
},
{
"code": null,
"e": 35826,
"s": 35810,
"text": "Write From Home"
},
{
"code": null,
"e": 35833,
"s": 35826,
"text": "Arrays"
},
{
"code": null,
"e": 35853,
"s": 35833,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 35865,
"s": 35853,
"text": "Game Theory"
},
{
"code": null,
"e": 35963,
"s": 35865,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35990,
"s": 35963,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 36021,
"s": 35990,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 36046,
"s": 36021,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 36084,
"s": 36046,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 36105,
"s": 36084,
"text": "Next Greater Element"
},
{
"code": null,
"e": 36148,
"s": 36105,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 36191,
"s": 36148,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 36232,
"s": 36191,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 36310,
"s": 36232,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
}
] |
CSS | scrollbar-width Property - GeeksforGeeks
|
30 Jun, 2021
The scrollbar-width property is used to set the width or thickness of an element’s scrollbar when shown. This property can be used on pages where the user interface requires the element to be displayed more prominently and shrinking the scrollbar width gives more space to the element.This a currently an experimental property and some of the major browsers may not be supported.Syntax:
scrollbar-width: auto | thin | none | initial | inherit
Property Values:
auto: It is used to set the scrollbar width to be automatically set by the browser. It is the default value.Example:
html
<!DOCTYPE html><html> <head> <title>CSS | scrollbar-width property</title> <style> .scrollbar-auto { scrollbar-width: auto; background-color: lightgreen; height: 150px; width: 200px; overflow-y: scroll; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | scrollbar-width</b> <p>scrollbar-width: auto</p> <div class="scrollbar-auto"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body> </html>
Output:
thin: It is used to set the scrollbar width to a thinner variant of the default scrollbar.Example:
html
<!DOCTYPE html><html> <head> <title>CSS | scrollbar-width</title> <style> .scrollbar-thin { scrollbar-width: thin; background-color: lightgreen; height: 150px; width: 200px; overflow-y: scroll; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | scrollbar-width</b> <p>scrollbar-width: thin</p> <div class="scrollbar-thin"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body> </html>
Output:
none: It is used to completely hide the scrollbar, however the content is still scrollable.Example:
html
<!DOCTYPE html><html> <head> <title>CSS | scrollbar-width</title> <style> .scrollbar-none { scrollbar-width: none; background-color: lightgreen; height: 150px; width: 200px; overflow-y: scroll; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | scrollbar-width</b> <p>scrollbar-width: none</p> <div class="scrollbar-none"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body> </html>
Output:
initial: It is used to set the scrollbar width to its default value.Example:
html
<!DOCTYPE html><html> <head> <title>CSS | scrollbar-width</title> <style> .scrollbar-initial { scrollbar-width: initial; background-color: lightgreen; height: 150px; width: 200px; overflow-y: scroll; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | scrollbar-width</b> <p>scrollbar-width: initial</p> <div class="scrollbar-initial"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body> </html>
Output:
inherit: It is used to inherit the scrollbar width from its parent.Example:
html
<!DOCTYPE html><html> <head> <title>CSS | scrollbar-width</title> <style> .scrollbar-thin { scrollbar-width: thin; background-color: lightgreen; height: 150px; width: 200px; overflow-y: scroll; margin: 10px; } .scrollbar-inherit { scrollbar-width: inherit; background-color: green; height: 50px; width: 150px; overflow-y: scroll; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | scrollbar-width</b> <p>scrollbar-width: inherit</p> <div class="scrollbar-thin"> <div class="scrollbar-inherit"> This text is inside a parent element. This div has an inherited scrollbar. </div> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body> </html>
Output:
Supported Browsers: The browser supported by scrollbar-width property are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
ysachin2314
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
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": 26621,
"s": 26593,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 27009,
"s": 26621,
"text": "The scrollbar-width property is used to set the width or thickness of an element’s scrollbar when shown. This property can be used on pages where the user interface requires the element to be displayed more prominently and shrinking the scrollbar width gives more space to the element.This a currently an experimental property and some of the major browsers may not be supported.Syntax: "
},
{
"code": null,
"e": 27065,
"s": 27009,
"text": "scrollbar-width: auto | thin | none | initial | inherit"
},
{
"code": null,
"e": 27084,
"s": 27065,
"text": "Property Values: "
},
{
"code": null,
"e": 27203,
"s": 27084,
"text": "auto: It is used to set the scrollbar width to be automatically set by the browser. It is the default value.Example: "
},
{
"code": null,
"e": 27208,
"s": 27203,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | scrollbar-width property</title> <style> .scrollbar-auto { scrollbar-width: auto; background-color: lightgreen; height: 150px; width: 200px; overflow-y: scroll; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | scrollbar-width</b> <p>scrollbar-width: auto</p> <div class=\"scrollbar-auto\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body> </html>",
"e": 28023,
"s": 27208,
"text": null
},
{
"code": null,
"e": 28033,
"s": 28023,
"text": "Output: "
},
{
"code": null,
"e": 28134,
"s": 28033,
"text": "thin: It is used to set the scrollbar width to a thinner variant of the default scrollbar.Example: "
},
{
"code": null,
"e": 28139,
"s": 28134,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | scrollbar-width</title> <style> .scrollbar-thin { scrollbar-width: thin; background-color: lightgreen; height: 150px; width: 200px; overflow-y: scroll; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | scrollbar-width</b> <p>scrollbar-width: thin</p> <div class=\"scrollbar-thin\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body> </html>",
"e": 28945,
"s": 28139,
"text": null
},
{
"code": null,
"e": 28955,
"s": 28945,
"text": "Output: "
},
{
"code": null,
"e": 29057,
"s": 28955,
"text": "none: It is used to completely hide the scrollbar, however the content is still scrollable.Example: "
},
{
"code": null,
"e": 29062,
"s": 29057,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | scrollbar-width</title> <style> .scrollbar-none { scrollbar-width: none; background-color: lightgreen; height: 150px; width: 200px; overflow-y: scroll; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | scrollbar-width</b> <p>scrollbar-width: none</p> <div class=\"scrollbar-none\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body> </html>",
"e": 29868,
"s": 29062,
"text": null
},
{
"code": null,
"e": 29878,
"s": 29868,
"text": "Output: "
},
{
"code": null,
"e": 29957,
"s": 29878,
"text": "initial: It is used to set the scrollbar width to its default value.Example: "
},
{
"code": null,
"e": 29962,
"s": 29957,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | scrollbar-width</title> <style> .scrollbar-initial { scrollbar-width: initial; background-color: lightgreen; height: 150px; width: 200px; overflow-y: scroll; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | scrollbar-width</b> <p>scrollbar-width: initial</p> <div class=\"scrollbar-initial\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body> </html>",
"e": 30780,
"s": 29962,
"text": null
},
{
"code": null,
"e": 30790,
"s": 30780,
"text": "Output: "
},
{
"code": null,
"e": 30868,
"s": 30790,
"text": "inherit: It is used to inherit the scrollbar width from its parent.Example: "
},
{
"code": null,
"e": 30873,
"s": 30868,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | scrollbar-width</title> <style> .scrollbar-thin { scrollbar-width: thin; background-color: lightgreen; height: 150px; width: 200px; overflow-y: scroll; margin: 10px; } .scrollbar-inherit { scrollbar-width: inherit; background-color: green; height: 50px; width: 150px; overflow-y: scroll; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | scrollbar-width</b> <p>scrollbar-width: inherit</p> <div class=\"scrollbar-thin\"> <div class=\"scrollbar-inherit\"> This text is inside a parent element. This div has an inherited scrollbar. </div> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body> </html>",
"e": 32048,
"s": 30873,
"text": null
},
{
"code": null,
"e": 32058,
"s": 32048,
"text": "Output: "
},
{
"code": null,
"e": 32147,
"s": 32058,
"text": "Supported Browsers: The browser supported by scrollbar-width property are listed below: "
},
{
"code": null,
"e": 32161,
"s": 32147,
"text": "Google Chrome"
},
{
"code": null,
"e": 32179,
"s": 32161,
"text": "Internet Explorer"
},
{
"code": null,
"e": 32187,
"s": 32179,
"text": "Firefox"
},
{
"code": null,
"e": 32193,
"s": 32187,
"text": "Opera"
},
{
"code": null,
"e": 32201,
"s": 32193,
"text": "Safari "
},
{
"code": null,
"e": 32213,
"s": 32201,
"text": "ysachin2314"
},
{
"code": null,
"e": 32228,
"s": 32213,
"text": "CSS-Properties"
},
{
"code": null,
"e": 32232,
"s": 32228,
"text": "CSS"
},
{
"code": null,
"e": 32249,
"s": 32232,
"text": "Web Technologies"
},
{
"code": null,
"e": 32347,
"s": 32249,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32386,
"s": 32347,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 32423,
"s": 32386,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 32452,
"s": 32423,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32494,
"s": 32452,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 32529,
"s": 32494,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 32569,
"s": 32529,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32602,
"s": 32569,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32647,
"s": 32602,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32690,
"s": 32647,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Benefit of NumPy arrays over Python arrays - GeeksforGeeks
|
05 Sep, 2020
The need for NumPy arises when we are working with multi-dimensional arrays. The traditional array module does not support multi-dimensional arrays.
Let’s first try to create a single-dimensional array (i.e one row & multiple columns) in Python without installing NumPy Package to get a more clear picture.
Python3
from array import * arr = array('i', [25, 16, 3])print(arr)
Output:
array('i', [25, 16, 3])
Now, Let’s try to create a multi-dimensional array by using the array module.
Python3
from array import * arr = array('i', [25, 16, 3], [5, 19, 28])print(arr)
Output:
TypeError: array() takes at most 2 arguments (3 given)
We see that the array module does not support multi-dimensional array, this is where we require NumPy. NumPy supports large, multi-dimensional arrays and has a large collection of high-level math functions that can operate on those arrays.
Let’s use NumPy to create a multi-dimensional array.
Python3
from numpy import * arr = array ([[25, 31, 3], [5, 19, 28]])print(arr)
Output:
[[25 31 3]
[ 5 19 28]]
Python-numpy
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 | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25563,
"s": 25535,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 25712,
"s": 25563,
"text": "The need for NumPy arises when we are working with multi-dimensional arrays. The traditional array module does not support multi-dimensional arrays."
},
{
"code": null,
"e": 25870,
"s": 25712,
"text": "Let’s first try to create a single-dimensional array (i.e one row & multiple columns) in Python without installing NumPy Package to get a more clear picture."
},
{
"code": null,
"e": 25878,
"s": 25870,
"text": "Python3"
},
{
"code": "from array import * arr = array('i', [25, 16, 3])print(arr)",
"e": 25941,
"s": 25878,
"text": null
},
{
"code": null,
"e": 25949,
"s": 25941,
"text": "Output:"
},
{
"code": null,
"e": 25974,
"s": 25949,
"text": "array('i', [25, 16, 3])\n"
},
{
"code": null,
"e": 26052,
"s": 25974,
"text": "Now, Let’s try to create a multi-dimensional array by using the array module."
},
{
"code": null,
"e": 26060,
"s": 26052,
"text": "Python3"
},
{
"code": "from array import * arr = array('i', [25, 16, 3], [5, 19, 28])print(arr)",
"e": 26136,
"s": 26060,
"text": null
},
{
"code": null,
"e": 26144,
"s": 26136,
"text": "Output:"
},
{
"code": null,
"e": 26200,
"s": 26144,
"text": "TypeError: array() takes at most 2 arguments (3 given)\n"
},
{
"code": null,
"e": 26440,
"s": 26200,
"text": "We see that the array module does not support multi-dimensional array, this is where we require NumPy. NumPy supports large, multi-dimensional arrays and has a large collection of high-level math functions that can operate on those arrays."
},
{
"code": null,
"e": 26493,
"s": 26440,
"text": "Let’s use NumPy to create a multi-dimensional array."
},
{
"code": null,
"e": 26501,
"s": 26493,
"text": "Python3"
},
{
"code": "from numpy import * arr = array ([[25, 31, 3], [5, 19, 28]])print(arr)",
"e": 26575,
"s": 26501,
"text": null
},
{
"code": null,
"e": 26583,
"s": 26575,
"text": "Output:"
},
{
"code": null,
"e": 26609,
"s": 26583,
"text": "[[25 31 3]\n [ 5 19 28]]\n"
},
{
"code": null,
"e": 26622,
"s": 26609,
"text": "Python-numpy"
},
{
"code": null,
"e": 26629,
"s": 26622,
"text": "Python"
},
{
"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": 26759,
"s": 26727,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26801,
"s": 26759,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26843,
"s": 26801,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26899,
"s": 26843,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26926,
"s": 26899,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26965,
"s": 26926,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26996,
"s": 26965,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27025,
"s": 26996,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27047,
"s": 27025,
"text": "Defaultdict in Python"
}
] |
How to display text on boxplot in Python? - GeeksforGeeks
|
21 Jul, 2021
Boxplot is an important graphical plot that can be used to get a summary of data present in numerical form. The plot can give us information about statistical measures such as percentile, median, minimum and maximum values of the numerical data. In the box plot, the line which passes through the center of the box represents the median value. In this article, we will be learning about how to add plot a boxplot and display text on the boxplot.
Firstly, to create boxplot we’ll use the seaborn library, and to display text on the boxplot we will be using the text() method available inside the matplotlib.pyplot class. The text() method enables us to write strings on the plots and add customizations to them.
Let’s plot a simple boxplot at first and add some text over it.
Python
# import modulesimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltplt.style.use('seaborn') # Reading the datasetdata = pd.read_csv('Dataset.csv')print("The shape of the dataframe is: ",data.shape)
Output:
The shape of the dataframe is: (20, 3)
Printing the first five rows in the dataset:
Python
# display dataprint(data.head())
Output:
Python
# depict box plot visualizationplt.figure(figsize=(10, 6))sns.boxplot(data['Width (in cm)'])plt.text(75, 0.07, 'Outliers beyond beyond 75% value', fontsize=14)plt.show()
Output:
We can observe from the above-written code, that plt.text() method was used to display the desired text that we want. It requires three compulsory positional arguments:
Syntax: plt.text(x, y, text)
Parameters:
x-coordinate: denotes the location of the text on x-axis
y-coordinate: denotes the location of text on y-axis
text: denotes the string that we want to insert.
To make our box plot look more appealing we can pass many other optional parameters for formatting the text which has been discussed in the next plot.
Python
# add textplt.figure(figsize=(10, 6))sns.boxplot(data['Height (in cm)']) plt.text(3, 0.07, 'Points beyond 25% value', bbox=dict(facecolor='red', alpha=0.5), fontsize=12) plt.text(95, 0.07, 'Points beyond beyond 75% value', bbox=dict(facecolor='pink', alpha=0.5), horizontalalignment='right', fontsize=12) plt.show()
Output:
As can be observed from the plot we have added a nice bounding box around our text and have also added colours onto our text that can be done by passing the optional parameters inside plt.text() method such as:
bbox: used to create a bounding box around the text which itself accepts a dictionary for adding color to the box and setting the opacity of color.
fontsize: used to set the size of our font.
horizontalalignment or ha: to set the alignment of the text horizontally.
verticalalignment or va: to set the alignment of the text vertically.
And there are many others as well that can be seen from the official documentation of the method.
sumitgumber28
Data Visualization
Picked
Python-matplotlib
Python-Seaborn
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 25983,
"s": 25537,
"text": "Boxplot is an important graphical plot that can be used to get a summary of data present in numerical form. The plot can give us information about statistical measures such as percentile, median, minimum and maximum values of the numerical data. In the box plot, the line which passes through the center of the box represents the median value. In this article, we will be learning about how to add plot a boxplot and display text on the boxplot."
},
{
"code": null,
"e": 26248,
"s": 25983,
"text": "Firstly, to create boxplot we’ll use the seaborn library, and to display text on the boxplot we will be using the text() method available inside the matplotlib.pyplot class. The text() method enables us to write strings on the plots and add customizations to them."
},
{
"code": null,
"e": 26312,
"s": 26248,
"text": "Let’s plot a simple boxplot at first and add some text over it."
},
{
"code": null,
"e": 26319,
"s": 26312,
"text": "Python"
},
{
"code": "# import modulesimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltplt.style.use('seaborn') # Reading the datasetdata = pd.read_csv('Dataset.csv')print(\"The shape of the dataframe is: \",data.shape)",
"e": 26555,
"s": 26319,
"text": null
},
{
"code": null,
"e": 26563,
"s": 26555,
"text": "Output:"
},
{
"code": null,
"e": 26603,
"s": 26563,
"text": "The shape of the dataframe is: (20, 3)"
},
{
"code": null,
"e": 26648,
"s": 26603,
"text": "Printing the first five rows in the dataset:"
},
{
"code": null,
"e": 26655,
"s": 26648,
"text": "Python"
},
{
"code": "# display dataprint(data.head())",
"e": 26688,
"s": 26655,
"text": null
},
{
"code": null,
"e": 26699,
"s": 26691,
"text": "Output:"
},
{
"code": null,
"e": 26710,
"s": 26703,
"text": "Python"
},
{
"code": "# depict box plot visualizationplt.figure(figsize=(10, 6))sns.boxplot(data['Width (in cm)'])plt.text(75, 0.07, 'Outliers beyond beyond 75% value', fontsize=14)plt.show()",
"e": 26880,
"s": 26710,
"text": null
},
{
"code": null,
"e": 26891,
"s": 26883,
"text": "Output:"
},
{
"code": null,
"e": 27064,
"s": 26895,
"text": "We can observe from the above-written code, that plt.text() method was used to display the desired text that we want. It requires three compulsory positional arguments:"
},
{
"code": null,
"e": 27096,
"s": 27066,
"text": "Syntax: plt.text(x, y, text) "
},
{
"code": null,
"e": 27108,
"s": 27096,
"text": "Parameters:"
},
{
"code": null,
"e": 27165,
"s": 27108,
"text": "x-coordinate: denotes the location of the text on x-axis"
},
{
"code": null,
"e": 27218,
"s": 27165,
"text": "y-coordinate: denotes the location of text on y-axis"
},
{
"code": null,
"e": 27267,
"s": 27218,
"text": "text: denotes the string that we want to insert."
},
{
"code": null,
"e": 27420,
"s": 27269,
"text": "To make our box plot look more appealing we can pass many other optional parameters for formatting the text which has been discussed in the next plot."
},
{
"code": null,
"e": 27427,
"s": 27420,
"text": "Python"
},
{
"code": "# add textplt.figure(figsize=(10, 6))sns.boxplot(data['Height (in cm)']) plt.text(3, 0.07, 'Points beyond 25% value', bbox=dict(facecolor='red', alpha=0.5), fontsize=12) plt.text(95, 0.07, 'Points beyond beyond 75% value', bbox=dict(facecolor='pink', alpha=0.5), horizontalalignment='right', fontsize=12) plt.show()",
"e": 27835,
"s": 27427,
"text": null
},
{
"code": null,
"e": 27843,
"s": 27835,
"text": "Output:"
},
{
"code": null,
"e": 28054,
"s": 27843,
"text": "As can be observed from the plot we have added a nice bounding box around our text and have also added colours onto our text that can be done by passing the optional parameters inside plt.text() method such as:"
},
{
"code": null,
"e": 28202,
"s": 28054,
"text": "bbox: used to create a bounding box around the text which itself accepts a dictionary for adding color to the box and setting the opacity of color."
},
{
"code": null,
"e": 28246,
"s": 28202,
"text": "fontsize: used to set the size of our font."
},
{
"code": null,
"e": 28320,
"s": 28246,
"text": "horizontalalignment or ha: to set the alignment of the text horizontally."
},
{
"code": null,
"e": 28390,
"s": 28320,
"text": "verticalalignment or va: to set the alignment of the text vertically."
},
{
"code": null,
"e": 28488,
"s": 28390,
"text": "And there are many others as well that can be seen from the official documentation of the method."
},
{
"code": null,
"e": 28502,
"s": 28488,
"text": "sumitgumber28"
},
{
"code": null,
"e": 28521,
"s": 28502,
"text": "Data Visualization"
},
{
"code": null,
"e": 28528,
"s": 28521,
"text": "Picked"
},
{
"code": null,
"e": 28546,
"s": 28528,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 28561,
"s": 28546,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 28568,
"s": 28561,
"text": "Python"
},
{
"code": null,
"e": 28666,
"s": 28568,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28698,
"s": 28666,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28740,
"s": 28698,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28782,
"s": 28740,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28809,
"s": 28782,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28865,
"s": 28809,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28887,
"s": 28865,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28926,
"s": 28887,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28957,
"s": 28926,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28986,
"s": 28957,
"text": "Create a directory in Python"
}
] |
Jetpack DataStore in Android - GeeksforGeeks
|
03 Sep, 2021
Jetpack DataStore is a data storage solution that uses protocol buffers to store key-value pairs or typed objects. DataStore stores data asynchronously, reliably, and transactionally using Kotlin coroutines and Flow. In this article, we will look at why we need Jetpack DataStore Preferences, how to build them in our Android application, and how to move our SharedPreferences to DataStore Preferences.
The following topics will be discussed in the blog:
Why should you use Jetpack DataStore?DataStore Preferences vs. SharedPreferencesJetpack DataStore Preferences ImplementationTransferring SharedPreferences to DataStore Preferences
Why should you use Jetpack DataStore?
DataStore Preferences vs. SharedPreferences
Jetpack DataStore Preferences Implementation
Transferring SharedPreferences to DataStore Preferences
But, First and foremost:
According to the official documentation:
Jetpack DataStore is a persistent and enhanced data store, which is here to revolutionize how we store prefs.
It is based on Coroutines and Flows in Kotlin.
Data is saved asynchronously, consistently, and transactionally, eliminating the majority of SharedPreferences’ shortcomings.
The above-mentioned enhancements are fantastic.
Example: It is assumed that you are working on an Android application with a high number of downloads, that the program is available on Google Play, and that it has undergone several upgrades and bug patches over time. As a result, the app began to get ANR at some point (Application Not Responding). The cause of ANR is that the program is doing a long-running operation on the UI Thread. (Longer than 5 seconds)
The main issue was that our shared preferences file had grown too large as we continued to add new key-value pairs one by one. On the UI Thread, we were attempting to retrieve the value for a specific key as soon as the program launched. However, when you visit SharedPreferences for the first time, it reads the entire file and loads the contents into memory. And this was occurring on UI Thread for us.
This is an input/output operation. It may take some time. In our instance, it was leading to ANR for the larger file. Furthermore, the present implementation of Jetpack DataStore discourages data reading on the UI Thread. This was one of my favorite aspects of it. And now, we’re integrating Jetpack DataStore into our app. Let’s compare SharedPreferences to DataStore Preferences
DataStore Preferences
SharedPreferences
Include the following dependency in your app’s build.gradle file.
implementation "androidx.datastore:datastore-preferences:1.0.0"
GeekTip: Always try to use the latest release.
Now, similarly to the SharedPreferences object, we must build the DataStore Preferences object.
Kotlin
val gfgDataStore: DataStore<Preferences> = context.createDataStore(name = "gfg-datastore") // A data store object sample
Then we construct two extension functions to read and write data. This is only for your convenience.
Kotlin
fun <gfg> DataStore<Preferences>.getValueFlow( your_key: Preferences.Key<gfg>, someDefaultValue: gfg // Value is gfg here): Flow<gfg> { return this.data .catch { exception -> if (exception is IOException) { emit(emptyPreferences()) } else { // Exception handling throw exception } }.map { preferences -> preferences[your_key] ?: someDefaultValue }} suspend fun <gfg> DataStore<Preferences>.setValue(your_key: Preferences.Key<gfg>, value: gfg) { this.edit { preferences -> preferences[your_key] = value }}
Then, as seen below, we establish Preferences Keys:
Kotlin
companion object { private val GEEKSFORGEEKS = preferencesKey<String>("spandan-saxena")}
Now, that’s how we read the following data from the DataStore Preferences:
Kotlin
sampleViewModel.launch { dataStore.getValueFlow(GEEKSFORGEEKS, "") .collect { value -> // get the value and then use it }}
We may manage the problem in this case by using the catch operator on the flow.
Kotlin
sampleViewModel.launch { dataStore.getValueFlow(GEEKSFORGEEKS, "") .catch { // exception handling } .collect { value -> // collect the value }}
This is how we can easily incorporate it into our Android app. Let us now discuss the conversion from SharedPreferences to DataStore Preferences.
When it comes to migration, DataStore takes care of everything. We just need to supply the names of the SharedPreferences. For example, if the name of SharedPreferences is “gfg-prefs,” we must perform the following:
Kotlin
val sampleDataStore: DataStore<Prefs> = context.createDataStore( name = "gfg-prefs", migrations = listOf(SharedPreferencesMigration(context, "gfg-prefs")) )
We can see that there are other alternatives accessible, which we may employ based on our use-cases. Migrating from SharedPreferences to DataStore Preferences is made much easier in this manner. SharedPreferences has numerous disadvantages, including asynchronous API that may look safe to call on the UI thread, no method for reporting failures, no transactional API, and more. DataStore is a substitute for SharedPreferences that address the majority of these issues. DataStore offers a completely asynchronous API built using Kotlin coroutines and Flow that manages data migration, data consistency, and data corruption.
kapoorsagar226
Android-Jetpack
Picked
Android
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?
How to Get Current Location in Android?
Android Listview in Java with Example
How to Save Data to the Firebase Realtime Database in Android?
How to Change the Background Color After Clicking the Button in Android?
GridView in Android with Example
|
[
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n03 Sep, 2021"
},
{
"code": null,
"e": 26784,
"s": 26381,
"text": "Jetpack DataStore is a data storage solution that uses protocol buffers to store key-value pairs or typed objects. DataStore stores data asynchronously, reliably, and transactionally using Kotlin coroutines and Flow. In this article, we will look at why we need Jetpack DataStore Preferences, how to build them in our Android application, and how to move our SharedPreferences to DataStore Preferences."
},
{
"code": null,
"e": 26836,
"s": 26784,
"text": "The following topics will be discussed in the blog:"
},
{
"code": null,
"e": 27016,
"s": 26836,
"text": "Why should you use Jetpack DataStore?DataStore Preferences vs. SharedPreferencesJetpack DataStore Preferences ImplementationTransferring SharedPreferences to DataStore Preferences"
},
{
"code": null,
"e": 27054,
"s": 27016,
"text": "Why should you use Jetpack DataStore?"
},
{
"code": null,
"e": 27098,
"s": 27054,
"text": "DataStore Preferences vs. SharedPreferences"
},
{
"code": null,
"e": 27143,
"s": 27098,
"text": "Jetpack DataStore Preferences Implementation"
},
{
"code": null,
"e": 27199,
"s": 27143,
"text": "Transferring SharedPreferences to DataStore Preferences"
},
{
"code": null,
"e": 27225,
"s": 27199,
"text": "But, First and foremost: "
},
{
"code": null,
"e": 27266,
"s": 27225,
"text": "According to the official documentation:"
},
{
"code": null,
"e": 27376,
"s": 27266,
"text": "Jetpack DataStore is a persistent and enhanced data store, which is here to revolutionize how we store prefs."
},
{
"code": null,
"e": 27423,
"s": 27376,
"text": "It is based on Coroutines and Flows in Kotlin."
},
{
"code": null,
"e": 27549,
"s": 27423,
"text": "Data is saved asynchronously, consistently, and transactionally, eliminating the majority of SharedPreferences’ shortcomings."
},
{
"code": null,
"e": 27597,
"s": 27549,
"text": "The above-mentioned enhancements are fantastic."
},
{
"code": null,
"e": 28011,
"s": 27597,
"text": "Example: It is assumed that you are working on an Android application with a high number of downloads, that the program is available on Google Play, and that it has undergone several upgrades and bug patches over time. As a result, the app began to get ANR at some point (Application Not Responding). The cause of ANR is that the program is doing a long-running operation on the UI Thread. (Longer than 5 seconds)"
},
{
"code": null,
"e": 28416,
"s": 28011,
"text": "The main issue was that our shared preferences file had grown too large as we continued to add new key-value pairs one by one. On the UI Thread, we were attempting to retrieve the value for a specific key as soon as the program launched. However, when you visit SharedPreferences for the first time, it reads the entire file and loads the contents into memory. And this was occurring on UI Thread for us."
},
{
"code": null,
"e": 28797,
"s": 28416,
"text": "This is an input/output operation. It may take some time. In our instance, it was leading to ANR for the larger file. Furthermore, the present implementation of Jetpack DataStore discourages data reading on the UI Thread. This was one of my favorite aspects of it. And now, we’re integrating Jetpack DataStore into our app. Let’s compare SharedPreferences to DataStore Preferences"
},
{
"code": null,
"e": 28819,
"s": 28797,
"text": "DataStore Preferences"
},
{
"code": null,
"e": 28837,
"s": 28819,
"text": "SharedPreferences"
},
{
"code": null,
"e": 28903,
"s": 28837,
"text": "Include the following dependency in your app’s build.gradle file."
},
{
"code": null,
"e": 28967,
"s": 28903,
"text": "implementation \"androidx.datastore:datastore-preferences:1.0.0\""
},
{
"code": null,
"e": 29014,
"s": 28967,
"text": "GeekTip: Always try to use the latest release."
},
{
"code": null,
"e": 29110,
"s": 29014,
"text": "Now, similarly to the SharedPreferences object, we must build the DataStore Preferences object."
},
{
"code": null,
"e": 29117,
"s": 29110,
"text": "Kotlin"
},
{
"code": "val gfgDataStore: DataStore<Preferences> = context.createDataStore(name = \"gfg-datastore\") // A data store object sample",
"e": 29244,
"s": 29117,
"text": null
},
{
"code": null,
"e": 29345,
"s": 29244,
"text": "Then we construct two extension functions to read and write data. This is only for your convenience."
},
{
"code": null,
"e": 29352,
"s": 29345,
"text": "Kotlin"
},
{
"code": "fun <gfg> DataStore<Preferences>.getValueFlow( your_key: Preferences.Key<gfg>, someDefaultValue: gfg // Value is gfg here): Flow<gfg> { return this.data .catch { exception -> if (exception is IOException) { emit(emptyPreferences()) } else { // Exception handling throw exception } }.map { preferences -> preferences[your_key] ?: someDefaultValue }} suspend fun <gfg> DataStore<Preferences>.setValue(your_key: Preferences.Key<gfg>, value: gfg) { this.edit { preferences -> preferences[your_key] = value }}",
"e": 29993,
"s": 29352,
"text": null
},
{
"code": null,
"e": 30045,
"s": 29993,
"text": "Then, as seen below, we establish Preferences Keys:"
},
{
"code": null,
"e": 30052,
"s": 30045,
"text": "Kotlin"
},
{
"code": "companion object { private val GEEKSFORGEEKS = preferencesKey<String>(\"spandan-saxena\")}",
"e": 30144,
"s": 30052,
"text": null
},
{
"code": null,
"e": 30219,
"s": 30144,
"text": "Now, that’s how we read the following data from the DataStore Preferences:"
},
{
"code": null,
"e": 30226,
"s": 30219,
"text": "Kotlin"
},
{
"code": "sampleViewModel.launch { dataStore.getValueFlow(GEEKSFORGEEKS, \"\") .collect { value -> // get the value and then use it }}",
"e": 30377,
"s": 30226,
"text": null
},
{
"code": null,
"e": 30457,
"s": 30377,
"text": "We may manage the problem in this case by using the catch operator on the flow."
},
{
"code": null,
"e": 30464,
"s": 30457,
"text": "Kotlin"
},
{
"code": "sampleViewModel.launch { dataStore.getValueFlow(GEEKSFORGEEKS, \"\") .catch { // exception handling } .collect { value -> // collect the value }}",
"e": 30661,
"s": 30464,
"text": null
},
{
"code": null,
"e": 30807,
"s": 30661,
"text": "This is how we can easily incorporate it into our Android app. Let us now discuss the conversion from SharedPreferences to DataStore Preferences."
},
{
"code": null,
"e": 31023,
"s": 30807,
"text": "When it comes to migration, DataStore takes care of everything. We just need to supply the names of the SharedPreferences. For example, if the name of SharedPreferences is “gfg-prefs,” we must perform the following:"
},
{
"code": null,
"e": 31030,
"s": 31023,
"text": "Kotlin"
},
{
"code": "val sampleDataStore: DataStore<Prefs> = context.createDataStore( name = \"gfg-prefs\", migrations = listOf(SharedPreferencesMigration(context, \"gfg-prefs\")) )",
"e": 31207,
"s": 31030,
"text": null
},
{
"code": null,
"e": 31831,
"s": 31207,
"text": "We can see that there are other alternatives accessible, which we may employ based on our use-cases. Migrating from SharedPreferences to DataStore Preferences is made much easier in this manner. SharedPreferences has numerous disadvantages, including asynchronous API that may look safe to call on the UI thread, no method for reporting failures, no transactional API, and more. DataStore is a substitute for SharedPreferences that address the majority of these issues. DataStore offers a completely asynchronous API built using Kotlin coroutines and Flow that manages data migration, data consistency, and data corruption."
},
{
"code": null,
"e": 31846,
"s": 31831,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 31862,
"s": 31846,
"text": "Android-Jetpack"
},
{
"code": null,
"e": 31869,
"s": 31862,
"text": "Picked"
},
{
"code": null,
"e": 31877,
"s": 31869,
"text": "Android"
},
{
"code": null,
"e": 31885,
"s": 31877,
"text": "Android"
},
{
"code": null,
"e": 31983,
"s": 31885,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32021,
"s": 31983,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 32060,
"s": 32021,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 32110,
"s": 32060,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 32152,
"s": 32110,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 32203,
"s": 32152,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 32243,
"s": 32203,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 32281,
"s": 32243,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 32344,
"s": 32281,
"text": "How to Save Data to the Firebase Realtime Database in Android?"
},
{
"code": null,
"e": 32417,
"s": 32344,
"text": "How to Change the Background Color After Clicking the Button in Android?"
}
] |
How to restrict UITextField to take only numbers in Swift?
|
In iOS apps sometimes we need to restrict our text field to take only numbers as an input, this can be done in several ways, let’s see some of them.
Select the text field that you want to restrict to numeric input.
Go to its attribute inspector.
Select the keyboard type and choose number pad from there.
Select the text field
Create its outlet in the view controller.
Conform the view controller to UITextFieldDelegate
Set the text field’s delegate
Add the following function
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let x = string.rangeOfCharacter(from: NSCharacterSet.decimalDigits) {
return true
} else {
return false
}
}
Our whole example class looks like
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var tf: UITextField!
override func viewDidLoad() {
tf.delegate = self
super.viewDidLoad()
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let x = string.rangeOfCharacter(from: NSCharacterSet.decimalDigits) {
return true
} else {
return false
}
}
}
This will create a text field that can only take digits as input and no other character.
|
[
{
"code": null,
"e": 1211,
"s": 1062,
"text": "In iOS apps sometimes we need to restrict our text field to take only numbers as an input, this can be done in several ways, let’s see some of them."
},
{
"code": null,
"e": 1277,
"s": 1211,
"text": "Select the text field that you want to restrict to numeric input."
},
{
"code": null,
"e": 1308,
"s": 1277,
"text": "Go to its attribute inspector."
},
{
"code": null,
"e": 1367,
"s": 1308,
"text": "Select the keyboard type and choose number pad from there."
},
{
"code": null,
"e": 1389,
"s": 1367,
"text": "Select the text field"
},
{
"code": null,
"e": 1431,
"s": 1389,
"text": "Create its outlet in the view controller."
},
{
"code": null,
"e": 1482,
"s": 1431,
"text": "Conform the view controller to UITextFieldDelegate"
},
{
"code": null,
"e": 1512,
"s": 1482,
"text": "Set the text field’s delegate"
},
{
"code": null,
"e": 1539,
"s": 1512,
"text": "Add the following function"
},
{
"code": null,
"e": 1797,
"s": 1539,
"text": "func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {\n if let x = string.rangeOfCharacter(from: NSCharacterSet.decimalDigits) {\n return true\n } else {\n return false\n }\n}"
},
{
"code": null,
"e": 1832,
"s": 1797,
"text": "Our whole example class looks like"
},
{
"code": null,
"e": 2340,
"s": 1832,
"text": "import UIKit\nclass ViewController: UIViewController, UITextFieldDelegate {\n @IBOutlet weak var tf: UITextField!\n override func viewDidLoad() {\n tf.delegate = self\n super.viewDidLoad()\n }\n func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {\n if let x = string.rangeOfCharacter(from: NSCharacterSet.decimalDigits) {\n return true\n } else {\n return false\n }\n }\n}"
},
{
"code": null,
"e": 2429,
"s": 2340,
"text": "This will create a text field that can only take digits as input and no other character."
}
] |
StAX XML Parser in Java - GeeksforGeeks
|
29 Dec, 2021
This article focuses on how one can parse a XML file in Java.XML : XML stands for eXtensible Markup Language. It was designed to store and transport data. It was designed to be both human- and machine-readable. That’s why, the design goals of XML emphasize simplicity, generality, and usability across the Internet.
Why StAX instead of SAX ?
SAX: The SAX is a push model API which means that it is the API which calls your handler, not your handler that calls the API . The SAX parser thus “pushes” events into your handler. With this push model of API you have no control over how and when the parser iterates over the file. Once you start the parser, it iterates all the way until the end, calling your handler for each and every XML event in the input XML document.
SAX Parser --> Handler
StAX : The StAX pull model means that it is your “handler” class that calls the parser API , not the other way around. Thus your handler class controls when the parser is to move on to the next event in the input. In other words, your handler “pulls” the XML events out of the parser. Additionally, you can stop the parsing at any point. The StAX parser is generally used instead of a file reader , when the input or database is given in the form of offline or online xml file. The pull model of is summarized like this:
Handler --> StAX Parser
Also StAX parser can read and write in the XML documents while SAX can only read. SAX provides the schema validation i.e. if the tags are nested correctly or XML is correctly written , but StAX provides no such method of schema validation.
Implementation
Idea of How StAX parser works :
Input File : This is sample input file made by the author as an example to show how StAX parser is used . Save it as data.xml and run the code . XML database files usually are large and contains many tags nested within each other .
Java
// Java Code to implement StAX parserimport java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.util.Iterator;import javax.xml.namespace.QName;import javax.xml.stream.XMLEventReader;import javax.xml.stream.XMLInputFactory;import javax.xml.stream.XMLStreamException;import javax.xml.stream.events.*; public class Main{ private static boolean bcompany,btitle,bname,bemail,bphone; public static void main(String[] args) throws FileNotFoundException, XMLStreamException { // Create a File object with appropriate xml file name File file = new File("data.xml"); // Function for accessing the data parser(file); } public static void parser(File file) throws FileNotFoundException, XMLStreamException { // Variables to make sure whether a element // in the xml is being accessed or not // if false that means elements is // not been used currently , if true the element or the // tag is being used currently bcompany = btitle = bname = bemail = bphone = false; // Instance of the class which helps on reading tags XMLInputFactory factory = XMLInputFactory.newInstance(); // Initializing the handler to access the tags in the XML file XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(file)); // Checking the availability of the next tag while (eventReader.hasNext()) { // Event is actually the tag . It is of 3 types // <name> = StartEvent // </name> = EndEvent // data between the StartEvent and the EndEvent // which is Characters Event XMLEvent event = eventReader.nextEvent(); // This will trigger when the tag is of type <...> if (event.isStartElement()) { StartElement element = (StartElement)event; // Iterator for accessing the metadeta related // the tag started. // Here, it would name of the company Iterator<Attribute> iterator = element.getAttributes(); while (iterator.hasNext()) { Attribute attribute = iterator.next(); QName name = attribute.getName(); String value = attribute.getValue(); System.out.println(name+" = " + value); } // Checking which tag needs to be opened for reading. // If the tag matches then the boolean of that tag // is set to be true. if (element.getName().toString().equalsIgnoreCase("company")) { bcompany = true; } if (element.getName().toString().equalsIgnoreCase("title")) { btitle = true; } if (element.getName().toString().equalsIgnoreCase("name")) { bname = true; } if (element.getName().toString().equalsIgnoreCase("email")) { bemail = true; } if (element.getName().toString().equalsIgnoreCase("phone")) { bphone = true; } } // This will be triggered when the tag is of type </...> if (event.isEndElement()) { EndElement element = (EndElement) event; // Checking which tag needs to be closed after reading. // If the tag matches then the boolean of that tag is // set to be false. if (element.getName().toString().equalsIgnoreCase("company")) { bcompany = false; } if (element.getName().toString().equalsIgnoreCase("title")) { btitle = false; } if (element.getName().toString().equalsIgnoreCase("name")) { bname = false; } if (element.getName().toString().equalsIgnoreCase("email")) { bemail = false; } if (element.getName().toString().equalsIgnoreCase("phone")) { bphone = false; } } // Triggered when there is data after the tag which is // currently opened. if (event.isCharacters()) { // Depending upon the tag opened the data is retrieved . Characters element = (Characters) event; if (bcompany) { System.out.println(element.getData()); } if (btitle) { System.out.println(element.getData()); } if (bname) { System.out.println(element.getData()); } if (bemail) { System.out.println(element.getData()); } if (bphone) { System.out.println(element.getData()); } } } }}
Output :
name = geeksforgeeks.org
Kunal Sharma
Student
kunal@example.com
(202) 456-1414
How does StAX work in the above Code ?
After creating the eventReader in the above code with the help of factory pattern to create a XML file reader, it basically starts by reading the <...> tag . As soon as <...> tag comes, a boolean variable is set to true indicating that the tag has been opened. This tag matching is done by identifying whether it is a start tag or end tag. Since <...> tag indicates the starting, therefore it is matched by StartElement. Next comes the data reading part. In the next step, it reads the character/data by matching the element by isCharacters, this is done only if the starting tag that we require is opened or its boolean variable is set true. After this comes closing of element indicated by </...> tag. As soon it encounters </..> it checks which of the elements was opened or set to true and it sets that element boolean to false or closes it.
Basically each event is first opening the tag, reading its data and then closing it.
https://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html
https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/SJSXP2.html
This article is contributed by Kunal Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
abhishek0719kadiyan
simranarora5sos
anikakapoor
GBlog
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
Types of Software Testing
How to Start Learning DSA?
Working with csv files in Python
12 pip Commands For Python Developers
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Stream In Java
|
[
{
"code": null,
"e": 26391,
"s": 26363,
"text": "\n29 Dec, 2021"
},
{
"code": null,
"e": 26708,
"s": 26391,
"text": "This article focuses on how one can parse a XML file in Java.XML : XML stands for eXtensible Markup Language. It was designed to store and transport data. It was designed to be both human- and machine-readable. That’s why, the design goals of XML emphasize simplicity, generality, and usability across the Internet. "
},
{
"code": null,
"e": 26734,
"s": 26708,
"text": "Why StAX instead of SAX ?"
},
{
"code": null,
"e": 27161,
"s": 26734,
"text": "SAX: The SAX is a push model API which means that it is the API which calls your handler, not your handler that calls the API . The SAX parser thus “pushes” events into your handler. With this push model of API you have no control over how and when the parser iterates over the file. Once you start the parser, it iterates all the way until the end, calling your handler for each and every XML event in the input XML document."
},
{
"code": null,
"e": 27184,
"s": 27161,
"text": "SAX Parser --> Handler"
},
{
"code": null,
"e": 27706,
"s": 27184,
"text": "StAX : The StAX pull model means that it is your “handler” class that calls the parser API , not the other way around. Thus your handler class controls when the parser is to move on to the next event in the input. In other words, your handler “pulls” the XML events out of the parser. Additionally, you can stop the parsing at any point. The StAX parser is generally used instead of a file reader , when the input or database is given in the form of offline or online xml file. The pull model of is summarized like this:"
},
{
"code": null,
"e": 27730,
"s": 27706,
"text": "Handler --> StAX Parser"
},
{
"code": null,
"e": 27970,
"s": 27730,
"text": "Also StAX parser can read and write in the XML documents while SAX can only read. SAX provides the schema validation i.e. if the tags are nested correctly or XML is correctly written , but StAX provides no such method of schema validation."
},
{
"code": null,
"e": 27985,
"s": 27970,
"text": "Implementation"
},
{
"code": null,
"e": 28018,
"s": 27985,
"text": "Idea of How StAX parser works : "
},
{
"code": null,
"e": 28251,
"s": 28018,
"text": "Input File : This is sample input file made by the author as an example to show how StAX parser is used . Save it as data.xml and run the code . XML database files usually are large and contains many tags nested within each other . "
},
{
"code": null,
"e": 28256,
"s": 28251,
"text": "Java"
},
{
"code": "// Java Code to implement StAX parserimport java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.util.Iterator;import javax.xml.namespace.QName;import javax.xml.stream.XMLEventReader;import javax.xml.stream.XMLInputFactory;import javax.xml.stream.XMLStreamException;import javax.xml.stream.events.*; public class Main{ private static boolean bcompany,btitle,bname,bemail,bphone; public static void main(String[] args) throws FileNotFoundException, XMLStreamException { // Create a File object with appropriate xml file name File file = new File(\"data.xml\"); // Function for accessing the data parser(file); } public static void parser(File file) throws FileNotFoundException, XMLStreamException { // Variables to make sure whether a element // in the xml is being accessed or not // if false that means elements is // not been used currently , if true the element or the // tag is being used currently bcompany = btitle = bname = bemail = bphone = false; // Instance of the class which helps on reading tags XMLInputFactory factory = XMLInputFactory.newInstance(); // Initializing the handler to access the tags in the XML file XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(file)); // Checking the availability of the next tag while (eventReader.hasNext()) { // Event is actually the tag . It is of 3 types // <name> = StartEvent // </name> = EndEvent // data between the StartEvent and the EndEvent // which is Characters Event XMLEvent event = eventReader.nextEvent(); // This will trigger when the tag is of type <...> if (event.isStartElement()) { StartElement element = (StartElement)event; // Iterator for accessing the metadeta related // the tag started. // Here, it would name of the company Iterator<Attribute> iterator = element.getAttributes(); while (iterator.hasNext()) { Attribute attribute = iterator.next(); QName name = attribute.getName(); String value = attribute.getValue(); System.out.println(name+\" = \" + value); } // Checking which tag needs to be opened for reading. // If the tag matches then the boolean of that tag // is set to be true. if (element.getName().toString().equalsIgnoreCase(\"company\")) { bcompany = true; } if (element.getName().toString().equalsIgnoreCase(\"title\")) { btitle = true; } if (element.getName().toString().equalsIgnoreCase(\"name\")) { bname = true; } if (element.getName().toString().equalsIgnoreCase(\"email\")) { bemail = true; } if (element.getName().toString().equalsIgnoreCase(\"phone\")) { bphone = true; } } // This will be triggered when the tag is of type </...> if (event.isEndElement()) { EndElement element = (EndElement) event; // Checking which tag needs to be closed after reading. // If the tag matches then the boolean of that tag is // set to be false. if (element.getName().toString().equalsIgnoreCase(\"company\")) { bcompany = false; } if (element.getName().toString().equalsIgnoreCase(\"title\")) { btitle = false; } if (element.getName().toString().equalsIgnoreCase(\"name\")) { bname = false; } if (element.getName().toString().equalsIgnoreCase(\"email\")) { bemail = false; } if (element.getName().toString().equalsIgnoreCase(\"phone\")) { bphone = false; } } // Triggered when there is data after the tag which is // currently opened. if (event.isCharacters()) { // Depending upon the tag opened the data is retrieved . Characters element = (Characters) event; if (bcompany) { System.out.println(element.getData()); } if (btitle) { System.out.println(element.getData()); } if (bname) { System.out.println(element.getData()); } if (bemail) { System.out.println(element.getData()); } if (bphone) { System.out.println(element.getData()); } } } }}",
"e": 33696,
"s": 28256,
"text": null
},
{
"code": null,
"e": 33707,
"s": 33696,
"text": "Output : "
},
{
"code": null,
"e": 33786,
"s": 33707,
"text": "name = geeksforgeeks.org\nKunal Sharma\nStudent\nkunal@example.com\n(202) 456-1414"
},
{
"code": null,
"e": 33825,
"s": 33786,
"text": "How does StAX work in the above Code ?"
},
{
"code": null,
"e": 34672,
"s": 33825,
"text": "After creating the eventReader in the above code with the help of factory pattern to create a XML file reader, it basically starts by reading the <...> tag . As soon as <...> tag comes, a boolean variable is set to true indicating that the tag has been opened. This tag matching is done by identifying whether it is a start tag or end tag. Since <...> tag indicates the starting, therefore it is matched by StartElement. Next comes the data reading part. In the next step, it reads the character/data by matching the element by isCharacters, this is done only if the starting tag that we require is opened or its boolean variable is set true. After this comes closing of element indicated by </...> tag. As soon it encounters </..> it checks which of the elements was opened or set to true and it sets that element boolean to false or closes it. "
},
{
"code": null,
"e": 34758,
"s": 34672,
"text": "Basically each event is first opening the tag, reading its data and then closing it. "
},
{
"code": null,
"e": 34820,
"s": 34758,
"text": "https://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html"
},
{
"code": null,
"e": 34915,
"s": 34820,
"text": "https://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/SJSXP2.html"
},
{
"code": null,
"e": 35336,
"s": 34915,
"text": "This article is contributed by Kunal Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 35356,
"s": 35336,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 35372,
"s": 35356,
"text": "simranarora5sos"
},
{
"code": null,
"e": 35384,
"s": 35372,
"text": "anikakapoor"
},
{
"code": null,
"e": 35390,
"s": 35384,
"text": "GBlog"
},
{
"code": null,
"e": 35395,
"s": 35390,
"text": "Java"
},
{
"code": null,
"e": 35414,
"s": 35395,
"text": "Technical Scripter"
},
{
"code": null,
"e": 35419,
"s": 35414,
"text": "Java"
},
{
"code": null,
"e": 35517,
"s": 35419,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35542,
"s": 35517,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 35568,
"s": 35542,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 35595,
"s": 35568,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 35628,
"s": 35595,
"text": "Working with csv files in Python"
},
{
"code": null,
"e": 35666,
"s": 35628,
"text": "12 pip Commands For Python Developers"
},
{
"code": null,
"e": 35681,
"s": 35666,
"text": "Arrays in Java"
},
{
"code": null,
"e": 35725,
"s": 35681,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 35747,
"s": 35725,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 35798,
"s": 35747,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Bloomberg Interview | Set 1 (Phone Interview) - GeeksforGeeks
|
05 May, 2015
Click here to see the documentation of the video conference.
Before proceeding to reading this, make sure you read a little about bloomberg, and most importantly its R&D center in London, you will be given a good portion of time to tell the interviewer what you know about bloomberg, the interviewer said he worked for more than 11 years in bloomberg, so it won’t be good if you just made up some answers, just have a little read about it.
The interview, Ian, started an hour earlier, and the interviewer gave me some time to prepare my machine, if it happened to you, just don’t panic, and of course you can tell him you prefer to have the interview on time.
The interviewer started by introducing himself, and the technology he has been using in bloomberg.Next, I was asked to introduce myself, and we had a talk about my resume, my education and projects.
The interviewer then jumped to the technical question, by pasting the body of the code, in order to fill in the functions:
#include <map>#include <set>#include <list>#include <cmath>#include <ctime>#include <deque>#include <queue>#include <stack>#include <bitset>#include <cstdio>#include <limits>#include <vector>#include <cstdlib>#include <numeric>#include <sstream>#include <iostream>#include <algorithm>using namespace std; //1234//1,234 // 104450 -> 104,450// 123123123 -> 123,123,123 // 1000000 -> 10,00,000// 00010100 string formatNum(int num) { } int main() { string res; int _num; cin >> _num; res = formatNum(_num); cout << res; return 0;}
//This was a part of bloomberg’s first phone interview
The question was rather easy, I was asked to implement a function that given an integer number num, it returns the a string representation of the number, comma separated.i.e. f(1234) = “1,234”
My implementation was as follows:
string formatNum(int num) { int total_processed = 0; string ret = ""; while (num > 0){ if (total_processed != 0 && total_processed %3 == 0) ret += ","; ret += (char) (num %10 + '0'); total_processed ++; num /= 10; } reverse (ret.begin(), ret.end()); return ret;}
The interviewer then asked that the function should support different comma styles, i.e. the US vs Indian style//Indian 1000000 -> 10,00,000//US 1000000 -> 1,000,000
I suggested that a certain style should be passed to the function, either as an integer mask or a vector of integers, representing the positions at which a comma is needed.He asked if only a string abbreviation can be sent to the function instead of a vector, so I suggested using a map, which stores for each style code the corresponding vector of integers.
My implementation was as follows:
//EN style = {3, 6, 9, 12, 15}//IN style = {3, 5, 7, 9, 11, 13} //map <string, vector <int> > style_map string formatNum(int num, string rec_style) { int total_processed = 0; string ret = ""; vector <int> style = style_map[rec_style]; int n = style.size(); n--; while (num > 0){ //if (total_processed != 0 && total_processed %3 == 0) if (total_processed == style[n]){ ret += ","; n--; } ret += (char) (num %10 + '0'); total_processed ++; num /= 10; } reverse (ret.begin(), ret.end()); return ret;}
We then moved to another question, that’s concerned about the OOP.The interviewer asked what class would I create in order to make this code more usable.I suggested that I should create a class for the represented integer, to encapsulate its numerical value, its string value, its style, and the functions associated to it.
The code went as follows:
class something{ string num, rec_style; something(int n, string style); change_style(string new_style); bool operator < (something e) const{ }}
The interviewer then asked me to elaborate the inheritance principle.I illustrated it using the example of the vehicles (cars, vans, trucks, buses ....etc)and then we discussed my design preferences, concerning classes inheritance and polymorphism, and what to do: more inheritance vs more coding.My answer covered code maintenance and reusability.
I was then given the chance to ask the interviewer whatever I like about the company and his work in bloomberg.
Result: I moved to video conference with the other interviewers.
Summary: The interview is easy, you just have to stay cool, and try to give the answers to the point without any exaggerations, Good Luck!
You can check the documentation of the video conference here.
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Bloomberg
Interview Experiences
Bloomberg
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Zoho Interview | Set 3 (Off-Campus)
Difference between ANN, CNN and RNN
Amazon Interview Experience
Amazon Interview Experience for SDE-1
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
Amazon Interview Experience (Off-Campus) 2022
Infosys Interview Experience for DSE 2022
Amazon Interview Experience for SDE-1 (On-Campus)
|
[
{
"code": null,
"e": 27105,
"s": 27077,
"text": "\n05 May, 2015"
},
{
"code": null,
"e": 27166,
"s": 27105,
"text": "Click here to see the documentation of the video conference."
},
{
"code": null,
"e": 27545,
"s": 27166,
"text": "Before proceeding to reading this, make sure you read a little about bloomberg, and most importantly its R&D center in London, you will be given a good portion of time to tell the interviewer what you know about bloomberg, the interviewer said he worked for more than 11 years in bloomberg, so it won’t be good if you just made up some answers, just have a little read about it."
},
{
"code": null,
"e": 27765,
"s": 27545,
"text": "The interview, Ian, started an hour earlier, and the interviewer gave me some time to prepare my machine, if it happened to you, just don’t panic, and of course you can tell him you prefer to have the interview on time."
},
{
"code": null,
"e": 27964,
"s": 27765,
"text": "The interviewer started by introducing himself, and the technology he has been using in bloomberg.Next, I was asked to introduce myself, and we had a talk about my resume, my education and projects."
},
{
"code": null,
"e": 28087,
"s": 27964,
"text": "The interviewer then jumped to the technical question, by pasting the body of the code, in order to fill in the functions:"
},
{
"code": "#include <map>#include <set>#include <list>#include <cmath>#include <ctime>#include <deque>#include <queue>#include <stack>#include <bitset>#include <cstdio>#include <limits>#include <vector>#include <cstdlib>#include <numeric>#include <sstream>#include <iostream>#include <algorithm>using namespace std; //1234//1,234 // 104450 -> 104,450// 123123123 -> 123,123,123 // 1000000 -> 10,00,000// 00010100 string formatNum(int num) { } int main() { string res; int _num; cin >> _num; res = formatNum(_num); cout << res; return 0;}",
"e": 28650,
"s": 28087,
"text": null
},
{
"code": null,
"e": 28705,
"s": 28650,
"text": "//This was a part of bloomberg’s first phone interview"
},
{
"code": null,
"e": 28898,
"s": 28705,
"text": "The question was rather easy, I was asked to implement a function that given an integer number num, it returns the a string representation of the number, comma separated.i.e. f(1234) = “1,234”"
},
{
"code": null,
"e": 28932,
"s": 28898,
"text": "My implementation was as follows:"
},
{
"code": "string formatNum(int num) { int total_processed = 0; string ret = \"\"; while (num > 0){ if (total_processed != 0 && total_processed %3 == 0) ret += \",\"; ret += (char) (num %10 + '0'); total_processed ++; num /= 10; } reverse (ret.begin(), ret.end()); return ret;}",
"e": 29258,
"s": 28932,
"text": null
},
{
"code": null,
"e": 29424,
"s": 29258,
"text": "The interviewer then asked that the function should support different comma styles, i.e. the US vs Indian style//Indian 1000000 -> 10,00,000//US 1000000 -> 1,000,000"
},
{
"code": null,
"e": 29783,
"s": 29424,
"text": "I suggested that a certain style should be passed to the function, either as an integer mask or a vector of integers, representing the positions at which a comma is needed.He asked if only a string abbreviation can be sent to the function instead of a vector, so I suggested using a map, which stores for each style code the corresponding vector of integers."
},
{
"code": null,
"e": 29817,
"s": 29783,
"text": "My implementation was as follows:"
},
{
"code": "//EN style = {3, 6, 9, 12, 15}//IN style = {3, 5, 7, 9, 11, 13} //map <string, vector <int> > style_map string formatNum(int num, string rec_style) { int total_processed = 0; string ret = \"\"; vector <int> style = style_map[rec_style]; int n = style.size(); n--; while (num > 0){ //if (total_processed != 0 && total_processed %3 == 0) if (total_processed == style[n]){ ret += \",\"; n--; } ret += (char) (num %10 + '0'); total_processed ++; num /= 10; } reverse (ret.begin(), ret.end()); return ret;}",
"e": 30417,
"s": 29817,
"text": null
},
{
"code": null,
"e": 30741,
"s": 30417,
"text": "We then moved to another question, that’s concerned about the OOP.The interviewer asked what class would I create in order to make this code more usable.I suggested that I should create a class for the represented integer, to encapsulate its numerical value, its string value, its style, and the functions associated to it."
},
{
"code": null,
"e": 30767,
"s": 30741,
"text": "The code went as follows:"
},
{
"code": "class something{ string num, rec_style; something(int n, string style); change_style(string new_style); bool operator < (something e) const{ }}",
"e": 30934,
"s": 30767,
"text": null
},
{
"code": null,
"e": 31283,
"s": 30934,
"text": "The interviewer then asked me to elaborate the inheritance principle.I illustrated it using the example of the vehicles (cars, vans, trucks, buses ....etc)and then we discussed my design preferences, concerning classes inheritance and polymorphism, and what to do: more inheritance vs more coding.My answer covered code maintenance and reusability."
},
{
"code": null,
"e": 31395,
"s": 31283,
"text": "I was then given the chance to ask the interviewer whatever I like about the company and his work in bloomberg."
},
{
"code": null,
"e": 31460,
"s": 31395,
"text": "Result: I moved to video conference with the other interviewers."
},
{
"code": null,
"e": 31599,
"s": 31460,
"text": "Summary: The interview is easy, you just have to stay cool, and try to give the answers to the point without any exaggerations, Good Luck!"
},
{
"code": null,
"e": 31661,
"s": 31599,
"text": "You can check the documentation of the video conference here."
},
{
"code": null,
"e": 31882,
"s": 31661,
"text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 31892,
"s": 31882,
"text": "Bloomberg"
},
{
"code": null,
"e": 31914,
"s": 31892,
"text": "Interview Experiences"
},
{
"code": null,
"e": 31924,
"s": 31914,
"text": "Bloomberg"
},
{
"code": null,
"e": 32022,
"s": 31924,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32073,
"s": 32022,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 32115,
"s": 32073,
"text": "Amazon AWS Interview Experience for SDE-1"
},
{
"code": null,
"e": 32151,
"s": 32115,
"text": "Zoho Interview | Set 3 (Off-Campus)"
},
{
"code": null,
"e": 32187,
"s": 32151,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 32215,
"s": 32187,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 32253,
"s": 32215,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 32325,
"s": 32253,
"text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021"
},
{
"code": null,
"e": 32371,
"s": 32325,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 32413,
"s": 32371,
"text": "Infosys Interview Experience for DSE 2022"
}
] |
Tryit Editor v3.7
|
Tryit: Different RGBA colors
|
[] |
Regular Dictionary vs Ordered Dictionary in Python - GeeksforGeeks
|
06 Aug, 2021
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. A regular dictionary type does not track the insertion order of the (key, value) pairs and thus iterates through the keys based on how they are stored in the hash table which in turn is based on random values so as to reduce collisions.In contrast to this Python provides the OrderedDict type which remembers the insertion order of (key, value) pairs in the dictionary and thus preserves the order. OrderedDict consumes more memory than a regular dictionary in Python because of the underlying Doubly LinkedList implementation to preserving the order.
Example:
Python
# A Python program to demonstrate# the difference between regular# and ordered dictionary. import collections # Creating a regular dictionaryprint('Regular dictionary:')d = {chr(k):k for k in range(ord('a'), ord('g'))} for k, v in d.items(): print(k, v) # Creating an Ordered dictionaryprint('\nOrderedDict:')d = collections.OrderedDict()[d.setdefault(chr(k), k) for k in range(ord('a'), ord('g'))] for k, v in d.items(): print(k, v)
Output :
Regular dictionary:
('a', 97)
('c', 99)
('b', 98)
('e', 101)
('d', 100)
('f', 102)
OrderedDict:
('a', 97)
('b', 98)
('c', 99)
('d', 100)
('e', 101)
('f', 102)
Note: Starting from Python 3.7, insertion order of Python dictionaries is guaranteed.
Deletion and Re-Inserting: Deleting and re-inserting the same key will push it to the back as OrderedDict however maintains the order of insertion.
Example:
Python
# A Python program to demonstrate# working of deletion and re-insertion in# regular and OrderedDict from collections import OrderedDict print("Before deleting:\n") d = {}print("Regular dictionary:")d['a'] = 1d['b'] = 2d['c'] = 3d['d'] = 4for key, value in d.items(): print(key, value) od = OrderedDict()print("\nOrdered dictionary:")od['a'] = 1od['b'] = 2od['c'] = 3od['d'] = 4for key, value in od.items(): print(key, value) print("\nAfter deleting:\n") print("Regular dictionary:")d.pop('c')for key, value in d.items(): print(key, value) print("\nOrdered dictionary:")od.pop('c')for key, value in od.items(): print(key, value) print("\nAfter re-inserting:\n") print("Regular dictionary:")d['c'] = 3for key, value in d.items(): print(key, value) print("\nOrdered dictionary:")od['c'] = 3for key, value in od.items(): print(key, value)
Output:
Before deleting:
Regular dictionary:
('a', 1)
('c', 3)
('b', 2)
('d', 4)
Ordered dictionary:
('a', 1)
('b', 2)
('c', 3)
('d', 4)
After deleting:
Regular dictionary:
('a', 1)
('b', 2)
('d', 4)
Ordered dictionary:
('a', 1)
('b', 2)
('d', 4)
After re-inserting:
Regular dictionary:
('a', 1)
('c', 3)
('b', 2)
('d', 4)
Ordered dictionary:
('a', 1)
('b', 2)
('d', 4)
('c', 3)
simmytarika5
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24104,
"s": 24076,
"text": "\n06 Aug, 2021"
},
{
"code": null,
"e": 24931,
"s": 24104,
"text": "Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. A regular dictionary type does not track the insertion order of the (key, value) pairs and thus iterates through the keys based on how they are stored in the hash table which in turn is based on random values so as to reduce collisions.In contrast to this Python provides the OrderedDict type which remembers the insertion order of (key, value) pairs in the dictionary and thus preserves the order. OrderedDict consumes more memory than a regular dictionary in Python because of the underlying Doubly LinkedList implementation to preserving the order."
},
{
"code": null,
"e": 24940,
"s": 24931,
"text": "Example:"
},
{
"code": null,
"e": 24947,
"s": 24940,
"text": "Python"
},
{
"code": "# A Python program to demonstrate# the difference between regular# and ordered dictionary. import collections # Creating a regular dictionaryprint('Regular dictionary:')d = {chr(k):k for k in range(ord('a'), ord('g'))} for k, v in d.items(): print(k, v) # Creating an Ordered dictionaryprint('\\nOrderedDict:')d = collections.OrderedDict()[d.setdefault(chr(k), k) for k in range(ord('a'), ord('g'))] for k, v in d.items(): print(k, v)",
"e": 25393,
"s": 24947,
"text": null
},
{
"code": null,
"e": 25402,
"s": 25393,
"text": "Output :"
},
{
"code": null,
"e": 25562,
"s": 25402,
"text": "Regular dictionary:\n('a', 97)\n('c', 99)\n('b', 98)\n('e', 101)\n('d', 100)\n('f', 102)\n\nOrderedDict:\n('a', 97)\n('b', 98)\n('c', 99)\n('d', 100)\n('e', 101)\n('f', 102)"
},
{
"code": null,
"e": 25648,
"s": 25562,
"text": "Note: Starting from Python 3.7, insertion order of Python dictionaries is guaranteed."
},
{
"code": null,
"e": 25796,
"s": 25648,
"text": "Deletion and Re-Inserting: Deleting and re-inserting the same key will push it to the back as OrderedDict however maintains the order of insertion."
},
{
"code": null,
"e": 25806,
"s": 25796,
"text": "Example: "
},
{
"code": null,
"e": 25813,
"s": 25806,
"text": "Python"
},
{
"code": "# A Python program to demonstrate# working of deletion and re-insertion in# regular and OrderedDict from collections import OrderedDict print(\"Before deleting:\\n\") d = {}print(\"Regular dictionary:\")d['a'] = 1d['b'] = 2d['c'] = 3d['d'] = 4for key, value in d.items(): print(key, value) od = OrderedDict()print(\"\\nOrdered dictionary:\")od['a'] = 1od['b'] = 2od['c'] = 3od['d'] = 4for key, value in od.items(): print(key, value) print(\"\\nAfter deleting:\\n\") print(\"Regular dictionary:\")d.pop('c')for key, value in d.items(): print(key, value) print(\"\\nOrdered dictionary:\")od.pop('c')for key, value in od.items(): print(key, value) print(\"\\nAfter re-inserting:\\n\") print(\"Regular dictionary:\")d['c'] = 3for key, value in d.items(): print(key, value) print(\"\\nOrdered dictionary:\")od['c'] = 3for key, value in od.items(): print(key, value)",
"e": 26691,
"s": 25813,
"text": null
},
{
"code": null,
"e": 26699,
"s": 26691,
"text": "Output:"
},
{
"code": null,
"e": 27078,
"s": 26699,
"text": "Before deleting:\n\nRegular dictionary:\n('a', 1)\n('c', 3)\n('b', 2)\n('d', 4)\n\nOrdered dictionary:\n('a', 1)\n('b', 2)\n('c', 3)\n('d', 4)\n\nAfter deleting:\n\nRegular dictionary:\n('a', 1)\n('b', 2)\n('d', 4)\n\nOrdered dictionary:\n('a', 1)\n('b', 2)\n('d', 4)\n\nAfter re-inserting:\n\nRegular dictionary:\n('a', 1)\n('c', 3)\n('b', 2)\n('d', 4)\n\nOrdered dictionary:\n('a', 1)\n('b', 2)\n('d', 4)\n('c', 3)"
},
{
"code": null,
"e": 27093,
"s": 27080,
"text": "simmytarika5"
},
{
"code": null,
"e": 27105,
"s": 27093,
"text": "python-dict"
},
{
"code": null,
"e": 27112,
"s": 27105,
"text": "Python"
},
{
"code": null,
"e": 27124,
"s": 27112,
"text": "python-dict"
},
{
"code": null,
"e": 27222,
"s": 27124,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27240,
"s": 27222,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27275,
"s": 27240,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27297,
"s": 27275,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27329,
"s": 27297,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27359,
"s": 27329,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27401,
"s": 27359,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27427,
"s": 27401,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27464,
"s": 27427,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27507,
"s": 27464,
"text": "Python program to convert a list to string"
}
] |
Gaussian Mixture Models:
implemented from scratch | by Vasile Păpăluță | Towards Data Science
|
From the rising of the Machine Learning and Artificial Intelligence fields Probability Theory was a powerful tool, that allowed us to handle uncertainty in a lot of applications, from classification to forecasting tasks. Today I would like to talk with you more about the use of Probability and Gaussian distribution in clustering problems, implementing on the way the GMM model. So let’s get started
GMM (or Gaussian Mixture Models) is an algorithm that using the estimation of the density of the dataset to split the dataset in a preliminary defined number of clusters. For a better understandability, I will explain in parallel the theory and will show the code for implementing it.
For this implementation, I will use the EM (Expectation-Maximization) algorithm.
Firstly let’s import all needed libraries:
import numpy as npimport pandas as pd
I highly recommend following the standards of sci-kit learn library when implementing a model on your own. That’s why we will implement GMM as a class. Let’s also the __init_function.
class GMM: def __init__(self, n_components, max_iter = 100, comp_names=None): self.n_componets = n_components self.max_iter = max_iter if comp_names == None: self.comp_names = [f"comp{index}" for index in range(self.n_componets)] else: self.comp_names = comp_names # pi list contains the fraction of the dataset for every cluster self.pi = [1/self.n_componets for comp in range(self.n_componets)]
Shortly saying, n_components is the number of cluster in which whe want to split our data. max_iter represents the number of interations taken by the algorithm and comp_names is a list of string with n_components number of elements, that are interpreted as names of clusters.
So before we get to the EM-algorithm we must split our dataset. after that, we must initiate 2 lists. One list containing the mean vectors (each element of the vector is the mean of columns) for every subset. The second list is containing the covariance matrix of each subset.
def fit(self, X): # Spliting the data in n_componets sub-sets new_X = np.array_split(X, self.n_componets) # Initial computation of the mean-vector and covarience matrix self.mean_vector = [np.mean(x, axis=0) for x in new_X] self.covariance_matrixes = [np.cov(x.T) for x in new_X] # Deleting the new_X matrix because we will not need it anymore del new_X
Now we can get to EM-algorithm.
As the name says the EM-algorithm is divided in 2 steps — E and M.
During the Estimation step, we calculate the r matrix. It is calculated using the formula below.
r matrix is also known as ‘responsibilities’ and can be interpreted in the following way. Rows are the samples from the dataset, while columns represent every cluster, the elements of this matrix are interpreted as follows rnk is the probability of sample n to be part of cluster k. When the algorithm will converge we will use this matrix to predict the points cluster.
Also, we calculate the N list, in which each element is basically the sum of the correspondent column in the r matrix. The following code is doing that.
for iteration in range(self.max_iter): ''' ---------------- E - STEP ------------------ ''' # Initiating the r matrix, evrey row contains the probabilities # for every cluster for this row self.r = np.zeros((len(X), self.n_componets)) # Calculating the r matrix for n in range(len(X)): for k in range(self.n_componets): self.r[n][k] = self.pi[k] * self.multivariate_normal(X[n], self.mean_vector[k], self.covariance_matrixes[k]) self.r[n][k] /= sum([self.pi[j]*self.multivariate_normal(X[n], self.mean_vector[j], self.covariance_matrixes[j]) for j in range(self.n_componets)]) # Calculating the N N = np.sum(self.r, axis=0)
Point that the multivariate_normal is just the formular for normal distribution applyed to vectors, it is used to calculate the probability for vectors in a normal sitribution.
and the code bellow implement it, taking the row vector, mean vector and the covariance matrix.
def multivariate_normal(self, X, mean_vector, covariance_matrix): return (2*np.pi)**(-len(X)/2)*np.linalg.det(covariance_matrix)**(-1/2)*np.exp(-np.dot(np.dot((X-mean_vector).T, np.linalg.inv(covariance_matrix)), (X-mean_vector))/2)
Looks a little bit messy but, you can find the full code there.
During the Maximization-step we will step-by-step set the value fo the mean vectors and covariance matrices to describe with them the clusters. To do that we will use the following formulas.
In the code I will like that:
''' --------------- M - STEP --------------- '''# Initializing the mean vector as a zero vectorself.mean_vector = np.zeros((self.n_componets, len(X[0])))# Updating the mean vectorfor k in range(self.n_componets): for n in range(len(X)): self.mean_vector[k] += self.r[n][k] * X[n] self.mean_vector = [1/N[k]*self.mean_vector[k] for k in range(self.n_componets)]# Initiating the list of the covariance matrixesself.covariance_matrixes = [np.zeros((len(X[0]), len(X[0]))) for k in range(self.n_componets)]# Updating the covariance matricesfor k in range(self.n_componets): self.covariance_matrixes[k] = np.cov(X.T, aweights=(self.r[:, k]), ddof=0)self.covariance_matrixes = [1/N[k]*self.covariance_matrixes[k] for k in range(self.n_componets)]# Updating the pi listself.pi = [N[k]/len(X) for k in range(self.n_componets)]
And we are done with fit function. Etiratively applying EM-algorithm will make the GMM fianlly to converge.
The predict function is actually very simple we simply use the multivariate normal function using the optimal mean vectors and covariance matrices for each cluster, to find using which gives the biggest values.
def predict(self, X): probas = [] for n in range(len(X)): probas.append([self.multivariate_normal(X[n], self.mean_vector[k], self.covariance_matrixes[k]) for k in range(self.n_componets)]) cluster = [] for proba in probas: cluster.append(self.comp_names[proba.index(max(proba))]) return cluster
To test the model I chose to compare it with the GMM implemented in the sci-kit library. I generated 2 datasets using sci-kit learn dataset generating function — make_blobs with different setings. So that is the result.
The clustering of our model and the sci-kit one are almost identical. A good result. The full code you can find there.
This article was made with ❤ by Sigmoid.
Useful links:
https://github.com/ScienceKot/mysklearn/tree/master/Gaussian%20Mixture%20Models
https://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm
Mathematics for Machine Learning by Cheng Soon Ong, Marc Peter Deisenroth and A. Aldo Faisal
|
[
{
"code": null,
"e": 573,
"s": 172,
"text": "From the rising of the Machine Learning and Artificial Intelligence fields Probability Theory was a powerful tool, that allowed us to handle uncertainty in a lot of applications, from classification to forecasting tasks. Today I would like to talk with you more about the use of Probability and Gaussian distribution in clustering problems, implementing on the way the GMM model. So let’s get started"
},
{
"code": null,
"e": 858,
"s": 573,
"text": "GMM (or Gaussian Mixture Models) is an algorithm that using the estimation of the density of the dataset to split the dataset in a preliminary defined number of clusters. For a better understandability, I will explain in parallel the theory and will show the code for implementing it."
},
{
"code": null,
"e": 939,
"s": 858,
"text": "For this implementation, I will use the EM (Expectation-Maximization) algorithm."
},
{
"code": null,
"e": 982,
"s": 939,
"text": "Firstly let’s import all needed libraries:"
},
{
"code": null,
"e": 1020,
"s": 982,
"text": "import numpy as npimport pandas as pd"
},
{
"code": null,
"e": 1204,
"s": 1020,
"text": "I highly recommend following the standards of sci-kit learn library when implementing a model on your own. That’s why we will implement GMM as a class. Let’s also the __init_function."
},
{
"code": null,
"e": 1668,
"s": 1204,
"text": "class GMM: def __init__(self, n_components, max_iter = 100, comp_names=None): self.n_componets = n_components self.max_iter = max_iter if comp_names == None: self.comp_names = [f\"comp{index}\" for index in range(self.n_componets)] else: self.comp_names = comp_names # pi list contains the fraction of the dataset for every cluster self.pi = [1/self.n_componets for comp in range(self.n_componets)]"
},
{
"code": null,
"e": 1944,
"s": 1668,
"text": "Shortly saying, n_components is the number of cluster in which whe want to split our data. max_iter represents the number of interations taken by the algorithm and comp_names is a list of string with n_components number of elements, that are interpreted as names of clusters."
},
{
"code": null,
"e": 2221,
"s": 1944,
"text": "So before we get to the EM-algorithm we must split our dataset. after that, we must initiate 2 lists. One list containing the mean vectors (each element of the vector is the mean of columns) for every subset. The second list is containing the covariance matrix of each subset."
},
{
"code": null,
"e": 2624,
"s": 2221,
"text": "def fit(self, X): # Spliting the data in n_componets sub-sets new_X = np.array_split(X, self.n_componets) # Initial computation of the mean-vector and covarience matrix self.mean_vector = [np.mean(x, axis=0) for x in new_X] self.covariance_matrixes = [np.cov(x.T) for x in new_X] # Deleting the new_X matrix because we will not need it anymore del new_X"
},
{
"code": null,
"e": 2656,
"s": 2624,
"text": "Now we can get to EM-algorithm."
},
{
"code": null,
"e": 2723,
"s": 2656,
"text": "As the name says the EM-algorithm is divided in 2 steps — E and M."
},
{
"code": null,
"e": 2820,
"s": 2723,
"text": "During the Estimation step, we calculate the r matrix. It is calculated using the formula below."
},
{
"code": null,
"e": 3191,
"s": 2820,
"text": "r matrix is also known as ‘responsibilities’ and can be interpreted in the following way. Rows are the samples from the dataset, while columns represent every cluster, the elements of this matrix are interpreted as follows rnk is the probability of sample n to be part of cluster k. When the algorithm will converge we will use this matrix to predict the points cluster."
},
{
"code": null,
"e": 3344,
"s": 3191,
"text": "Also, we calculate the N list, in which each element is basically the sum of the correspondent column in the r matrix. The following code is doing that."
},
{
"code": null,
"e": 4025,
"s": 3344,
"text": "for iteration in range(self.max_iter): ''' ---------------- E - STEP ------------------ ''' # Initiating the r matrix, evrey row contains the probabilities # for every cluster for this row self.r = np.zeros((len(X), self.n_componets)) # Calculating the r matrix for n in range(len(X)): for k in range(self.n_componets): self.r[n][k] = self.pi[k] * self.multivariate_normal(X[n], self.mean_vector[k], self.covariance_matrixes[k]) self.r[n][k] /= sum([self.pi[j]*self.multivariate_normal(X[n], self.mean_vector[j], self.covariance_matrixes[j]) for j in range(self.n_componets)]) # Calculating the N N = np.sum(self.r, axis=0)"
},
{
"code": null,
"e": 4202,
"s": 4025,
"text": "Point that the multivariate_normal is just the formular for normal distribution applyed to vectors, it is used to calculate the probability for vectors in a normal sitribution."
},
{
"code": null,
"e": 4298,
"s": 4202,
"text": "and the code bellow implement it, taking the row vector, mean vector and the covariance matrix."
},
{
"code": null,
"e": 4534,
"s": 4298,
"text": "def multivariate_normal(self, X, mean_vector, covariance_matrix): return (2*np.pi)**(-len(X)/2)*np.linalg.det(covariance_matrix)**(-1/2)*np.exp(-np.dot(np.dot((X-mean_vector).T, np.linalg.inv(covariance_matrix)), (X-mean_vector))/2)"
},
{
"code": null,
"e": 4598,
"s": 4534,
"text": "Looks a little bit messy but, you can find the full code there."
},
{
"code": null,
"e": 4789,
"s": 4598,
"text": "During the Maximization-step we will step-by-step set the value fo the mean vectors and covariance matrices to describe with them the clusters. To do that we will use the following formulas."
},
{
"code": null,
"e": 4819,
"s": 4789,
"text": "In the code I will like that:"
},
{
"code": null,
"e": 5662,
"s": 4819,
"text": "''' --------------- M - STEP --------------- '''# Initializing the mean vector as a zero vectorself.mean_vector = np.zeros((self.n_componets, len(X[0])))# Updating the mean vectorfor k in range(self.n_componets): for n in range(len(X)): self.mean_vector[k] += self.r[n][k] * X[n] self.mean_vector = [1/N[k]*self.mean_vector[k] for k in range(self.n_componets)]# Initiating the list of the covariance matrixesself.covariance_matrixes = [np.zeros((len(X[0]), len(X[0]))) for k in range(self.n_componets)]# Updating the covariance matricesfor k in range(self.n_componets): self.covariance_matrixes[k] = np.cov(X.T, aweights=(self.r[:, k]), ddof=0)self.covariance_matrixes = [1/N[k]*self.covariance_matrixes[k] for k in range(self.n_componets)]# Updating the pi listself.pi = [N[k]/len(X) for k in range(self.n_componets)]"
},
{
"code": null,
"e": 5770,
"s": 5662,
"text": "And we are done with fit function. Etiratively applying EM-algorithm will make the GMM fianlly to converge."
},
{
"code": null,
"e": 5981,
"s": 5770,
"text": "The predict function is actually very simple we simply use the multivariate normal function using the optimal mean vectors and covariance matrices for each cluster, to find using which gives the biggest values."
},
{
"code": null,
"e": 6359,
"s": 5981,
"text": "def predict(self, X): probas = [] for n in range(len(X)): probas.append([self.multivariate_normal(X[n], self.mean_vector[k], self.covariance_matrixes[k]) for k in range(self.n_componets)]) cluster = [] for proba in probas: cluster.append(self.comp_names[proba.index(max(proba))]) return cluster"
},
{
"code": null,
"e": 6579,
"s": 6359,
"text": "To test the model I chose to compare it with the GMM implemented in the sci-kit library. I generated 2 datasets using sci-kit learn dataset generating function — make_blobs with different setings. So that is the result."
},
{
"code": null,
"e": 6698,
"s": 6579,
"text": "The clustering of our model and the sci-kit one are almost identical. A good result. The full code you can find there."
},
{
"code": null,
"e": 6739,
"s": 6698,
"text": "This article was made with ❤ by Sigmoid."
},
{
"code": null,
"e": 6753,
"s": 6739,
"text": "Useful links:"
},
{
"code": null,
"e": 6833,
"s": 6753,
"text": "https://github.com/ScienceKot/mysklearn/tree/master/Gaussian%20Mixture%20Models"
},
{
"code": null,
"e": 6906,
"s": 6833,
"text": "https://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm"
}
] |
OpenCV - Drawing a Circle
|
You can draw various shapes like Circle, Rectangle, Line, Ellipse, Polylines, Convex, Polylines, Polylines on an image using the respective methods of the org.opencv.imgproc package.
You can draw a circle on an image using the method circle() of the imgproc class. Following is the syntax of this method −
circle(img, center, radius, color, thickness)
This method accepts the following parameters −
mat − A Mat object representing the image on which the circle is to be drawn.
mat − A Mat object representing the image on which the circle is to be drawn.
point − A Point object representing the center of the circle.
point − A Point object representing the center of the circle.
radius − A variable of the type integer representing the radius of the circle.
radius − A variable of the type integer representing the radius of the circle.
scalar − A Scalar object representing the color of the circle. (BGR)
scalar − A Scalar object representing the color of the circle. (BGR)
thickness − An integer representing the thickness of the circle; by default, the value of thickness is 1.
thickness − An integer representing the thickness of the circle; by default, the value of thickness is 1.
The following program demonstrates how to draw a circle on an image and display it using JavaFX window.
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class DrawingCircle extends Application {
Mat matrix = null;
@Override
public void start(Stage stage) throws Exception {
// Capturing the snapshot from the camera
DrawingCircle obj = new DrawingCircle();
WritableImage writableImage = obj.LoadImage();
// Setting the image view
ImageView imageView = new ImageView(writableImage);
// setting the fit height and width of the image view
imageView.setFitHeight(600);
imageView.setFitWidth(600);
// Setting the preserve ratio of the image view
imageView.setPreserveRatio(true);
// Creating a Group object
Group root = new Group(imageView);
// Creating a scene object
Scene scene = new Scene(root, 600, 400);
// Setting title to the Stage
stage.setTitle("Drawing Circle on the image");
// Adding scene to the stage
stage.setScene(scene);
// Displaying the contents of the stage
stage.show();
}
public WritableImage LoadImage() throws Exception {
// 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/chap8/input.jpg";
Mat matrix = Imgcodecs.imread(file);
//Drawing a Circle
Imgproc.circle (
matrix, //Matrix obj of the image
new Point(230, 160), //Center of the circle
100, //Radius
new Scalar(0, 0, 255), //Scalar object for color
10 //Thickness of the circle
);
// Encoding the image
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", matrix, matOfByte);
// Storing the encoded Mat in a byte array
byte[] byteArray = matOfByte.toArray();
// Displaying the image
InputStream in = new ByteArrayInputStream(byteArray);
BufferedImage bufImage = ImageIO.read(in);
this.matrix = matrix;
// Creating the Writable Image
WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
return writableImage;
}
public static void main(String args[]) {
launch(args);
}
}
On executing the above program, you will get the following output −
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": 3187,
"s": 3004,
"text": "You can draw various shapes like Circle, Rectangle, Line, Ellipse, Polylines, Convex, Polylines, Polylines on an image using the respective methods of the org.opencv.imgproc package."
},
{
"code": null,
"e": 3310,
"s": 3187,
"text": "You can draw a circle on an image using the method circle() of the imgproc class. Following is the syntax of this method −"
},
{
"code": null,
"e": 3357,
"s": 3310,
"text": "circle(img, center, radius, color, thickness)\n"
},
{
"code": null,
"e": 3404,
"s": 3357,
"text": "This method accepts the following parameters −"
},
{
"code": null,
"e": 3482,
"s": 3404,
"text": "mat − A Mat object representing the image on which the circle is to be drawn."
},
{
"code": null,
"e": 3560,
"s": 3482,
"text": "mat − A Mat object representing the image on which the circle is to be drawn."
},
{
"code": null,
"e": 3622,
"s": 3560,
"text": "point − A Point object representing the center of the circle."
},
{
"code": null,
"e": 3684,
"s": 3622,
"text": "point − A Point object representing the center of the circle."
},
{
"code": null,
"e": 3763,
"s": 3684,
"text": "radius − A variable of the type integer representing the radius of the circle."
},
{
"code": null,
"e": 3842,
"s": 3763,
"text": "radius − A variable of the type integer representing the radius of the circle."
},
{
"code": null,
"e": 3911,
"s": 3842,
"text": "scalar − A Scalar object representing the color of the circle. (BGR)"
},
{
"code": null,
"e": 3980,
"s": 3911,
"text": "scalar − A Scalar object representing the color of the circle. (BGR)"
},
{
"code": null,
"e": 4086,
"s": 3980,
"text": "thickness − An integer representing the thickness of the circle; by default, the value of thickness is 1."
},
{
"code": null,
"e": 4192,
"s": 4086,
"text": "thickness − An integer representing the thickness of the circle; by default, the value of thickness is 1."
},
{
"code": null,
"e": 4296,
"s": 4192,
"text": "The following program demonstrates how to draw a circle on an image and display it using JavaFX window."
},
{
"code": null,
"e": 7171,
"s": 4296,
"text": "import java.awt.image.BufferedImage;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStream;\nimport javax.imageio.ImageIO;\n\nimport javafx.application.Application;\nimport javafx.embed.swing.SwingFXUtils;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.image.WritableImage;\nimport javafx.stage.Stage;\n\nimport org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.MatOfByte;\nimport org.opencv.core.Point;\nimport org.opencv.core.Scalar;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class DrawingCircle extends Application {\n Mat matrix = null;\n \n @Override\n public void start(Stage stage) throws Exception {\n // Capturing the snapshot from the camera\n DrawingCircle obj = new DrawingCircle();\n WritableImage writableImage = obj.LoadImage();\n\n // Setting the image view\n ImageView imageView = new ImageView(writableImage);\n\n // setting the fit height and width of the image view\n imageView.setFitHeight(600);\n imageView.setFitWidth(600);\n\n // Setting the preserve ratio of the image view\n imageView.setPreserveRatio(true);\n\n // Creating a Group object\n Group root = new Group(imageView);\n\n // Creating a scene object\n Scene scene = new Scene(root, 600, 400);\n\n // Setting title to the Stage\n stage.setTitle(\"Drawing Circle on the image\");\n \n // Adding scene to the stage\n stage.setScene(scene);\n\n // Displaying the contents of the stage\n stage.show();\n } \n public WritableImage LoadImage() throws Exception {\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/chap8/input.jpg\";\n Mat matrix = Imgcodecs.imread(file);\n\n //Drawing a Circle\n Imgproc.circle (\n matrix, //Matrix obj of the image\n new Point(230, 160), //Center of the circle\n 100, //Radius\n new Scalar(0, 0, 255), //Scalar object for color\n 10 //Thickness of the circle\n );\n \n // Encoding the image\n MatOfByte matOfByte = new MatOfByte();\n Imgcodecs.imencode(\".jpg\", matrix, matOfByte);\n\n // Storing the encoded Mat in a byte array\n byte[] byteArray = matOfByte.toArray();\n\n // Displaying the image\n InputStream in = new ByteArrayInputStream(byteArray);\n BufferedImage bufImage = ImageIO.read(in);\n this.matrix = matrix;\n \n // Creating the Writable Image\n WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);\n\n return writableImage;\n }\n public static void main(String args[]) {\n launch(args);\n }\n}"
},
{
"code": null,
"e": 7239,
"s": 7171,
"text": "On executing the above program, you will get the following output −"
},
{
"code": null,
"e": 7272,
"s": 7239,
"text": "\n 70 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 7289,
"s": 7272,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7322,
"s": 7289,
"text": "\n 41 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7339,
"s": 7322,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7372,
"s": 7339,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7386,
"s": 7372,
"text": " Spotle Learn"
},
{
"code": null,
"e": 7418,
"s": 7386,
"text": "\n 12 Lectures \n 46 mins\n"
},
{
"code": null,
"e": 7435,
"s": 7418,
"text": " Srikanth Guskra"
},
{
"code": null,
"e": 7468,
"s": 7435,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7483,
"s": 7468,
"text": " Haithem Gasmi"
},
{
"code": null,
"e": 7518,
"s": 7483,
"text": "\n 67 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 7536,
"s": 7518,
"text": " Gianluca Mottola"
},
{
"code": null,
"e": 7543,
"s": 7536,
"text": " Print"
},
{
"code": null,
"e": 7554,
"s": 7543,
"text": " Add Notes"
}
] |
An introduction to Debugging (in C and lldb), Part- I | by Shubhadeep Roychowdhury | Towards Data Science
|
How the word “bug” (and hence the word “debugging”) took the meaning that we (computer programmers) have associated with it, is not entirely clear. It could be thanks to the legendary moth in the Mark II computer at Harvard or could have been coined long ago than that. Whatever the origin is, as programmers, we all have stories to share about debugging. Sometimes they are sad, some other times they are a description of several grueling hours, but most of the time they have a happy ending. But one thing we all have in common, we encounter debugging. Almost daily. So, before starting the little tour into debugging, let us define what it is.
I propose the definition of debugging as follows—
Debugging is the process in which a developer (who could be the author or not of the code he is trying to debug), using various tools available to him, makes an effort to change part of a previously written code in order to get rid of an error that was not caught at the compile (or syntax checking) time (in other words that has surfaced at the run time subject to certain conditions).
Does it sound cool? or intimidating? If it is the later, then you should read on. Maybe this little post will help you after all.
There are many different ways people perform debugging. But before listing them out we need to understand that any debugging process is mainly (most of the time) composed of two major activities. First — to investigate values of different variables at different stages of the program execution, and second — to examine in which way the control flows (Are we entering the “if” block? Is the “break” statement inside the “while” loop ever reached? ...)
Print statements — You use “print” (or “printf” or “echo” or whatever is the equivalent) to output some values while running the code. This is possibly the easiest way to start debugging anything. It is also the most clumsy and time taking way. It is clumsy because we can very easily leave all those (or part of those) print statements behind us in the code once we are done, causing an unclean code (and in some very rare occasions, breaking it in production.). It is time taking because we have to write all the print statements and then have to monitor them while the program is being executed.
Using logging — This method is also text-based, like printing, but with many goodies. Instead of only having “stdout” as the output mechanism (as for the printing) we can actually forward structured messages from our program to log management platforms and then use those tools to perform various searches over the corpus of text to gather the necessary info. It is a very effective way. And logging is a must for any serious production app. But it has its own limitations as well. We still have to write all the log statements inside our code by hand (and remove them later if they are not needed) and also we can not (in most of the cases) peek under the hood of program execution.
Interactive (Symbolic) debugger — If you have ever used something like “gdb” (or “ipdb” or “pydb” or “lldb” or anything like that) then you know what I am talking about. For the rest, there are tools available in your own development machines, which give you an all-powerful access to the program at runtime in an interactive mode and let you perform very low level (and high level) investigation on a running piece of code. The advantage of this kind of debugging is that it does not need from your part any extra effort to start debugging the code. You just fire-up the debugger and point it to the executable, and voila! you are in the middle of a running program but you also have all the power to investigate (and even change if needed) it in realtime. Cool!
Before we can do any serious debugging using debugger, we need to understand how OS assigns memory to a program. There is an excellent (probably the best) introduction to interactive debugging by Peter Salzman and my post is just a small summary of the first few pages of it (with small extra due to lldb) but I will still take the time to say few words about VM. Anyone feeling curious please follow Peter’s guide (and links he mentioned there).
When a program starts, the OS allocates a chunk of memory in the primary memory (RAM) so that the process can run. This is called the virtual memory space. It is a complicated and advanced mechanism involving the OS and the MMU (Memory Management Unit) of the CPU. We do not need to go into great details about that. But we do need to know that inside VM there is a chunk of memory allocated for the process which is used by two different data structures. The Stack and The Heap (apart from some other blocks reserved for some other things). It looks like the following —
Any dynamic memory, allocated by us or the libraries we are using, will be located inside the Heap. The Stack is composed for “Frames”. Each frame represents one function call. When a new function call is made, a new frame is inserted at the top of the Stack. If you imagine the allocated VM as a vertical block of memory inside the primary memory then the stack grows downward and the heap grows upward as the process proceeds(As shown in the figure above).
We will need the concept of frames when we debug.
I will be showing commands that are relevant to the lldb, and are executed in a recent MacBook Pro (which comes preinstalled with llvm). The versions for both cc and lldb are following
Apple LLVM version 9.1.0 (clang-902.0.39.2) (result of cc --version)lldb-902.0.79.7 (result of lldb --version)
Let’s first write the simplest C program you can imagine. I am going to use “vim” as the editor. You can use anything you want.
vim hello.c
Once inside the editor, please copy-paste (or type) the following code —
#include<stdio.h>int main(int argc, char* argv){ printf("Hello World!\n"); return 0;}
Save and exit the editor and then do the following
cc -g --std=c99 -Wall hello.c -o hello
Here are some descriptions of the flags we used for the compiler
-g It tells our compiler to embed debugging info inside the output file (Symbol Table, as an example)
--std=c99 The standard of C language that we are using
-Wall Catch all the warnings
To see that what we did actually runs we can try the following
./helloHello World!
So far so good! Let’s fire up the debugger now. Use the following command in order to do so
lldb hello
If everything goes right then it will show something like the following —
This is the prompt of the interactive debugger. In our case it is lldb
The commands in gdb were, to quote the lldb documentation, “free form”. However, lldb had made an effort to have a standardization in commands. The commands in lldb follow the following pattern —
<noun> <verb> [-options [option-value]] [argument [argument...]]
Here noun represents the object you are trying to work on. This can be thread or frame or similar. And the verb is the actual command. So unlike gdb, to see the all the frames of the current stack, you have to enter thread backtrace (For gdb it was simply backtrace). If you enter this command at the very beginning, you will get “error: invalid process”. This is because although we had started the debugger with the name of the executable ( hello in our case) we had not actually asked to run it. So here goes the first command that you should run — run. It will produce an output like the following —
We have successfully ran the executable inside the debugger. BUT! we did not have any control on it. It ran. Succeeded. And finally exited with 0 status. No magic here. So, let’s create some. We are gonna use the breakpoint set command. Breakpoints are specific lines of code inside the source file where the debugger will suspend the execution and will give us an interactive prompt to mingle with the running process :) (the -l 10 signifies the line in my source file where I want to suspend the execution. For you the line number can be different)
Notice the magic here. We had set the breakpoint following the original source file line number but we are loading and running the executable, and yet the debugger somehow knows how to connect them and suspends at the right line of code. At this stage we can examine what are the different variables in the present frame and what are their values. To examine the variables, we do this
Voila! we have all the variables related to the present frame and their types and values. And now it is time for thread backtrace —
As we can see, our function call main is the top of the stack. But it is not the only frame we have in the stack. We have some other frames related to function calls that we did not do. These are dynamic libraries that are loaded at the run time.
Finally, as we do not have anything to investigate further (we are running a very simple code) we need to know how to resume the process from the point it is suspended. How do we move forward? Well, there are two commands. step or s in short and continue or c in short. The difference between them is the fact that step just executes the very next instruction and suspends again. It is kind of one-step-at-a-time journey through the running process, whereas c will execute all the instructions until it hits a next breakpoint or the process ends. Here we do not want to step through the process, so we use c and as there are no more breakpoints the process will finish running.
This is the end of Part-I. We learnt about the basics of debugging here. But we have not performed any real debugging yet. We will be seeing that in Part-II.
If you like this little write up then please clap as many times as you feel. This will encourage me to write more like this. Also please share and comment. They are immensely helpful :)
See you in Part-II. Happy debugging!
|
[
{
"code": null,
"e": 819,
"s": 172,
"text": "How the word “bug” (and hence the word “debugging”) took the meaning that we (computer programmers) have associated with it, is not entirely clear. It could be thanks to the legendary moth in the Mark II computer at Harvard or could have been coined long ago than that. Whatever the origin is, as programmers, we all have stories to share about debugging. Sometimes they are sad, some other times they are a description of several grueling hours, but most of the time they have a happy ending. But one thing we all have in common, we encounter debugging. Almost daily. So, before starting the little tour into debugging, let us define what it is."
},
{
"code": null,
"e": 869,
"s": 819,
"text": "I propose the definition of debugging as follows—"
},
{
"code": null,
"e": 1256,
"s": 869,
"text": "Debugging is the process in which a developer (who could be the author or not of the code he is trying to debug), using various tools available to him, makes an effort to change part of a previously written code in order to get rid of an error that was not caught at the compile (or syntax checking) time (in other words that has surfaced at the run time subject to certain conditions)."
},
{
"code": null,
"e": 1386,
"s": 1256,
"text": "Does it sound cool? or intimidating? If it is the later, then you should read on. Maybe this little post will help you after all."
},
{
"code": null,
"e": 1837,
"s": 1386,
"text": "There are many different ways people perform debugging. But before listing them out we need to understand that any debugging process is mainly (most of the time) composed of two major activities. First — to investigate values of different variables at different stages of the program execution, and second — to examine in which way the control flows (Are we entering the “if” block? Is the “break” statement inside the “while” loop ever reached? ...)"
},
{
"code": null,
"e": 2436,
"s": 1837,
"text": "Print statements — You use “print” (or “printf” or “echo” or whatever is the equivalent) to output some values while running the code. This is possibly the easiest way to start debugging anything. It is also the most clumsy and time taking way. It is clumsy because we can very easily leave all those (or part of those) print statements behind us in the code once we are done, causing an unclean code (and in some very rare occasions, breaking it in production.). It is time taking because we have to write all the print statements and then have to monitor them while the program is being executed."
},
{
"code": null,
"e": 3120,
"s": 2436,
"text": "Using logging — This method is also text-based, like printing, but with many goodies. Instead of only having “stdout” as the output mechanism (as for the printing) we can actually forward structured messages from our program to log management platforms and then use those tools to perform various searches over the corpus of text to gather the necessary info. It is a very effective way. And logging is a must for any serious production app. But it has its own limitations as well. We still have to write all the log statements inside our code by hand (and remove them later if they are not needed) and also we can not (in most of the cases) peek under the hood of program execution."
},
{
"code": null,
"e": 3884,
"s": 3120,
"text": "Interactive (Symbolic) debugger — If you have ever used something like “gdb” (or “ipdb” or “pydb” or “lldb” or anything like that) then you know what I am talking about. For the rest, there are tools available in your own development machines, which give you an all-powerful access to the program at runtime in an interactive mode and let you perform very low level (and high level) investigation on a running piece of code. The advantage of this kind of debugging is that it does not need from your part any extra effort to start debugging the code. You just fire-up the debugger and point it to the executable, and voila! you are in the middle of a running program but you also have all the power to investigate (and even change if needed) it in realtime. Cool!"
},
{
"code": null,
"e": 4331,
"s": 3884,
"text": "Before we can do any serious debugging using debugger, we need to understand how OS assigns memory to a program. There is an excellent (probably the best) introduction to interactive debugging by Peter Salzman and my post is just a small summary of the first few pages of it (with small extra due to lldb) but I will still take the time to say few words about VM. Anyone feeling curious please follow Peter’s guide (and links he mentioned there)."
},
{
"code": null,
"e": 4903,
"s": 4331,
"text": "When a program starts, the OS allocates a chunk of memory in the primary memory (RAM) so that the process can run. This is called the virtual memory space. It is a complicated and advanced mechanism involving the OS and the MMU (Memory Management Unit) of the CPU. We do not need to go into great details about that. But we do need to know that inside VM there is a chunk of memory allocated for the process which is used by two different data structures. The Stack and The Heap (apart from some other blocks reserved for some other things). It looks like the following —"
},
{
"code": null,
"e": 5362,
"s": 4903,
"text": "Any dynamic memory, allocated by us or the libraries we are using, will be located inside the Heap. The Stack is composed for “Frames”. Each frame represents one function call. When a new function call is made, a new frame is inserted at the top of the Stack. If you imagine the allocated VM as a vertical block of memory inside the primary memory then the stack grows downward and the heap grows upward as the process proceeds(As shown in the figure above)."
},
{
"code": null,
"e": 5412,
"s": 5362,
"text": "We will need the concept of frames when we debug."
},
{
"code": null,
"e": 5597,
"s": 5412,
"text": "I will be showing commands that are relevant to the lldb, and are executed in a recent MacBook Pro (which comes preinstalled with llvm). The versions for both cc and lldb are following"
},
{
"code": null,
"e": 5708,
"s": 5597,
"text": "Apple LLVM version 9.1.0 (clang-902.0.39.2) (result of cc --version)lldb-902.0.79.7 (result of lldb --version)"
},
{
"code": null,
"e": 5836,
"s": 5708,
"text": "Let’s first write the simplest C program you can imagine. I am going to use “vim” as the editor. You can use anything you want."
},
{
"code": null,
"e": 5848,
"s": 5836,
"text": "vim hello.c"
},
{
"code": null,
"e": 5921,
"s": 5848,
"text": "Once inside the editor, please copy-paste (or type) the following code —"
},
{
"code": null,
"e": 6013,
"s": 5921,
"text": "#include<stdio.h>int main(int argc, char* argv){ printf(\"Hello World!\\n\"); return 0;}"
},
{
"code": null,
"e": 6064,
"s": 6013,
"text": "Save and exit the editor and then do the following"
},
{
"code": null,
"e": 6103,
"s": 6064,
"text": "cc -g --std=c99 -Wall hello.c -o hello"
},
{
"code": null,
"e": 6168,
"s": 6103,
"text": "Here are some descriptions of the flags we used for the compiler"
},
{
"code": null,
"e": 6270,
"s": 6168,
"text": "-g It tells our compiler to embed debugging info inside the output file (Symbol Table, as an example)"
},
{
"code": null,
"e": 6325,
"s": 6270,
"text": "--std=c99 The standard of C language that we are using"
},
{
"code": null,
"e": 6354,
"s": 6325,
"text": "-Wall Catch all the warnings"
},
{
"code": null,
"e": 6417,
"s": 6354,
"text": "To see that what we did actually runs we can try the following"
},
{
"code": null,
"e": 6437,
"s": 6417,
"text": "./helloHello World!"
},
{
"code": null,
"e": 6529,
"s": 6437,
"text": "So far so good! Let’s fire up the debugger now. Use the following command in order to do so"
},
{
"code": null,
"e": 6540,
"s": 6529,
"text": "lldb hello"
},
{
"code": null,
"e": 6614,
"s": 6540,
"text": "If everything goes right then it will show something like the following —"
},
{
"code": null,
"e": 6685,
"s": 6614,
"text": "This is the prompt of the interactive debugger. In our case it is lldb"
},
{
"code": null,
"e": 6881,
"s": 6685,
"text": "The commands in gdb were, to quote the lldb documentation, “free form”. However, lldb had made an effort to have a standardization in commands. The commands in lldb follow the following pattern —"
},
{
"code": null,
"e": 6946,
"s": 6881,
"text": "<noun> <verb> [-options [option-value]] [argument [argument...]]"
},
{
"code": null,
"e": 7550,
"s": 6946,
"text": "Here noun represents the object you are trying to work on. This can be thread or frame or similar. And the verb is the actual command. So unlike gdb, to see the all the frames of the current stack, you have to enter thread backtrace (For gdb it was simply backtrace). If you enter this command at the very beginning, you will get “error: invalid process”. This is because although we had started the debugger with the name of the executable ( hello in our case) we had not actually asked to run it. So here goes the first command that you should run — run. It will produce an output like the following —"
},
{
"code": null,
"e": 8101,
"s": 7550,
"text": "We have successfully ran the executable inside the debugger. BUT! we did not have any control on it. It ran. Succeeded. And finally exited with 0 status. No magic here. So, let’s create some. We are gonna use the breakpoint set command. Breakpoints are specific lines of code inside the source file where the debugger will suspend the execution and will give us an interactive prompt to mingle with the running process :) (the -l 10 signifies the line in my source file where I want to suspend the execution. For you the line number can be different)"
},
{
"code": null,
"e": 8486,
"s": 8101,
"text": "Notice the magic here. We had set the breakpoint following the original source file line number but we are loading and running the executable, and yet the debugger somehow knows how to connect them and suspends at the right line of code. At this stage we can examine what are the different variables in the present frame and what are their values. To examine the variables, we do this"
},
{
"code": null,
"e": 8618,
"s": 8486,
"text": "Voila! we have all the variables related to the present frame and their types and values. And now it is time for thread backtrace —"
},
{
"code": null,
"e": 8865,
"s": 8618,
"text": "As we can see, our function call main is the top of the stack. But it is not the only frame we have in the stack. We have some other frames related to function calls that we did not do. These are dynamic libraries that are loaded at the run time."
},
{
"code": null,
"e": 9543,
"s": 8865,
"text": "Finally, as we do not have anything to investigate further (we are running a very simple code) we need to know how to resume the process from the point it is suspended. How do we move forward? Well, there are two commands. step or s in short and continue or c in short. The difference between them is the fact that step just executes the very next instruction and suspends again. It is kind of one-step-at-a-time journey through the running process, whereas c will execute all the instructions until it hits a next breakpoint or the process ends. Here we do not want to step through the process, so we use c and as there are no more breakpoints the process will finish running."
},
{
"code": null,
"e": 9701,
"s": 9543,
"text": "This is the end of Part-I. We learnt about the basics of debugging here. But we have not performed any real debugging yet. We will be seeing that in Part-II."
},
{
"code": null,
"e": 9887,
"s": 9701,
"text": "If you like this little write up then please clap as many times as you feel. This will encourage me to write more like this. Also please share and comment. They are immensely helpful :)"
}
] |
Dynamic ImageView in Kotlin - GeeksforGeeks
|
22 Jun, 2021
An ImageView as the name suggests is used to display images in Android Applications. In this article, we will be discussing how to create an ImageView programmatically in Kotlin.
The first step is to create a new project in Android Studio. For this follow these steps:
Click on File, then New, and then New Project, and give name whatever you like
Then, select Kotlin language Support and click next button.
Select minimum SDK, whatever you need.
Select Empty Activity and then click finish.
After doing this you will see some directories on the left-hand side after your project/gradle is finished loading. It should look like this:
After that, we need to design our layout. For that, we need to work with the XML file. Go to app > res > layout and paste the following code:
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:id="@+id/layout" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="20dp" android:text="Add Image" android:layout_centerInParent="true"/> </RelativeLayout>
Adding Images We will be needing an image to be used in the application. You can use the images that you like but the images need to be copied from our local computer path to app/res/drawable folder.
Open app/src/main/java/yourPackageName/MainActivity.kt and do the following changes:Create ImageView widget like this:
val imageView = ImageView(this)
// setting height and width of imageview
imageView.layoutParams = LinearLayout.LayoutParams(400, 400)
imageView.x = 20F //setting margin from left
imageView.y = 20F //setting margin from top
then add the widget in layout using this
//accessing our relative layout from activity_main.xml
val layout = findViewById(R.id.layout)
// Add ImageView to LinearLayout
layout?.addView(imageView) //adding image to the layout
MainActivity.kt
Java
package com.geeksforgeeks.myfirstKotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.ImageViewimport android.widget.LinearLayoutimport android.widget.RelativeLayout class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val imageView = ImageView(this) // setting height and width of imageview imageView.layoutParams= LinearLayout.LayoutParams(400, 400) imageView.x= 20F // setting margin from left imageView.y= 20F // setting margin from top // accessing our custom image which we added in drawable folder val imgResId = R.drawable.img var resId = imgResId // button onClick listener val button = findViewById<Button>(R.id.button) button?.setOnClickListener{ imageView.setImageResource(resId) } // accessing our relative layout from activity_main.xml val layout = findViewById<RelativeLayout>(R.id.layout) // Add ImageView to LinearLayout layout?.addView(imageView) // adding image to the layout }}
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="i.apps.imageview"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest>
Pushpender007
Android-View
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Broadcast Receiver in Android With Example
Services in Android with Example
How to Create and Add Data to SQLite Database in Android?
Content Providers in Android with Example
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Services in Android with Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
|
[
{
"code": null,
"e": 24050,
"s": 24022,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 24229,
"s": 24050,
"text": "An ImageView as the name suggests is used to display images in Android Applications. In this article, we will be discussing how to create an ImageView programmatically in Kotlin."
},
{
"code": null,
"e": 24320,
"s": 24229,
"text": "The first step is to create a new project in Android Studio. For this follow these steps: "
},
{
"code": null,
"e": 24399,
"s": 24320,
"text": "Click on File, then New, and then New Project, and give name whatever you like"
},
{
"code": null,
"e": 24459,
"s": 24399,
"text": "Then, select Kotlin language Support and click next button."
},
{
"code": null,
"e": 24498,
"s": 24459,
"text": "Select minimum SDK, whatever you need."
},
{
"code": null,
"e": 24543,
"s": 24498,
"text": "Select Empty Activity and then click finish."
},
{
"code": null,
"e": 24685,
"s": 24543,
"text": "After doing this you will see some directories on the left-hand side after your project/gradle is finished loading. It should look like this:"
},
{
"code": null,
"e": 24827,
"s": 24685,
"text": "After that, we need to design our layout. For that, we need to work with the XML file. Go to app > res > layout and paste the following code:"
},
{
"code": null,
"e": 24831,
"s": 24827,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:id=\"@+id/layout\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginBottom=\"20dp\" android:text=\"Add Image\" android:layout_centerInParent=\"true\"/> </RelativeLayout>",
"e": 25515,
"s": 24831,
"text": null
},
{
"code": null,
"e": 25715,
"s": 25515,
"text": "Adding Images We will be needing an image to be used in the application. You can use the images that you like but the images need to be copied from our local computer path to app/res/drawable folder."
},
{
"code": null,
"e": 25835,
"s": 25715,
"text": "Open app/src/main/java/yourPackageName/MainActivity.kt and do the following changes:Create ImageView widget like this: "
},
{
"code": null,
"e": 26092,
"s": 25835,
"text": " val imageView = ImageView(this)\n // setting height and width of imageview\n imageView.layoutParams = LinearLayout.LayoutParams(400, 400) \n imageView.x = 20F //setting margin from left\n imageView.y = 20F //setting margin from top"
},
{
"code": null,
"e": 26133,
"s": 26092,
"text": "then add the widget in layout using this"
},
{
"code": null,
"e": 26349,
"s": 26133,
"text": " //accessing our relative layout from activity_main.xml\n val layout = findViewById(R.id.layout) \n // Add ImageView to LinearLayout\n layout?.addView(imageView) //adding image to the layout"
},
{
"code": null,
"e": 26365,
"s": 26349,
"text": "MainActivity.kt"
},
{
"code": null,
"e": 26370,
"s": 26365,
"text": "Java"
},
{
"code": "package com.geeksforgeeks.myfirstKotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.ImageViewimport android.widget.LinearLayoutimport android.widget.RelativeLayout class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val imageView = ImageView(this) // setting height and width of imageview imageView.layoutParams= LinearLayout.LayoutParams(400, 400) imageView.x= 20F // setting margin from left imageView.y= 20F // setting margin from top // accessing our custom image which we added in drawable folder val imgResId = R.drawable.img var resId = imgResId // button onClick listener val button = findViewById<Button>(R.id.button) button?.setOnClickListener{ imageView.setImageResource(resId) } // accessing our relative layout from activity_main.xml val layout = findViewById<RelativeLayout>(R.id.layout) // Add ImageView to LinearLayout layout?.addView(imageView) // adding image to the layout }}",
"e": 27614,
"s": 26370,
"text": null
},
{
"code": null,
"e": 27618,
"s": 27614,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"i.apps.imageview\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\"/> <category android:name=\"android.intent.category.LAUNCHER\"/> </intent-filter> </activity> </application> </manifest>",
"e": 28340,
"s": 27618,
"text": null
},
{
"code": null,
"e": 28354,
"s": 28340,
"text": "Pushpender007"
},
{
"code": null,
"e": 28367,
"s": 28354,
"text": "Android-View"
},
{
"code": null,
"e": 28382,
"s": 28367,
"text": "Kotlin Android"
},
{
"code": null,
"e": 28389,
"s": 28382,
"text": "Picked"
},
{
"code": null,
"e": 28397,
"s": 28389,
"text": "Android"
},
{
"code": null,
"e": 28404,
"s": 28397,
"text": "Kotlin"
},
{
"code": null,
"e": 28412,
"s": 28404,
"text": "Android"
},
{
"code": null,
"e": 28510,
"s": 28412,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28553,
"s": 28510,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 28586,
"s": 28553,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 28644,
"s": 28586,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 28686,
"s": 28644,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 28717,
"s": 28686,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 28760,
"s": 28717,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 28793,
"s": 28760,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 28835,
"s": 28793,
"text": "Content Providers in Android with Example"
}
] |
Convert JSON to/from Map using Jackson library in Java?
|
The JSON Jackson is a library for Java and it has very powerful data binding capabilities and provides a framework to serialize custom java objects to JSON and deserialize JSON back to Java object. We can convert JSON to/from
Map using readValue() and writeValueAsString() methods of com.fasterxml.jackson.databind.ObjectMapper class.
public <T> T readValue(String content, TypeReference valueTypeRef) throws IOException, JsonParseException, JsonMappingException
import java.io.*;
import java.util.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
public class ConvertJSONToMapTest {
public static void main(String args[]) {
try {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"Name\":\"Raja\", \"Technology\":\"Java\"}";
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap = mapper.readValue(jsonString, new TypeReference<Map<String, String>>(){}); // converts JSON to Map
System.out.println(jsonMap);
} catch(IOException ie) {
ie.printStackTrace();
}
}
}
{Name=Raja, Technology=Java}
public String writeValueAsString(Object value) throws JsonProcessingException
import java.io.*;
import java.util.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ConvertMapToJSONTest {
public static void main(String args[]) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "";
Map<String, Object> map = new HashMap<String, Object>();
map.put("Raja", "Java Technology");
map.put("Ravi", "Python Technology");
map.put("Adithya", "Spark Technology");
map.put("Vamsi", "Web Technology");
jsonString = mapper.writeValueAsString(map); // converts Map to JSON
System.out.println(map);
}
}
{"Raja":"Java Technology", "Vamsi":"Web Technology", "Ravi":"Python Technology", "Adithya":"Spark Technology"}
|
[
{
"code": null,
"e": 1397,
"s": 1062,
"text": "The JSON Jackson is a library for Java and it has very powerful data binding capabilities and provides a framework to serialize custom java objects to JSON and deserialize JSON back to Java object. We can convert JSON to/from\nMap using readValue() and writeValueAsString() methods of com.fasterxml.jackson.databind.ObjectMapper class."
},
{
"code": null,
"e": 1525,
"s": 1397,
"text": "public <T> T readValue(String content, TypeReference valueTypeRef) throws IOException, JsonParseException, JsonMappingException"
},
{
"code": null,
"e": 2192,
"s": 1525,
"text": "import java.io.*;\nimport java.util.*;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.core.type.TypeReference;\npublic class ConvertJSONToMapTest {\n public static void main(String args[]) {\n try {\n ObjectMapper mapper = new ObjectMapper();\n String jsonString = \"{\\\"Name\\\":\\\"Raja\\\", \\\"Technology\\\":\\\"Java\\\"}\";\n Map<String, Object> jsonMap = new HashMap<String, Object>();\n jsonMap = mapper.readValue(jsonString, new TypeReference<Map<String, String>>(){}); // converts JSON to Map\n System.out.println(jsonMap);\n } catch(IOException ie) {\n ie.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 2221,
"s": 2192,
"text": "{Name=Raja, Technology=Java}"
},
{
"code": null,
"e": 2299,
"s": 2221,
"text": "public String writeValueAsString(Object value) throws JsonProcessingException"
},
{
"code": null,
"e": 2953,
"s": 2299,
"text": "import java.io.*;\nimport java.util.*;\nimport com.fasterxml.jackson.core.*;\nimport com.fasterxml.jackson.databind.ObjectMapper;\npublic class ConvertMapToJSONTest {\n public static void main(String args[]) throws IOException {\n ObjectMapper mapper = new ObjectMapper();\n String jsonString = \"\";\n Map<String, Object> map = new HashMap<String, Object>();\n map.put(\"Raja\", \"Java Technology\");\n map.put(\"Ravi\", \"Python Technology\");\n map.put(\"Adithya\", \"Spark Technology\");\n map.put(\"Vamsi\", \"Web Technology\");\n jsonString = mapper.writeValueAsString(map); // converts Map to JSON\n System.out.println(map);\n }\n}"
},
{
"code": null,
"e": 3064,
"s": 2953,
"text": "{\"Raja\":\"Java Technology\", \"Vamsi\":\"Web Technology\", \"Ravi\":\"Python Technology\", \"Adithya\":\"Spark Technology\"}"
}
] |
How to give a div tag 100% height of the browser window using CSS - GeeksforGeeks
|
04 Dec, 2018
CSS allows to adjust the height of an element using the height property. While there are several units to specify the height of an element. The vh is a relative unit that is commonly used.
vh: It stands for viewport-height. The viewport refers to the browser window size. Thus when use vh as a unit, the element’s height is adjusted relative to the browser window (viewport’s) height.vw: It stands for viewport-width. It is used to set the browser width 100% relative to the browser window (viewport’s) width.
Syntax: To set a div element height to 100% of the browser window, it can simply use the following property of CSS:
height:100vh;
Example:
<!DOCTYPE html><!DOCTYPE html><html> <head> <title>Make div 100% of height</title> <style> #geeks { height: 100vh; width: 100vw; font-size: 20px; font-family: Times; padding-top: 250px; margin: 0px; background-color: green; text-align: center; color:white; } .gfg { font-size:40px; font-weight:bold; } </style> </head> <body> <div id="geeks"> <div class = "gfg">GeeksforGeeks</div> <div>A computer science portal for geeks</div> </div> </body></html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
Picked
Web technologies
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
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 ?
CSS to put icon inside an input element in a form
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 24807,
"s": 24779,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 24996,
"s": 24807,
"text": "CSS allows to adjust the height of an element using the height property. While there are several units to specify the height of an element. The vh is a relative unit that is commonly used."
},
{
"code": null,
"e": 25317,
"s": 24996,
"text": "vh: It stands for viewport-height. The viewport refers to the browser window size. Thus when use vh as a unit, the element’s height is adjusted relative to the browser window (viewport’s) height.vw: It stands for viewport-width. It is used to set the browser width 100% relative to the browser window (viewport’s) width."
},
{
"code": null,
"e": 25433,
"s": 25317,
"text": "Syntax: To set a div element height to 100% of the browser window, it can simply use the following property of CSS:"
},
{
"code": null,
"e": 25447,
"s": 25433,
"text": "height:100vh;"
},
{
"code": null,
"e": 25456,
"s": 25447,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><!DOCTYPE html><html> <head> <title>Make div 100% of height</title> <style> #geeks { height: 100vh; width: 100vw; font-size: 20px; font-family: Times; padding-top: 250px; margin: 0px; background-color: green; text-align: center; color:white; } .gfg { font-size:40px; font-weight:bold; } </style> </head> <body> <div id=\"geeks\"> <div class = \"gfg\">GeeksforGeeks</div> <div>A computer science portal for geeks</div> </div> </body></html> ",
"e": 26223,
"s": 25456,
"text": null
},
{
"code": null,
"e": 26231,
"s": 26223,
"text": "Output:"
},
{
"code": null,
"e": 26368,
"s": 26231,
"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": 26377,
"s": 26368,
"text": "CSS-Misc"
},
{
"code": null,
"e": 26384,
"s": 26377,
"text": "Picked"
},
{
"code": null,
"e": 26401,
"s": 26384,
"text": "Web technologies"
},
{
"code": null,
"e": 26405,
"s": 26401,
"text": "CSS"
},
{
"code": null,
"e": 26410,
"s": 26405,
"text": "HTML"
},
{
"code": null,
"e": 26427,
"s": 26410,
"text": "Web Technologies"
},
{
"code": null,
"e": 26432,
"s": 26427,
"text": "HTML"
},
{
"code": null,
"e": 26530,
"s": 26432,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26592,
"s": 26530,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26642,
"s": 26592,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 26700,
"s": 26642,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 26748,
"s": 26700,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26798,
"s": 26748,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 26860,
"s": 26798,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26910,
"s": 26860,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 26970,
"s": 26910,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 27018,
"s": 26970,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Difference Between JavaScript and jQuery - GeeksforGeeks
|
24 Nov, 2021
In this article, we will learn Javascript & jQuery, & their basic differences through the examples.
JavaScript: It is a major scripting programming language that is used to make websites more responsive and interactive. It is one of the pivoted parts alongside HTML and CSS which are used to create web pages. If HTML & CSS decorates and designed the web-pages so, Javascript makes the web pages dynamic(we can say it gives them life). JavaScript is a major client-side language. It’s not only confined to websites development but also used in many desktop and server programs ( Node.js is the best-known example) and Some databases, like MongoDB and CouchDB, also use JavaScript. Whenever your browser parses a web page, its responsibility is to create a tree-structure presentation in memory.
Example: This example uses the Javascript loop concept to print the numbers.
HTML
<!DOCTYPE html><html> <body> <p>A loop with a <mark>continue</mark> statement. </p> <p>loop will skip the iteration where k = 7.</p> <p id="maddy"></p> <script> var text = ""; var k; for (k = 0; k < 10; k++) { if (k === 7) { continue; } text += "The number is " + k + "<br>"; } document.getElementById("maddy").innerHTML = text; </script></body> </html>
Output:
JavaScript Output
jQuery: JQuery is a framework for javaScript which developed from JavaScript. It is the most popular JavaScript library invented by John Resign and was released in January 2006 at BarCamp NYC. It is a free, open-source library and It’s a fast, concise, and rich-featured JavaScript library and also has cross-browser compatibility. The purpose of jQuery is to make life easier for the masses so that they can easily develop websites and browser-based applications using javaScript. In a concise manner, we can say that the “JQuery is a library to provide better client-side web page development” environment to the developer with the help of its feature-rich library.
DOM manipulation: DOM elements can be easily traversed, modified.
Animations Lots of built-in features for animations.
HTML event handling and manipulation.
Ajax is much simpler with an easy-to-use API that works across a multitude of browsers.
CSS manipulation
Has a high-level UI widget library.
Cross-browser support: work well on browsers like Chrome, Opera, etc.
Lightweight: Only 19kb in size.
And other common utilities
Example: This example uses the show() method & hide() method to toggle the element to display.
HTML
<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("#hide").click(function () { $("h1").hide(); }); $("#show").click(function () { $("h1").show(); }); }); </script></head> <body> <h1> <mark> On clicking the "Hide_me" button, I will disappear. </mark> </h1> <button id="hide">Hide_me</button> <button id="show">Show_me</button></body> </html>
Output: As we click on the Hide_me button, the above-marked heading will disappear, but as soon as we click on the Show_me button it’ll again appear.
Toggle to view the hidden element
Key differences between JavaScript and JQuery are as follow :
JavaScript uses JIT[Just in Time Compiler] which is a combination of interpreter and Compile and is written in C. It’s a combination of ECMA script and DOM (Document Object Model).
While JQuery Uses the resources that are provided by JavaScript to make things easier. It is a lightweight JavaScript library. It has only the DOM.
JavaScript uses long lines of code as an individual has to write the code own-self.
With JQuery, one has to write fewer lines of code than JavaScript. We just need to import the library and use the only specific functions or methods of the library in our code.
In JavaScript, we have to write extra code or move around to have cross-browser compatibility.
JQuery has an inbuilt feature of cross-browser compatibility. We don’t need to worry about writing extra lines of code or moving around in order to make our code compatible with any browser.
JavaScript can be a burden over a developer as it may take a number of lines of lengthy code to attain functionality.
Unlike JavaScript, JQuery is more user-friendly only a few lines of code have to write in order to have its functionality.
JavaScript is verbose because one has to write their own scripting code which is time-consuming.
JQuery is concise and one need not write much as scripting already exists.
Pure JavaScript can be faster for DOM selection/manipulation than jQuery as JavaScript is directly processed by the browser and it curtails the overhead which JQuery actually has.
JQuery is also fast with modern browsers and modern computers. JQuery has to be converted into JavaScript to make it run in a browser.
We can make animations in JavaScript with many lines of code. Animations are mainly done by manipulating the style of an Html page.
In JQuery, we can add animation effects easily with fewer lines of code.
JavaScript is a language, obviously, it would be heavier than JQuery.
While JQuery is a library, derived from JavaScript hence, it is lightweight.
JavaScript is an independent language and can exist on its own.
JQuery is a JavaScript library. It would not have been invented had JavaScript was not there. jQuery is still dependent on JavaScript as it has to be converted to JavaScript for the browser in-built JavaScript engine to interpret and run it.
jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous for its philosophy of “Write less, do more”. Please refer to the jQuery Tutorial and jQuery Examples articles for further details.
thor98571
bhaskargeeksforgeeks
JavaScript-Questions
jQuery-Questions
JavaScript
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to add options to a select element using jQuery?
How to fetch data from JSON file and display in HTML table using jQuery ?
|
[
{
"code": null,
"e": 24994,
"s": 24966,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 25094,
"s": 24994,
"text": "In this article, we will learn Javascript & jQuery, & their basic differences through the examples."
},
{
"code": null,
"e": 25789,
"s": 25094,
"text": "JavaScript: It is a major scripting programming language that is used to make websites more responsive and interactive. It is one of the pivoted parts alongside HTML and CSS which are used to create web pages. If HTML & CSS decorates and designed the web-pages so, Javascript makes the web pages dynamic(we can say it gives them life). JavaScript is a major client-side language. It’s not only confined to websites development but also used in many desktop and server programs ( Node.js is the best-known example) and Some databases, like MongoDB and CouchDB, also use JavaScript. Whenever your browser parses a web page, its responsibility is to create a tree-structure presentation in memory."
},
{
"code": null,
"e": 25866,
"s": 25789,
"text": "Example: This example uses the Javascript loop concept to print the numbers."
},
{
"code": null,
"e": 25871,
"s": 25866,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <p>A loop with a <mark>continue</mark> statement. </p> <p>loop will skip the iteration where k = 7.</p> <p id=\"maddy\"></p> <script> var text = \"\"; var k; for (k = 0; k < 10; k++) { if (k === 7) { continue; } text += \"The number is \" + k + \"<br>\"; } document.getElementById(\"maddy\").innerHTML = text; </script></body> </html>",
"e": 26345,
"s": 25871,
"text": null
},
{
"code": null,
"e": 26353,
"s": 26345,
"text": "Output:"
},
{
"code": null,
"e": 26371,
"s": 26353,
"text": "JavaScript Output"
},
{
"code": null,
"e": 27039,
"s": 26371,
"text": "jQuery: JQuery is a framework for javaScript which developed from JavaScript. It is the most popular JavaScript library invented by John Resign and was released in January 2006 at BarCamp NYC. It is a free, open-source library and It’s a fast, concise, and rich-featured JavaScript library and also has cross-browser compatibility. The purpose of jQuery is to make life easier for the masses so that they can easily develop websites and browser-based applications using javaScript. In a concise manner, we can say that the “JQuery is a library to provide better client-side web page development” environment to the developer with the help of its feature-rich library."
},
{
"code": null,
"e": 27105,
"s": 27039,
"text": "DOM manipulation: DOM elements can be easily traversed, modified."
},
{
"code": null,
"e": 27158,
"s": 27105,
"text": "Animations Lots of built-in features for animations."
},
{
"code": null,
"e": 27196,
"s": 27158,
"text": "HTML event handling and manipulation."
},
{
"code": null,
"e": 27284,
"s": 27196,
"text": "Ajax is much simpler with an easy-to-use API that works across a multitude of browsers."
},
{
"code": null,
"e": 27301,
"s": 27284,
"text": "CSS manipulation"
},
{
"code": null,
"e": 27337,
"s": 27301,
"text": "Has a high-level UI widget library."
},
{
"code": null,
"e": 27407,
"s": 27337,
"text": "Cross-browser support: work well on browsers like Chrome, Opera, etc."
},
{
"code": null,
"e": 27439,
"s": 27407,
"text": "Lightweight: Only 19kb in size."
},
{
"code": null,
"e": 27466,
"s": 27439,
"text": "And other common utilities"
},
{
"code": null,
"e": 27561,
"s": 27466,
"text": "Example: This example uses the show() method & hide() method to toggle the element to display."
},
{
"code": null,
"e": 27566,
"s": 27561,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(\"#hide\").click(function () { $(\"h1\").hide(); }); $(\"#show\").click(function () { $(\"h1\").show(); }); }); </script></head> <body> <h1> <mark> On clicking the \"Hide_me\" button, I will disappear. </mark> </h1> <button id=\"hide\">Hide_me</button> <button id=\"show\">Show_me</button></body> </html>",
"e": 28161,
"s": 27566,
"text": null
},
{
"code": null,
"e": 28311,
"s": 28161,
"text": "Output: As we click on the Hide_me button, the above-marked heading will disappear, but as soon as we click on the Show_me button it’ll again appear."
},
{
"code": null,
"e": 28345,
"s": 28311,
"text": "Toggle to view the hidden element"
},
{
"code": null,
"e": 28407,
"s": 28345,
"text": "Key differences between JavaScript and JQuery are as follow :"
},
{
"code": null,
"e": 28588,
"s": 28407,
"text": "JavaScript uses JIT[Just in Time Compiler] which is a combination of interpreter and Compile and is written in C. It’s a combination of ECMA script and DOM (Document Object Model)."
},
{
"code": null,
"e": 28738,
"s": 28590,
"text": "While JQuery Uses the resources that are provided by JavaScript to make things easier. It is a lightweight JavaScript library. It has only the DOM."
},
{
"code": null,
"e": 28822,
"s": 28738,
"text": "JavaScript uses long lines of code as an individual has to write the code own-self."
},
{
"code": null,
"e": 29002,
"s": 28824,
"text": " With JQuery, one has to write fewer lines of code than JavaScript. We just need to import the library and use the only specific functions or methods of the library in our code."
},
{
"code": null,
"e": 29097,
"s": 29002,
"text": "In JavaScript, we have to write extra code or move around to have cross-browser compatibility."
},
{
"code": null,
"e": 29290,
"s": 29099,
"text": "JQuery has an inbuilt feature of cross-browser compatibility. We don’t need to worry about writing extra lines of code or moving around in order to make our code compatible with any browser."
},
{
"code": null,
"e": 29408,
"s": 29290,
"text": "JavaScript can be a burden over a developer as it may take a number of lines of lengthy code to attain functionality."
},
{
"code": null,
"e": 29533,
"s": 29410,
"text": "Unlike JavaScript, JQuery is more user-friendly only a few lines of code have to write in order to have its functionality."
},
{
"code": null,
"e": 29630,
"s": 29533,
"text": "JavaScript is verbose because one has to write their own scripting code which is time-consuming."
},
{
"code": null,
"e": 29707,
"s": 29632,
"text": "JQuery is concise and one need not write much as scripting already exists."
},
{
"code": null,
"e": 29887,
"s": 29707,
"text": "Pure JavaScript can be faster for DOM selection/manipulation than jQuery as JavaScript is directly processed by the browser and it curtails the overhead which JQuery actually has."
},
{
"code": null,
"e": 30024,
"s": 29889,
"text": "JQuery is also fast with modern browsers and modern computers. JQuery has to be converted into JavaScript to make it run in a browser."
},
{
"code": null,
"e": 30156,
"s": 30024,
"text": "We can make animations in JavaScript with many lines of code. Animations are mainly done by manipulating the style of an Html page."
},
{
"code": null,
"e": 30231,
"s": 30158,
"text": "In JQuery, we can add animation effects easily with fewer lines of code."
},
{
"code": null,
"e": 30301,
"s": 30231,
"text": "JavaScript is a language, obviously, it would be heavier than JQuery."
},
{
"code": null,
"e": 30380,
"s": 30303,
"text": "While JQuery is a library, derived from JavaScript hence, it is lightweight."
},
{
"code": null,
"e": 30444,
"s": 30380,
"text": "JavaScript is an independent language and can exist on its own."
},
{
"code": null,
"e": 30688,
"s": 30446,
"text": "JQuery is a JavaScript library. It would not have been invented had JavaScript was not there. jQuery is still dependent on JavaScript as it has to be converted to JavaScript for the browser in-built JavaScript engine to interpret and run it."
},
{
"code": null,
"e": 30946,
"s": 30688,
"text": "jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous for its philosophy of “Write less, do more”. Please refer to the jQuery Tutorial and jQuery Examples articles for further details."
},
{
"code": null,
"e": 30956,
"s": 30946,
"text": "thor98571"
},
{
"code": null,
"e": 30977,
"s": 30956,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 30998,
"s": 30977,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 31015,
"s": 30998,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 31026,
"s": 31015,
"text": "JavaScript"
},
{
"code": null,
"e": 31033,
"s": 31026,
"text": "JQuery"
},
{
"code": null,
"e": 31050,
"s": 31033,
"text": "Web Technologies"
},
{
"code": null,
"e": 31148,
"s": 31050,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31157,
"s": 31148,
"text": "Comments"
},
{
"code": null,
"e": 31170,
"s": 31157,
"text": "Old Comments"
},
{
"code": null,
"e": 31231,
"s": 31170,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31272,
"s": 31231,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 31312,
"s": 31272,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31366,
"s": 31312,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 31428,
"s": 31366,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 31474,
"s": 31428,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 31503,
"s": 31474,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 31566,
"s": 31503,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 31619,
"s": 31566,
"text": "How to add options to a select element using jQuery?"
}
] |
SciPy - ODR
|
ODR stands for Orthogonal Distance Regression, which is used in the regression studies. Basic linear regression is often used to estimate the relationship between the two variables y and x by drawing the line of best fit on the graph.
The mathematical method that is used for this is known as Least Squares, and aims to minimize the sum of the squared error for each point. The key question here is how do you calculate the error (also known as the residual) for each point?
In a standard linear regression, the aim is to predict the Y value from the X value – so the sensible thing to do is to calculate the error in the Y values (shown as the gray lines in the following image). However, sometimes it is more sensible to take into account the error in both X and Y (as shown by the dotted red lines in the following image).
For example − When you know your measurements of X are uncertain, or when you do not want to focus on the errors of one variable over another.
Orthogonal Distance Regression (ODR) is a method that can do this (orthogonal in this context means perpendicular – so it calculates errors perpendicular to the line, rather than just ‘vertically’).
The following example demonstrates scipy.odr implementation for univariate regression.
import numpy as np
import matplotlib.pyplot as plt
from scipy.odr import *
import random
# Initiate some data, giving some randomness using random.random().
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([i**2 + random.random() for i in x])
# Define a function (quadratic in our case) to fit the data with.
def linear_func(p, x):
m, c = p
return m*x + c
# Create a model for fitting.
linear_model = Model(linear_func)
# Create a RealData object using our initiated data from above.
data = RealData(x, y)
# Set up ODR with the model and data.
odr = ODR(data, linear_model, beta0=[0., 1.])
# Run the regression.
out = odr.run()
# Use the in-built pprint method to give us results.
out.pprint()
The above program will generate the following output.
Beta: [ 5.51846098 -4.25744878]
Beta Std Error: [ 0.7786442 2.33126407]
Beta Covariance: [
[ 1.93150969 -4.82877433]
[ -4.82877433 17.31417201
]]
Residual Variance: 0.313892697582
Inverse Condition #: 0.146618499389
Reason(s) for Halting:
Sum of squares convergence
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2122,
"s": 1887,
"text": "ODR stands for Orthogonal Distance Regression, which is used in the regression studies. Basic linear regression is often used to estimate the relationship between the two variables y and x by drawing the line of best fit on the graph."
},
{
"code": null,
"e": 2362,
"s": 2122,
"text": "The mathematical method that is used for this is known as Least Squares, and aims to minimize the sum of the squared error for each point. The key question here is how do you calculate the error (also known as the residual) for each point?"
},
{
"code": null,
"e": 2713,
"s": 2362,
"text": "In a standard linear regression, the aim is to predict the Y value from the X value – so the sensible thing to do is to calculate the error in the Y values (shown as the gray lines in the following image). However, sometimes it is more sensible to take into account the error in both X and Y (as shown by the dotted red lines in the following image)."
},
{
"code": null,
"e": 2856,
"s": 2713,
"text": "For example − When you know your measurements of X are uncertain, or when you do not want to focus on the errors of one variable over another."
},
{
"code": null,
"e": 3055,
"s": 2856,
"text": "Orthogonal Distance Regression (ODR) is a method that can do this (orthogonal in this context means perpendicular – so it calculates errors perpendicular to the line, rather than just ‘vertically’)."
},
{
"code": null,
"e": 3142,
"s": 3055,
"text": "The following example demonstrates scipy.odr implementation for univariate regression."
},
{
"code": null,
"e": 3846,
"s": 3142,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.odr import *\nimport random\n\n# Initiate some data, giving some randomness using random.random().\nx = np.array([0, 1, 2, 3, 4, 5])\ny = np.array([i**2 + random.random() for i in x])\n\n# Define a function (quadratic in our case) to fit the data with.\ndef linear_func(p, x):\n m, c = p\n return m*x + c\n\n# Create a model for fitting.\nlinear_model = Model(linear_func)\n\n# Create a RealData object using our initiated data from above.\ndata = RealData(x, y)\n\n# Set up ODR with the model and data.\nodr = ODR(data, linear_model, beta0=[0., 1.])\n\n# Run the regression.\nout = odr.run()\n\n# Use the in-built pprint method to give us results.\nout.pprint()"
},
{
"code": null,
"e": 3900,
"s": 3846,
"text": "The above program will generate the following output."
},
{
"code": null,
"e": 4178,
"s": 3900,
"text": "Beta: [ 5.51846098 -4.25744878]\nBeta Std Error: [ 0.7786442 2.33126407]\n\nBeta Covariance: [\n [ 1.93150969 -4.82877433]\n [ -4.82877433 17.31417201\n]]\n\nResidual Variance: 0.313892697582\nInverse Condition #: 0.146618499389\nReason(s) for Halting:\n Sum of squares convergence\n"
},
{
"code": null,
"e": 4185,
"s": 4178,
"text": " Print"
},
{
"code": null,
"e": 4196,
"s": 4185,
"text": " Add Notes"
}
] |
How to use the IndexOf(,) method of array class in C#?
|
The IndexOf() method of array class in C# searches for the specified object and returns the index of the first occurrence within the entire one-dimensional Array.
We have set the array.
int[] arr = new int[10];
arr[0] = 100;
arr[1] = 200;
arr[2] = 300;
arr[3] = 400;
arr[4] = 500;
arr[5] = 600;
arr[6] = 700;
arr[7] = 800;
arr[8] = 900;
arr[9] = 1000;
Now use the IndexOf() method and set the element for which you want the index, for example, I have set it for element 800.
int a = Array.IndexOf(arr, 800);
The following is the example showing the usage of IndexOf(,) method in C#.
Live Demo
using System;
class Program {
static void Main() {
int[] arr = new int[10];
arr[0] = 100;
arr[1] = 200;
arr[2] = 300;
arr[3] = 400;
arr[4] = 500;
arr[5] = 600;
arr[6] = 700;
arr[7] = 800;
arr[8] = 900;
arr[9] = 1000;
int a = Array.IndexOf(arr, 800);
Console.WriteLine(a);
}
}
7
|
[
{
"code": null,
"e": 1225,
"s": 1062,
"text": "The IndexOf() method of array class in C# searches for the specified object and returns the index of the first occurrence within the entire one-dimensional Array."
},
{
"code": null,
"e": 1248,
"s": 1225,
"text": "We have set the array."
},
{
"code": null,
"e": 1414,
"s": 1248,
"text": "int[] arr = new int[10];\narr[0] = 100;\narr[1] = 200;\narr[2] = 300;\narr[3] = 400;\narr[4] = 500;\narr[5] = 600;\narr[6] = 700;\narr[7] = 800;\narr[8] = 900;\narr[9] = 1000;"
},
{
"code": null,
"e": 1537,
"s": 1414,
"text": "Now use the IndexOf() method and set the element for which you want the index, for example, I have set it for element 800."
},
{
"code": null,
"e": 1570,
"s": 1537,
"text": "int a = Array.IndexOf(arr, 800);"
},
{
"code": null,
"e": 1645,
"s": 1570,
"text": "The following is the example showing the usage of IndexOf(,) method in C#."
},
{
"code": null,
"e": 1656,
"s": 1645,
"text": " Live Demo"
},
{
"code": null,
"e": 2016,
"s": 1656,
"text": "using System;\nclass Program {\n static void Main() {\n int[] arr = new int[10];\n arr[0] = 100;\n arr[1] = 200;\n arr[2] = 300;\n arr[3] = 400;\n arr[4] = 500;\n arr[5] = 600;\n arr[6] = 700;\n arr[7] = 800;\n arr[8] = 900;\n arr[9] = 1000;\n int a = Array.IndexOf(arr, 800);\n Console.WriteLine(a);\n }\n}"
},
{
"code": null,
"e": 2018,
"s": 2016,
"text": "7"
}
] |
Python & Vectorization. In this story, I have discussed... | by Rochak Agrawal | Towards Data Science
|
Computer hardware in today’s world leverages parallel computing for faster computation by making use of SIMD (Single Instruction, Multiple Data) architectures. SIMD is a class of parallel computing in which the logical processors perform a single instruction on multiple data points simultaneously. We need to vectorize our deep learning code so that we can harness all the computing power that our system provides. The faster the computation, the faster our neural network is trained and the faster we get our results. Therefore, the ability to vectorize a piece of code has become a crucial skill for a deep learning practitioner. In this story, I will be explaining the basics of vectorization using python.
In the context of logistic regression, let us try to understand what vectorization exactly means with the help of the equation below:
The convention for storing the inputs and weights is not standard but I prefer to store it the following way. Let X be the input matrix of dimensions (n,m) where n is the number of features present in X and m is the number of training examples present in our training dataset i.e. we are storing one data point in 1 column. For each feature, there will be a weight associated with it, therefore let W be the weight matrix of dimensions (n,1).
Now, if we were to code the example equation using for loops, we would come up with something like:
The above snippet of code consists of explicit for loops and will not make use of parallelization. Therefore, we need to convert it into a vectorized version. This can be done easily by leveraging the built-in Numpy functions in the following way:
Z will be a (1,m) matrix as per matrix multiplication rules. The np.dot() function performs matrix multiplication of the given input matrices. It not only makes the code more readable and understandable, but it also makes use of parallelization for faster computation. The code snippet below shows how fast the vectorized implementation works as compared to non vectorized one.
import numpy as npimport time# Number of featuresn = 1000# Number of training examplesm = 10000# Initialize X and WX = np.random.rand(n,m)W = np.random.rand(n,1)# Vectorized codet1=time.time()Z = np.dot(W.T,X)print("Time taken for vectorized code is : ",(time.time()-t1)*1000,"ms")# Non Vectorized codeZ1 = np.zeros((1,m))t2 = time.time()for i in range(X.shape[1]): for j in range(X.shape[0]): Z[0][i] += W[j]*X[j][i]print("Time taken for non vectorized code is : ",(time.time()-t2)*1000,"ms")''' OutputTime taken for vectorized code is : 5.964040756225586 msTime taken for non vectorized code is : 40915.54665565491 ms'''
The above implementation considers only 10k training examples and 1k features. Although there are code optimization strategies, clearly the vectorized implementation is much faster than the non vectorized one. Numpy is a python library that is used for scientific computation. It offers various inbuilt functions that make it easy for us to write a vectorized code.
As a rule of thumb, we should write a vectorized code for any future implementations using built-in numpy functions.
Now that we have seen how beneficial it is to write a vectorized code, let us delve deeper and write a vectorized code for logistic regression. It is not possible to write a vectorized code for each and every case but we should try to follow the rule of thumb wherever possible. Let us see a non vectorized version of logistic regression and try to figure out the parts which can be vectorized. This way we will understand how to convert a given piece of code into its vectorized version. For simplicity, we will consider only 2 features in X and therefore only 2 weights.
In the above example, we have considered only 2 weights i.e. w1 and w2 but in real life scenarios there will lot more weights, handling them will become a complex task. Therefore, we will vectorize the calculation and updation of weight derivates dw1 and dw2 by:
dW = X[i].dZ[i]dW /= m
With the help of the above changes, we have managed to vectorize only a small part of the code. Most of part still depends on the for loop which is used to iterate over all the training examples. Let us see how we can remove that for loop and vectorize that as well:
The value A for all training examples can be easily found out by:
A = sigmoid(np.dot(W.T,X)+b)
The cost J can be found out by:
J = -(np.dot(Y,np.log(A).T)+np.dot((1-Y),np.log(1-A).T))
The derivatives dZ, dW and dB for all training examples can be found out by:
dZ = A - Y dW = np.dot(X*(dZ.T))/mdB = (np.sum(dZ))/m
The Weight Matrix W and bias B can be updated by:
W = W - alpha*dWb = b - alpha*dB
These conversions may seem perplexing at first. Therefore, I urge the readers to see how the dimension of each matrix changes after each calculation. This will help in understanding things in a better way. Let us apply the changes and see how the vectorized code looks like when everything is compiled together.
The above code is much cleaner, readable, short and computationally faster.
Amidst the code, you may have found that two matrices of incompatible dimensions are added, subtracted, multiplied and divided. Numpy has a great feature called Broadcasting. Under some constraints, the smaller matrix is broadcasted to the bigger matrix so that they have compatible dimensions to carry out various mathematical operations. Let us see how broadcasting works with the help of some examples. Let A and B be input matrices and C be the output matrix as a result of any mathematical operation on A and B.
Shape of A : 5 x 4Shape of B : 4Shape of C : 5 x 4Shape of A : 15 x 3 x 5Shape of B : 15 x 1 x 5Shape of C : 15 x 3 x 5Shape of A : 8 x 1 x 6 x 1Shape of B : 7 x 1 x 5Shape of C : 8 x 7 x 6 x 5Shape of A : 2 x 3 x 3Shape of B : 1 x 5Shape of C : Error
It follows that broadcasting works on 2 principles:
The trailing dimensions of A and B should be equal orTrailing dimensions of either A or B should be 1.
The trailing dimensions of A and B should be equal or
Trailing dimensions of either A or B should be 1.
The best way to understand Vectorization and convert a given code in vectorized format is to keep a track of the dimensions of various matrices that are at the table.
Writing a Vectorized version of the code can be daunting at first but, together with the help of Numpy’s built-in function and broadcasting and with practice, it becomes really easy. It will make the code more readable and immensely fast.
StackOverflow — What is Vectorization?Scipy Docs — BroadcastingNumpyCoursera — Deep Learning Course 1
StackOverflow — What is Vectorization?
Scipy Docs — Broadcasting
Numpy
Coursera — Deep Learning Course 1
I would like to thank the readers for reading the story. If you have any questions or doubts, feel free to ask them in the comments section below. I’ll be more than happy to answer them and help you out. If you like the story, please follow me to get regular updates when I publish a new story. I welcome any suggestions that will improve my stories.
|
[
{
"code": null,
"e": 882,
"s": 171,
"text": "Computer hardware in today’s world leverages parallel computing for faster computation by making use of SIMD (Single Instruction, Multiple Data) architectures. SIMD is a class of parallel computing in which the logical processors perform a single instruction on multiple data points simultaneously. We need to vectorize our deep learning code so that we can harness all the computing power that our system provides. The faster the computation, the faster our neural network is trained and the faster we get our results. Therefore, the ability to vectorize a piece of code has become a crucial skill for a deep learning practitioner. In this story, I will be explaining the basics of vectorization using python."
},
{
"code": null,
"e": 1016,
"s": 882,
"text": "In the context of logistic regression, let us try to understand what vectorization exactly means with the help of the equation below:"
},
{
"code": null,
"e": 1459,
"s": 1016,
"text": "The convention for storing the inputs and weights is not standard but I prefer to store it the following way. Let X be the input matrix of dimensions (n,m) where n is the number of features present in X and m is the number of training examples present in our training dataset i.e. we are storing one data point in 1 column. For each feature, there will be a weight associated with it, therefore let W be the weight matrix of dimensions (n,1)."
},
{
"code": null,
"e": 1559,
"s": 1459,
"text": "Now, if we were to code the example equation using for loops, we would come up with something like:"
},
{
"code": null,
"e": 1807,
"s": 1559,
"text": "The above snippet of code consists of explicit for loops and will not make use of parallelization. Therefore, we need to convert it into a vectorized version. This can be done easily by leveraging the built-in Numpy functions in the following way:"
},
{
"code": null,
"e": 2185,
"s": 1807,
"text": "Z will be a (1,m) matrix as per matrix multiplication rules. The np.dot() function performs matrix multiplication of the given input matrices. It not only makes the code more readable and understandable, but it also makes use of parallelization for faster computation. The code snippet below shows how fast the vectorized implementation works as compared to non vectorized one."
},
{
"code": null,
"e": 2820,
"s": 2185,
"text": "import numpy as npimport time# Number of featuresn = 1000# Number of training examplesm = 10000# Initialize X and WX = np.random.rand(n,m)W = np.random.rand(n,1)# Vectorized codet1=time.time()Z = np.dot(W.T,X)print(\"Time taken for vectorized code is : \",(time.time()-t1)*1000,\"ms\")# Non Vectorized codeZ1 = np.zeros((1,m))t2 = time.time()for i in range(X.shape[1]): for j in range(X.shape[0]): Z[0][i] += W[j]*X[j][i]print(\"Time taken for non vectorized code is : \",(time.time()-t2)*1000,\"ms\")''' OutputTime taken for vectorized code is : 5.964040756225586 msTime taken for non vectorized code is : 40915.54665565491 ms'''"
},
{
"code": null,
"e": 3186,
"s": 2820,
"text": "The above implementation considers only 10k training examples and 1k features. Although there are code optimization strategies, clearly the vectorized implementation is much faster than the non vectorized one. Numpy is a python library that is used for scientific computation. It offers various inbuilt functions that make it easy for us to write a vectorized code."
},
{
"code": null,
"e": 3303,
"s": 3186,
"text": "As a rule of thumb, we should write a vectorized code for any future implementations using built-in numpy functions."
},
{
"code": null,
"e": 3876,
"s": 3303,
"text": "Now that we have seen how beneficial it is to write a vectorized code, let us delve deeper and write a vectorized code for logistic regression. It is not possible to write a vectorized code for each and every case but we should try to follow the rule of thumb wherever possible. Let us see a non vectorized version of logistic regression and try to figure out the parts which can be vectorized. This way we will understand how to convert a given piece of code into its vectorized version. For simplicity, we will consider only 2 features in X and therefore only 2 weights."
},
{
"code": null,
"e": 4139,
"s": 3876,
"text": "In the above example, we have considered only 2 weights i.e. w1 and w2 but in real life scenarios there will lot more weights, handling them will become a complex task. Therefore, we will vectorize the calculation and updation of weight derivates dw1 and dw2 by:"
},
{
"code": null,
"e": 4162,
"s": 4139,
"text": "dW = X[i].dZ[i]dW /= m"
},
{
"code": null,
"e": 4429,
"s": 4162,
"text": "With the help of the above changes, we have managed to vectorize only a small part of the code. Most of part still depends on the for loop which is used to iterate over all the training examples. Let us see how we can remove that for loop and vectorize that as well:"
},
{
"code": null,
"e": 4495,
"s": 4429,
"text": "The value A for all training examples can be easily found out by:"
},
{
"code": null,
"e": 4524,
"s": 4495,
"text": "A = sigmoid(np.dot(W.T,X)+b)"
},
{
"code": null,
"e": 4556,
"s": 4524,
"text": "The cost J can be found out by:"
},
{
"code": null,
"e": 4613,
"s": 4556,
"text": "J = -(np.dot(Y,np.log(A).T)+np.dot((1-Y),np.log(1-A).T))"
},
{
"code": null,
"e": 4690,
"s": 4613,
"text": "The derivatives dZ, dW and dB for all training examples can be found out by:"
},
{
"code": null,
"e": 4744,
"s": 4690,
"text": "dZ = A - Y dW = np.dot(X*(dZ.T))/mdB = (np.sum(dZ))/m"
},
{
"code": null,
"e": 4794,
"s": 4744,
"text": "The Weight Matrix W and bias B can be updated by:"
},
{
"code": null,
"e": 4827,
"s": 4794,
"text": "W = W - alpha*dWb = b - alpha*dB"
},
{
"code": null,
"e": 5139,
"s": 4827,
"text": "These conversions may seem perplexing at first. Therefore, I urge the readers to see how the dimension of each matrix changes after each calculation. This will help in understanding things in a better way. Let us apply the changes and see how the vectorized code looks like when everything is compiled together."
},
{
"code": null,
"e": 5215,
"s": 5139,
"text": "The above code is much cleaner, readable, short and computationally faster."
},
{
"code": null,
"e": 5732,
"s": 5215,
"text": "Amidst the code, you may have found that two matrices of incompatible dimensions are added, subtracted, multiplied and divided. Numpy has a great feature called Broadcasting. Under some constraints, the smaller matrix is broadcasted to the bigger matrix so that they have compatible dimensions to carry out various mathematical operations. Let us see how broadcasting works with the help of some examples. Let A and B be input matrices and C be the output matrix as a result of any mathematical operation on A and B."
},
{
"code": null,
"e": 5996,
"s": 5732,
"text": "Shape of A : 5 x 4Shape of B : 4Shape of C : 5 x 4Shape of A : 15 x 3 x 5Shape of B : 15 x 1 x 5Shape of C : 15 x 3 x 5Shape of A : 8 x 1 x 6 x 1Shape of B : 7 x 1 x 5Shape of C : 8 x 7 x 6 x 5Shape of A : 2 x 3 x 3Shape of B : 1 x 5Shape of C : Error"
},
{
"code": null,
"e": 6048,
"s": 5996,
"text": "It follows that broadcasting works on 2 principles:"
},
{
"code": null,
"e": 6151,
"s": 6048,
"text": "The trailing dimensions of A and B should be equal orTrailing dimensions of either A or B should be 1."
},
{
"code": null,
"e": 6205,
"s": 6151,
"text": "The trailing dimensions of A and B should be equal or"
},
{
"code": null,
"e": 6255,
"s": 6205,
"text": "Trailing dimensions of either A or B should be 1."
},
{
"code": null,
"e": 6422,
"s": 6255,
"text": "The best way to understand Vectorization and convert a given code in vectorized format is to keep a track of the dimensions of various matrices that are at the table."
},
{
"code": null,
"e": 6661,
"s": 6422,
"text": "Writing a Vectorized version of the code can be daunting at first but, together with the help of Numpy’s built-in function and broadcasting and with practice, it becomes really easy. It will make the code more readable and immensely fast."
},
{
"code": null,
"e": 6763,
"s": 6661,
"text": "StackOverflow — What is Vectorization?Scipy Docs — BroadcastingNumpyCoursera — Deep Learning Course 1"
},
{
"code": null,
"e": 6802,
"s": 6763,
"text": "StackOverflow — What is Vectorization?"
},
{
"code": null,
"e": 6828,
"s": 6802,
"text": "Scipy Docs — Broadcasting"
},
{
"code": null,
"e": 6834,
"s": 6828,
"text": "Numpy"
},
{
"code": null,
"e": 6868,
"s": 6834,
"text": "Coursera — Deep Learning Course 1"
}
] |
Number of Irreflexive Relations on a Set - GeeksforGeeks
|
30 Apr, 2021
Given a positive integer N, the task is to find the number of irreflexive relations that can be formed over the given set of elements. Since the count can be very large, print it to modulo 109 + 7.
A relation R on a set A is called reflexive if no (a, a) € R holds for every element a € A.For Example: If set A = {a, b} then R = {(a, b), (b, a)} is irreflexive relation.
Examples:
Input: N = 2Output: 4Explanation:Considering the set {1, 2}, the total possible irreflexive relations are:
{}
{(1, 2)}
{(2, 1)}
{(1, 2), (2, 1)}
Input: N = 5Output: 1048576
Approach: Follow the steps below to solve the problem:
A relation R on a set A is a subset of the cartesian product of a set, i.e. A * A with N2 elements.
Irreflexive Relation: A relation R on a set A is called Irreflexive if and only if x R x [(x, x) does not belong to R] for every element x in A.
There are total N pairs of (x, x) are present in the Cartesian product which should not be included in an irreflexive relation. Therefore, for the remaining (N2 – N) elements, each element has two choices i.e., either to include or exclude it in the subset.
Hence, the total number of possible irreflexive relations is given by 2(N2 – N).
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <iostream>using namespace std; const int mod = 1000000007; // Function to calculate x^y// modulo 1000000007 in O(log y)int power(long long x, unsigned int y){ // Stores the result of x^y int res = 1; // Update x if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with result if (y & 1) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the resultant value of x^y return res;} // Function to count the number of// irreflixive relations in a set// consisting of N elementsint irreflexiveRelation(int N){ // Return the resultant count return power(2, N * N - N);} // Driver Codeint main(){ int N = 2; cout << irreflexiveRelation(N); return 0;}
// Java program for the above approachimport java.io.*;import java.util.*;class GFG{ static int mod = 1000000007; // Function to calculate x^y// modulo 1000000007 in O(log y)static int power(int x, int y){ // Stores the result of x^y int res = 1; // Update x if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with result if ((y & 1) != 0) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the resultant value of x^y return res;} // Function to count the number of// irreflixive relations in a set// consisting of N elementsstatic int irreflexiveRelation(int N){ // Return the resultant count return power(2, N * N - N);} // Driver Codepublic static void main(String[] args){ int N = 2; System.out.println(irreflexiveRelation(N));}} // This code is contributed by code_hunt.
# Python3 program for the above approachmod = 1000000007 # Function to calculate x^y# modulo 1000000007 in O(log y)def power(x, y): global mod # Stores the result of x^y res = 1 # Update x if it exceeds mod x = x % mod # If x is divisible by mod if (x == 0): return 0 while (y > 0): # If y is odd, then # multiply x with result if (y & 1): res = (res * x) % mod # Divide y by 2 y = y >> 1 # Update the value of x x = (x * x) % mod # Return the resultant value of x^y return res # Function to count the number of# irreflixive relations in a set# consisting of N elementsdef irreflexiveRelation(N): # Return the resultant count return power(2, N * N - N) # Driver Codeif __name__ == '__main__': N = 2 print(irreflexiveRelation(N)) # This code is contributed by mohit kumar 29.
// C# program for above approachusing System; public class GFG{ static int mod = 1000000007; // Function to calculate x^y // modulo 1000000007 in O(log y) static int power(int x, int y) { // Stores the result of x^y int res = 1; // Update x if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with result if ((y & 1) != 0) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the resultant value of x^y return res; } // Function to count the number of // irreflixive relations in a set // consisting of N elements static int irreflexiveRelation(int N) { // Return the resultant count return power(2, N * N - N); } // Driver code public static void Main(String[] args) { int N = 2; Console.WriteLine(irreflexiveRelation(N)); }} // This code is contributed by sanjoy_62.
<script> // Javascript program for the above approach let mod = 1000000007; // Function to calculate x^y// modulo 1000000007 in O(log y)function power(x, y){ // Stores the result of x^y let res = 1; // Update x if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with result if ((y & 1) != 0) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the resultant value of x^y return res;} // Function to count the number of// irreflixive relations in a set// consisting of N elementsfunction irreflexiveRelation(N){ // Return the resultant count return power(2, N * N - N);} // Driver code let N = 2; document.write(irreflexiveRelation(N)); </script>
4
Time Complexity: O(log N)Auxiliary Space: O(1)
mohit kumar 29
code_hunt
sanjoy_62
chinmoy1997pal
maths-power
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Program to find GCD or HCF of two numbers
Prime Numbers
Modulo Operator (%) in C/C++ with Examples
Sieve of Eratosthenes
Program for Decimal to Binary Conversion
Find all factors of a natural number | Set 1
Program to find sum of elements in a given array
Modulo 10^9+7 (1000000007)
The Knight's tour problem | Backtracking-1
|
[
{
"code": null,
"e": 25003,
"s": 24975,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 25202,
"s": 25003,
"text": "Given a positive integer N, the task is to find the number of irreflexive relations that can be formed over the given set of elements. Since the count can be very large, print it to modulo 109 + 7."
},
{
"code": null,
"e": 25375,
"s": 25202,
"text": "A relation R on a set A is called reflexive if no (a, a) € R holds for every element a € A.For Example: If set A = {a, b} then R = {(a, b), (b, a)} is irreflexive relation."
},
{
"code": null,
"e": 25385,
"s": 25375,
"text": "Examples:"
},
{
"code": null,
"e": 25492,
"s": 25385,
"text": "Input: N = 2Output: 4Explanation:Considering the set {1, 2}, the total possible irreflexive relations are:"
},
{
"code": null,
"e": 25495,
"s": 25492,
"text": "{}"
},
{
"code": null,
"e": 25504,
"s": 25495,
"text": "{(1, 2)}"
},
{
"code": null,
"e": 25513,
"s": 25504,
"text": "{(2, 1)}"
},
{
"code": null,
"e": 25530,
"s": 25513,
"text": "{(1, 2), (2, 1)}"
},
{
"code": null,
"e": 25558,
"s": 25530,
"text": "Input: N = 5Output: 1048576"
},
{
"code": null,
"e": 25613,
"s": 25558,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25713,
"s": 25613,
"text": "A relation R on a set A is a subset of the cartesian product of a set, i.e. A * A with N2 elements."
},
{
"code": null,
"e": 25858,
"s": 25713,
"text": "Irreflexive Relation: A relation R on a set A is called Irreflexive if and only if x R x [(x, x) does not belong to R] for every element x in A."
},
{
"code": null,
"e": 26116,
"s": 25858,
"text": "There are total N pairs of (x, x) are present in the Cartesian product which should not be included in an irreflexive relation. Therefore, for the remaining (N2 – N) elements, each element has two choices i.e., either to include or exclude it in the subset."
},
{
"code": null,
"e": 26197,
"s": 26116,
"text": "Hence, the total number of possible irreflexive relations is given by 2(N2 – N)."
},
{
"code": null,
"e": 26248,
"s": 26197,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26252,
"s": 26248,
"text": "C++"
},
{
"code": null,
"e": 26257,
"s": 26252,
"text": "Java"
},
{
"code": null,
"e": 26265,
"s": 26257,
"text": "Python3"
},
{
"code": null,
"e": 26268,
"s": 26265,
"text": "C#"
},
{
"code": null,
"e": 26279,
"s": 26268,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <iostream>using namespace std; const int mod = 1000000007; // Function to calculate x^y// modulo 1000000007 in O(log y)int power(long long x, unsigned int y){ // Stores the result of x^y int res = 1; // Update x if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with result if (y & 1) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the resultant value of x^y return res;} // Function to count the number of// irreflixive relations in a set// consisting of N elementsint irreflexiveRelation(int N){ // Return the resultant count return power(2, N * N - N);} // Driver Codeint main(){ int N = 2; cout << irreflexiveRelation(N); return 0;}",
"e": 27226,
"s": 26279,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*;class GFG{ static int mod = 1000000007; // Function to calculate x^y// modulo 1000000007 in O(log y)static int power(int x, int y){ // Stores the result of x^y int res = 1; // Update x if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with result if ((y & 1) != 0) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the resultant value of x^y return res;} // Function to count the number of// irreflixive relations in a set// consisting of N elementsstatic int irreflexiveRelation(int N){ // Return the resultant count return power(2, N * N - N);} // Driver Codepublic static void main(String[] args){ int N = 2; System.out.println(irreflexiveRelation(N));}} // This code is contributed by code_hunt.",
"e": 28264,
"s": 27226,
"text": null
},
{
"code": "# Python3 program for the above approachmod = 1000000007 # Function to calculate x^y# modulo 1000000007 in O(log y)def power(x, y): global mod # Stores the result of x^y res = 1 # Update x if it exceeds mod x = x % mod # If x is divisible by mod if (x == 0): return 0 while (y > 0): # If y is odd, then # multiply x with result if (y & 1): res = (res * x) % mod # Divide y by 2 y = y >> 1 # Update the value of x x = (x * x) % mod # Return the resultant value of x^y return res # Function to count the number of# irreflixive relations in a set# consisting of N elementsdef irreflexiveRelation(N): # Return the resultant count return power(2, N * N - N) # Driver Codeif __name__ == '__main__': N = 2 print(irreflexiveRelation(N)) # This code is contributed by mohit kumar 29.",
"e": 29165,
"s": 28264,
"text": null
},
{
"code": "// C# program for above approachusing System; public class GFG{ static int mod = 1000000007; // Function to calculate x^y // modulo 1000000007 in O(log y) static int power(int x, int y) { // Stores the result of x^y int res = 1; // Update x if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with result if ((y & 1) != 0) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the resultant value of x^y return res; } // Function to count the number of // irreflixive relations in a set // consisting of N elements static int irreflexiveRelation(int N) { // Return the resultant count return power(2, N * N - N); } // Driver code public static void Main(String[] args) { int N = 2; Console.WriteLine(irreflexiveRelation(N)); }} // This code is contributed by sanjoy_62.",
"e": 30190,
"s": 29165,
"text": null
},
{
"code": "<script> // Javascript program for the above approach let mod = 1000000007; // Function to calculate x^y// modulo 1000000007 in O(log y)function power(x, y){ // Stores the result of x^y let res = 1; // Update x if it exceeds mod x = x % mod; // If x is divisible by mod if (x == 0) return 0; while (y > 0) { // If y is odd, then // multiply x with result if ((y & 1) != 0) res = (res * x) % mod; // Divide y by 2 y = y >> 1; // Update the value of x x = (x * x) % mod; } // Return the resultant value of x^y return res;} // Function to count the number of// irreflixive relations in a set// consisting of N elementsfunction irreflexiveRelation(N){ // Return the resultant count return power(2, N * N - N);} // Driver code let N = 2; document.write(irreflexiveRelation(N)); </script>",
"e": 31105,
"s": 30190,
"text": null
},
{
"code": null,
"e": 31107,
"s": 31105,
"text": "4"
},
{
"code": null,
"e": 31156,
"s": 31109,
"text": "Time Complexity: O(log N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31171,
"s": 31156,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 31181,
"s": 31171,
"text": "code_hunt"
},
{
"code": null,
"e": 31191,
"s": 31181,
"text": "sanjoy_62"
},
{
"code": null,
"e": 31206,
"s": 31191,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 31218,
"s": 31206,
"text": "maths-power"
},
{
"code": null,
"e": 31231,
"s": 31218,
"text": "Mathematical"
},
{
"code": null,
"e": 31244,
"s": 31231,
"text": "Mathematical"
},
{
"code": null,
"e": 31342,
"s": 31244,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31351,
"s": 31342,
"text": "Comments"
},
{
"code": null,
"e": 31364,
"s": 31351,
"text": "Old Comments"
},
{
"code": null,
"e": 31388,
"s": 31364,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 31430,
"s": 31388,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 31444,
"s": 31430,
"text": "Prime Numbers"
},
{
"code": null,
"e": 31487,
"s": 31444,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 31509,
"s": 31487,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 31550,
"s": 31509,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 31595,
"s": 31550,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 31644,
"s": 31595,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 31671,
"s": 31644,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
What is the difference between append() and appendTo() in jQuery?
|
The append (content) method appends content to the inside of every matched element, whereas the appendTo (selector) method appends all of the matched elements to another, specified, set of elements.
jQuery append() function
The append (content) method appends content to the inside of every matched element.
Here is the description of all the parameters used by this method −
content − Content to insert after each target. This could be HTML or Text content
You can try to run the following code to learn how to work with append() function in jQuery:
Live Demo
<html>
<head>
<title>jQuery append() method</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function () {
$(this).append('<div class = "div"></div>' );
});
});
</script>
<style>
.div{
margin:10px;
padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class = "div" style = "background-color:blue;"></div>
<div class = "div" style = "background-color:green;"></div>
<div class = "div" style = "background-color:red;"></div>
</body>
</html>
jQuery appendTo() function
The appendTo (selector) method appends all of the matched elements to another, specified, set of elements. Here is the description of all the parameters used by this method −
selector − This is the target to which the content will be appended.
You can try to run the following code to learn how to work with appendTo() function in jQuery:
Live Demo
<html>
<head>
<title>jQuery appendTo()</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function () {
$(this).appendTo("#result");
});
});
</script>
<style>
.div{
margin:10px;
padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<p id = "result"> THIS IS TEST </p>
<hr />
<div class = "div" style = "background-color:blue;"></div>
<div class = "div" style = "background-color:green;"></div>
<div class = "div" style = "background-color:red;"></div>
</body>
</html>
|
[
{
"code": null,
"e": 1261,
"s": 1062,
"text": "The append (content) method appends content to the inside of every matched element, whereas the appendTo (selector) method appends all of the matched elements to another, specified, set of elements."
},
{
"code": null,
"e": 1286,
"s": 1261,
"text": "jQuery append() function"
},
{
"code": null,
"e": 1370,
"s": 1286,
"text": "The append (content) method appends content to the inside of every matched element."
},
{
"code": null,
"e": 1438,
"s": 1370,
"text": "Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 1520,
"s": 1438,
"text": "content − Content to insert after each target. This could be HTML or Text content"
},
{
"code": null,
"e": 1613,
"s": 1520,
"text": "You can try to run the following code to learn how to work with append() function in jQuery:"
},
{
"code": null,
"e": 1623,
"s": 1613,
"text": "Live Demo"
},
{
"code": null,
"e": 2482,
"s": 1623,
"text": "<html>\n\n <head>\n <title>jQuery append() method</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n $(\"div\").click(function () {\n $(this).append('<div class = \"div\"></div>' );\n });\n });\n </script>\n \n <style>\n .div{\n margin:10px;\n padding:12px;\n border:2px solid #666;\n width:60px;\n }\n </style>\n </head>\n \n <body>\n \n <p>Click on any square below to see the result:</p>\n \n <div class = \"div\" style = \"background-color:blue;\"></div>\n <div class = \"div\" style = \"background-color:green;\"></div>\n <div class = \"div\" style = \"background-color:red;\"></div>\n \n </body>\n</html>"
},
{
"code": null,
"e": 2509,
"s": 2482,
"text": "jQuery appendTo() function"
},
{
"code": null,
"e": 2684,
"s": 2509,
"text": "The appendTo (selector) method appends all of the matched elements to another, specified, set of elements. Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 2753,
"s": 2684,
"text": "selector − This is the target to which the content will be appended."
},
{
"code": null,
"e": 2848,
"s": 2753,
"text": "You can try to run the following code to learn how to work with appendTo() function in jQuery:"
},
{
"code": null,
"e": 2858,
"s": 2848,
"text": "Live Demo"
},
{
"code": null,
"e": 3749,
"s": 2858,
"text": "<html>\n <head>\n <title>jQuery appendTo()</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n $(\"div\").click(function () {\n $(this).appendTo(\"#result\");\n });\n });\n </script>\n \n <style>\n .div{\n margin:10px;\n padding:12px;\n border:2px solid #666;\n width:60px;\n }\n </style>\n </head>\n \n <body>\n <p>Click on any square below to see the result:</p>\n <p id = \"result\"> THIS IS TEST </p>\n <hr />\n \n <div class = \"div\" style = \"background-color:blue;\"></div>\n <div class = \"div\" style = \"background-color:green;\"></div>\n <div class = \"div\" style = \"background-color:red;\"></div>\n \n </body>\n</html>"
}
] |
A Beginner’s Guide to Graph Neural Networks Using PyTorch Geometric — Part 1 | by Rohith Teja | Towards Data Science
|
You have stumbled on Graph Neural Networks somehow and now you’re interested in using it to solve a problem. Let’s explore on how we can model a problem using different tools available at our disposal.
At first, we need a problem to solve.
Let’s pick a simple graph dataset like Zachary’s Karate Club. Here, the nodes represent 34 students who were involved in the club and the links represent 78 different interactions between pairs of members outside the club. There are two different types of labels i.e, the two factions. We can use this information to formulate a node classification task.
We divide the graph into train and test sets where we use the train set to build a graph neural network model and use the model to predict the missing node labels in the test set.
Here, we use PyTorch Geometric (PyG) python library to model the graph neural network. Alternatively, Deep Graph Library (DGL) can also be used for the same purpose.
PyTorch Geometric is a geometric deep learning library built on top of PyTorch. Several popular graph neural network methods have been implemented using PyG and you can play around with the code using built-in datasets or create your own dataset. PyG uses a nifty implementation where it provides an InMemoryDataset class which can be used to create the custom dataset (Note: InMemoryDataset should be used for datasets small enough to load in the memory).
A simple visualization of Zachary’s Karate Club graph dataset looks as follows:
In order to formulate the problem, we need:
The graph itself and the labels for each nodeThe edge data in the Coordinate Format (COO)Embeddings or numerical representations for the nodes
The graph itself and the labels for each node
The edge data in the Coordinate Format (COO)
Embeddings or numerical representations for the nodes
Note: For the numerical representation for nodes, we can use graph properties like degree or use different embedding generation methods like node2vec, DeepWalk etc. In this example, I will be using node degree as its numerical representation.
Let’s get into the coding part.
The karate club dataset can be loaded directly from the NetworkX library. We retrieve the labels from the graph and create an edge index in the coordinate format. The node degree was used as embeddings/ numerical representations for the nodes (In the case of a directed graph, in-degree can be used for the same purpose). Since degree values tend to be diverse, we normalize them before using the values as input to the GNN model.
With this, we have prepared all the necessary parts to construct the Pytorch Geometric custom dataset.
The KarateDataset class inherits from the InMemoryDataset class and use a Data object to collate all information relating to the karate club dataset. The graph data is then split into train and test sets, thereby creating the train and test masks using the splits.
The data object contains the following variables:
Data(edge_index=[2, 156], num_classes=[1], test_mask=[34], train_mask=[34], x=[34, 1], y=[34])
This custom dataset can now be used with several graph neural network models from the Pytorch Geometric library. Let’s pick a Graph Convolutional Network model and use it to predict the missing labels on the test set.
Note: PyG library focuses more on node classification task but it can also be used for link prediction.
The GCN model is built with 2 hidden layers and each hidden layer contains 16 neurons. Let’s train the model!
Initial experiments with random hyperparameters gave these results:
Train Accuracy: 0.913Test Accuracy: 0.727
This is not impressive and we can certainly do better. In my next post, I will discuss how we can use Optuna (python library on hyperparameter tuning) to tune the hyperparameters easily and find the best model. The code used in this example was taken from the PyTorch Geometric’s GitHub repository with some modifications (link).
To summarize everything we have done so far:
Generate numerical representations for each node in the graph (node degree in this case).Construct a PyG custom dataset and split data into train and test.Use a GNN model like GCN and train the model.Make predictions on the test set and calculate the accuracy score.
Generate numerical representations for each node in the graph (node degree in this case).
Construct a PyG custom dataset and split data into train and test.
Use a GNN model like GCN and train the model.
Make predictions on the test set and calculate the accuracy score.
Acknowledgement: Most of the explanations made in this post were the concepts that I learned and applied during my internship at Orange Labs in Cesson-Sévigné. I worked with graph embedding methods and also graph neural networks which can be applied on a knowledge graph.
In the coming parts, I will explain more on how we can use graph embeddings as initial node representations to handle the same task of node classification.
Thanks for reading, and cheers!
Want to Connect? Reach me at LinkedIn, Twitter, GitHub or my Website.You can also consider to 👇
|
[
{
"code": null,
"e": 374,
"s": 172,
"text": "You have stumbled on Graph Neural Networks somehow and now you’re interested in using it to solve a problem. Let’s explore on how we can model a problem using different tools available at our disposal."
},
{
"code": null,
"e": 412,
"s": 374,
"text": "At first, we need a problem to solve."
},
{
"code": null,
"e": 767,
"s": 412,
"text": "Let’s pick a simple graph dataset like Zachary’s Karate Club. Here, the nodes represent 34 students who were involved in the club and the links represent 78 different interactions between pairs of members outside the club. There are two different types of labels i.e, the two factions. We can use this information to formulate a node classification task."
},
{
"code": null,
"e": 947,
"s": 767,
"text": "We divide the graph into train and test sets where we use the train set to build a graph neural network model and use the model to predict the missing node labels in the test set."
},
{
"code": null,
"e": 1113,
"s": 947,
"text": "Here, we use PyTorch Geometric (PyG) python library to model the graph neural network. Alternatively, Deep Graph Library (DGL) can also be used for the same purpose."
},
{
"code": null,
"e": 1570,
"s": 1113,
"text": "PyTorch Geometric is a geometric deep learning library built on top of PyTorch. Several popular graph neural network methods have been implemented using PyG and you can play around with the code using built-in datasets or create your own dataset. PyG uses a nifty implementation where it provides an InMemoryDataset class which can be used to create the custom dataset (Note: InMemoryDataset should be used for datasets small enough to load in the memory)."
},
{
"code": null,
"e": 1650,
"s": 1570,
"text": "A simple visualization of Zachary’s Karate Club graph dataset looks as follows:"
},
{
"code": null,
"e": 1694,
"s": 1650,
"text": "In order to formulate the problem, we need:"
},
{
"code": null,
"e": 1837,
"s": 1694,
"text": "The graph itself and the labels for each nodeThe edge data in the Coordinate Format (COO)Embeddings or numerical representations for the nodes"
},
{
"code": null,
"e": 1883,
"s": 1837,
"text": "The graph itself and the labels for each node"
},
{
"code": null,
"e": 1928,
"s": 1883,
"text": "The edge data in the Coordinate Format (COO)"
},
{
"code": null,
"e": 1982,
"s": 1928,
"text": "Embeddings or numerical representations for the nodes"
},
{
"code": null,
"e": 2225,
"s": 1982,
"text": "Note: For the numerical representation for nodes, we can use graph properties like degree or use different embedding generation methods like node2vec, DeepWalk etc. In this example, I will be using node degree as its numerical representation."
},
{
"code": null,
"e": 2257,
"s": 2225,
"text": "Let’s get into the coding part."
},
{
"code": null,
"e": 2688,
"s": 2257,
"text": "The karate club dataset can be loaded directly from the NetworkX library. We retrieve the labels from the graph and create an edge index in the coordinate format. The node degree was used as embeddings/ numerical representations for the nodes (In the case of a directed graph, in-degree can be used for the same purpose). Since degree values tend to be diverse, we normalize them before using the values as input to the GNN model."
},
{
"code": null,
"e": 2791,
"s": 2688,
"text": "With this, we have prepared all the necessary parts to construct the Pytorch Geometric custom dataset."
},
{
"code": null,
"e": 3056,
"s": 2791,
"text": "The KarateDataset class inherits from the InMemoryDataset class and use a Data object to collate all information relating to the karate club dataset. The graph data is then split into train and test sets, thereby creating the train and test masks using the splits."
},
{
"code": null,
"e": 3106,
"s": 3056,
"text": "The data object contains the following variables:"
},
{
"code": null,
"e": 3201,
"s": 3106,
"text": "Data(edge_index=[2, 156], num_classes=[1], test_mask=[34], train_mask=[34], x=[34, 1], y=[34])"
},
{
"code": null,
"e": 3419,
"s": 3201,
"text": "This custom dataset can now be used with several graph neural network models from the Pytorch Geometric library. Let’s pick a Graph Convolutional Network model and use it to predict the missing labels on the test set."
},
{
"code": null,
"e": 3523,
"s": 3419,
"text": "Note: PyG library focuses more on node classification task but it can also be used for link prediction."
},
{
"code": null,
"e": 3633,
"s": 3523,
"text": "The GCN model is built with 2 hidden layers and each hidden layer contains 16 neurons. Let’s train the model!"
},
{
"code": null,
"e": 3701,
"s": 3633,
"text": "Initial experiments with random hyperparameters gave these results:"
},
{
"code": null,
"e": 3743,
"s": 3701,
"text": "Train Accuracy: 0.913Test Accuracy: 0.727"
},
{
"code": null,
"e": 4073,
"s": 3743,
"text": "This is not impressive and we can certainly do better. In my next post, I will discuss how we can use Optuna (python library on hyperparameter tuning) to tune the hyperparameters easily and find the best model. The code used in this example was taken from the PyTorch Geometric’s GitHub repository with some modifications (link)."
},
{
"code": null,
"e": 4118,
"s": 4073,
"text": "To summarize everything we have done so far:"
},
{
"code": null,
"e": 4385,
"s": 4118,
"text": "Generate numerical representations for each node in the graph (node degree in this case).Construct a PyG custom dataset and split data into train and test.Use a GNN model like GCN and train the model.Make predictions on the test set and calculate the accuracy score."
},
{
"code": null,
"e": 4475,
"s": 4385,
"text": "Generate numerical representations for each node in the graph (node degree in this case)."
},
{
"code": null,
"e": 4542,
"s": 4475,
"text": "Construct a PyG custom dataset and split data into train and test."
},
{
"code": null,
"e": 4588,
"s": 4542,
"text": "Use a GNN model like GCN and train the model."
},
{
"code": null,
"e": 4655,
"s": 4588,
"text": "Make predictions on the test set and calculate the accuracy score."
},
{
"code": null,
"e": 4929,
"s": 4655,
"text": "Acknowledgement: Most of the explanations made in this post were the concepts that I learned and applied during my internship at Orange Labs in Cesson-Sévigné. I worked with graph embedding methods and also graph neural networks which can be applied on a knowledge graph."
},
{
"code": null,
"e": 5085,
"s": 4929,
"text": "In the coming parts, I will explain more on how we can use graph embeddings as initial node representations to handle the same task of node classification."
},
{
"code": null,
"e": 5117,
"s": 5085,
"text": "Thanks for reading, and cheers!"
}
] |
Demonstrate static variables, methods and blocks in Java
|
The static variable is a class level variable and it is common to all the class objects i.e. a single copy of the static variable is shared among all the class objects.
A static method manipulates the static variables in a class. It belongs to the class instead of the class objects and can be invoked without using a class object.
The static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded.
A program that demonstrates this is given as follows:
Live Demo
public class Demo {
static int x = 10;
static int y;
static void func(int z) {
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);
}
static {
System.out.println("Running static initialization block.");
y = x + 5;
}
public static void main(String args[]) {
func(8);
}
}
Running static initialization block.
x = 10
y = 15
z = 8
Now let us understand the above program.
The class Demo contains static variables x and y. The static method func() prints the values of x, y and z. A code snippet which demonstrates this is as follows:
static int x = 10;
static int y;
static void func(int z) {
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);
}
The static initialization block initializes the static variable y. In the main() method, the func() method is called. A code snippet which demonstrates this is as follows:
static {
System.out.println("Running static initialization block.");
y = x + 5;
}
public static void main(String args[]) {
func(8);
}
|
[
{
"code": null,
"e": 1231,
"s": 1062,
"text": "The static variable is a class level variable and it is common to all the class objects i.e. a single copy of the static variable is shared among all the class objects."
},
{
"code": null,
"e": 1394,
"s": 1231,
"text": "A static method manipulates the static variables in a class. It belongs to the class instead of the class objects and can be invoked without using a class object."
},
{
"code": null,
"e": 1540,
"s": 1394,
"text": "The static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded."
},
{
"code": null,
"e": 1594,
"s": 1540,
"text": "A program that demonstrates this is given as follows:"
},
{
"code": null,
"e": 1605,
"s": 1594,
"text": " Live Demo"
},
{
"code": null,
"e": 1978,
"s": 1605,
"text": "public class Demo {\n static int x = 10;\n static int y;\n static void func(int z) {\n System.out.println(\"x = \" + x);\n System.out.println(\"y = \" + y);\n System.out.println(\"z = \" + z);\n }\n static {\n System.out.println(\"Running static initialization block.\");\n y = x + 5;\n }\n public static void main(String args[]) {\n func(8);\n }\n}"
},
{
"code": null,
"e": 2035,
"s": 1978,
"text": "Running static initialization block.\nx = 10\ny = 15\nz = 8"
},
{
"code": null,
"e": 2076,
"s": 2035,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2238,
"s": 2076,
"text": "The class Demo contains static variables x and y. The static method func() prints the values of x, y and z. A code snippet which demonstrates this is as follows:"
},
{
"code": null,
"e": 2404,
"s": 2238,
"text": "static int x = 10;\nstatic int y;\nstatic void func(int z) {\n System.out.println(\"x = \" + x);\n System.out.println(\"y = \" + y);\n System.out.println(\"z = \" + z);\n}"
},
{
"code": null,
"e": 2576,
"s": 2404,
"text": "The static initialization block initializes the static variable y. In the main() method, the func() method is called. A code snippet which demonstrates this is as follows:"
},
{
"code": null,
"e": 2719,
"s": 2576,
"text": "static {\n System.out.println(\"Running static initialization block.\");\n y = x + 5;\n}\npublic static void main(String args[]) {\n func(8);\n}"
}
] |
How to Deploy a Secure API with FastAPI, Docker and Traefik | by Ahmed Besbes | Towards Data Science
|
When we deploy an API to serve a machine learning model, we rarely care about that green padlock that makes the HTTP connection supposedly safe and the browser happy.
We usually take HTTPS for granted, and we may think that it just can be turned on with some easy configuration.
The truth is, adding HTTPS requires a few steps.
And that’s what this post is for: explaining why HTTPS matter and how you can add it as part of your deployment when you build web apps and APIs in Python.
Here’s what we’ll cover in this post:
A brief introduction to HTTPS: how does it work and why you should care about it?Building an API with FastAPIIntroducing Traefik and how it can handle HTTPSIntegrating FastAPI with Traefik via DockerDeploying on AWS
A brief introduction to HTTPS: how does it work and why you should care about it?
Building an API with FastAPI
Introducing Traefik and how it can handle HTTPS
Integrating FastAPI with Traefik via Docker
Deploying on AWS
This guide will ultimately help you add HTTPS to your projects. You can reuse the following code to build secure projects.
Without further ado, let’s jump right in 🚀
PS*: this code is available on Github.
PS**: if you want to learn more about FastAPI, Docker and Github Actions, make sure to have a look at my previous post.
towardsdatascience.com
A registered domain name. You can buy one on Namecheap for a few bucks
Docker and docker-compose installed on your local machine: you can follow the official documentation
A remote server to deploy the API: I’m using a t2-medium instance on AWS EC2. Anything equivalent should be good as well. Make sure this instance has a fixed IP address.
On your domain provider, create an A record that points to the instance’s IP address. I currently own ahmedbesbes.com and for this tutorial, I created the following A record: ssl.ahmedbesbes.com. You can do the same with your domain by picking any subdomain you want.Here’s what it looks like on OVH’s interface (OVH is my domain’s provider)
HTTPS is HTTP over an encryption protocol. This protocol is called Transport Layer Security (TLS) and it was formerly known as Secure Sockets Layer (SSL).
In other words, HTTPS is encrypted in order to increase the security of data transfer.
TLS, the protocol behind HTTPS, uses an asymmetric public key infrastructure. This system uses two different keys to encrypt communications between two parties:
A private key 🔐: this key is controlled by the owner of the website, it’s kept private and lives on the remote web server. It’s used to decrypt the information encrypted by the public keyA public key 🔑: this key is used by anyone who wants to interact with the server in a secure manner. This key’s role is to encrypt data that the private key will later decrypt.
A private key 🔐: this key is controlled by the owner of the website, it’s kept private and lives on the remote web server. It’s used to decrypt the information encrypted by the public key
A public key 🔑: this key is used by anyone who wants to interact with the server in a secure manner. This key’s role is to encrypt data that the private key will later decrypt.
HTTPS is a very useful protocol. You need it for 3 main reasons:
Privacy: So that no one can intercept or eavesdrop on your message (a message can be a text you post to your friend, a credit card information you fill in a form, an image, a video, or anything you upload through the network). When sent through HTTPS, this data is encrypted, i.e. turned into a long alphanumerical string.
Integrity: So that the message you send is not manipulated in any form on the way to its destination.
Authentication: So that the remote server you request is sure that you are the one who you claim to be
Besides adding a security layer to your app, HTTPS is a pledge for good-quality software practices. This is very important to build a trusted user base.
HTTPS is taken very seriously by major internet players. As a matter of fact, Google announced in 2014 that having HTTPS will increase your ranking in the search results. Google has also made Chrome flag any website without HTTPS as insecure.
Time to add HTTPS to your apps now!
In this section, we’ll get FastAPI up and running on a very simple example. We’ll see next how to secure it.
Before going into the code, here’s what the project structure looks like:
Let’s start by creating a virtual environment:
mkdir fastapi-ssl && cd _pipenv install fastapi
Nothing really fancy, we’ll create an API that has two routes:
one that handles GET requests and displays the following JSON response on the browser
{"message": "Hello FastAPI + SSL"}
another one that handles POST requests. This route expects a body containing two keys: text and author and sends a JSON object back as a response with the same text and author already sent and an additional status message.
{"status": "message received", "text": "Hello", "author": "Ahmed"}
The following code defines these two routes.
Check this post to learn more about building APIs with FastAPI.
Before packaging the app with Docker, let’s introduce Traefik.
Traefik is an open-source reverse proxy and load-balancer for HTTP and TCP-based applications that is easy, dynamic, automatic, fast, full-featured, production-proven, provides metrics, and integrates with every major cluster technology...
Traefik’s goal is to intercept incoming HTTP requests from the internet and route them towards the dedicated containers that are run by Docker. It can attach any DNS record to the running services.
Traefik is cloud-native. This means that it integrates easily with cloud technologies such as Docker and Kubernetes. In this tutorial, we’ll link Traefik to Docker.
The cherry on top: Traefik has automatic support for Let’s Encrypt certificates. This means that it automatically handles the creation and the renewal of these files for you to ensure that HTTPS is properly configured.
Let’s Encrypt is a free, automated, and open certificate authority (CA), run for the public’s benefit. It is a service provided by the Internet Security Research Group (ISRG).
Let’s Encrypt is an organization that will issue free SSL certificates for us.
An SSL certificate is what allows a website to have HTTPS.
It’s a file that’s kept on the remote server where your app is deployed. It makes SSL/TLS encryption possible and holds information such as the public key and the website’s identity.
When a client (your browser for example) attempts to connect to a secure website, it first gets a copy of this certificate. This allows the client to check the identity of the remote server and to get the public key in order to start an encrypted session.
Let’s start by configuring Traefik. This can be done using the following TOML file. This file will be located inside services/traefik
Let’s detail what happens in each of these sections:
[entrypoints]
This section specifies the ports that Traefik will listen to. These ports are 80 and 443. 80 is the default HTTP port and 443 is the HTTPS port. We’ll call them web and websecure respectively.
Then, we tell Traefik to redirect HTTP to HTTPS.
[accessLog]
This section tells Traefik to print out the logs to stdoutto know who calls whom.
[providers]
In this section, we configure the so-called providers.
Providers are infrastructure components, whether orchestrators, container engines, cloud providers, or key-value stores. The idea is that Traefik queries the provider APIs in order to find relevant information about routing, and when Traefik detects a change, it dynamically updates the routes.
We want Traefik to act as a proxy in front of Docker containers, so we’ll simply pick Docker as one of the providers.
Setting exposedByDefault to false simply means that Traefik will not act as a proxy in front of all containers. It’ll only act so in front of those who have specific labels that are described in docker-compose. (we’ll cover these labels in the Docker part below)
[certificatesResolvers.letsencrypt.name]
This section configures the certificates resolver. In other words, Traefik will communicate with Let’s Encrypt via the ACME protocol: to do that, you’ll have to set a valid email address and a filename where Traefik will save the information it receives from Let’s Encrypt. When Traefik communicates with Let’s Encrypt, certificates can be successfully generated and renewed.
In this section, we define two containers inside a docker-compose file: a container for our FastAPI web service and another one that launches Traefik.
Note that you can have multiple containers running different services to whom Traefik will route the traffic.
Let’s detail what happens in each container:
— api
We first start by building the image by referencing the path to the following Dockerfile:
Then, we define docker labels that will be read by Traefik
traefik.enable=true ensures that Traefik sees this container and routes traffic to it
The other labels define the DNS record that points to the container (ssl.ahmedbesbes.com, i.e. the domain I set up for this API). They also tell Traefik to use TLS and to resolve the certificates with Let’s Encrypt.
— traefik
We first pull the image from the official registry.
We map the ports 80 and 443 on the container to the ports 80 and 443 on the host.
We define three volumes:
The first volume makes Traefik aware of other containersThe second volume passes the Traefik configuration file to the containerThe third volume keeps the generated certificates on the host so that they are not regenerated every time the container restarts. This is important because Let’s Encrypt has a limit on the number of certificates that you can acquire
The first volume makes Traefik aware of other containers
The second volume passes the Traefik configuration file to the container
The third volume keeps the generated certificates on the host so that they are not regenerated every time the container restarts. This is important because Let’s Encrypt has a limit on the number of certificates that you can acquire
Make sure everything is working locally, connect to the VM, clone the repo and run the following command at the root:
docker-compose up --build -d
To make the deployment smooth with Github Actions, have a look at my previous post.
Here’s a compiled list of the resources I used to learn about HTTPS, Traefik and deploying FastAPI applications with Docker.
Don’t hesitate to let me know about other resources you found useful in this area 😉
howhttps. works
www.valentinog.com
fastapi.tiangolo.com
www.digitalocean.com
traefik.io
www.digitalocean.com
https://www.cloudflare.com/fr-fr/learning/ssl/what-is-https/
Let’s wrap it up. This post was an opportunity to:
learn about HTTPS and what it brings to the table
learn more about Traefik and how to use it as a reverse proxy to create an HTTPS connection
use Docker to deploy and manage FastAPI with Traefik
I hope this was a good starting point to implementing HTTPS into your projects.
Again, the code is available on Github: feel free to use it as is or modify it for projects of yours.
That’s all for me now, see you next time!
|
[
{
"code": null,
"e": 339,
"s": 172,
"text": "When we deploy an API to serve a machine learning model, we rarely care about that green padlock that makes the HTTP connection supposedly safe and the browser happy."
},
{
"code": null,
"e": 451,
"s": 339,
"text": "We usually take HTTPS for granted, and we may think that it just can be turned on with some easy configuration."
},
{
"code": null,
"e": 500,
"s": 451,
"text": "The truth is, adding HTTPS requires a few steps."
},
{
"code": null,
"e": 656,
"s": 500,
"text": "And that’s what this post is for: explaining why HTTPS matter and how you can add it as part of your deployment when you build web apps and APIs in Python."
},
{
"code": null,
"e": 694,
"s": 656,
"text": "Here’s what we’ll cover in this post:"
},
{
"code": null,
"e": 910,
"s": 694,
"text": "A brief introduction to HTTPS: how does it work and why you should care about it?Building an API with FastAPIIntroducing Traefik and how it can handle HTTPSIntegrating FastAPI with Traefik via DockerDeploying on AWS"
},
{
"code": null,
"e": 992,
"s": 910,
"text": "A brief introduction to HTTPS: how does it work and why you should care about it?"
},
{
"code": null,
"e": 1021,
"s": 992,
"text": "Building an API with FastAPI"
},
{
"code": null,
"e": 1069,
"s": 1021,
"text": "Introducing Traefik and how it can handle HTTPS"
},
{
"code": null,
"e": 1113,
"s": 1069,
"text": "Integrating FastAPI with Traefik via Docker"
},
{
"code": null,
"e": 1130,
"s": 1113,
"text": "Deploying on AWS"
},
{
"code": null,
"e": 1253,
"s": 1130,
"text": "This guide will ultimately help you add HTTPS to your projects. You can reuse the following code to build secure projects."
},
{
"code": null,
"e": 1296,
"s": 1253,
"text": "Without further ado, let’s jump right in 🚀"
},
{
"code": null,
"e": 1335,
"s": 1296,
"text": "PS*: this code is available on Github."
},
{
"code": null,
"e": 1455,
"s": 1335,
"text": "PS**: if you want to learn more about FastAPI, Docker and Github Actions, make sure to have a look at my previous post."
},
{
"code": null,
"e": 1478,
"s": 1455,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1549,
"s": 1478,
"text": "A registered domain name. You can buy one on Namecheap for a few bucks"
},
{
"code": null,
"e": 1650,
"s": 1549,
"text": "Docker and docker-compose installed on your local machine: you can follow the official documentation"
},
{
"code": null,
"e": 1820,
"s": 1650,
"text": "A remote server to deploy the API: I’m using a t2-medium instance on AWS EC2. Anything equivalent should be good as well. Make sure this instance has a fixed IP address."
},
{
"code": null,
"e": 2162,
"s": 1820,
"text": "On your domain provider, create an A record that points to the instance’s IP address. I currently own ahmedbesbes.com and for this tutorial, I created the following A record: ssl.ahmedbesbes.com. You can do the same with your domain by picking any subdomain you want.Here’s what it looks like on OVH’s interface (OVH is my domain’s provider)"
},
{
"code": null,
"e": 2317,
"s": 2162,
"text": "HTTPS is HTTP over an encryption protocol. This protocol is called Transport Layer Security (TLS) and it was formerly known as Secure Sockets Layer (SSL)."
},
{
"code": null,
"e": 2404,
"s": 2317,
"text": "In other words, HTTPS is encrypted in order to increase the security of data transfer."
},
{
"code": null,
"e": 2565,
"s": 2404,
"text": "TLS, the protocol behind HTTPS, uses an asymmetric public key infrastructure. This system uses two different keys to encrypt communications between two parties:"
},
{
"code": null,
"e": 2929,
"s": 2565,
"text": "A private key 🔐: this key is controlled by the owner of the website, it’s kept private and lives on the remote web server. It’s used to decrypt the information encrypted by the public keyA public key 🔑: this key is used by anyone who wants to interact with the server in a secure manner. This key’s role is to encrypt data that the private key will later decrypt."
},
{
"code": null,
"e": 3117,
"s": 2929,
"text": "A private key 🔐: this key is controlled by the owner of the website, it’s kept private and lives on the remote web server. It’s used to decrypt the information encrypted by the public key"
},
{
"code": null,
"e": 3294,
"s": 3117,
"text": "A public key 🔑: this key is used by anyone who wants to interact with the server in a secure manner. This key’s role is to encrypt data that the private key will later decrypt."
},
{
"code": null,
"e": 3359,
"s": 3294,
"text": "HTTPS is a very useful protocol. You need it for 3 main reasons:"
},
{
"code": null,
"e": 3682,
"s": 3359,
"text": "Privacy: So that no one can intercept or eavesdrop on your message (a message can be a text you post to your friend, a credit card information you fill in a form, an image, a video, or anything you upload through the network). When sent through HTTPS, this data is encrypted, i.e. turned into a long alphanumerical string."
},
{
"code": null,
"e": 3784,
"s": 3682,
"text": "Integrity: So that the message you send is not manipulated in any form on the way to its destination."
},
{
"code": null,
"e": 3887,
"s": 3784,
"text": "Authentication: So that the remote server you request is sure that you are the one who you claim to be"
},
{
"code": null,
"e": 4040,
"s": 3887,
"text": "Besides adding a security layer to your app, HTTPS is a pledge for good-quality software practices. This is very important to build a trusted user base."
},
{
"code": null,
"e": 4283,
"s": 4040,
"text": "HTTPS is taken very seriously by major internet players. As a matter of fact, Google announced in 2014 that having HTTPS will increase your ranking in the search results. Google has also made Chrome flag any website without HTTPS as insecure."
},
{
"code": null,
"e": 4319,
"s": 4283,
"text": "Time to add HTTPS to your apps now!"
},
{
"code": null,
"e": 4428,
"s": 4319,
"text": "In this section, we’ll get FastAPI up and running on a very simple example. We’ll see next how to secure it."
},
{
"code": null,
"e": 4502,
"s": 4428,
"text": "Before going into the code, here’s what the project structure looks like:"
},
{
"code": null,
"e": 4549,
"s": 4502,
"text": "Let’s start by creating a virtual environment:"
},
{
"code": null,
"e": 4597,
"s": 4549,
"text": "mkdir fastapi-ssl && cd _pipenv install fastapi"
},
{
"code": null,
"e": 4660,
"s": 4597,
"text": "Nothing really fancy, we’ll create an API that has two routes:"
},
{
"code": null,
"e": 4746,
"s": 4660,
"text": "one that handles GET requests and displays the following JSON response on the browser"
},
{
"code": null,
"e": 4781,
"s": 4746,
"text": "{\"message\": \"Hello FastAPI + SSL\"}"
},
{
"code": null,
"e": 5004,
"s": 4781,
"text": "another one that handles POST requests. This route expects a body containing two keys: text and author and sends a JSON object back as a response with the same text and author already sent and an additional status message."
},
{
"code": null,
"e": 5071,
"s": 5004,
"text": "{\"status\": \"message received\", \"text\": \"Hello\", \"author\": \"Ahmed\"}"
},
{
"code": null,
"e": 5116,
"s": 5071,
"text": "The following code defines these two routes."
},
{
"code": null,
"e": 5180,
"s": 5116,
"text": "Check this post to learn more about building APIs with FastAPI."
},
{
"code": null,
"e": 5243,
"s": 5180,
"text": "Before packaging the app with Docker, let’s introduce Traefik."
},
{
"code": null,
"e": 5483,
"s": 5243,
"text": "Traefik is an open-source reverse proxy and load-balancer for HTTP and TCP-based applications that is easy, dynamic, automatic, fast, full-featured, production-proven, provides metrics, and integrates with every major cluster technology..."
},
{
"code": null,
"e": 5681,
"s": 5483,
"text": "Traefik’s goal is to intercept incoming HTTP requests from the internet and route them towards the dedicated containers that are run by Docker. It can attach any DNS record to the running services."
},
{
"code": null,
"e": 5846,
"s": 5681,
"text": "Traefik is cloud-native. This means that it integrates easily with cloud technologies such as Docker and Kubernetes. In this tutorial, we’ll link Traefik to Docker."
},
{
"code": null,
"e": 6065,
"s": 5846,
"text": "The cherry on top: Traefik has automatic support for Let’s Encrypt certificates. This means that it automatically handles the creation and the renewal of these files for you to ensure that HTTPS is properly configured."
},
{
"code": null,
"e": 6241,
"s": 6065,
"text": "Let’s Encrypt is a free, automated, and open certificate authority (CA), run for the public’s benefit. It is a service provided by the Internet Security Research Group (ISRG)."
},
{
"code": null,
"e": 6320,
"s": 6241,
"text": "Let’s Encrypt is an organization that will issue free SSL certificates for us."
},
{
"code": null,
"e": 6379,
"s": 6320,
"text": "An SSL certificate is what allows a website to have HTTPS."
},
{
"code": null,
"e": 6562,
"s": 6379,
"text": "It’s a file that’s kept on the remote server where your app is deployed. It makes SSL/TLS encryption possible and holds information such as the public key and the website’s identity."
},
{
"code": null,
"e": 6818,
"s": 6562,
"text": "When a client (your browser for example) attempts to connect to a secure website, it first gets a copy of this certificate. This allows the client to check the identity of the remote server and to get the public key in order to start an encrypted session."
},
{
"code": null,
"e": 6952,
"s": 6818,
"text": "Let’s start by configuring Traefik. This can be done using the following TOML file. This file will be located inside services/traefik"
},
{
"code": null,
"e": 7005,
"s": 6952,
"text": "Let’s detail what happens in each of these sections:"
},
{
"code": null,
"e": 7019,
"s": 7005,
"text": "[entrypoints]"
},
{
"code": null,
"e": 7212,
"s": 7019,
"text": "This section specifies the ports that Traefik will listen to. These ports are 80 and 443. 80 is the default HTTP port and 443 is the HTTPS port. We’ll call them web and websecure respectively."
},
{
"code": null,
"e": 7261,
"s": 7212,
"text": "Then, we tell Traefik to redirect HTTP to HTTPS."
},
{
"code": null,
"e": 7273,
"s": 7261,
"text": "[accessLog]"
},
{
"code": null,
"e": 7355,
"s": 7273,
"text": "This section tells Traefik to print out the logs to stdoutto know who calls whom."
},
{
"code": null,
"e": 7367,
"s": 7355,
"text": "[providers]"
},
{
"code": null,
"e": 7422,
"s": 7367,
"text": "In this section, we configure the so-called providers."
},
{
"code": null,
"e": 7717,
"s": 7422,
"text": "Providers are infrastructure components, whether orchestrators, container engines, cloud providers, or key-value stores. The idea is that Traefik queries the provider APIs in order to find relevant information about routing, and when Traefik detects a change, it dynamically updates the routes."
},
{
"code": null,
"e": 7835,
"s": 7717,
"text": "We want Traefik to act as a proxy in front of Docker containers, so we’ll simply pick Docker as one of the providers."
},
{
"code": null,
"e": 8098,
"s": 7835,
"text": "Setting exposedByDefault to false simply means that Traefik will not act as a proxy in front of all containers. It’ll only act so in front of those who have specific labels that are described in docker-compose. (we’ll cover these labels in the Docker part below)"
},
{
"code": null,
"e": 8139,
"s": 8098,
"text": "[certificatesResolvers.letsencrypt.name]"
},
{
"code": null,
"e": 8515,
"s": 8139,
"text": "This section configures the certificates resolver. In other words, Traefik will communicate with Let’s Encrypt via the ACME protocol: to do that, you’ll have to set a valid email address and a filename where Traefik will save the information it receives from Let’s Encrypt. When Traefik communicates with Let’s Encrypt, certificates can be successfully generated and renewed."
},
{
"code": null,
"e": 8666,
"s": 8515,
"text": "In this section, we define two containers inside a docker-compose file: a container for our FastAPI web service and another one that launches Traefik."
},
{
"code": null,
"e": 8776,
"s": 8666,
"text": "Note that you can have multiple containers running different services to whom Traefik will route the traffic."
},
{
"code": null,
"e": 8821,
"s": 8776,
"text": "Let’s detail what happens in each container:"
},
{
"code": null,
"e": 8827,
"s": 8821,
"text": "— api"
},
{
"code": null,
"e": 8917,
"s": 8827,
"text": "We first start by building the image by referencing the path to the following Dockerfile:"
},
{
"code": null,
"e": 8976,
"s": 8917,
"text": "Then, we define docker labels that will be read by Traefik"
},
{
"code": null,
"e": 9062,
"s": 8976,
"text": "traefik.enable=true ensures that Traefik sees this container and routes traffic to it"
},
{
"code": null,
"e": 9278,
"s": 9062,
"text": "The other labels define the DNS record that points to the container (ssl.ahmedbesbes.com, i.e. the domain I set up for this API). They also tell Traefik to use TLS and to resolve the certificates with Let’s Encrypt."
},
{
"code": null,
"e": 9288,
"s": 9278,
"text": "— traefik"
},
{
"code": null,
"e": 9340,
"s": 9288,
"text": "We first pull the image from the official registry."
},
{
"code": null,
"e": 9422,
"s": 9340,
"text": "We map the ports 80 and 443 on the container to the ports 80 and 443 on the host."
},
{
"code": null,
"e": 9447,
"s": 9422,
"text": "We define three volumes:"
},
{
"code": null,
"e": 9808,
"s": 9447,
"text": "The first volume makes Traefik aware of other containersThe second volume passes the Traefik configuration file to the containerThe third volume keeps the generated certificates on the host so that they are not regenerated every time the container restarts. This is important because Let’s Encrypt has a limit on the number of certificates that you can acquire"
},
{
"code": null,
"e": 9865,
"s": 9808,
"text": "The first volume makes Traefik aware of other containers"
},
{
"code": null,
"e": 9938,
"s": 9865,
"text": "The second volume passes the Traefik configuration file to the container"
},
{
"code": null,
"e": 10171,
"s": 9938,
"text": "The third volume keeps the generated certificates on the host so that they are not regenerated every time the container restarts. This is important because Let’s Encrypt has a limit on the number of certificates that you can acquire"
},
{
"code": null,
"e": 10289,
"s": 10171,
"text": "Make sure everything is working locally, connect to the VM, clone the repo and run the following command at the root:"
},
{
"code": null,
"e": 10318,
"s": 10289,
"text": "docker-compose up --build -d"
},
{
"code": null,
"e": 10402,
"s": 10318,
"text": "To make the deployment smooth with Github Actions, have a look at my previous post."
},
{
"code": null,
"e": 10527,
"s": 10402,
"text": "Here’s a compiled list of the resources I used to learn about HTTPS, Traefik and deploying FastAPI applications with Docker."
},
{
"code": null,
"e": 10611,
"s": 10527,
"text": "Don’t hesitate to let me know about other resources you found useful in this area 😉"
},
{
"code": null,
"e": 10627,
"s": 10611,
"text": "howhttps. works"
},
{
"code": null,
"e": 10646,
"s": 10627,
"text": "www.valentinog.com"
},
{
"code": null,
"e": 10667,
"s": 10646,
"text": "fastapi.tiangolo.com"
},
{
"code": null,
"e": 10688,
"s": 10667,
"text": "www.digitalocean.com"
},
{
"code": null,
"e": 10699,
"s": 10688,
"text": "traefik.io"
},
{
"code": null,
"e": 10720,
"s": 10699,
"text": "www.digitalocean.com"
},
{
"code": null,
"e": 10781,
"s": 10720,
"text": "https://www.cloudflare.com/fr-fr/learning/ssl/what-is-https/"
},
{
"code": null,
"e": 10832,
"s": 10781,
"text": "Let’s wrap it up. This post was an opportunity to:"
},
{
"code": null,
"e": 10882,
"s": 10832,
"text": "learn about HTTPS and what it brings to the table"
},
{
"code": null,
"e": 10974,
"s": 10882,
"text": "learn more about Traefik and how to use it as a reverse proxy to create an HTTPS connection"
},
{
"code": null,
"e": 11027,
"s": 10974,
"text": "use Docker to deploy and manage FastAPI with Traefik"
},
{
"code": null,
"e": 11107,
"s": 11027,
"text": "I hope this was a good starting point to implementing HTTPS into your projects."
},
{
"code": null,
"e": 11209,
"s": 11107,
"text": "Again, the code is available on Github: feel free to use it as is or modify it for projects of yours."
}
] |
Arithmetic operations with std::bitset in C++ - GeeksforGeeks
|
17 Jun, 2021
A bitset is an array of boolean values, but each boolean value is not stored separately. Instead, bitset optimizes the space such that each bool takes 1-bit space only, so space taken by bitset say, bs is less than that of bool bs[N] and vector<bool> bs(N). However, a limitation of bitset is, N must be known at compile-time, i.e., a constant (this limitation is not there with vector and dynamic array)
Important Note:
Take care of integer overflow say if bitset is declared of size 3 and addition results 9, this is the case of integer overflow because 9 cannot be stored in 3 bits.
Take care for negative results as bitsets are converted to unsigned long integer, so negative numbers cannot be stored.
Addition of 2 bitsets: Follow the steps below to solve the problem:
Initialize a bool carry to false.
Create a bitset ans to store the sum of the two bitsets x and y.
Traverse the length of the bitsets x and y and use the fullAdder function to determine the value of the current bit in ans.
Return ans.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Utility function to add two bool values and calculate// carry and sumbool fullAdder(bool b1, bool b2, bool& carry){ bool sum = (b1 ^ b2) ^ carry; carry = (b1 && b2) || (b1 && carry) || (b2 && carry); return sum;}// Function to add two bitsetsbitset<33> bitsetAdd(bitset<32>& x, bitset<32>& y){ bool carry = false; // bitset to store the sum of the two bitsets bitset<33> ans; for (int i = 0; i < 33; i++) { ans[i] = fullAdder(x[i], y[i], carry); } return ans;}// Driver Codeint main(){ // Given Input bitset<32> a(25); bitset<32> b(15); // Store the result of addition bitset<33> result = bitsetAdd(a, b); cout << result; return 0;}
000000000000000000000000000101000
Time Complexity: O(N), N is length of bitsetAuxiliary Space: O(N)
Subtraction of 2 bitsets: Follow the steps below to solve the problem:
Initialize a bool borrow to false.
Create a bitset ans to store the difference between the two bitsets x and y.
Traverse the length of the bitsets x and y and use the fullSubtractor function to determine the value of the current bit in ans.
Return ans.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Utility function to subtract two bools and calculate diff// and borrowbool fullSubtractor(bool b1, bool b2, bool& borrow){ bool diff; if (borrow) { diff = !(b1 ^ b2); borrow = !b1 || (b1 && b2); } else { diff = b1 ^ b2; borrow = !b1 && b2; } return diff;}// Function to calculate difference between two bitsetsbitset<33> bitsetSubtract(bitset<32> x, bitset<32> y){ bool borrow = false; // bitset to store the sum of the two bitsets bitset<33> ans; for (int i = 0; i < 32; i++) { ans[i] = fullSubtractor(x[i], y[i], borrow); } return ans;}// Driver Codeint main(){ // Given Input bitset<32> a(25); bitset<32> b(15); // Store the result of addition bitset<33> result = bitsetSubtract(a, b); cout << result; return 0;}
000000000000000000000000000001010
Time Complexity: O(N), N is length of bitsetAuxiliary Space: O(N)
CPP-bitset
Bit Magic
C++
Bit Magic
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Check whether K-th bit is set or not
Program to find parity
Write an Efficient Method to Check if a Number is Multiple of 3
Hamming code Implementation in C/C++
Vector in C++ STL
Arrays in C/C++
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 24988,
"s": 24960,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 25393,
"s": 24988,
"text": "A bitset is an array of boolean values, but each boolean value is not stored separately. Instead, bitset optimizes the space such that each bool takes 1-bit space only, so space taken by bitset say, bs is less than that of bool bs[N] and vector<bool> bs(N). However, a limitation of bitset is, N must be known at compile-time, i.e., a constant (this limitation is not there with vector and dynamic array)"
},
{
"code": null,
"e": 25409,
"s": 25393,
"text": "Important Note:"
},
{
"code": null,
"e": 25574,
"s": 25409,
"text": "Take care of integer overflow say if bitset is declared of size 3 and addition results 9, this is the case of integer overflow because 9 cannot be stored in 3 bits."
},
{
"code": null,
"e": 25694,
"s": 25574,
"text": "Take care for negative results as bitsets are converted to unsigned long integer, so negative numbers cannot be stored."
},
{
"code": null,
"e": 25762,
"s": 25694,
"text": "Addition of 2 bitsets: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25796,
"s": 25762,
"text": "Initialize a bool carry to false."
},
{
"code": null,
"e": 25861,
"s": 25796,
"text": "Create a bitset ans to store the sum of the two bitsets x and y."
},
{
"code": null,
"e": 25985,
"s": 25861,
"text": "Traverse the length of the bitsets x and y and use the fullAdder function to determine the value of the current bit in ans."
},
{
"code": null,
"e": 25997,
"s": 25985,
"text": "Return ans."
},
{
"code": null,
"e": 26048,
"s": 25997,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26052,
"s": 26048,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Utility function to add two bool values and calculate// carry and sumbool fullAdder(bool b1, bool b2, bool& carry){ bool sum = (b1 ^ b2) ^ carry; carry = (b1 && b2) || (b1 && carry) || (b2 && carry); return sum;}// Function to add two bitsetsbitset<33> bitsetAdd(bitset<32>& x, bitset<32>& y){ bool carry = false; // bitset to store the sum of the two bitsets bitset<33> ans; for (int i = 0; i < 33; i++) { ans[i] = fullAdder(x[i], y[i], carry); } return ans;}// Driver Codeint main(){ // Given Input bitset<32> a(25); bitset<32> b(15); // Store the result of addition bitset<33> result = bitsetAdd(a, b); cout << result; return 0;}",
"e": 26828,
"s": 26052,
"text": null
},
{
"code": null,
"e": 26862,
"s": 26828,
"text": "000000000000000000000000000101000"
},
{
"code": null,
"e": 26928,
"s": 26862,
"text": "Time Complexity: O(N), N is length of bitsetAuxiliary Space: O(N)"
},
{
"code": null,
"e": 26999,
"s": 26928,
"text": "Subtraction of 2 bitsets: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27034,
"s": 26999,
"text": "Initialize a bool borrow to false."
},
{
"code": null,
"e": 27111,
"s": 27034,
"text": "Create a bitset ans to store the difference between the two bitsets x and y."
},
{
"code": null,
"e": 27240,
"s": 27111,
"text": "Traverse the length of the bitsets x and y and use the fullSubtractor function to determine the value of the current bit in ans."
},
{
"code": null,
"e": 27252,
"s": 27240,
"text": "Return ans."
},
{
"code": null,
"e": 27303,
"s": 27252,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27307,
"s": 27303,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Utility function to subtract two bools and calculate diff// and borrowbool fullSubtractor(bool b1, bool b2, bool& borrow){ bool diff; if (borrow) { diff = !(b1 ^ b2); borrow = !b1 || (b1 && b2); } else { diff = b1 ^ b2; borrow = !b1 && b2; } return diff;}// Function to calculate difference between two bitsetsbitset<33> bitsetSubtract(bitset<32> x, bitset<32> y){ bool borrow = false; // bitset to store the sum of the two bitsets bitset<33> ans; for (int i = 0; i < 32; i++) { ans[i] = fullSubtractor(x[i], y[i], borrow); } return ans;}// Driver Codeint main(){ // Given Input bitset<32> a(25); bitset<32> b(15); // Store the result of addition bitset<33> result = bitsetSubtract(a, b); cout << result; return 0;}",
"e": 28203,
"s": 27307,
"text": null
},
{
"code": null,
"e": 28237,
"s": 28203,
"text": "000000000000000000000000000001010"
},
{
"code": null,
"e": 28303,
"s": 28237,
"text": "Time Complexity: O(N), N is length of bitsetAuxiliary Space: O(N)"
},
{
"code": null,
"e": 28314,
"s": 28303,
"text": "CPP-bitset"
},
{
"code": null,
"e": 28324,
"s": 28314,
"text": "Bit Magic"
},
{
"code": null,
"e": 28328,
"s": 28324,
"text": "C++"
},
{
"code": null,
"e": 28338,
"s": 28328,
"text": "Bit Magic"
},
{
"code": null,
"e": 28342,
"s": 28338,
"text": "CPP"
},
{
"code": null,
"e": 28440,
"s": 28342,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28491,
"s": 28440,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 28528,
"s": 28491,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 28551,
"s": 28528,
"text": "Program to find parity"
},
{
"code": null,
"e": 28615,
"s": 28551,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 28652,
"s": 28615,
"text": "Hamming code Implementation in C/C++"
},
{
"code": null,
"e": 28670,
"s": 28652,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 28686,
"s": 28670,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 28732,
"s": 28686,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 28751,
"s": 28732,
"text": "Inheritance in C++"
}
] |
PyQt5 - QLineEdit Widget
|
QLineEdit object is the most commonly used input field. It provides a box in which one line of text can be entered. In order to enter multi-line text, QTextEdit object is required.
The following table lists a few important methods of QLineEdit class −
setAlignment()
Aligns the text as per alignment constants
Qt.AlignLeft
Qt.AlignRight
Qt.AlignCenter
Qt.AlignJustify
clear()
Erases the contents
setEchoMode()
Controls the appearance of the text inside the box. Echomode values are −
QLineEdit.Normal
QLineEdit.NoEcho
QLineEdit.Password
QLineEdit.PasswordEchoOnEdit
setMaxLength()
Sets the maximum number of characters for input
setReadOnly()
Makes the text box non-editable
setText()
Programmatically sets the text
text()
Retrieves text in the field
setValidator()
Sets the validation rules. Available validators are
QIntValidator − Restricts input to integer
QDoubleValidator − Fraction part of number limited to specified decimals
QRegexpValidator − Checks input against a Regex expression
setInputMask()
Applies mask of combination of characters for input
setFont()
Displays the contents QFont object
QLineEdit object emits the following signals −
Given below are the most commonly used methods of signals.
cursorPositionChanged()
Whenever the cursor moves
editingFinished()
When you press ‘Enter’ or the field loses focus
returnPressed()
When you press ‘Enter’
selectionChanged()
Whenever the selected text changes
textChanged()
As text in the box changes either by input or by programmatic means
textEdited()
Whenever the text is edited
QLineEdit objects in this example demonstrate use of some of these methods.
First field e1 shows text using a custom font, in right alignment and allows integer input. Second field restricts input to a number with 2 digits after decimal point. An input mask for entering the phone number is applied on the third field. textChanged() signal on the field e4 is connected to textchanged() slot method.
Contents of e5 field are echoed in password form as its EchoMode property is set to Password. Its editingfinished() signal is connected to presenter() method. So, once the user presses the Enter key, the function will be executed. The field e6 shows a default text, which cannot be edited as it is set to read only.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def window():
app = QApplication(sys.argv)
win = QWidget()
e1 = QLineEdit()
e1.setValidator(QIntValidator())
e1.setMaxLength(4)
e1.setAlignment(Qt.AlignRight)
e1.setFont(QFont("Arial",20))
e2 = QLineEdit()
e2.setValidator(QDoubleValidator(0.99,99.99,2))
flo = QFormLayout()
flo.addRow("integer validator", e1)
flo.addRow("Double validator",e2)
e3 = QLineEdit()
e3.setInputMask('+99_9999_999999')
flo.addRow("Input Mask",e3)
e4 = QLineEdit()
e4.textChanged.connect(textchanged)
flo.addRow("Text changed",e4)
e5 = QLineEdit()
e5.setEchoMode(QLineEdit.Password)
flo.addRow("Password",e5)
e6 = QLineEdit("Hello Python")
e6.setReadOnly(True)
flo.addRow("Read Only",e6)
e5.editingFinished.connect(enterPress)
win.setLayout(flo)
win.setWindowTitle("PyQt")
win.show()
sys.exit(app.exec_())
def textchanged(text):
print "contents of text box: "+text
def enterPress():
print "edited"
if __name__ == '__main__':
window()
The above code produces the following output −
contents of text box: h
contents of text box: he
contents of text box: hel
contents of text box: hell
contents of text box: hello
editing finished
146 Lectures
22.5 hours
ALAA EID
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2144,
"s": 1963,
"text": "QLineEdit object is the most commonly used input field. It provides a box in which one line of text can be entered. In order to enter multi-line text, QTextEdit object is required."
},
{
"code": null,
"e": 2215,
"s": 2144,
"text": "The following table lists a few important methods of QLineEdit class −"
},
{
"code": null,
"e": 2230,
"s": 2215,
"text": "setAlignment()"
},
{
"code": null,
"e": 2273,
"s": 2230,
"text": "Aligns the text as per alignment constants"
},
{
"code": null,
"e": 2286,
"s": 2273,
"text": "Qt.AlignLeft"
},
{
"code": null,
"e": 2300,
"s": 2286,
"text": "Qt.AlignRight"
},
{
"code": null,
"e": 2315,
"s": 2300,
"text": "Qt.AlignCenter"
},
{
"code": null,
"e": 2331,
"s": 2315,
"text": "Qt.AlignJustify"
},
{
"code": null,
"e": 2339,
"s": 2331,
"text": "clear()"
},
{
"code": null,
"e": 2359,
"s": 2339,
"text": "Erases the contents"
},
{
"code": null,
"e": 2373,
"s": 2359,
"text": "setEchoMode()"
},
{
"code": null,
"e": 2447,
"s": 2373,
"text": "Controls the appearance of the text inside the box. Echomode values are −"
},
{
"code": null,
"e": 2464,
"s": 2447,
"text": "QLineEdit.Normal"
},
{
"code": null,
"e": 2481,
"s": 2464,
"text": "QLineEdit.NoEcho"
},
{
"code": null,
"e": 2500,
"s": 2481,
"text": "QLineEdit.Password"
},
{
"code": null,
"e": 2529,
"s": 2500,
"text": "QLineEdit.PasswordEchoOnEdit"
},
{
"code": null,
"e": 2544,
"s": 2529,
"text": "setMaxLength()"
},
{
"code": null,
"e": 2592,
"s": 2544,
"text": "Sets the maximum number of characters for input"
},
{
"code": null,
"e": 2606,
"s": 2592,
"text": "setReadOnly()"
},
{
"code": null,
"e": 2638,
"s": 2606,
"text": "Makes the text box non-editable"
},
{
"code": null,
"e": 2648,
"s": 2638,
"text": "setText()"
},
{
"code": null,
"e": 2679,
"s": 2648,
"text": "Programmatically sets the text"
},
{
"code": null,
"e": 2686,
"s": 2679,
"text": "text()"
},
{
"code": null,
"e": 2714,
"s": 2686,
"text": "Retrieves text in the field"
},
{
"code": null,
"e": 2729,
"s": 2714,
"text": "setValidator()"
},
{
"code": null,
"e": 2781,
"s": 2729,
"text": "Sets the validation rules. Available validators are"
},
{
"code": null,
"e": 2824,
"s": 2781,
"text": "QIntValidator − Restricts input to integer"
},
{
"code": null,
"e": 2897,
"s": 2824,
"text": "QDoubleValidator − Fraction part of number limited to specified decimals"
},
{
"code": null,
"e": 2956,
"s": 2897,
"text": "QRegexpValidator − Checks input against a Regex expression"
},
{
"code": null,
"e": 2971,
"s": 2956,
"text": "setInputMask()"
},
{
"code": null,
"e": 3023,
"s": 2971,
"text": "Applies mask of combination of characters for input"
},
{
"code": null,
"e": 3033,
"s": 3023,
"text": "setFont()"
},
{
"code": null,
"e": 3068,
"s": 3033,
"text": "Displays the contents QFont object"
},
{
"code": null,
"e": 3115,
"s": 3068,
"text": "QLineEdit object emits the following signals −"
},
{
"code": null,
"e": 3174,
"s": 3115,
"text": "Given below are the most commonly used methods of signals."
},
{
"code": null,
"e": 3198,
"s": 3174,
"text": "cursorPositionChanged()"
},
{
"code": null,
"e": 3224,
"s": 3198,
"text": "Whenever the cursor moves"
},
{
"code": null,
"e": 3242,
"s": 3224,
"text": "editingFinished()"
},
{
"code": null,
"e": 3290,
"s": 3242,
"text": "When you press ‘Enter’ or the field loses focus"
},
{
"code": null,
"e": 3306,
"s": 3290,
"text": "returnPressed()"
},
{
"code": null,
"e": 3329,
"s": 3306,
"text": "When you press ‘Enter’"
},
{
"code": null,
"e": 3348,
"s": 3329,
"text": "selectionChanged()"
},
{
"code": null,
"e": 3383,
"s": 3348,
"text": "Whenever the selected text changes"
},
{
"code": null,
"e": 3397,
"s": 3383,
"text": "textChanged()"
},
{
"code": null,
"e": 3465,
"s": 3397,
"text": "As text in the box changes either by input or by programmatic means"
},
{
"code": null,
"e": 3478,
"s": 3465,
"text": "textEdited()"
},
{
"code": null,
"e": 3506,
"s": 3478,
"text": "Whenever the text is edited"
},
{
"code": null,
"e": 3582,
"s": 3506,
"text": "QLineEdit objects in this example demonstrate use of some of these methods."
},
{
"code": null,
"e": 3905,
"s": 3582,
"text": "First field e1 shows text using a custom font, in right alignment and allows integer input. Second field restricts input to a number with 2 digits after decimal point. An input mask for entering the phone number is applied on the third field. textChanged() signal on the field e4 is connected to textchanged() slot method."
},
{
"code": null,
"e": 4221,
"s": 3905,
"text": "Contents of e5 field are echoed in password form as its EchoMode property is set to Password. Its editingfinished() signal is connected to presenter() method. So, once the user presses the Enter key, the function will be executed. The field e6 shows a default text, which cannot be edited as it is set to read only."
},
{
"code": null,
"e": 5343,
"s": 4221,
"text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\ndef window():\n app = QApplication(sys.argv)\n win = QWidget()\n\t\n e1 = QLineEdit()\n e1.setValidator(QIntValidator())\n e1.setMaxLength(4)\n e1.setAlignment(Qt.AlignRight)\n e1.setFont(QFont(\"Arial\",20))\n\t\n e2 = QLineEdit()\n e2.setValidator(QDoubleValidator(0.99,99.99,2))\n\t\n flo = QFormLayout()\n flo.addRow(\"integer validator\", e1)\n flo.addRow(\"Double validator\",e2)\n\t\n e3 = QLineEdit()\n e3.setInputMask('+99_9999_999999')\n flo.addRow(\"Input Mask\",e3)\n\t\n e4 = QLineEdit()\n e4.textChanged.connect(textchanged)\n flo.addRow(\"Text changed\",e4)\n\t\n e5 = QLineEdit()\n e5.setEchoMode(QLineEdit.Password)\n flo.addRow(\"Password\",e5)\n\t\n e6 = QLineEdit(\"Hello Python\")\n e6.setReadOnly(True)\n flo.addRow(\"Read Only\",e6)\n\t\n e5.editingFinished.connect(enterPress)\n win.setLayout(flo)\n win.setWindowTitle(\"PyQt\")\n win.show()\n\t\n sys.exit(app.exec_())\n\ndef textchanged(text):\n print \"contents of text box: \"+text\n\t\ndef enterPress():\n print \"edited\"\n\nif __name__ == '__main__':\n window()"
},
{
"code": null,
"e": 5390,
"s": 5343,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 5538,
"s": 5390,
"text": "contents of text box: h\ncontents of text box: he\ncontents of text box: hel\ncontents of text box: hell\ncontents of text box: hello\nediting finished\n"
},
{
"code": null,
"e": 5575,
"s": 5538,
"text": "\n 146 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 5585,
"s": 5575,
"text": " ALAA EID"
},
{
"code": null,
"e": 5592,
"s": 5585,
"text": " Print"
},
{
"code": null,
"e": 5603,
"s": 5592,
"text": " Add Notes"
}
] |
How to convert String to Number in JavaScript?
|
You can try to run the following to learn how to convert String to Number in JavaScript −
Live Demo
<!DOCTYPE html>
<html>
<body>
<p>Convert String to Number</p>
<script>
var myString = "Amit";
document.write("Number : " + Number(myString));
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1152,
"s": 1062,
"text": "You can try to run the following to learn how to convert String to Number in JavaScript −"
},
{
"code": null,
"e": 1162,
"s": 1152,
"text": "Live Demo"
},
{
"code": null,
"e": 1372,
"s": 1162,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <p>Convert String to Number</p>\n <script>\n var myString = \"Amit\";\n document.write(\"Number : \" + Number(myString));\n </script>\n </body>\n</html>"
}
] |
Caret Bootstrap class
|
Use carets to indicate dropdown functionality and direction. To get this functionality use the class caret with a <span> element.
You can try to run the following code to implement caret Bootstrap class
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<p>Caret Example<span class = "caret"></span></p>
</body>
</html>
|
[
{
"code": null,
"e": 1192,
"s": 1062,
"text": "Use carets to indicate dropdown functionality and direction. To get this functionality use the class caret with a <span> element."
},
{
"code": null,
"e": 1265,
"s": 1192,
"text": "You can try to run the following code to implement caret Bootstrap class"
},
{
"code": null,
"e": 1275,
"s": 1265,
"text": "Live Demo"
},
{
"code": null,
"e": 1635,
"s": 1275,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <p>Caret Example<span class = \"caret\"></span></p>\n </body>\n</html>"
}
] |
In CSS using Images as List Markers
|
The CSS list-style-image property is used to set an image as a marker for the list item.
The syntax of CSS list-style-image property is as follows −
Selector {
list-style-image: /*value*/
}
The following examples illustrate CSS list-style-image property −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
ul {
width: 150px;
list-style-image: url("https://www.tutorialspoint.com/images/Servlets.png");
background: goldenrod;
}
li {
text-align: center;
background: lavenderblush;
margin: 5px 30px;
}
</style>
</head>
<body>
<h2>Servlets</h2>
<ul>
<li>Client Request</li>
<li>Server Response</li>
<li>Cookies Handling</li>
<li>Session Tracking</li>
</ul>
</body>
</html>
This gives the following output −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
ul {
margin-left: 20px;
list-style-image: url("https://www.tutorialspoint.com/images/hibernate.png");
}
li {
font-size: 1.3em;
text-align: center;
background: burlywood;
margin: 3px;
}
</style>
</head>
<body>
<h2>Hibernate Tutorial</h2>
<ul>
<li>Sessions</li>
<li>Persistent Class</li>
<li>Mapping Files</li>
<li>Mapping Types</li>
<li>Annotations</li>
</ul>
</body>
</html>
This gives the following output −
|
[
{
"code": null,
"e": 1151,
"s": 1062,
"text": "The CSS list-style-image property is used to set an image as a marker for the list item."
},
{
"code": null,
"e": 1211,
"s": 1151,
"text": "The syntax of CSS list-style-image property is as follows −"
},
{
"code": null,
"e": 1255,
"s": 1211,
"text": "Selector {\n list-style-image: /*value*/\n}"
},
{
"code": null,
"e": 1321,
"s": 1255,
"text": "The following examples illustrate CSS list-style-image property −"
},
{
"code": null,
"e": 1332,
"s": 1321,
"text": " Live Demo"
},
{
"code": null,
"e": 1751,
"s": 1332,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nul {\n width: 150px;\n list-style-image: url(\"https://www.tutorialspoint.com/images/Servlets.png\");\n background: goldenrod;\n}\nli {\n text-align: center;\n background: lavenderblush;\n margin: 5px 30px;\n}\n</style>\n</head>\n<body>\n<h2>Servlets</h2>\n<ul>\n<li>Client Request</li>\n<li>Server Response</li>\n<li>Cookies Handling</li>\n<li>Session Tracking</li>\n</ul>\n</body>\n</html>"
},
{
"code": null,
"e": 1785,
"s": 1751,
"text": "This gives the following output −"
},
{
"code": null,
"e": 1796,
"s": 1785,
"text": " Live Demo"
},
{
"code": null,
"e": 2227,
"s": 1796,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nul {\n margin-left: 20px;\n list-style-image: url(\"https://www.tutorialspoint.com/images/hibernate.png\");\n}\nli {\n font-size: 1.3em;\n text-align: center;\n background: burlywood;\n margin: 3px;\n}\n</style>\n</head>\n<body>\n<h2>Hibernate Tutorial</h2>\n<ul>\n<li>Sessions</li>\n<li>Persistent Class</li>\n<li>Mapping Files</li>\n<li>Mapping Types</li>\n<li>Annotations</li>\n</ul>\n</body>\n</html>"
},
{
"code": null,
"e": 2261,
"s": 2227,
"text": "This gives the following output −"
}
] |
Infinity or exception in Java when divide by 0?
|
Consider the following code snippet where we divide a number by 0.
Live Demo
public class Tester{
public static void main(String[] args) {
double d = 100;
System.out.println(d/0);
}
}
Infinity
Now consider the following code snippet.
Live Demo
public class Tester{
public static void main(String[] args) {
int d = 100;
System.out.println(d/0);
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Tester.main(Tester.java:5)
As you've noted, the Infinity vs ArithmeticException, a different result for similar divide by zero program. The difference lies in floating point arithmetic used in first program and integer arithmetic used in second program.
|
[
{
"code": null,
"e": 1129,
"s": 1062,
"text": "Consider the following code snippet where we divide a number by 0."
},
{
"code": null,
"e": 1140,
"s": 1129,
"text": " Live Demo"
},
{
"code": null,
"e": 1265,
"s": 1140,
"text": "public class Tester{\n public static void main(String[] args) {\n double d = 100;\n System.out.println(d/0);\n }\n}"
},
{
"code": null,
"e": 1274,
"s": 1265,
"text": "Infinity"
},
{
"code": null,
"e": 1315,
"s": 1274,
"text": "Now consider the following code snippet."
},
{
"code": null,
"e": 1326,
"s": 1315,
"text": " Live Demo"
},
{
"code": null,
"e": 1448,
"s": 1326,
"text": "public class Tester{\n public static void main(String[] args) {\n int d = 100;\n System.out.println(d/0);\n }\n}"
},
{
"code": null,
"e": 1546,
"s": 1448,
"text": "Exception in thread \"main\" java.lang.ArithmeticException: / by zero\nat Tester.main(Tester.java:5)"
},
{
"code": null,
"e": 1773,
"s": 1546,
"text": "As you've noted, the Infinity vs ArithmeticException, a different result for similar divide by zero program. The difference lies in floating point arithmetic used in first program and integer arithmetic used in second program."
}
] |
Batch Script - How to Modifying an Array - GeeksforGeeks
|
04 Jan, 2022
In this article, we are going to learn how we can modify any array using Batch Script.
We can modify any array in two ways. We can add elements in any array or we can replace elements of any array.
Modify an array by adding an element.
Code :
@echo off
set arr[0]=Geeks
set arr[1]=for
set arr[2]=Geeks
::adding an element at the end of array.
set arr[3]=GFG
echo The last element of the array is %arr[3]%
pause
Explanation:
We are creating an array with name ‘array’.
By using ‘set’ we are creating an array, by specifying the index of every element.
set arr[0]=Geeks
set arr[1]=for
set arr[2]=Geeks
Now we will add an element at the end of ‘array’ by using last index of array.
In above code our last index will be ‘3’. So we will use below expression.
set arr[3]=GFG
Above command will add ‘GFG’ at the end of array ‘arr’.
At last we are printing last element of array by using ‘%arr[3]%’ , which will print ‘GFG’ as output as it is last element of our array now.
Output:
Output of above code
Modify an array by replacing its Element :
Code :
@echo off
set arr[0]=Geeks
set arr[1]=and
set arr[2]=Geeks
::replacing an element in any array.
set arr[1]=for
echo The new element at 1 index is %arr[1]%
pause
Explanation:
Now we are creating an array ‘arr’.
We want to replace ‘and’ by ‘for’ . So now we will use below expression to replace ‘and’ with ‘for’.
set arr[1]=for
We are using index of ‘and’ in given array for replacing it by ‘for’.
Then we are printing element at index 1, just to check whether its replaced or not.
At last ‘pause’ is used to hold the screen, so that we can see our output.
Output :
Replacing element of any array
Batch-script
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples
|
[
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 24493,
"s": 24406,
"text": "In this article, we are going to learn how we can modify any array using Batch Script."
},
{
"code": null,
"e": 24604,
"s": 24493,
"text": "We can modify any array in two ways. We can add elements in any array or we can replace elements of any array."
},
{
"code": null,
"e": 24642,
"s": 24604,
"text": "Modify an array by adding an element."
},
{
"code": null,
"e": 24649,
"s": 24642,
"text": "Code :"
},
{
"code": null,
"e": 24818,
"s": 24649,
"text": "@echo off \nset arr[0]=Geeks\nset arr[1]=for\nset arr[2]=Geeks\n::adding an element at the end of array.\nset arr[3]=GFG\necho The last element of the array is %arr[3]%\npause"
},
{
"code": null,
"e": 24831,
"s": 24818,
"text": "Explanation:"
},
{
"code": null,
"e": 24875,
"s": 24831,
"text": "We are creating an array with name ‘array’."
},
{
"code": null,
"e": 24958,
"s": 24875,
"text": "By using ‘set’ we are creating an array, by specifying the index of every element."
},
{
"code": null,
"e": 25007,
"s": 24958,
"text": "set arr[0]=Geeks\nset arr[1]=for\nset arr[2]=Geeks"
},
{
"code": null,
"e": 25086,
"s": 25007,
"text": "Now we will add an element at the end of ‘array’ by using last index of array."
},
{
"code": null,
"e": 25161,
"s": 25086,
"text": "In above code our last index will be ‘3’. So we will use below expression."
},
{
"code": null,
"e": 25176,
"s": 25161,
"text": "set arr[3]=GFG"
},
{
"code": null,
"e": 25232,
"s": 25176,
"text": "Above command will add ‘GFG’ at the end of array ‘arr’."
},
{
"code": null,
"e": 25373,
"s": 25232,
"text": "At last we are printing last element of array by using ‘%arr[3]%’ , which will print ‘GFG’ as output as it is last element of our array now."
},
{
"code": null,
"e": 25381,
"s": 25373,
"text": "Output:"
},
{
"code": null,
"e": 25402,
"s": 25381,
"text": "Output of above code"
},
{
"code": null,
"e": 25445,
"s": 25402,
"text": "Modify an array by replacing its Element :"
},
{
"code": null,
"e": 25452,
"s": 25445,
"text": "Code :"
},
{
"code": null,
"e": 25614,
"s": 25452,
"text": "@echo off \nset arr[0]=Geeks\nset arr[1]=and\nset arr[2]=Geeks\n::replacing an element in any array.\nset arr[1]=for\necho The new element at 1 index is %arr[1]%\npause"
},
{
"code": null,
"e": 25627,
"s": 25614,
"text": "Explanation:"
},
{
"code": null,
"e": 25663,
"s": 25627,
"text": "Now we are creating an array ‘arr’."
},
{
"code": null,
"e": 25764,
"s": 25663,
"text": "We want to replace ‘and’ by ‘for’ . So now we will use below expression to replace ‘and’ with ‘for’."
},
{
"code": null,
"e": 25779,
"s": 25764,
"text": "set arr[1]=for"
},
{
"code": null,
"e": 25850,
"s": 25779,
"text": "We are using index of ‘and’ in given array for replacing it by ‘for’."
},
{
"code": null,
"e": 25934,
"s": 25850,
"text": "Then we are printing element at index 1, just to check whether its replaced or not."
},
{
"code": null,
"e": 26009,
"s": 25934,
"text": "At last ‘pause’ is used to hold the screen, so that we can see our output."
},
{
"code": null,
"e": 26018,
"s": 26009,
"text": "Output :"
},
{
"code": null,
"e": 26049,
"s": 26018,
"text": "Replacing element of any array"
},
{
"code": null,
"e": 26062,
"s": 26049,
"text": "Batch-script"
},
{
"code": null,
"e": 26069,
"s": 26062,
"text": "Picked"
},
{
"code": null,
"e": 26080,
"s": 26069,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26178,
"s": 26080,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26215,
"s": 26178,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26250,
"s": 26215,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 26276,
"s": 26250,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26310,
"s": 26276,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26347,
"s": 26310,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26376,
"s": 26347,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26402,
"s": 26376,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 26442,
"s": 26402,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 26477,
"s": 26442,
"text": "Basic Operators in Shell Scripting"
}
] |
Lambda expression in Python to rearrange positive and negative numbers
|
In this article, we will learn about using lambda expressions that will take an input array of positive and negative integers. We compute two separate arrays one containing negative numbers and other containing positive numbers.
Here we define a Rearrange() function that accepts only one argument i.e. array of integers. The function returns both arrays merged together with each type on different sides of the array.
Now let’s see the code to understand it better.
def Rearrange(arr):
# First lambda expression returns a list of negative numbers in arr.
# Second lambda expression returns a list of positive numbers in arr.
arr_neg=[x for x in arr if x < 0]
arr_pos=[x for x in arr if x >= 0]
return arr_neg+ arr_pos
# Driver function
if __name__ == "__main__":
arr = [19,-56,3,-1,-45,-23,45,89,90]
print (Rearrange(arr))
[-56, -1, -45, -23, 19, 3, 45, 89, 90]
In this article, we learned how to implement lambda expressions to rearrange positive and negative integers in the input array.
|
[
{
"code": null,
"e": 1291,
"s": 1062,
"text": "In this article, we will learn about using lambda expressions that will take an input array of positive and negative integers. We compute two separate arrays one containing negative numbers and other containing positive numbers."
},
{
"code": null,
"e": 1481,
"s": 1291,
"text": "Here we define a Rearrange() function that accepts only one argument i.e. array of integers. The function returns both arrays merged together with each type on different sides of the array."
},
{
"code": null,
"e": 1529,
"s": 1481,
"text": "Now let’s see the code to understand it better."
},
{
"code": null,
"e": 1893,
"s": 1529,
"text": "def Rearrange(arr):\n# First lambda expression returns a list of negative numbers in arr.\n# Second lambda expression returns a list of positive numbers in arr.\narr_neg=[x for x in arr if x < 0]\narr_pos=[x for x in arr if x >= 0]\nreturn arr_neg+ arr_pos\n\n# Driver function\nif __name__ == \"__main__\":\n arr = [19,-56,3,-1,-45,-23,45,89,90]\n print (Rearrange(arr))"
},
{
"code": null,
"e": 1932,
"s": 1893,
"text": "[-56, -1, -45, -23, 19, 3, 45, 89, 90]"
},
{
"code": null,
"e": 2060,
"s": 1932,
"text": "In this article, we learned how to implement lambda expressions to rearrange positive and negative integers in the input array."
}
] |
The Basics of Regular Expressions | by SAURABH RANA | Towards Data Science
|
What are Regular Expressions?
Regular Expression is a special text string command which is used to match specific string sequences from huge chunks of data which if done manually by a person can take a lot of time. You can use regular expressions to match various patterns of string like:-
To extract all the email addresses
To extract only Gmail email addresses
To extract all the names starting with a specific alphabet and ending with a specific alphabet
To extract all the names where the first alphabet is capital
To extract all the numbers which have decimals points
To extract numbers in a specific range
And the list is endless, the above-mentioned cases are the first six scenarios that crossed my mind while writing this article but honestly you can use regular expressions to extract any kind of string pattern from data no matter how big it is within seconds and that is the beauty of regular expressions. These days the importance of regular expression has increased because many companies are using natural language processing techniques where regular expressions are used very frequently.
The best thing about regular expression is that it is supported by most of the popular programming languages therefore once you understand the syntax and concept of regular expressions, you can use it with various languages.
So let’s get started with regular expressions, I am using regular expressions with python but you guys can use any language of your choice but it should support regular expressions.
First is to match only the first time occurrence of a particular string pattern, second is to match all the occurrences of a particular string pattern.
Now whether you want to match only first occurrence or all the occurrence depends on your requirement. In my experience wherever I have used Regular Expressions most of the problems require all the occurrences to be matched therefore in all the examples in this blog I have intentionally written Regular expressions to match with all the occurrences.
Let’s get started with the most basic regex expression that is literal characters where you are basically searching a particular alphabet or a word from the data, it is similar to what you get when you search something on a web page or pdf using Ctrl+F. Let’s try one example:-
Since I am a big marvel fan so I will be using marvel as a reference in my example
Input = “Avatar did a business of 2.788 billion dollars($) where as Endgame has grossed 2.79 billions dollars($) till date”Regular Expression => “a”It will match with every single alphabet — “a”“Avatar did a business of 2.788 billion dollars($) where as Endgame has grossed 2.79 billions dollars($) till date”Output => a a a a a a a a a a
In output “a” is repeated 10 times because there are exactly ten occurrences of the alphabet “a”Now let’s try a combination of alphabets for our next example:-
Regular Expression => “as”Avatar did a business of 2.788 billion dollars($) where as Endgame has grossed 2.79 billion dollars($) till dateOutput => as as
Note: The sequence of alphabets is very important, in the above example only those stings will be matched where alphabet “a” is followed by the alphabet “s”.
“\w” stands for word character which basically is shorthand for [a-zA-Z0–9_] which means it matches with all capital alphabet, small alphabets and all the digits. Let’s try this regular expression in our marvel text to analyse which characters doesn’t match with “\w”:-
Text=”Avatar did a business of 2.788 billion dollars($) where as Endgame has grossed 2.79 billions dollars($) till date”Regular Expression => “\w”Output => “A v a t a r d i d a b u s i n e s s o f 2 7 8 8 b i l l i o n d o l l a r s w h e r e a s E n d g a m e h a s g r o s s e d 2 7 9 b i l l i o n s d o l l a r s t i l l d a t e”
As you can see the expression “\w” has matched with all the characters in the sentence except for [“$”,”(“,”)”,”.”]
Even though ”\w” is matching with all the characters in [a-zA-Z0–9_] but it matches with them one at a time because of which the output will display one alphabet after another, therefore I have used for loop in python to display them all together because of which there is space between every character that is matched.
Now let’s move onto the second example where we are searching for two consecutive characters
Regular Expression => “\w\w”Text=”Avatar did a business of 2.788 billion dollars($) where as Endgame has grossed 2.79 billions dollars($) till date”Note:It will match with two consecutive alphabet one at a timeOutput =>Av at ar di bu si ne ss of 78 bi ll io do ll
I have not copied the whole output but a part of it just to give you an idea
Note: Words which have an even number of characters are printed fully in groups of two but words where there are odd number of characters the last alphabet is missing in the output(Hint: When you divide an odd number by 2 the output is 1) because the last alphabet could not create a pair with another alphabet.
Similarly, we can search for three consecutive characters one at a time
Regular Expression => “\w\w\w”Text=”Avatar did a business of 2.788 billion dollar where as Endgame has grossed 2.79 billions dollars till date”Output => Ava tar did bus ine 788 bil lio dol lar
Instead of repeating “\w”, we can directly mention the number of consecutive alphabets we are searching for using curly({}) brackets about which we will discuss later
This shorthand character where “W” is capital will match every character except these [a-zA-Z0–9_]. So only those characters which were not matching in our previous example where we were using shorthand character class “\w” (w is small) will match in this case.
Text=”Avatar did a business of 2.788 billion dollar where as Endgame has grossed 2.79 billions dollars till date”Regular Expression => “\W”Output =>. ( $ ) . ( $ )
This shorthand character matches all numbers ([0–9]) in a source string.
Regular Expression => “\d”It will match with every single alphabet one at a time,unlike “\w” which matches with alphabets as well as digits,”\d” matches only with digitsText=”Avatar did a business of 2.788 billion dollars($) where as Endgame has grossed 2.79 billions dollars($) till date”Output =>2 7 8 8 2 7 9
Now let’s search for two consecutive numbers in source string.
Regular Expression =>” \d\d”It will match with two consecutive digits one at a timeAvatar did a business of 2.788 billion dollars($) \n where as Endgame has grossed 2.79 billions dollars($) till dateOutput =>78 79
Similar to “\W” (W is capital) this regular expression is also the complete opposite of its counterpart “\d” i.e. it will match only those characters which shorthand character “d” doesn’t matches.
. -> Matches any single character except a line break[ ] -> Matches any character contained between the square brackets[^ ] -> Matches any character that is not contained between the square brackets* -> Matches 0 or more repetitions of the preceding symbol+ -> Matches 1 or more repetitions of the preceding symbol? -> Makes the preceding symbol optional.{n,m} -> Matches at least "n" but not more than "m" repetitions of the preceding symbol| -> Matches either the characters before or the characters after the symbol\ -> Escapes the next character. This allows you to match reserved characters { } . * + ? ^ $ \ |^ -> Matches the beginning of the input$ -> Matches the end of the input
Following meta characters +, * or ? are used to specify how many times a subpattern can occur. These meta characters act differently in different situations.
Meta character “+” is used to match with one or more than one occurrences of the preceding symbol.
For example:-
“\w+” Matches with strings which have one or more than one [a-zA-Z0–9_] character
“\d+” Matches with numbers which have one or more than one digits
a+ Matches with one or more than one occurrences of the alphabet “a”.We can use any alphabet in place of “a”.
Now let’s try out these examples on raw text
Regular Expression=”\w+”Text = “Avatar did a business of 2.788 billion dollars($) where as Endgame has grossed 2.79 billions dollars($) till date”Output =>Avatar did a business of 2 788 billion dollars where as Endgame has grossed 2 79 billions dollars till date
Now let’s try the “+” operator with “\d”
Regular Expression =”\d+”Text=”Avatar did a business of 2.788 billion dollar where as Endgame has grossed 2.79 billions dollars till date”Output => 2 788 2 79
Note: In the output “2” and “788” are not matched together because these two numbers are separated by “.”
Now, what if want the number“2.788” to be matched, in that case, we can use the following regular expression:-
Regular Expression => "\d+.\d+"Text=”Avatar did a business of 2.788 billion dollar where as Endgame has grossed 2.79 billions dollars till date”Output=> 2.788 2.79Regular Expression Breakdown=>Match one or more digit(\d+) + Match a full stop(.) + Match one or more digit(\d+)
Note: In complex regular expressions like the one mentioned above where we search for strings with multiple conditions, the conditions should match consecutively in the same order as mentioned in regular Expression, for instance in the example mentioned above we are searching for numbers which have one or more than one digits, followed by a full stop, followed by one or more than one digits. If these three conditions are not matched consecutively then there won’t be any match.
Exercise:Question 1) Find all gmail email id’s from given below data.Text =“abc@yahoo.com saurabh@outlook.com abc@gmail.com saurabh88@gmail.com saurabh11@outlook.com xyz@gmail.com”Solution:Regular Expression=”\w+@gmail.com”Output =>”abc@gmail.com saurabh88@gmail.com xyz@gmail.com”Question 2) Find all words in the text which are ending with “ing”Text=”dancing trek swimming sleeping jump running studying”Solution:Regular Expression=”\w+ing”Output => dancing swimming sleeping running studying
Unlike “+” operator which is used to match with one or more repetitions of preceding symbol,”*” is used to match with 0 or more repetitions of the preceding symbol.
For example:-
Suppose we are asked to find out of all the user id’s mentioned below only those which have string “saurabh” in it then, in that case, we will have to use “*”
Text =”saurabh13 kartik95 shreyashsingh ranasaurabh15 kumararindam yash_paryani saurabh_rana_22"Regular Expression = “\w*saurabh\w*”Output => saurabh13 ranasaurabh15 saurabh_rana_22
A string of characters enclosed in square brackets ([]) matches any one character in that string.Let’s try to understand it with the help of an example:-
Text=”ring king ping ding running”Regular Expression => “[rk]ing”Regular Expression Breakdown => Match with alphabet “r” or “k” + Match with “ing”Output => ring king
Note: As I mentioned before that in regular expressions the conditions should match consecutively in the same order as mentioned in Regular Expression. In the above example “running” is not matched even though it starts with “r” and ends with “ing” because these conditions are not matched consecutively since there are other alphabets between “r” and “ing” in running.
The special character “^” is used inside square brackets when we want to match all characters except for those mentioned in square brackets
Text=”ring king ping ding running”Regular Expression =>“‘[^rk]ing”Output => ping ding ning
We can use a hyphen(“-”)between two characters set to specify the characters range
Text=”ring king ping ding running”Regular Expression => “[a-z]ing”Output => ring king ping ding ning
The meta character “.” matches any single character except for return or newline characters
Input=”1_3@a!b+c de”Regular Expression => “.”Output =>1 _ 3 @ a ! b + c d e
Here the regular expression is matching with every type of character including the whitespace between alphabet “d” and “e”
We use curly braces ({}) when we are very specific about the number of occurrences an operator or sub-expression must match in the source string. In the below-mentioned example, we are trying to derive the same output as we did in earlier examples where we wanted to match 3 consecutive digits for which we used regular expression “\d\d\d”, now instead of repeating the expression we can mention the specific number of occurrences that we want inside the curly brackets.
Text=”123 4643 6642 5 6545 8974 45 17 8659 1 34 88 654 564 786 4536 4 76 89 684568 "regular expression = “\d{3}”Output=>123 464 664 654 897 865 654 564 786 453
“?” in regex is used for making the previous group/character optional.
Let me explain the importance of this expression using an example=>
Suppose we are asked to extract all the numbers from the text given below, now in the given text there are three types of numbers:-
some numbers are whole numbers(without fraction)
some numbers which are greater than 1 and have decimal values
and some are less than “1” which will have decimal values
Now we want to extract all three types of numbers, let’s try it out
text=”2.55 300 153.54 .45 1234.1234 435 5.2435 .345"Regular expression = “\d*\.?\d*”Output = 2.55 300 153.54 .45 1234.1234 435 5.2435 .345Regular expression breakdown = Match 0 or more digits(\d*) + Match a decimal point on not(.?) + Match 0 or more digits(\d*)
The caret ^ and dollar $ characters are called “anchors” where the caret ^ matches at the beginning of the text, and the dollar $ at the end. They do not match any character at all. Instead, they match a position before, after, or between characters
Suppose in a data set we want to extract mobile numbers but there are many errors in the data set because of which there might be cases where the mobile number is not valid(Valid mobile number consists of 10 digits). In that case, anchors are very useful. Let’s try to understand this using various cases:-
Case-1Text=”9851245245s"Regular Expression=”^\d\d{8}\d$”Regular expression breakdown = First character of string should be a digit + match 8 digits + Last character of the string should be a digitsOutput= Null
Output is null because the number is not ending with a number which makes it an invalid mobile number.
Case-2Text=”98512f45245”Regular Expression=”^\d\d{8}\d$”Output= Null
Output is again null because there is an alphabet in between the numbers
Case-3Text=”985125245”Regular Expression=”^\d\d{8}\d$”Output= Null
This time there is no alphabet string in the source string but still, we are getting null output because the length of our source string is not equal to 10.
Case-4Text=”9851425245”Regular Expression=”^\d\d{8}\d$”Output= 9851425245
In this case, we are getting output because the source string full fills all the conditions of a valid mobile number as we mentioned in our regular expression.
So these are the most fundamental and important concepts of Regular expressions which I have tried to explain using some interesting examples, some of them were made up but most of them were actual problems that I came across while data cleaning so in future if you are stuck on a problem then just go through the examples once again and you might find the exact answer in one of the examples.
Apart from the basic regular expressions, you might come across regular expressions like this “ /^[a-z0–9_-]{6,18}$/”.When people see such long regular expression they just ignore them as if they have seen a Russian word in an English sentence. The trick to understanding the meaning of such regular expressions is to break them down and solve them separately.
If you are still not confident enough to understand such regular expression then please mention in the comment section, I may upload a second article on Regular Expression to explain how to solve such regular expression.
|
[
{
"code": null,
"e": 202,
"s": 172,
"text": "What are Regular Expressions?"
},
{
"code": null,
"e": 462,
"s": 202,
"text": "Regular Expression is a special text string command which is used to match specific string sequences from huge chunks of data which if done manually by a person can take a lot of time. You can use regular expressions to match various patterns of string like:-"
},
{
"code": null,
"e": 497,
"s": 462,
"text": "To extract all the email addresses"
},
{
"code": null,
"e": 535,
"s": 497,
"text": "To extract only Gmail email addresses"
},
{
"code": null,
"e": 630,
"s": 535,
"text": "To extract all the names starting with a specific alphabet and ending with a specific alphabet"
},
{
"code": null,
"e": 691,
"s": 630,
"text": "To extract all the names where the first alphabet is capital"
},
{
"code": null,
"e": 745,
"s": 691,
"text": "To extract all the numbers which have decimals points"
},
{
"code": null,
"e": 784,
"s": 745,
"text": "To extract numbers in a specific range"
},
{
"code": null,
"e": 1276,
"s": 784,
"text": "And the list is endless, the above-mentioned cases are the first six scenarios that crossed my mind while writing this article but honestly you can use regular expressions to extract any kind of string pattern from data no matter how big it is within seconds and that is the beauty of regular expressions. These days the importance of regular expression has increased because many companies are using natural language processing techniques where regular expressions are used very frequently."
},
{
"code": null,
"e": 1501,
"s": 1276,
"text": "The best thing about regular expression is that it is supported by most of the popular programming languages therefore once you understand the syntax and concept of regular expressions, you can use it with various languages."
},
{
"code": null,
"e": 1683,
"s": 1501,
"text": "So let’s get started with regular expressions, I am using regular expressions with python but you guys can use any language of your choice but it should support regular expressions."
},
{
"code": null,
"e": 1835,
"s": 1683,
"text": "First is to match only the first time occurrence of a particular string pattern, second is to match all the occurrences of a particular string pattern."
},
{
"code": null,
"e": 2186,
"s": 1835,
"text": "Now whether you want to match only first occurrence or all the occurrence depends on your requirement. In my experience wherever I have used Regular Expressions most of the problems require all the occurrences to be matched therefore in all the examples in this blog I have intentionally written Regular expressions to match with all the occurrences."
},
{
"code": null,
"e": 2464,
"s": 2186,
"text": "Let’s get started with the most basic regex expression that is literal characters where you are basically searching a particular alphabet or a word from the data, it is similar to what you get when you search something on a web page or pdf using Ctrl+F. Let’s try one example:-"
},
{
"code": null,
"e": 2547,
"s": 2464,
"text": "Since I am a big marvel fan so I will be using marvel as a reference in my example"
},
{
"code": null,
"e": 2886,
"s": 2547,
"text": "Input = “Avatar did a business of 2.788 billion dollars($) where as Endgame has grossed 2.79 billions dollars($) till date”Regular Expression => “a”It will match with every single alphabet — “a”“Avatar did a business of 2.788 billion dollars($) where as Endgame has grossed 2.79 billions dollars($) till date”Output => a a a a a a a a a a"
},
{
"code": null,
"e": 3046,
"s": 2886,
"text": "In output “a” is repeated 10 times because there are exactly ten occurrences of the alphabet “a”Now let’s try a combination of alphabets for our next example:-"
},
{
"code": null,
"e": 3200,
"s": 3046,
"text": "Regular Expression => “as”Avatar did a business of 2.788 billion dollars($) where as Endgame has grossed 2.79 billion dollars($) till dateOutput => as as"
},
{
"code": null,
"e": 3358,
"s": 3200,
"text": "Note: The sequence of alphabets is very important, in the above example only those stings will be matched where alphabet “a” is followed by the alphabet “s”."
},
{
"code": null,
"e": 3628,
"s": 3358,
"text": "“\\w” stands for word character which basically is shorthand for [a-zA-Z0–9_] which means it matches with all capital alphabet, small alphabets and all the digits. Let’s try this regular expression in our marvel text to analyse which characters doesn’t match with “\\w”:-"
},
{
"code": null,
"e": 3962,
"s": 3628,
"text": "Text=”Avatar did a business of 2.788 billion dollars($) where as Endgame has grossed 2.79 billions dollars($) till date”Regular Expression => “\\w”Output => “A v a t a r d i d a b u s i n e s s o f 2 7 8 8 b i l l i o n d o l l a r s w h e r e a s E n d g a m e h a s g r o s s e d 2 7 9 b i l l i o n s d o l l a r s t i l l d a t e”"
},
{
"code": null,
"e": 4078,
"s": 3962,
"text": "As you can see the expression “\\w” has matched with all the characters in the sentence except for [“$”,”(“,”)”,”.”]"
},
{
"code": null,
"e": 4398,
"s": 4078,
"text": "Even though ”\\w” is matching with all the characters in [a-zA-Z0–9_] but it matches with them one at a time because of which the output will display one alphabet after another, therefore I have used for loop in python to display them all together because of which there is space between every character that is matched."
},
{
"code": null,
"e": 4491,
"s": 4398,
"text": "Now let’s move onto the second example where we are searching for two consecutive characters"
},
{
"code": null,
"e": 4755,
"s": 4491,
"text": "Regular Expression => “\\w\\w”Text=”Avatar did a business of 2.788 billion dollars($) where as Endgame has grossed 2.79 billions dollars($) till date”Note:It will match with two consecutive alphabet one at a timeOutput =>Av at ar di bu si ne ss of 78 bi ll io do ll"
},
{
"code": null,
"e": 4832,
"s": 4755,
"text": "I have not copied the whole output but a part of it just to give you an idea"
},
{
"code": null,
"e": 5144,
"s": 4832,
"text": "Note: Words which have an even number of characters are printed fully in groups of two but words where there are odd number of characters the last alphabet is missing in the output(Hint: When you divide an odd number by 2 the output is 1) because the last alphabet could not create a pair with another alphabet."
},
{
"code": null,
"e": 5216,
"s": 5144,
"text": "Similarly, we can search for three consecutive characters one at a time"
},
{
"code": null,
"e": 5409,
"s": 5216,
"text": "Regular Expression => “\\w\\w\\w”Text=”Avatar did a business of 2.788 billion dollar where as Endgame has grossed 2.79 billions dollars till date”Output => Ava tar did bus ine 788 bil lio dol lar"
},
{
"code": null,
"e": 5576,
"s": 5409,
"text": "Instead of repeating “\\w”, we can directly mention the number of consecutive alphabets we are searching for using curly({}) brackets about which we will discuss later"
},
{
"code": null,
"e": 5838,
"s": 5576,
"text": "This shorthand character where “W” is capital will match every character except these [a-zA-Z0–9_]. So only those characters which were not matching in our previous example where we were using shorthand character class “\\w” (w is small) will match in this case."
},
{
"code": null,
"e": 6002,
"s": 5838,
"text": "Text=”Avatar did a business of 2.788 billion dollar where as Endgame has grossed 2.79 billions dollars till date”Regular Expression => “\\W”Output =>. ( $ ) . ( $ )"
},
{
"code": null,
"e": 6075,
"s": 6002,
"text": "This shorthand character matches all numbers ([0–9]) in a source string."
},
{
"code": null,
"e": 6387,
"s": 6075,
"text": "Regular Expression => “\\d”It will match with every single alphabet one at a time,unlike “\\w” which matches with alphabets as well as digits,”\\d” matches only with digitsText=”Avatar did a business of 2.788 billion dollars($) where as Endgame has grossed 2.79 billions dollars($) till date”Output =>2 7 8 8 2 7 9"
},
{
"code": null,
"e": 6450,
"s": 6387,
"text": "Now let’s search for two consecutive numbers in source string."
},
{
"code": null,
"e": 6664,
"s": 6450,
"text": "Regular Expression =>” \\d\\d”It will match with two consecutive digits one at a timeAvatar did a business of 2.788 billion dollars($) \\n where as Endgame has grossed 2.79 billions dollars($) till dateOutput =>78 79"
},
{
"code": null,
"e": 6861,
"s": 6664,
"text": "Similar to “\\W” (W is capital) this regular expression is also the complete opposite of its counterpart “\\d” i.e. it will match only those characters which shorthand character “d” doesn’t matches."
},
{
"code": null,
"e": 7588,
"s": 6861,
"text": ". -> Matches any single character except a line break[ ] -> Matches any character contained between the square brackets[^ ] -> Matches any character that is not contained between the square brackets* -> Matches 0 or more repetitions of the preceding symbol+ -> Matches 1 or more repetitions of the preceding symbol? -> Makes the preceding symbol optional.{n,m} -> Matches at least \"n\" but not more than \"m\" repetitions of the preceding symbol| -> Matches either the characters before or the characters after the symbol\\ -> Escapes the next character. This allows you to match reserved characters { } . * + ? ^ $ \\ |^ -> Matches the beginning of the input$ -> Matches the end of the input"
},
{
"code": null,
"e": 7746,
"s": 7588,
"text": "Following meta characters +, * or ? are used to specify how many times a subpattern can occur. These meta characters act differently in different situations."
},
{
"code": null,
"e": 7845,
"s": 7746,
"text": "Meta character “+” is used to match with one or more than one occurrences of the preceding symbol."
},
{
"code": null,
"e": 7859,
"s": 7845,
"text": "For example:-"
},
{
"code": null,
"e": 7941,
"s": 7859,
"text": "“\\w+” Matches with strings which have one or more than one [a-zA-Z0–9_] character"
},
{
"code": null,
"e": 8007,
"s": 7941,
"text": "“\\d+” Matches with numbers which have one or more than one digits"
},
{
"code": null,
"e": 8117,
"s": 8007,
"text": "a+ Matches with one or more than one occurrences of the alphabet “a”.We can use any alphabet in place of “a”."
},
{
"code": null,
"e": 8162,
"s": 8117,
"text": "Now let’s try out these examples on raw text"
},
{
"code": null,
"e": 8425,
"s": 8162,
"text": "Regular Expression=”\\w+”Text = “Avatar did a business of 2.788 billion dollars($) where as Endgame has grossed 2.79 billions dollars($) till date”Output =>Avatar did a business of 2 788 billion dollars where as Endgame has grossed 2 79 billions dollars till date"
},
{
"code": null,
"e": 8466,
"s": 8425,
"text": "Now let’s try the “+” operator with “\\d”"
},
{
"code": null,
"e": 8625,
"s": 8466,
"text": "Regular Expression =”\\d+”Text=”Avatar did a business of 2.788 billion dollar where as Endgame has grossed 2.79 billions dollars till date”Output => 2 788 2 79"
},
{
"code": null,
"e": 8731,
"s": 8625,
"text": "Note: In the output “2” and “788” are not matched together because these two numbers are separated by “.”"
},
{
"code": null,
"e": 8842,
"s": 8731,
"text": "Now, what if want the number“2.788” to be matched, in that case, we can use the following regular expression:-"
},
{
"code": null,
"e": 9118,
"s": 8842,
"text": "Regular Expression => \"\\d+.\\d+\"Text=”Avatar did a business of 2.788 billion dollar where as Endgame has grossed 2.79 billions dollars till date”Output=> 2.788 2.79Regular Expression Breakdown=>Match one or more digit(\\d+) + Match a full stop(.) + Match one or more digit(\\d+)"
},
{
"code": null,
"e": 9600,
"s": 9118,
"text": "Note: In complex regular expressions like the one mentioned above where we search for strings with multiple conditions, the conditions should match consecutively in the same order as mentioned in regular Expression, for instance in the example mentioned above we are searching for numbers which have one or more than one digits, followed by a full stop, followed by one or more than one digits. If these three conditions are not matched consecutively then there won’t be any match."
},
{
"code": null,
"e": 10095,
"s": 9600,
"text": "Exercise:Question 1) Find all gmail email id’s from given below data.Text =“abc@yahoo.com saurabh@outlook.com abc@gmail.com saurabh88@gmail.com saurabh11@outlook.com xyz@gmail.com”Solution:Regular Expression=”\\w+@gmail.com”Output =>”abc@gmail.com saurabh88@gmail.com xyz@gmail.com”Question 2) Find all words in the text which are ending with “ing”Text=”dancing trek swimming sleeping jump running studying”Solution:Regular Expression=”\\w+ing”Output => dancing swimming sleeping running studying"
},
{
"code": null,
"e": 10260,
"s": 10095,
"text": "Unlike “+” operator which is used to match with one or more repetitions of preceding symbol,”*” is used to match with 0 or more repetitions of the preceding symbol."
},
{
"code": null,
"e": 10274,
"s": 10260,
"text": "For example:-"
},
{
"code": null,
"e": 10433,
"s": 10274,
"text": "Suppose we are asked to find out of all the user id’s mentioned below only those which have string “saurabh” in it then, in that case, we will have to use “*”"
},
{
"code": null,
"e": 10615,
"s": 10433,
"text": "Text =”saurabh13 kartik95 shreyashsingh ranasaurabh15 kumararindam yash_paryani saurabh_rana_22\"Regular Expression = “\\w*saurabh\\w*”Output => saurabh13 ranasaurabh15 saurabh_rana_22"
},
{
"code": null,
"e": 10769,
"s": 10615,
"text": "A string of characters enclosed in square brackets ([]) matches any one character in that string.Let’s try to understand it with the help of an example:-"
},
{
"code": null,
"e": 10935,
"s": 10769,
"text": "Text=”ring king ping ding running”Regular Expression => “[rk]ing”Regular Expression Breakdown => Match with alphabet “r” or “k” + Match with “ing”Output => ring king"
},
{
"code": null,
"e": 11305,
"s": 10935,
"text": "Note: As I mentioned before that in regular expressions the conditions should match consecutively in the same order as mentioned in Regular Expression. In the above example “running” is not matched even though it starts with “r” and ends with “ing” because these conditions are not matched consecutively since there are other alphabets between “r” and “ing” in running."
},
{
"code": null,
"e": 11445,
"s": 11305,
"text": "The special character “^” is used inside square brackets when we want to match all characters except for those mentioned in square brackets"
},
{
"code": null,
"e": 11536,
"s": 11445,
"text": "Text=”ring king ping ding running”Regular Expression =>“‘[^rk]ing”Output => ping ding ning"
},
{
"code": null,
"e": 11619,
"s": 11536,
"text": "We can use a hyphen(“-”)between two characters set to specify the characters range"
},
{
"code": null,
"e": 11720,
"s": 11619,
"text": "Text=”ring king ping ding running”Regular Expression => “[a-z]ing”Output => ring king ping ding ning"
},
{
"code": null,
"e": 11812,
"s": 11720,
"text": "The meta character “.” matches any single character except for return or newline characters"
},
{
"code": null,
"e": 11892,
"s": 11812,
"text": "Input=”1_3@a!b+c de”Regular Expression => “.”Output =>1 _ 3 @ a ! b + c d e"
},
{
"code": null,
"e": 12015,
"s": 11892,
"text": "Here the regular expression is matching with every type of character including the whitespace between alphabet “d” and “e”"
},
{
"code": null,
"e": 12486,
"s": 12015,
"text": "We use curly braces ({}) when we are very specific about the number of occurrences an operator or sub-expression must match in the source string. In the below-mentioned example, we are trying to derive the same output as we did in earlier examples where we wanted to match 3 consecutive digits for which we used regular expression “\\d\\d\\d”, now instead of repeating the expression we can mention the specific number of occurrences that we want inside the curly brackets."
},
{
"code": null,
"e": 12646,
"s": 12486,
"text": "Text=”123 4643 6642 5 6545 8974 45 17 8659 1 34 88 654 564 786 4536 4 76 89 684568 \"regular expression = “\\d{3}”Output=>123 464 664 654 897 865 654 564 786 453"
},
{
"code": null,
"e": 12717,
"s": 12646,
"text": "“?” in regex is used for making the previous group/character optional."
},
{
"code": null,
"e": 12785,
"s": 12717,
"text": "Let me explain the importance of this expression using an example=>"
},
{
"code": null,
"e": 12917,
"s": 12785,
"text": "Suppose we are asked to extract all the numbers from the text given below, now in the given text there are three types of numbers:-"
},
{
"code": null,
"e": 12966,
"s": 12917,
"text": "some numbers are whole numbers(without fraction)"
},
{
"code": null,
"e": 13028,
"s": 12966,
"text": "some numbers which are greater than 1 and have decimal values"
},
{
"code": null,
"e": 13086,
"s": 13028,
"text": "and some are less than “1” which will have decimal values"
},
{
"code": null,
"e": 13154,
"s": 13086,
"text": "Now we want to extract all three types of numbers, let’s try it out"
},
{
"code": null,
"e": 13416,
"s": 13154,
"text": "text=”2.55 300 153.54 .45 1234.1234 435 5.2435 .345\"Regular expression = “\\d*\\.?\\d*”Output = 2.55 300 153.54 .45 1234.1234 435 5.2435 .345Regular expression breakdown = Match 0 or more digits(\\d*) + Match a decimal point on not(.?) + Match 0 or more digits(\\d*)"
},
{
"code": null,
"e": 13666,
"s": 13416,
"text": "The caret ^ and dollar $ characters are called “anchors” where the caret ^ matches at the beginning of the text, and the dollar $ at the end. They do not match any character at all. Instead, they match a position before, after, or between characters"
},
{
"code": null,
"e": 13973,
"s": 13666,
"text": "Suppose in a data set we want to extract mobile numbers but there are many errors in the data set because of which there might be cases where the mobile number is not valid(Valid mobile number consists of 10 digits). In that case, anchors are very useful. Let’s try to understand this using various cases:-"
},
{
"code": null,
"e": 14183,
"s": 13973,
"text": "Case-1Text=”9851245245s\"Regular Expression=”^\\d\\d{8}\\d$”Regular expression breakdown = First character of string should be a digit + match 8 digits + Last character of the string should be a digitsOutput= Null"
},
{
"code": null,
"e": 14286,
"s": 14183,
"text": "Output is null because the number is not ending with a number which makes it an invalid mobile number."
},
{
"code": null,
"e": 14355,
"s": 14286,
"text": "Case-2Text=”98512f45245”Regular Expression=”^\\d\\d{8}\\d$”Output= Null"
},
{
"code": null,
"e": 14428,
"s": 14355,
"text": "Output is again null because there is an alphabet in between the numbers"
},
{
"code": null,
"e": 14495,
"s": 14428,
"text": "Case-3Text=”985125245”Regular Expression=”^\\d\\d{8}\\d$”Output= Null"
},
{
"code": null,
"e": 14652,
"s": 14495,
"text": "This time there is no alphabet string in the source string but still, we are getting null output because the length of our source string is not equal to 10."
},
{
"code": null,
"e": 14726,
"s": 14652,
"text": "Case-4Text=”9851425245”Regular Expression=”^\\d\\d{8}\\d$”Output= 9851425245"
},
{
"code": null,
"e": 14886,
"s": 14726,
"text": "In this case, we are getting output because the source string full fills all the conditions of a valid mobile number as we mentioned in our regular expression."
},
{
"code": null,
"e": 15280,
"s": 14886,
"text": "So these are the most fundamental and important concepts of Regular expressions which I have tried to explain using some interesting examples, some of them were made up but most of them were actual problems that I came across while data cleaning so in future if you are stuck on a problem then just go through the examples once again and you might find the exact answer in one of the examples."
},
{
"code": null,
"e": 15641,
"s": 15280,
"text": "Apart from the basic regular expressions, you might come across regular expressions like this “ /^[a-z0–9_-]{6,18}$/”.When people see such long regular expression they just ignore them as if they have seen a Russian word in an English sentence. The trick to understanding the meaning of such regular expressions is to break them down and solve them separately."
}
] |
Count of Prime digits in a Number - GeeksforGeeks
|
24 Nov, 2021
Given an integer N, the task is to count the number of prime digits in N.Examples:
Input: N = 12 Output: 1 Explanation: Digits of the number – {1, 2} But, only 2 is prime number.Input: N = 1032 Output: 2 Explanation: Digits of the number – {1, 0, 3, 2} 3 and 2 are prime number
Approach: The idea is to iterate through all the digits of the number and check whether the digit is a prime or not. Since there are only four possible prime numbers in the range [0, 9] and every digit for sure lies in this range, we only need to check the number of digits equal to either of the elements in the set {2, 3, 5, 7}. Below is the implementation of this approach:
CPP
Java
Python3
C#
Javascript
// C++ program to count the number of// prime digits in a number #include <bits/stdc++.h>using namespace std; // Function to find the count of// prime digits in a numberint countDigit(int n){ int temp = n, count = 0; // Loop to compute all the digits // of the number while (temp != 0) { // Finding every digit of the // given number int d = temp % 10; temp /= 10; // Checking if digit is prime or not // Only 2, 3, 5 and 7 are prime // one-digit number if (d == 2 || d == 3 || d == 5 || d == 7) count++; } return count;} // Driver codeint main(){ int n = 1234567890; cout << countDigit(n) << endl; return 0;}
// Java program to count the number of// prime digits in a numberclass GFG { // Function to find the count of // prime digits in a number static int countDigit(int n) { int temp = n, count = 0; // Loop to compute all the digits // of the number while (temp != 0) { // Finding every digit of the // given number int d = temp % 10; temp /= 10; // Checking if digit is prime or not // Only 2, 3, 5 and 7 are prime // one-digit number if (d == 2 || d == 3 || d == 5 || d == 7) count++; } return count; } // Driver code public static void main (String[] args) { int n = 1234567890; System.out.println(countDigit(n)) ; }} // This code is contributed by AnkitRai01
# Python3 program to count the number of# prime digits in a number # Function to find the count of# prime digits in a numberdef countDigit(n): temp = n count = 0 # Loop to compute all the digits # of the number while (temp != 0): # Finding every digit of the # given number d = temp % 10 temp //= 10 # Checking if digit is prime or not # Only 2, 3, 5 and 7 are prime # one-digit number if (d == 2 or d == 3 or d == 5 or d == 7): count += 1 return count # Driver codeif __name__ == '__main__': n = 1234567890 print(countDigit(n)) # This code is contributed by mohit kumar 29
// C# program to count the number of// prime digits in a numberusing System; class GFG { // Function to find the count of // prime digits in a number static int countDigit(int n) { int temp = n, count = 0; // Loop to compute all the digits // of the number while (temp != 0) { // Finding every digit of the // given number int d = temp % 10; temp /= 10; // Checking if digit is prime or not // Only 2, 3, 5 and 7 are prime // one-digit number if (d == 2 || d == 3 || d == 5 || d == 7) count++; } return count; } // Driver code public static void Main (string[] args) { int n = 1234567890; Console.WriteLine(countDigit(n)) ; }} // This code is contributed by AnkitRai01
<script> // JavaScript program to count the number of// prime digits in a number // Function to find the count of// prime digits in a numberfunction countDigit(n){ let temp = n, count = 0; // Loop to compute all the digits // of the number while (temp != 0) { // Finding every digit of the // given number let d = temp % 10; temp = Math.floor(temp / 10); // Checking if digit is prime or not // Only 2, 3, 5 and 7 are prime // one-digit number if (d == 2 || d == 3 || d == 5 || d == 7) count++; } return count;} // Driver code let n = 1234567890; document.write(countDigit(n) + "<br>"); // This code is contributed by gfgking </script>
4
Time Complexity: O(log10N), where N is the length of the number.
Auxiliary Space: O(1)
mohit kumar 29
ankthon
gfgking
subham348
number-digits
Prime Number
Mathematical
Mathematical
Prime Number
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 sum of elements in a given array
Program for Decimal to Binary Conversion
Program for factorial of a number
Operators in C / C++
The Knight's tour problem | Backtracking-1
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Print all possible combinations of r elements in a given array of size n
|
[
{
"code": null,
"e": 24824,
"s": 24796,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 24909,
"s": 24824,
"text": "Given an integer N, the task is to count the number of prime digits in N.Examples: "
},
{
"code": null,
"e": 25106,
"s": 24909,
"text": "Input: N = 12 Output: 1 Explanation: Digits of the number – {1, 2} But, only 2 is prime number.Input: N = 1032 Output: 2 Explanation: Digits of the number – {1, 0, 3, 2} 3 and 2 are prime number "
},
{
"code": null,
"e": 25485,
"s": 25106,
"text": "Approach: The idea is to iterate through all the digits of the number and check whether the digit is a prime or not. Since there are only four possible prime numbers in the range [0, 9] and every digit for sure lies in this range, we only need to check the number of digits equal to either of the elements in the set {2, 3, 5, 7}. Below is the implementation of this approach: "
},
{
"code": null,
"e": 25489,
"s": 25485,
"text": "CPP"
},
{
"code": null,
"e": 25494,
"s": 25489,
"text": "Java"
},
{
"code": null,
"e": 25502,
"s": 25494,
"text": "Python3"
},
{
"code": null,
"e": 25505,
"s": 25502,
"text": "C#"
},
{
"code": null,
"e": 25516,
"s": 25505,
"text": "Javascript"
},
{
"code": "// C++ program to count the number of// prime digits in a number #include <bits/stdc++.h>using namespace std; // Function to find the count of// prime digits in a numberint countDigit(int n){ int temp = n, count = 0; // Loop to compute all the digits // of the number while (temp != 0) { // Finding every digit of the // given number int d = temp % 10; temp /= 10; // Checking if digit is prime or not // Only 2, 3, 5 and 7 are prime // one-digit number if (d == 2 || d == 3 || d == 5 || d == 7) count++; } return count;} // Driver codeint main(){ int n = 1234567890; cout << countDigit(n) << endl; return 0;}",
"e": 26237,
"s": 25516,
"text": null
},
{
"code": "// Java program to count the number of// prime digits in a numberclass GFG { // Function to find the count of // prime digits in a number static int countDigit(int n) { int temp = n, count = 0; // Loop to compute all the digits // of the number while (temp != 0) { // Finding every digit of the // given number int d = temp % 10; temp /= 10; // Checking if digit is prime or not // Only 2, 3, 5 and 7 are prime // one-digit number if (d == 2 || d == 3 || d == 5 || d == 7) count++; } return count; } // Driver code public static void main (String[] args) { int n = 1234567890; System.out.println(countDigit(n)) ; }} // This code is contributed by AnkitRai01",
"e": 27137,
"s": 26237,
"text": null
},
{
"code": "# Python3 program to count the number of# prime digits in a number # Function to find the count of# prime digits in a numberdef countDigit(n): temp = n count = 0 # Loop to compute all the digits # of the number while (temp != 0): # Finding every digit of the # given number d = temp % 10 temp //= 10 # Checking if digit is prime or not # Only 2, 3, 5 and 7 are prime # one-digit number if (d == 2 or d == 3 or d == 5 or d == 7): count += 1 return count # Driver codeif __name__ == '__main__': n = 1234567890 print(countDigit(n)) # This code is contributed by mohit kumar 29",
"e": 27808,
"s": 27137,
"text": null
},
{
"code": "// C# program to count the number of// prime digits in a numberusing System; class GFG { // Function to find the count of // prime digits in a number static int countDigit(int n) { int temp = n, count = 0; // Loop to compute all the digits // of the number while (temp != 0) { // Finding every digit of the // given number int d = temp % 10; temp /= 10; // Checking if digit is prime or not // Only 2, 3, 5 and 7 are prime // one-digit number if (d == 2 || d == 3 || d == 5 || d == 7) count++; } return count; } // Driver code public static void Main (string[] args) { int n = 1234567890; Console.WriteLine(countDigit(n)) ; }} // This code is contributed by AnkitRai01",
"e": 28718,
"s": 27808,
"text": null
},
{
"code": "<script> // JavaScript program to count the number of// prime digits in a number // Function to find the count of// prime digits in a numberfunction countDigit(n){ let temp = n, count = 0; // Loop to compute all the digits // of the number while (temp != 0) { // Finding every digit of the // given number let d = temp % 10; temp = Math.floor(temp / 10); // Checking if digit is prime or not // Only 2, 3, 5 and 7 are prime // one-digit number if (d == 2 || d == 3 || d == 5 || d == 7) count++; } return count;} // Driver code let n = 1234567890; document.write(countDigit(n) + \"<br>\"); // This code is contributed by gfgking </script>",
"e": 29457,
"s": 28718,
"text": null
},
{
"code": null,
"e": 29459,
"s": 29457,
"text": "4"
},
{
"code": null,
"e": 29526,
"s": 29461,
"text": "Time Complexity: O(log10N), where N is the length of the number."
},
{
"code": null,
"e": 29549,
"s": 29526,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 29564,
"s": 29549,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 29572,
"s": 29564,
"text": "ankthon"
},
{
"code": null,
"e": 29580,
"s": 29572,
"text": "gfgking"
},
{
"code": null,
"e": 29590,
"s": 29580,
"text": "subham348"
},
{
"code": null,
"e": 29604,
"s": 29590,
"text": "number-digits"
},
{
"code": null,
"e": 29617,
"s": 29604,
"text": "Prime Number"
},
{
"code": null,
"e": 29630,
"s": 29617,
"text": "Mathematical"
},
{
"code": null,
"e": 29643,
"s": 29630,
"text": "Mathematical"
},
{
"code": null,
"e": 29656,
"s": 29643,
"text": "Prime Number"
},
{
"code": null,
"e": 29754,
"s": 29656,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29778,
"s": 29754,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 29821,
"s": 29778,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 29870,
"s": 29821,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 29911,
"s": 29870,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 29945,
"s": 29911,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 29966,
"s": 29945,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 30009,
"s": 29966,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 30062,
"s": 30009,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 30099,
"s": 30062,
"text": "Minimum number of jumps to reach end"
}
] |
DynamoDB - Local Secondary Indexes
|
Some applications only perform queries with the primary key, but some situations benefit from an alternate sort key. Allow your application a choice by creating a single or multiple local secondary indexes.
Complex data access requirements, such as combing millions of items, make it necessary to perform more efficient queries/scans. Local secondary indices provide an alternate sort key for a partition key value. They also hold copies of all or some table attributes. They organize data by table partition key, but use a different sort key.
Using a local secondary index removes the need for a whole table scan, and allows a simple and quick query using a sort key.
All the local secondary indexes must satisfy certain conditions −
Identical partition key and source table partition key.
A sort key of only one scalar attribute.
Projection of the source table sort key acting as a non-key attribute.
All the local secondary indexes automatically hold partition and sort keys from parent tables. In queries, this means efficient gathering of projected attributes, and also retrieval of attributes not projected.
The storage limit for a local secondary index remains 10GB per partition key value, which includes all table items, and index items sharing a partition key value.
Some operations require excess reads/fetching due to complexity. These operations can consume substantial throughput. Projection allows you to avoid costly fetching and perform rich queries by isolating these attributes. Remember projections consist of attributes copied into a secondary index.
When making a secondary index, you specify the attributes projected. Recall the three options provided by DynamoDB: KEYS_ONLY, INCLUDE, and ALL.
When opting for certain attributes in projection, consider the associated cost tradeoffs −
If you project only a small set of necessary attributes, you dramatically reduce the storage costs.
If you project only a small set of necessary attributes, you dramatically reduce the storage costs.
If you project frequently accessed non-key attributes, you offset scan costs with storage costs.
If you project frequently accessed non-key attributes, you offset scan costs with storage costs.
If you project most or all non-key attributes, this maximizes flexibility and reduces throughput (no retrievals); however, storage costs rise.
If you project most or all non-key attributes, this maximizes flexibility and reduces throughput (no retrievals); however, storage costs rise.
If you project KEYS_ONLY for frequent writes/updates and infrequent queries, it minimizes size, but maintains query preparation.
If you project KEYS_ONLY for frequent writes/updates and infrequent queries, it minimizes size, but maintains query preparation.
Use the LocalSecondaryIndex parameter of CreateTable to make a single or multiple local secondary indexes. You must specify one non-key attribute for the sort key. On table creation, you create local secondary indices. On deletion, you delete these indexes.
Tables with a local secondary index must obey a limit of 10GB in size per partition key value, but can store any amount of items.
A query operation on local secondary indexes returns all items with a matching partition key value when multiple items in the index share sort key values. Matching items do not return in a certain order. Queries for local secondary indexes use either eventual or strong consistency, with strongly consistent reads delivering the latest values.
A scan operation returns all local secondary index data. Scans require you to provide a table and index name, and allow the use of a filter expression to discard data.
On creation of a local secondary index, you specify a sort key attribute and its data type. When you write an item, its type must match the data type of the key schema if the item defines an attribute of an index key.
DynamoDB imposes no one-to-one relationship requirements on table items and local secondary index items. The tables with multiple local secondary indexes carry higher write costs than those with less.
Read capacity consumption of a query depends on the nature of data access. Queries use either eventual or strong consistency, with strongly consistent reads using one unit compared to half a unit in eventually consistent reads.
Result limitations include a 1MB size maximum. Result sizes come from the sum of matching index item size rounded up to the nearest 4KB, and matching table item size also rounded up to the nearest 4KB.
The write capacity consumption remains within provisioned units. Calculate the total provisioned cost by finding the sum of consumed units in table writing and consumed units in updating indices.
You can also consider the key factors influencing cost, some of which can be −
When you write an item defining an indexed attribute or update an item to define an undefined indexed attribute, a single write operation occurs.
When you write an item defining an indexed attribute or update an item to define an undefined indexed attribute, a single write operation occurs.
When a table update changes an indexed key attribute value, two writes occur to delete and then – add an item.
When a table update changes an indexed key attribute value, two writes occur to delete and then – add an item.
When a write causes the deletion of an indexed attribute, one write occurs to remove the old item projection.
When a write causes the deletion of an indexed attribute, one write occurs to remove the old item projection.
When an item does not exist within the index prior to or after an update, no writes occur.
When an item does not exist within the index prior to or after an update, no writes occur.
On a table item write, DynamoDB automatically copies the right attribute set to the required local secondary indexes. This charges your account. The space used results from the sum of table primary key byte size, index key attribute byte size, any present projected attribute byte size, and 100 bytes in overhead for each index item.
The estimate storage is got by estimating average index item size and multiplying by table item quantity.
Create a local secondary index by first creating a DynamoDB class instance. Then, create a CreateTableRequest class instance with necessary request information. Finally, use the createTable method.
DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
new ProfileCredentialsProvider()));
String tableName = "Tools";
CreateTableRequest createTableRequest = new
CreateTableRequest().withTableName(tableName);
//Provisioned Throughput
createTableRequest.setProvisionedThroughput (
new ProvisionedThroughput()
.withReadCapacityUnits((long)5)
.withWriteCapacityUnits(( long)5));
//Attributes
ArrayList<AttributeDefinition> attributeDefinitions =
new ArrayList<AttributeDefinition>();
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("Make")
.withAttributeType("S"));
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("Model")
.withAttributeType("S"));
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("Line")
.withAttributeType("S"));
createTableRequest.setAttributeDefinitions(attributeDefinitions);
//Key Schema
ArrayList<KeySchemaElement> tableKeySchema = new
ArrayList<KeySchemaElement>();
tableKeySchema.add(new KeySchemaElement()
.withAttributeName("Make")
.withKeyType(KeyType.HASH)); //Partition key
tableKeySchema.add(new KeySchemaElement()
.withAttributeName("Model")
.withKeyType(KeyType.RANGE)); //Sort key
createTableRequest.setKeySchema(tableKeySchema);
ArrayList<KeySchemaElement> indexKeySchema = new
ArrayList<KeySchemaElement>();
indexKeySchema.add(new KeySchemaElement()
.withAttributeName("Make")
.withKeyType(KeyType.HASH)); //Partition key
indexKeySchema.add(new KeySchemaElement()
.withAttributeName("Line")
.withKeyType(KeyType.RANGE)); //Sort key
Projection projection = new Projection()
.withProjectionType(ProjectionType.INCLUDE);
ArrayList<String> nonKeyAttributes = new ArrayList<String>();
nonKeyAttributes.add("Type");
nonKeyAttributes.add("Year");
projection.setNonKeyAttributes(nonKeyAttributes);
LocalSecondaryIndex localSecondaryIndex = new LocalSecondaryIndex()
.withIndexName("ModelIndex")
.withKeySchema(indexKeySchema)
.withProjection(p rojection);
ArrayList<LocalSecondaryIndex> localSecondaryIndexes = new
ArrayList<LocalSecondaryIndex>();
localSecondaryIndexes.add(localSecondaryIndex);
createTableRequest.setLocalSecondaryIndexes(localSecondaryIndexes);
Table table = dynamoDB.createTable(createTableRequest);
System.out.println(table.getDescription());
Retrieve information about a local secondary index with the describe method. Simply create a DynamoDB class instance, create a Table class instance, and pass the table to the describe method.
DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
new ProfileCredentialsProvider()));
String tableName = "Tools";
Table table = dynamoDB.getTable(tableName);
TableDescription tableDescription = table.describe();
List<LocalSecondaryIndexDescription> localSecondaryIndexes =
tableDescription.getLocalSecondaryIndexes();
Iterator<LocalSecondaryIndexDescription> lsiIter =
localSecondaryIndexes.iterator();
while (lsiIter.hasNext()) {
LocalSecondaryIndexDescription lsiDescription = lsiIter.next();
System.out.println("Index info " + lsiDescription.getIndexName() + ":");
Iterator<KeySchemaElement> kseIter = lsiDescription.getKeySchema().iterator();
while (kseIter.hasNext()) {
KeySchemaElement kse = kseIter.next();
System.out.printf("\t%s: %s\n", kse.getAttributeName(), kse.getKeyType());
}
Projection projection = lsiDescription.getProjection();
System.out.println("\tProjection type: " + projection.getProjectionType());
if (projection.getProjectionType().toString().equals("INCLUDE")) {
System.out.println("\t\tNon-key projected attributes: " +
projection.getNonKeyAttributes());
}
}
Perform a query by using the same steps as a table query. Merely create a DynamoDB class instance, a Table class instance, an Index class instance, a query object, and utilize the query method.
DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
new ProfileCredentialsProvider()));
String tableName = "Tools";
Table table = dynamoDB.getTable(tableName);
Index index = table.getIndex("LineIndex");
QuerySpec spec = new QuerySpec()
.withKeyConditionExpression("Make = :v_make and Line = :v_line")
.withValueMap(new ValueMap()
.withString(":v_make", "Depault")
.withString(":v_line", "SuperSawz"));
ItemCollection<QueryOutcome> items = index.query(spec);
Iterator<Item> itemsIter = items.iterator();
while (itemsIter.hasNext()) {
Item item = itemsIter.next();
System.out.println(item.toJSONPretty());
}
You can also review the following example.
Note − The following example may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources).
The following example also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project.
import java.util.ArrayList;
import java.util.Iterator;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Index;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.ItemCollection;
import com.amazonaws.services.dynamodbv2.document.PutItemOutcome;
import com.amazonaws.services.dynamodbv2.document.QueryOutcome;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndex;
import com.amazonaws.services.dynamodbv2.model.Projection;
import com.amazonaws.services.dynamodbv2.model.ProjectionType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ReturnConsumedCapacity;
import com.amazonaws.services.dynamodbv2.model.Select;
public class LocalSecondaryIndexSample {
static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
new ProfileCredentialsProvider()));
public static String tableName = "ProductOrders";
public static void main(String[] args) throws Exception {
createTable();
query(null);
query("IsOpenIndex");
query("OrderCreationDateIndex");
}
public static void createTable() {
CreateTableRequest createTableRequest = new CreateTableRequest()
.withTableName(tableName)
.withProvisionedThroughput(new ProvisionedThroughput()
.withReadCapacityUnits((long) 1)
.withWriteCapacityUnits((long) 1));
// Table partition and sort keys attributes
ArrayList<AttributeDefinition> attributeDefinitions = new
ArrayList<AttributeDefinition>();
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("CustomerID")
.withAttributeType("S"));
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("OrderID")
.withAttributeType("N"));
// Index primary key attributes
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("OrderDate")
.withAttributeType("N"));
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("OpenStatus")
.withAttributeType("N"));
createTableRequest.setAttributeDefinitions(attributeDefinitions);
// Table key schema
ArrayList<KeySchemaElement> tableKeySchema = new
ArrayList<KeySchemaElement>();
tableKeySchema.add(new KeySchemaElement()
.withAttributeName("CustomerID")
.withKeyType(KeyType.HASH)); //Partition key
tableKeySchema.add(new KeySchemaElement()
.withAttributeName("OrderID")
.withKeyType(KeyType.RANGE)); //Sort key
createTableRequest.setKeySchema(tableKeySchema);
ArrayList<LocalSecondaryIndex> localSecondaryIndexes = new
ArrayList<LocalSecondaryIndex>();
// OrderDateIndex
LocalSecondaryIndex orderDateIndex = new LocalSecondaryIndex()
.withIndexName("OrderDateIndex");
// OrderDateIndex key schema
ArrayList<KeySchemaElement> indexKeySchema = new
ArrayList<KeySchemaElement>();
indexKeySchema.add(new KeySchemaElement()
.withAttributeName("CustomerID")
.withKeyType(KeyType.HASH)); //Partition key
indexKeySchema.add(new KeySchemaElement()
.withAttributeName("OrderDate")
.withKeyType(KeyType.RANGE)); //Sort key
orderDateIndex.setKeySchema(indexKeySchema);
// OrderCreationDateIndex projection w/attributes list
Projection projection = new Projection()
.withProjectionType(ProjectionType.INCLUDE);
ArrayList<String> nonKeyAttributes = new ArrayList<String>();
nonKeyAttributes.add("ProdCat");
nonKeyAttributes.add("ProdNomenclature");
projection.setNonKeyAttributes(nonKeyAttributes);
orderCreationDateIndex.setProjection(projection);
localSecondaryIndexes.add(orderDateIndex);
// IsOpenIndex
LocalSecondaryIndex isOpenIndex = new LocalSecondaryIndex()
.withIndexName("IsOpenIndex");
// OpenStatusIndex key schema
indexKeySchema = new ArrayList<KeySchemaElement>();
indexKeySchema.add(new KeySchemaElement()
.withAttributeName("CustomerID")
.withKeyType(KeyType.HASH)); //Partition key
indexKeySchema.add(new KeySchemaElement()
.withAttributeName("OpenStatus")
.withKeyType(KeyType.RANGE)); //Sort key
// OpenStatusIndex projection
projection = new Projection() .withProjectionType(ProjectionType.ALL);
OpenStatusIndex.setKeySchema(indexKeySchema);
OpenStatusIndex.setProjection(projection);
localSecondaryIndexes.add(OpenStatusIndex);
// Put definitions in CreateTable request
createTableRequest.setLocalSecondaryIndexes(localSecondaryIndexes);
System.out.println("Spawning table " + tableName + "...");
System.out.println(dynamoDB.createTable(createTableRequest));
// Pause for ACTIVE status
System.out.println("Waiting for ACTIVE table:" + tableName);
try {
Table table = dynamoDB.getTable(tableName);
table.waitForActive();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void query(String indexName) {
Table table = dynamoDB.getTable(tableName);
System.out.println("\n*************************************************\n");
System.out.println("Executing query on" + tableName);
QuerySpec querySpec = new QuerySpec()
.withConsistentRead(true)
.withScanIndexForward(true)
.withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL);
if (indexName == "OpenStatusIndex") {
System.out.println("\nEmploying index: '" + indexName
+ "' open orders for this customer.");
System.out.println(
"Returns only user-specified attribute list\n");
Index index = table.getIndex(indexName);
querySpec.withKeyConditionExpression("CustomerID = :v_custmid and
OpenStatus = :v_openstat")
.withValueMap(new ValueMap()
.withString(":v_custmid", "jane@sample.com")
.withNumber(":v_openstat", 1));
querySpec.withProjectionExpression(
"OrderDate, ProdCat, ProdNomenclature, OrderStatus");
ItemCollection<QueryOutcome> items = index.query(querySpec);
Iterator<Item> iterator = items.iterator();
System.out.println("Printing query results...");
while (iterator.hasNext()) {
System.out.println(iterator.next().toJSONPretty());
}
} else if (indexName == "OrderDateIndex") {
System.out.println("\nUsing index: '" + indexName
+ "': this customer's orders placed after 05/22/2016.");
System.out.println("Projected attributes are returned\n");
Index index = table.getIndex(indexName);
querySpec.withKeyConditionExpression("CustomerID = :v_custmid and OrderDate
>= :v_ordrdate")
.withValueMap(new ValueMap()
.withString(":v_custmid", "jane@sample.com")
.withNumber(":v_ordrdate", 20160522));
querySpec.withSelect(Select.ALL_PROJECTED_ATTRIBUTES);
ItemCollection<QueryOutcome> items = index.query(querySpec);
Iterator<Item> iterator = items.iterator();
System.out.println("Printing query results...");
while (iterator.hasNext()) {
System.out.println(iterator.next().toJSONPretty());
}
} else {
System.out.println("\nNo index: All Jane's orders by OrderID:\n");
querySpec.withKeyConditionExpression("CustomerID = :v_custmid")
.withValueMap(new ValueMap()
.withString(":v_custmid", "jane@example.com"));
ItemCollection<QueryOutcome> items = table.query(querySpec);
Iterator<Item> iterator = items.iterator();
System.out.println("Printing query results...");
while (iterator.hasNext()) {
System.out.println(iterator.next().toJSONPretty());
}
}
}
}
16 Lectures
1.5 hours
Harshit Srivastava
49 Lectures
3.5 hours
Niyazi Erdogan
48 Lectures
3 hours
Niyazi Erdogan
13 Lectures
1 hours
Harshit Srivastava
45 Lectures
4 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2598,
"s": 2391,
"text": "Some applications only perform queries with the primary key, but some situations benefit from an alternate sort key. Allow your application a choice by creating a single or multiple local secondary indexes."
},
{
"code": null,
"e": 2935,
"s": 2598,
"text": "Complex data access requirements, such as combing millions of items, make it necessary to perform more efficient queries/scans. Local secondary indices provide an alternate sort key for a partition key value. They also hold copies of all or some table attributes. They organize data by table partition key, but use a different sort key."
},
{
"code": null,
"e": 3060,
"s": 2935,
"text": "Using a local secondary index removes the need for a whole table scan, and allows a simple and quick query using a sort key."
},
{
"code": null,
"e": 3126,
"s": 3060,
"text": "All the local secondary indexes must satisfy certain conditions −"
},
{
"code": null,
"e": 3182,
"s": 3126,
"text": "Identical partition key and source table partition key."
},
{
"code": null,
"e": 3223,
"s": 3182,
"text": "A sort key of only one scalar attribute."
},
{
"code": null,
"e": 3294,
"s": 3223,
"text": "Projection of the source table sort key acting as a non-key attribute."
},
{
"code": null,
"e": 3505,
"s": 3294,
"text": "All the local secondary indexes automatically hold partition and sort keys from parent tables. In queries, this means efficient gathering of projected attributes, and also retrieval of attributes not projected."
},
{
"code": null,
"e": 3668,
"s": 3505,
"text": "The storage limit for a local secondary index remains 10GB per partition key value, which includes all table items, and index items sharing a partition key value."
},
{
"code": null,
"e": 3963,
"s": 3668,
"text": "Some operations require excess reads/fetching due to complexity. These operations can consume substantial throughput. Projection allows you to avoid costly fetching and perform rich queries by isolating these attributes. Remember projections consist of attributes copied into a secondary index."
},
{
"code": null,
"e": 4108,
"s": 3963,
"text": "When making a secondary index, you specify the attributes projected. Recall the three options provided by DynamoDB: KEYS_ONLY, INCLUDE, and ALL."
},
{
"code": null,
"e": 4199,
"s": 4108,
"text": "When opting for certain attributes in projection, consider the associated cost tradeoffs −"
},
{
"code": null,
"e": 4299,
"s": 4199,
"text": "If you project only a small set of necessary attributes, you dramatically reduce the storage costs."
},
{
"code": null,
"e": 4399,
"s": 4299,
"text": "If you project only a small set of necessary attributes, you dramatically reduce the storage costs."
},
{
"code": null,
"e": 4496,
"s": 4399,
"text": "If you project frequently accessed non-key attributes, you offset scan costs with storage costs."
},
{
"code": null,
"e": 4593,
"s": 4496,
"text": "If you project frequently accessed non-key attributes, you offset scan costs with storage costs."
},
{
"code": null,
"e": 4736,
"s": 4593,
"text": "If you project most or all non-key attributes, this maximizes flexibility and reduces throughput (no retrievals); however, storage costs rise."
},
{
"code": null,
"e": 4879,
"s": 4736,
"text": "If you project most or all non-key attributes, this maximizes flexibility and reduces throughput (no retrievals); however, storage costs rise."
},
{
"code": null,
"e": 5008,
"s": 4879,
"text": "If you project KEYS_ONLY for frequent writes/updates and infrequent queries, it minimizes size, but maintains query preparation."
},
{
"code": null,
"e": 5137,
"s": 5008,
"text": "If you project KEYS_ONLY for frequent writes/updates and infrequent queries, it minimizes size, but maintains query preparation."
},
{
"code": null,
"e": 5395,
"s": 5137,
"text": "Use the LocalSecondaryIndex parameter of CreateTable to make a single or multiple local secondary indexes. You must specify one non-key attribute for the sort key. On table creation, you create local secondary indices. On deletion, you delete these indexes."
},
{
"code": null,
"e": 5525,
"s": 5395,
"text": "Tables with a local secondary index must obey a limit of 10GB in size per partition key value, but can store any amount of items."
},
{
"code": null,
"e": 5869,
"s": 5525,
"text": "A query operation on local secondary indexes returns all items with a matching partition key value when multiple items in the index share sort key values. Matching items do not return in a certain order. Queries for local secondary indexes use either eventual or strong consistency, with strongly consistent reads delivering the latest values."
},
{
"code": null,
"e": 6037,
"s": 5869,
"text": "A scan operation returns all local secondary index data. Scans require you to provide a table and index name, and allow the use of a filter expression to discard data."
},
{
"code": null,
"e": 6255,
"s": 6037,
"text": "On creation of a local secondary index, you specify a sort key attribute and its data type. When you write an item, its type must match the data type of the key schema if the item defines an attribute of an index key."
},
{
"code": null,
"e": 6456,
"s": 6255,
"text": "DynamoDB imposes no one-to-one relationship requirements on table items and local secondary index items. The tables with multiple local secondary indexes carry higher write costs than those with less."
},
{
"code": null,
"e": 6684,
"s": 6456,
"text": "Read capacity consumption of a query depends on the nature of data access. Queries use either eventual or strong consistency, with strongly consistent reads using one unit compared to half a unit in eventually consistent reads."
},
{
"code": null,
"e": 6886,
"s": 6684,
"text": "Result limitations include a 1MB size maximum. Result sizes come from the sum of matching index item size rounded up to the nearest 4KB, and matching table item size also rounded up to the nearest 4KB."
},
{
"code": null,
"e": 7082,
"s": 6886,
"text": "The write capacity consumption remains within provisioned units. Calculate the total provisioned cost by finding the sum of consumed units in table writing and consumed units in updating indices."
},
{
"code": null,
"e": 7161,
"s": 7082,
"text": "You can also consider the key factors influencing cost, some of which can be −"
},
{
"code": null,
"e": 7307,
"s": 7161,
"text": "When you write an item defining an indexed attribute or update an item to define an undefined indexed attribute, a single write operation occurs."
},
{
"code": null,
"e": 7453,
"s": 7307,
"text": "When you write an item defining an indexed attribute or update an item to define an undefined indexed attribute, a single write operation occurs."
},
{
"code": null,
"e": 7564,
"s": 7453,
"text": "When a table update changes an indexed key attribute value, two writes occur to delete and then – add an item."
},
{
"code": null,
"e": 7675,
"s": 7564,
"text": "When a table update changes an indexed key attribute value, two writes occur to delete and then – add an item."
},
{
"code": null,
"e": 7785,
"s": 7675,
"text": "When a write causes the deletion of an indexed attribute, one write occurs to remove the old item projection."
},
{
"code": null,
"e": 7895,
"s": 7785,
"text": "When a write causes the deletion of an indexed attribute, one write occurs to remove the old item projection."
},
{
"code": null,
"e": 7986,
"s": 7895,
"text": "When an item does not exist within the index prior to or after an update, no writes occur."
},
{
"code": null,
"e": 8077,
"s": 7986,
"text": "When an item does not exist within the index prior to or after an update, no writes occur."
},
{
"code": null,
"e": 8411,
"s": 8077,
"text": "On a table item write, DynamoDB automatically copies the right attribute set to the required local secondary indexes. This charges your account. The space used results from the sum of table primary key byte size, index key attribute byte size, any present projected attribute byte size, and 100 bytes in overhead for each index item."
},
{
"code": null,
"e": 8517,
"s": 8411,
"text": "The estimate storage is got by estimating average index item size and multiplying by table item quantity."
},
{
"code": null,
"e": 8715,
"s": 8517,
"text": "Create a local secondary index by first creating a DynamoDB class instance. Then, create a CreateTableRequest class instance with necessary request information. Finally, use the createTable method."
},
{
"code": null,
"e": 11205,
"s": 8715,
"text": "DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient( \n new ProfileCredentialsProvider()));\nString tableName = \"Tools\"; \nCreateTableRequest createTableRequest = new \n CreateTableRequest().withTableName(tableName);\n \n//Provisioned Throughput\ncreateTableRequest.setProvisionedThroughput (\n new ProvisionedThroughput()\n .withReadCapacityUnits((long)5)\n .withWriteCapacityUnits(( long)5));\n \n//Attributes \nArrayList<AttributeDefinition> attributeDefinitions = \n new ArrayList<AttributeDefinition>();\n attributeDefinitions.add(new AttributeDefinition()\n .withAttributeName(\"Make\")\n .withAttributeType(\"S\"));\n \nattributeDefinitions.add(new AttributeDefinition()\n .withAttributeName(\"Model\")\n .withAttributeType(\"S\"));\n \nattributeDefinitions.add(new AttributeDefinition()\n .withAttributeName(\"Line\")\n .withAttributeType(\"S\"));\n \ncreateTableRequest.setAttributeDefinitions(attributeDefinitions);\n\n//Key Schema \nArrayList<KeySchemaElement> tableKeySchema = new \n ArrayList<KeySchemaElement>();\n \ntableKeySchema.add(new KeySchemaElement()\n .withAttributeName(\"Make\")\n .withKeyType(KeyType.HASH)); //Partition key\n \ntableKeySchema.add(new KeySchemaElement()\n .withAttributeName(\"Model\")\n .withKeyType(KeyType.RANGE)); //Sort key\n \ncreateTableRequest.setKeySchema(tableKeySchema);\nArrayList<KeySchemaElement> indexKeySchema = new \n ArrayList<KeySchemaElement>();\n \nindexKeySchema.add(new KeySchemaElement()\n .withAttributeName(\"Make\")\n .withKeyType(KeyType.HASH)); //Partition key\n \nindexKeySchema.add(new KeySchemaElement()\n .withAttributeName(\"Line\")\n .withKeyType(KeyType.RANGE)); //Sort key\n \nProjection projection = new Projection()\n .withProjectionType(ProjectionType.INCLUDE);\n\nArrayList<String> nonKeyAttributes = new ArrayList<String>(); \nnonKeyAttributes.add(\"Type\"); \nnonKeyAttributes.add(\"Year\"); \nprojection.setNonKeyAttributes(nonKeyAttributes); \n\nLocalSecondaryIndex localSecondaryIndex = new LocalSecondaryIndex() \n .withIndexName(\"ModelIndex\")\n .withKeySchema(indexKeySchema)\n .withProjection(p rojection); \n\nArrayList<LocalSecondaryIndex> localSecondaryIndexes = new \n ArrayList<LocalSecondaryIndex>(); \n\nlocalSecondaryIndexes.add(localSecondaryIndex); \ncreateTableRequest.setLocalSecondaryIndexes(localSecondaryIndexes); \nTable table = dynamoDB.createTable(createTableRequest); \nSystem.out.println(table.getDescription());"
},
{
"code": null,
"e": 11397,
"s": 11205,
"text": "Retrieve information about a local secondary index with the describe method. Simply create a DynamoDB class instance, create a Table class instance, and pass the table to the describe method."
},
{
"code": null,
"e": 12598,
"s": 11397,
"text": "DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient( \n new ProfileCredentialsProvider()));\n \nString tableName = \"Tools\";\nTable table = dynamoDB.getTable(tableName);\nTableDescription tableDescription = table.describe();\n\nList<LocalSecondaryIndexDescription> localSecondaryIndexes = \n tableDescription.getLocalSecondaryIndexes();\n \nIterator<LocalSecondaryIndexDescription> lsiIter = \n localSecondaryIndexes.iterator();\n \nwhile (lsiIter.hasNext()) { \n LocalSecondaryIndexDescription lsiDescription = lsiIter.next(); \n System.out.println(\"Index info \" + lsiDescription.getIndexName() + \":\"); \n Iterator<KeySchemaElement> kseIter = lsiDescription.getKeySchema().iterator(); \n \n while (kseIter.hasNext()) { \n KeySchemaElement kse = kseIter.next(); \n System.out.printf(\"\\t%s: %s\\n\", kse.getAttributeName(), kse.getKeyType()); \n }\n \n Projection projection = lsiDescription.getProjection(); \n System.out.println(\"\\tProjection type: \" + projection.getProjectionType()); \n \n if (projection.getProjectionType().toString().equals(\"INCLUDE\")) { \n System.out.println(\"\\t\\tNon-key projected attributes: \" + \n projection.getNonKeyAttributes()); \n } \n}"
},
{
"code": null,
"e": 12792,
"s": 12598,
"text": "Perform a query by using the same steps as a table query. Merely create a DynamoDB class instance, a Table class instance, an Index class instance, a query object, and utilize the query method."
},
{
"code": null,
"e": 13451,
"s": 12792,
"text": "DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient( \n new ProfileCredentialsProvider()));\n \nString tableName = \"Tools\"; \nTable table = dynamoDB.getTable(tableName); \nIndex index = table.getIndex(\"LineIndex\"); \nQuerySpec spec = new QuerySpec() \n .withKeyConditionExpression(\"Make = :v_make and Line = :v_line\") \n .withValueMap(new ValueMap() \n .withString(\":v_make\", \"Depault\") \n .withString(\":v_line\", \"SuperSawz\"));\n \nItemCollection<QueryOutcome> items = index.query(spec);\nIterator<Item> itemsIter = items.iterator();\n\nwhile (itemsIter.hasNext()) { \n Item item = itemsIter.next(); \n System.out.println(item.toJSONPretty()); \n}"
},
{
"code": null,
"e": 13494,
"s": 13451,
"text": "You can also review the following example."
},
{
"code": null,
"e": 13730,
"s": 13494,
"text": "Note − The following example may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources)."
},
{
"code": null,
"e": 13856,
"s": 13730,
"text": "The following example also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project."
},
{
"code": null,
"e": 23101,
"s": 13856,
"text": "import java.util.ArrayList;\nimport java.util.Iterator;\n\nimport com.amazonaws.auth.profile.ProfileCredentialsProvider;\nimport com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;\n\nimport com.amazonaws.services.dynamodbv2.document.DynamoDB;\nimport com.amazonaws.services.dynamodbv2.document.Index;\nimport com.amazonaws.services.dynamodbv2.document.Item;\nimport com.amazonaws.services.dynamodbv2.document.ItemCollection;\nimport com.amazonaws.services.dynamodbv2.document.PutItemOutcome;\nimport com.amazonaws.services.dynamodbv2.document.QueryOutcome;\nimport com.amazonaws.services.dynamodbv2.document.Table;\nimport com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;\nimport com.amazonaws.services.dynamodbv2.document.utils.ValueMap;\n\nimport com.amazonaws.services.dynamodbv2.model.AttributeDefinition;\nimport com.amazonaws.services.dynamodbv2.model.CreateTableRequest;\nimport com.amazonaws.services.dynamodbv2.model.KeySchemaElement;\nimport com.amazonaws.services.dynamodbv2.model.KeyType;\nimport com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndex;\nimport com.amazonaws.services.dynamodbv2.model.Projection;\nimport com.amazonaws.services.dynamodbv2.model.ProjectionType;\nimport com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;\nimport com.amazonaws.services.dynamodbv2.model.ReturnConsumedCapacity;\nimport com.amazonaws.services.dynamodbv2.model.Select;\n\npublic class LocalSecondaryIndexSample { \n static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient( \n new ProfileCredentialsProvider())); \n public static String tableName = \"ProductOrders\"; \n \n public static void main(String[] args) throws Exception { \n createTable();\n query(null); \n query(\"IsOpenIndex\"); \n query(\"OrderCreationDateIndex\"); \n }\n public static void createTable() { \n CreateTableRequest createTableRequest = new CreateTableRequest() \n .withTableName(tableName) \n .withProvisionedThroughput(new ProvisionedThroughput() \n .withReadCapacityUnits((long) 1) \n .withWriteCapacityUnits((long) 1));\n \n // Table partition and sort keys attributes \n ArrayList<AttributeDefinition> attributeDefinitions = new \n ArrayList<AttributeDefinition>(); \n \n attributeDefinitions.add(new AttributeDefinition() \n .withAttributeName(\"CustomerID\") \n .withAttributeType(\"S\"));\n \n attributeDefinitions.add(new AttributeDefinition() \n .withAttributeName(\"OrderID\") \n .withAttributeType(\"N\"));\n \n // Index primary key attributes \n attributeDefinitions.add(new AttributeDefinition() \n .withAttributeName(\"OrderDate\") \n .withAttributeType(\"N\"));\n \n attributeDefinitions.add(new AttributeDefinition() \n .withAttributeName(\"OpenStatus\") \n .withAttributeType(\"N\")); \n createTableRequest.setAttributeDefinitions(attributeDefinitions);\n \n // Table key schema \n ArrayList<KeySchemaElement> tableKeySchema = new\n ArrayList<KeySchemaElement>(); \n tableKeySchema.add(new KeySchemaElement() \n .withAttributeName(\"CustomerID\") \n .withKeyType(KeyType.HASH)); //Partition key\n \n tableKeySchema.add(new KeySchemaElement() \n .withAttributeName(\"OrderID\") \n .withKeyType(KeyType.RANGE)); //Sort key\n \n createTableRequest.setKeySchema(tableKeySchema); \n ArrayList<LocalSecondaryIndex> localSecondaryIndexes = new \n ArrayList<LocalSecondaryIndex>(); \n \n // OrderDateIndex \n LocalSecondaryIndex orderDateIndex = new LocalSecondaryIndex() \n .withIndexName(\"OrderDateIndex\");\n \n // OrderDateIndex key schema \n ArrayList<KeySchemaElement> indexKeySchema = new \n ArrayList<KeySchemaElement>(); \n indexKeySchema.add(new KeySchemaElement() \n .withAttributeName(\"CustomerID\") \n .withKeyType(KeyType.HASH)); //Partition key\n \n indexKeySchema.add(new KeySchemaElement() \n .withAttributeName(\"OrderDate\") \n .withKeyType(KeyType.RANGE)); //Sort key\n orderDateIndex.setKeySchema(indexKeySchema);\n \n // OrderCreationDateIndex projection w/attributes list \n Projection projection = new Projection() \n .withProjectionType(ProjectionType.INCLUDE); \n \n ArrayList<String> nonKeyAttributes = new ArrayList<String>(); \n nonKeyAttributes.add(\"ProdCat\"); \n nonKeyAttributes.add(\"ProdNomenclature\"); \n projection.setNonKeyAttributes(nonKeyAttributes);\n orderCreationDateIndex.setProjection(projection); \n localSecondaryIndexes.add(orderDateIndex); \n \n // IsOpenIndex \n LocalSecondaryIndex isOpenIndex = new LocalSecondaryIndex() \n .withIndexName(\"IsOpenIndex\"); \n \n // OpenStatusIndex key schema \n indexKeySchema = new ArrayList<KeySchemaElement>(); \n indexKeySchema.add(new KeySchemaElement() \n .withAttributeName(\"CustomerID\") \n .withKeyType(KeyType.HASH)); //Partition key\n \n indexKeySchema.add(new KeySchemaElement() \n .withAttributeName(\"OpenStatus\") \n .withKeyType(KeyType.RANGE)); //Sort key\n \n // OpenStatusIndex projection \n projection = new Projection() .withProjectionType(ProjectionType.ALL); \n OpenStatusIndex.setKeySchema(indexKeySchema); \n OpenStatusIndex.setProjection(projection); \n localSecondaryIndexes.add(OpenStatusIndex); \n \n // Put definitions in CreateTable request \n createTableRequest.setLocalSecondaryIndexes(localSecondaryIndexes); \n System.out.println(\"Spawning table \" + tableName + \"...\"); \n System.out.println(dynamoDB.createTable(createTableRequest)); \n \n // Pause for ACTIVE status \n System.out.println(\"Waiting for ACTIVE table:\" + tableName); \n try { \n Table table = dynamoDB.getTable(tableName);\n table.waitForActive(); \n } catch (InterruptedException e) { \n e.printStackTrace(); \n } \n }\n public static void query(String indexName) { \n Table table = dynamoDB.getTable(tableName); \n System.out.println(\"\\n*************************************************\\n\"); \n System.out.println(\"Executing query on\" + tableName); \n QuerySpec querySpec = new QuerySpec() \n .withConsistentRead(true) \n .withScanIndexForward(true) \n .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL);\n \n if (indexName == \"OpenStatusIndex\") { \n System.out.println(\"\\nEmploying index: '\" + indexName \n + \"' open orders for this customer.\");\n \n System.out.println( \n \"Returns only user-specified attribute list\\n\"); \n Index index = table.getIndex(indexName); \n \n querySpec.withKeyConditionExpression(\"CustomerID = :v_custmid and \n OpenStatus = :v_openstat\") \n .withValueMap(new ValueMap() \n .withString(\":v_custmid\", \"jane@sample.com\") \n .withNumber(\":v_openstat\", 1)); \n \n querySpec.withProjectionExpression( \n \"OrderDate, ProdCat, ProdNomenclature, OrderStatus\"); \n ItemCollection<QueryOutcome> items = index.query(querySpec); \n Iterator<Item> iterator = items.iterator(); \n System.out.println(\"Printing query results...\"); \n \n while (iterator.hasNext()) { \n System.out.println(iterator.next().toJSONPretty()); \n } \n } else if (indexName == \"OrderDateIndex\") { \n System.out.println(\"\\nUsing index: '\" + indexName \n + \"': this customer's orders placed after 05/22/2016.\"); \n System.out.println(\"Projected attributes are returned\\n\"); \n Index index = table.getIndex(indexName); \n \n querySpec.withKeyConditionExpression(\"CustomerID = :v_custmid and OrderDate \n >= :v_ordrdate\") \n .withValueMap(new ValueMap() \n .withString(\":v_custmid\", \"jane@sample.com\") \n .withNumber(\":v_ordrdate\", 20160522));\n \n querySpec.withSelect(Select.ALL_PROJECTED_ATTRIBUTES); \n ItemCollection<QueryOutcome> items = index.query(querySpec); \n Iterator<Item> iterator = items.iterator(); \n System.out.println(\"Printing query results...\"); \n \n while (iterator.hasNext()) { \n System.out.println(iterator.next().toJSONPretty()); \n } \n } else { \n System.out.println(\"\\nNo index: All Jane's orders by OrderID:\\n\"); \n querySpec.withKeyConditionExpression(\"CustomerID = :v_custmid\") \n .withValueMap(new ValueMap()\n .withString(\":v_custmid\", \"jane@example.com\")); \n \n ItemCollection<QueryOutcome> items = table.query(querySpec); \n Iterator<Item> iterator = items.iterator(); \n System.out.println(\"Printing query results...\"); \n \n while (iterator.hasNext()) { \n System.out.println(iterator.next().toJSONPretty()); \n } \n } \n } \n}"
},
{
"code": null,
"e": 23136,
"s": 23101,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 23156,
"s": 23136,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 23191,
"s": 23156,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 23207,
"s": 23191,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 23240,
"s": 23207,
"text": "\n 48 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 23256,
"s": 23240,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 23289,
"s": 23256,
"text": "\n 13 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 23309,
"s": 23289,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 23342,
"s": 23309,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 23382,
"s": 23342,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 23389,
"s": 23382,
"text": " Print"
},
{
"code": null,
"e": 23400,
"s": 23389,
"text": " Add Notes"
}
] |
Create an N-Gram Ranking in Power BI | by Ednalyn C. De Dios | Towards Data Science
|
In a previous article, I wrote a quick start guide on creating and visualizing n-gram ranking using nltk for natural language processing. However, I needed a way to share my findings with others who don’t have Python or Jupyter Notebook installed in their machines. I needed to use our organization’s BI reporting tool: Power BI.
Enter Python Visual.
The Python visual allows you to create a visualization generated by running Python code. In this post, we’ll walk through the steps needed to visualize the results of our n-gram ranking using this visual.
First, let’s get our data. You can download the sample dataset here. Then, we could load the data into Power BI Desktop as shown below:
Select Text/CSV and click on “Connect”.
Select the file in the Windows Explorer folder and click open:
Click on “Load”.
Next, find the Py icon on the “Visualizations” panel.
Then, click on “Enable” at the prompt that appears to enable script visuals.
You’ll see a placeholder appear in the main area and a Python script editor panel at the bottom of the dashboard.
Select the ‘text’ column on the “Fields” panel.
You’ll see a predefined script that serves as a preamble for the script that we’re going to write.
In the Python script editor panel, place your cursor at the end of line #6 and hit enter twice.
Then, copy and paste the following code:
import reimport unicodedataimport nltkfrom nltk.corpus import stopwordsADDITIONAL_STOPWORDS = ['covfefe']import matplotlib.pyplot as pltdef basic_clean(text): wnl = nltk.stem.WordNetLemmatizer() stopwords = nltk.corpus.stopwords.words('english') + ADDITIONAL_STOPWORDS text = (unicodedata.normalize('NFKD', text) .encode('ascii', 'ignore') .decode('utf-8', 'ignore') .lower()) words = re.sub(r'[^\w\s]', '', text).split() return [wnl.lemmatize(word) for word in words if word not in stopwords]words = basic_clean(''.join(str(dataset['text'].tolist())))bigrams_series = (pandas.Series(nltk.ngrams(words, 2)).value_counts())[:12]bigrams_series.sort_values().plot.barh(color='blue', width=.9, figsize=(12, 8))plt.show()
In a nutshell, the code above transforms extracts n-grams from the 'text' column of thedataset dataframe and creates a horizontal bar graph out of it using matplotlib. The result of plt.show() is what Power BI displays on the Python visual.
For more information on this code, please visit my previous tutorial.
towardsdatascience.com
After you’re done pasting the code, click on the “play” icon at the upper right corner of the Python script editor panel.
After a few moments, you should now be able to see the horizontal bar graph like the one below:
And that’s it!
With a few simple clicks of the mouse, along with some help from our Python script, we’re able to visualize the results of our n-gram ranking.
I hope you enjoyed today’s post on one of Power BI’s strongest features. Power BI already has some useful and beautiful built-in visuals but sometimes, you just need a little bit more flexibility. Running Python code helps with this. I hope this gentle introduction will encourage you to explore more and expand your repertoire.
In the next article, I’ll share a quick-start guide to extracting named-entities from a Pandas dataframe using spaCy.
Stay tuned!
You can reach me on Twitter or LinkedIn.
|
[
{
"code": null,
"e": 502,
"s": 172,
"text": "In a previous article, I wrote a quick start guide on creating and visualizing n-gram ranking using nltk for natural language processing. However, I needed a way to share my findings with others who don’t have Python or Jupyter Notebook installed in their machines. I needed to use our organization’s BI reporting tool: Power BI."
},
{
"code": null,
"e": 523,
"s": 502,
"text": "Enter Python Visual."
},
{
"code": null,
"e": 728,
"s": 523,
"text": "The Python visual allows you to create a visualization generated by running Python code. In this post, we’ll walk through the steps needed to visualize the results of our n-gram ranking using this visual."
},
{
"code": null,
"e": 864,
"s": 728,
"text": "First, let’s get our data. You can download the sample dataset here. Then, we could load the data into Power BI Desktop as shown below:"
},
{
"code": null,
"e": 904,
"s": 864,
"text": "Select Text/CSV and click on “Connect”."
},
{
"code": null,
"e": 967,
"s": 904,
"text": "Select the file in the Windows Explorer folder and click open:"
},
{
"code": null,
"e": 984,
"s": 967,
"text": "Click on “Load”."
},
{
"code": null,
"e": 1038,
"s": 984,
"text": "Next, find the Py icon on the “Visualizations” panel."
},
{
"code": null,
"e": 1115,
"s": 1038,
"text": "Then, click on “Enable” at the prompt that appears to enable script visuals."
},
{
"code": null,
"e": 1229,
"s": 1115,
"text": "You’ll see a placeholder appear in the main area and a Python script editor panel at the bottom of the dashboard."
},
{
"code": null,
"e": 1277,
"s": 1229,
"text": "Select the ‘text’ column on the “Fields” panel."
},
{
"code": null,
"e": 1376,
"s": 1277,
"text": "You’ll see a predefined script that serves as a preamble for the script that we’re going to write."
},
{
"code": null,
"e": 1472,
"s": 1376,
"text": "In the Python script editor panel, place your cursor at the end of line #6 and hit enter twice."
},
{
"code": null,
"e": 1513,
"s": 1472,
"text": "Then, copy and paste the following code:"
},
{
"code": null,
"e": 2244,
"s": 1513,
"text": "import reimport unicodedataimport nltkfrom nltk.corpus import stopwordsADDITIONAL_STOPWORDS = ['covfefe']import matplotlib.pyplot as pltdef basic_clean(text): wnl = nltk.stem.WordNetLemmatizer() stopwords = nltk.corpus.stopwords.words('english') + ADDITIONAL_STOPWORDS text = (unicodedata.normalize('NFKD', text) .encode('ascii', 'ignore') .decode('utf-8', 'ignore') .lower()) words = re.sub(r'[^\\w\\s]', '', text).split() return [wnl.lemmatize(word) for word in words if word not in stopwords]words = basic_clean(''.join(str(dataset['text'].tolist())))bigrams_series = (pandas.Series(nltk.ngrams(words, 2)).value_counts())[:12]bigrams_series.sort_values().plot.barh(color='blue', width=.9, figsize=(12, 8))plt.show()"
},
{
"code": null,
"e": 2485,
"s": 2244,
"text": "In a nutshell, the code above transforms extracts n-grams from the 'text' column of thedataset dataframe and creates a horizontal bar graph out of it using matplotlib. The result of plt.show() is what Power BI displays on the Python visual."
},
{
"code": null,
"e": 2555,
"s": 2485,
"text": "For more information on this code, please visit my previous tutorial."
},
{
"code": null,
"e": 2578,
"s": 2555,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2700,
"s": 2578,
"text": "After you’re done pasting the code, click on the “play” icon at the upper right corner of the Python script editor panel."
},
{
"code": null,
"e": 2796,
"s": 2700,
"text": "After a few moments, you should now be able to see the horizontal bar graph like the one below:"
},
{
"code": null,
"e": 2811,
"s": 2796,
"text": "And that’s it!"
},
{
"code": null,
"e": 2954,
"s": 2811,
"text": "With a few simple clicks of the mouse, along with some help from our Python script, we’re able to visualize the results of our n-gram ranking."
},
{
"code": null,
"e": 3283,
"s": 2954,
"text": "I hope you enjoyed today’s post on one of Power BI’s strongest features. Power BI already has some useful and beautiful built-in visuals but sometimes, you just need a little bit more flexibility. Running Python code helps with this. I hope this gentle introduction will encourage you to explore more and expand your repertoire."
},
{
"code": null,
"e": 3401,
"s": 3283,
"text": "In the next article, I’ll share a quick-start guide to extracting named-entities from a Pandas dataframe using spaCy."
},
{
"code": null,
"e": 3413,
"s": 3401,
"text": "Stay tuned!"
}
] |
Rich: Generate Rich and Beautiful Text in the Terminal with Python | by Khuyen Tran | Towards Data Science
|
After developing a useful Python package or a useful function, you might wish for your teammates or other users to use your code. However, the output of your code in the terminal is a little bit boring and is confusing to understand.
Is there a way that you can make the output clearer and prettier like below?
That is when Rich comes in handy. Besides beautiful printing, Rich also allows you to:
Produce a beautiful report on any Python object
Debug the output of your function
Create a tree to display a file structure
Create progress bars and status
Create beautiful columns
In this tutorial, I will show you how to do everything mentioned above in a few lines of Python code.
To install Rich, type
pip install rich
To have a quick summary of Rich’s functionalities, type
python -m rich
The outputs are pretty! But how can we reproduce the output like above?
Rich makes it easy to debug with the pretty print function. While icecream allows you to view the code that produces the output, Rich highlights the output based on its datatype.
In the output above, different outputs were highlighted with different colors based on their datatypes. This output is not only pretty but is also useful for debugging when there are many outputs with different datatypes.
Scenerio: You are not sure about the functionalities of the Python object you are using. Instead of searching on Google, you want to have a quick overview of the Python object in your terminal. This could be done using help()
However, the output is quite long and difficult to read.
Luckily, Rich provides inspect , which makes it much easier to view documentation of a Python object within your terminal.
Now you know which datasets are provided withinsklearn.datasets and how to use them!
Scenerio: You want to know which elements in the function created a certain output. So you print every variable in the function.
Solution: You can simply use Console object to print both the output and all the variables in the function.
You can view relevant details that produce the output of your function by simply using console.log ! This will make it easier for you to detect any mistakes in your code and fix them accordingly.
If we want to know the structure of a directory, viewing the directory tree structure can be really helpful. Rich allows us to do so using Tree object.
For example, if our data directory contains 2 types of data: data1 and data2 , we can add these 2 files to the parent directory using tree.add method
Under data2 , we have 3 other files. We can add them to data2 using the same approach as above. But to make it more interesting, we will also add color to our string using ['color_name]your_text'
Now we have a neat tree structure with different colors for different leaves!
It is often useful to know the progress or status of our code. Rich allows us to create a progress bar using progress.track method.
If we want to record the time when a particular task is finished executing, we can use console.status instead
Isn’t it cool? If you don’t like the current spinner, you can search for other spinner options using:
python -m rich.spinner
Then change the default spinner by specifying a different value for spinner parameter inside the console.status method.
Instead of viewing many features in a dataset at once, you might just want to compare the relationship between 2 different features. Rich allows you to view many rows of data at once using neat columns with equal width.
We will download Open ML’s Speed Dating dataset to view the relationship between the age difference between 2 people and whether they matched or not.
Congratulations! You have just learned how to generate beautiful terminal outputs using a few lines of Python code. We all love the Python packages that are cool to look at in the terminal while we’re waiting for the package to do its work.
I hope this article will give you ideas on how to make your workflow more efficient and to develop a package with a cool user interface. I encourage you to explore Rich to learn other features that I didn’t mention in this article.
Feel free to fork and play with the source code of this article here.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
|
[
{
"code": null,
"e": 405,
"s": 171,
"text": "After developing a useful Python package or a useful function, you might wish for your teammates or other users to use your code. However, the output of your code in the terminal is a little bit boring and is confusing to understand."
},
{
"code": null,
"e": 482,
"s": 405,
"text": "Is there a way that you can make the output clearer and prettier like below?"
},
{
"code": null,
"e": 569,
"s": 482,
"text": "That is when Rich comes in handy. Besides beautiful printing, Rich also allows you to:"
},
{
"code": null,
"e": 617,
"s": 569,
"text": "Produce a beautiful report on any Python object"
},
{
"code": null,
"e": 651,
"s": 617,
"text": "Debug the output of your function"
},
{
"code": null,
"e": 693,
"s": 651,
"text": "Create a tree to display a file structure"
},
{
"code": null,
"e": 725,
"s": 693,
"text": "Create progress bars and status"
},
{
"code": null,
"e": 750,
"s": 725,
"text": "Create beautiful columns"
},
{
"code": null,
"e": 852,
"s": 750,
"text": "In this tutorial, I will show you how to do everything mentioned above in a few lines of Python code."
},
{
"code": null,
"e": 874,
"s": 852,
"text": "To install Rich, type"
},
{
"code": null,
"e": 891,
"s": 874,
"text": "pip install rich"
},
{
"code": null,
"e": 947,
"s": 891,
"text": "To have a quick summary of Rich’s functionalities, type"
},
{
"code": null,
"e": 962,
"s": 947,
"text": "python -m rich"
},
{
"code": null,
"e": 1034,
"s": 962,
"text": "The outputs are pretty! But how can we reproduce the output like above?"
},
{
"code": null,
"e": 1213,
"s": 1034,
"text": "Rich makes it easy to debug with the pretty print function. While icecream allows you to view the code that produces the output, Rich highlights the output based on its datatype."
},
{
"code": null,
"e": 1435,
"s": 1213,
"text": "In the output above, different outputs were highlighted with different colors based on their datatypes. This output is not only pretty but is also useful for debugging when there are many outputs with different datatypes."
},
{
"code": null,
"e": 1661,
"s": 1435,
"text": "Scenerio: You are not sure about the functionalities of the Python object you are using. Instead of searching on Google, you want to have a quick overview of the Python object in your terminal. This could be done using help()"
},
{
"code": null,
"e": 1718,
"s": 1661,
"text": "However, the output is quite long and difficult to read."
},
{
"code": null,
"e": 1841,
"s": 1718,
"text": "Luckily, Rich provides inspect , which makes it much easier to view documentation of a Python object within your terminal."
},
{
"code": null,
"e": 1926,
"s": 1841,
"text": "Now you know which datasets are provided withinsklearn.datasets and how to use them!"
},
{
"code": null,
"e": 2055,
"s": 1926,
"text": "Scenerio: You want to know which elements in the function created a certain output. So you print every variable in the function."
},
{
"code": null,
"e": 2163,
"s": 2055,
"text": "Solution: You can simply use Console object to print both the output and all the variables in the function."
},
{
"code": null,
"e": 2359,
"s": 2163,
"text": "You can view relevant details that produce the output of your function by simply using console.log ! This will make it easier for you to detect any mistakes in your code and fix them accordingly."
},
{
"code": null,
"e": 2511,
"s": 2359,
"text": "If we want to know the structure of a directory, viewing the directory tree structure can be really helpful. Rich allows us to do so using Tree object."
},
{
"code": null,
"e": 2661,
"s": 2511,
"text": "For example, if our data directory contains 2 types of data: data1 and data2 , we can add these 2 files to the parent directory using tree.add method"
},
{
"code": null,
"e": 2857,
"s": 2661,
"text": "Under data2 , we have 3 other files. We can add them to data2 using the same approach as above. But to make it more interesting, we will also add color to our string using ['color_name]your_text'"
},
{
"code": null,
"e": 2935,
"s": 2857,
"text": "Now we have a neat tree structure with different colors for different leaves!"
},
{
"code": null,
"e": 3067,
"s": 2935,
"text": "It is often useful to know the progress or status of our code. Rich allows us to create a progress bar using progress.track method."
},
{
"code": null,
"e": 3177,
"s": 3067,
"text": "If we want to record the time when a particular task is finished executing, we can use console.status instead"
},
{
"code": null,
"e": 3279,
"s": 3177,
"text": "Isn’t it cool? If you don’t like the current spinner, you can search for other spinner options using:"
},
{
"code": null,
"e": 3302,
"s": 3279,
"text": "python -m rich.spinner"
},
{
"code": null,
"e": 3422,
"s": 3302,
"text": "Then change the default spinner by specifying a different value for spinner parameter inside the console.status method."
},
{
"code": null,
"e": 3642,
"s": 3422,
"text": "Instead of viewing many features in a dataset at once, you might just want to compare the relationship between 2 different features. Rich allows you to view many rows of data at once using neat columns with equal width."
},
{
"code": null,
"e": 3792,
"s": 3642,
"text": "We will download Open ML’s Speed Dating dataset to view the relationship between the age difference between 2 people and whether they matched or not."
},
{
"code": null,
"e": 4033,
"s": 3792,
"text": "Congratulations! You have just learned how to generate beautiful terminal outputs using a few lines of Python code. We all love the Python packages that are cool to look at in the terminal while we’re waiting for the package to do its work."
},
{
"code": null,
"e": 4265,
"s": 4033,
"text": "I hope this article will give you ideas on how to make your workflow more efficient and to develop a package with a cool user interface. I encourage you to explore Rich to learn other features that I didn’t mention in this article."
},
{
"code": null,
"e": 4335,
"s": 4265,
"text": "Feel free to fork and play with the source code of this article here."
},
{
"code": null,
"e": 4495,
"s": 4335,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
] |
MySQL Tryit Editor v1.0
|
SELECT OrderID, Quantity,
CASE WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
|
[
{
"code": null,
"e": 26,
"s": 0,
"text": "SELECT OrderID, Quantity,"
},
{
"code": null,
"e": 89,
"s": 26,
"text": "CASE WHEN Quantity > 30 THEN 'The quantity is greater than 30'"
},
{
"code": null,
"e": 134,
"s": 89,
"text": "WHEN Quantity = 30 THEN 'The quantity is 30'"
},
{
"code": null,
"e": 166,
"s": 134,
"text": "ELSE 'The quantity is under 30'"
},
{
"code": null,
"e": 186,
"s": 166,
"text": "END AS QuantityText"
},
{
"code": null,
"e": 205,
"s": 186,
"text": "FROM OrderDetails;"
},
{
"code": null,
"e": 207,
"s": 205,
"text": ""
},
{
"code": null,
"e": 279,
"s": 216,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 339,
"s": 279,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 407,
"s": 339,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 445,
"s": 407,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 530,
"s": 445,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 704,
"s": 530,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 755,
"s": 704,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 823,
"s": 755,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 994,
"s": 823,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 1094,
"s": 994,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 1144,
"s": 1094,
"text": "WebSQL is supported in Chrome, Safari, and Opera."
}
] |
Python program for most frequent word in Strings List - GeeksforGeeks
|
04 Oct, 2021
Given Strings List, write a Python program to get word with most number of occurrences.
Example:
Input : test_list = [“gfg is best for geeks”, “geeks love gfg”, “gfg is best”] Output : gfg Explanation : gfg occurs 3 times, most in strings in total.
Input : test_list = [“geeks love gfg”, “geeks are best”] Output : geeks Explanation : geeks occurs 2 times, most in strings in total.
Method #1 : Using loop + max() + split() + defaultdict()
In this, we perform task of getting each word using split(), and increase its frequency by memorizing it using defaultdict(). At last, max(), is used with parameter to get count of maximum frequency string.
Python3
# Python3 code to demonstrate working of# Most frequent word in Strings List# Using loop + max() + split() + defaultdict()from collections import defaultdict # initializing Matrixtest_list = ["gfg is best for geeks", "geeks love gfg", "gfg is best"] # printing original listprint("The original list is : " + str(test_list)) temp = defaultdict(int) # memoizing countfor sub in test_list: for wrd in sub.split(): temp[wrd] += 1 # getting max frequencyres = max(temp, key=temp.get) # printing resultprint("Word with maximum frequency : " + str(res))
Output:
The original list is : ['gfg is best for geeks', 'geeks love gfg', 'gfg is best']
Word with maximum frequency : gfg
Method #2 : Using list comprehension + mode()
In this, we get all the words using list comprehension and get maximum frequency using mode().
Python3
# Python3 code to demonstrate working of# Most frequent word in Strings List# Using list comprehension + mode()from statistics import mode # initializing Matrixtest_list = ["gfg is best for geeks", "geeks love gfg", "gfg is best"] # printing original listprint("The original list is : " + str(test_list)) # getting all wordstemp = [wrd for sub in test_list for wrd in sub.split()] # getting frequencyres = mode(temp) # printing resultprint("Word with maximum frequency : " + str(res))
Output:
The original list is : ['gfg is best for geeks', 'geeks love gfg', 'gfg is best']
Word with maximum frequency : gfg
Append all words to empty list and calculate frequency of all words using Counter() function.
Find max count and print that key.
Below is the implementation:
Python3
# Python3 code to demonstrate working of# Most frequent word in Strings List from collections import Counter # function which returns# most frequent worddef mostFrequentWord(words): # Taking empty list lis = [] for i in words: # Getting all words for j in i.split(): lis.append(j) # Calculating frequency of all words freq = Counter(lis) # find max count and print that key max = 0 for i in freq: if(freq[i] > max): max = freq[i] word = i return word # Driver code# initializing strings listwords = ["gfg is best for geeks", "geeks love gfg", "gfg is best"] # printing original listprint("The original list is : " + str(words)) # passing this words to mostFrequencyWord function# printing resultprint("Word with maximum frequency : " + mostFrequentWord(words))# This code is contributed by vikkycirus
Output:
The original list is : ['gfg is best for geeks', 'geeks love gfg', 'gfg is best']
Word with maximum frequency : gfg
vikkycirus
simranarora5sos
sooda367
simmytarika5
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 24735,
"s": 24707,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 24823,
"s": 24735,
"text": "Given Strings List, write a Python program to get word with most number of occurrences."
},
{
"code": null,
"e": 24832,
"s": 24823,
"text": "Example:"
},
{
"code": null,
"e": 24984,
"s": 24832,
"text": "Input : test_list = [“gfg is best for geeks”, “geeks love gfg”, “gfg is best”] Output : gfg Explanation : gfg occurs 3 times, most in strings in total."
},
{
"code": null,
"e": 25119,
"s": 24984,
"text": "Input : test_list = [“geeks love gfg”, “geeks are best”] Output : geeks Explanation : geeks occurs 2 times, most in strings in total. "
},
{
"code": null,
"e": 25176,
"s": 25119,
"text": "Method #1 : Using loop + max() + split() + defaultdict()"
},
{
"code": null,
"e": 25383,
"s": 25176,
"text": "In this, we perform task of getting each word using split(), and increase its frequency by memorizing it using defaultdict(). At last, max(), is used with parameter to get count of maximum frequency string."
},
{
"code": null,
"e": 25391,
"s": 25383,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Most frequent word in Strings List# Using loop + max() + split() + defaultdict()from collections import defaultdict # initializing Matrixtest_list = [\"gfg is best for geeks\", \"geeks love gfg\", \"gfg is best\"] # printing original listprint(\"The original list is : \" + str(test_list)) temp = defaultdict(int) # memoizing countfor sub in test_list: for wrd in sub.split(): temp[wrd] += 1 # getting max frequencyres = max(temp, key=temp.get) # printing resultprint(\"Word with maximum frequency : \" + str(res))",
"e": 25948,
"s": 25391,
"text": null
},
{
"code": null,
"e": 25956,
"s": 25948,
"text": "Output:"
},
{
"code": null,
"e": 26072,
"s": 25956,
"text": "The original list is : ['gfg is best for geeks', 'geeks love gfg', 'gfg is best']\nWord with maximum frequency : gfg"
},
{
"code": null,
"e": 26118,
"s": 26072,
"text": "Method #2 : Using list comprehension + mode()"
},
{
"code": null,
"e": 26213,
"s": 26118,
"text": "In this, we get all the words using list comprehension and get maximum frequency using mode()."
},
{
"code": null,
"e": 26221,
"s": 26213,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Most frequent word in Strings List# Using list comprehension + mode()from statistics import mode # initializing Matrixtest_list = [\"gfg is best for geeks\", \"geeks love gfg\", \"gfg is best\"] # printing original listprint(\"The original list is : \" + str(test_list)) # getting all wordstemp = [wrd for sub in test_list for wrd in sub.split()] # getting frequencyres = mode(temp) # printing resultprint(\"Word with maximum frequency : \" + str(res))",
"e": 26706,
"s": 26221,
"text": null
},
{
"code": null,
"e": 26714,
"s": 26706,
"text": "Output:"
},
{
"code": null,
"e": 26830,
"s": 26714,
"text": "The original list is : ['gfg is best for geeks', 'geeks love gfg', 'gfg is best']\nWord with maximum frequency : gfg"
},
{
"code": null,
"e": 26924,
"s": 26830,
"text": "Append all words to empty list and calculate frequency of all words using Counter() function."
},
{
"code": null,
"e": 26959,
"s": 26924,
"text": "Find max count and print that key."
},
{
"code": null,
"e": 26988,
"s": 26959,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 26996,
"s": 26988,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Most frequent word in Strings List from collections import Counter # function which returns# most frequent worddef mostFrequentWord(words): # Taking empty list lis = [] for i in words: # Getting all words for j in i.split(): lis.append(j) # Calculating frequency of all words freq = Counter(lis) # find max count and print that key max = 0 for i in freq: if(freq[i] > max): max = freq[i] word = i return word # Driver code# initializing strings listwords = [\"gfg is best for geeks\", \"geeks love gfg\", \"gfg is best\"] # printing original listprint(\"The original list is : \" + str(words)) # passing this words to mostFrequencyWord function# printing resultprint(\"Word with maximum frequency : \" + mostFrequentWord(words))# This code is contributed by vikkycirus",
"e": 27915,
"s": 26996,
"text": null
},
{
"code": null,
"e": 27923,
"s": 27915,
"text": "Output:"
},
{
"code": null,
"e": 28039,
"s": 27923,
"text": "The original list is : ['gfg is best for geeks', 'geeks love gfg', 'gfg is best']\nWord with maximum frequency : gfg"
},
{
"code": null,
"e": 28050,
"s": 28039,
"text": "vikkycirus"
},
{
"code": null,
"e": 28066,
"s": 28050,
"text": "simranarora5sos"
},
{
"code": null,
"e": 28075,
"s": 28066,
"text": "sooda367"
},
{
"code": null,
"e": 28088,
"s": 28075,
"text": "simmytarika5"
},
{
"code": null,
"e": 28109,
"s": 28088,
"text": "Python list-programs"
},
{
"code": null,
"e": 28132,
"s": 28109,
"text": "Python string-programs"
},
{
"code": null,
"e": 28139,
"s": 28132,
"text": "Python"
},
{
"code": null,
"e": 28155,
"s": 28139,
"text": "Python Programs"
},
{
"code": null,
"e": 28253,
"s": 28155,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28262,
"s": 28253,
"text": "Comments"
},
{
"code": null,
"e": 28275,
"s": 28262,
"text": "Old Comments"
},
{
"code": null,
"e": 28293,
"s": 28275,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28328,
"s": 28293,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28350,
"s": 28328,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28382,
"s": 28350,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28412,
"s": 28382,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28434,
"s": 28412,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28473,
"s": 28434,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28519,
"s": 28473,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28576,
"s": 28519,
"text": "Python program to check whether a number is Prime or not"
}
] |
JavaScript - Get href value
|
Let’s say we have the following anchor tag with URL −
<a class="demo" title="get the url" href="./mainPage.jsp/1245">href value at console</a>
We need to get only the URL value i.e. the href attribute value. For this, use attr() −
attr('href')
Following is the code −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<ul class="getURLDemo">
<li>
<a class="demo" title="get the url" href="./mainPage.jsp/1245">href value at console</a>
</li>
</ul>
</body>
<script>
var hrefValue = $('ul.getURLDemo li a.demo').attr('href');
console.log(hrefValue);
</script>
</html>
To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VSCode editor −
This will produce the following output on console −
The output in console −
|
[
{
"code": null,
"e": 1116,
"s": 1062,
"text": "Let’s say we have the following anchor tag with URL −"
},
{
"code": null,
"e": 1205,
"s": 1116,
"text": "<a class=\"demo\" title=\"get the url\" href=\"./mainPage.jsp/1245\">href value at console</a>"
},
{
"code": null,
"e": 1293,
"s": 1205,
"text": "We need to get only the URL value i.e. the href attribute value. For this, use attr() −"
},
{
"code": null,
"e": 1306,
"s": 1293,
"text": "attr('href')"
},
{
"code": null,
"e": 1330,
"s": 1306,
"text": "Following is the code −"
},
{
"code": null,
"e": 1341,
"s": 1330,
"text": " Live Demo"
},
{
"code": null,
"e": 2026,
"s": 1341,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n</head>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<body>\n <ul class=\"getURLDemo\">\n <li>\n <a class=\"demo\" title=\"get the url\" href=\"./mainPage.jsp/1245\">href value at console</a>\n </li>\n </ul>\n</body>\n<script>\n var hrefValue = $('ul.getURLDemo li a.demo').attr('href');\n console.log(hrefValue);\n</script> \n</html>"
},
{
"code": null,
"e": 2188,
"s": 2026,
"text": "To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VSCode editor −"
},
{
"code": null,
"e": 2240,
"s": 2188,
"text": "This will produce the following output on console −"
},
{
"code": null,
"e": 2264,
"s": 2240,
"text": "The output in console −"
}
] |
Get the union of two sets in Java
|
To get the union of two sets, use the addAll() method.
The first set −
HashSet <String> set1 = new HashSet <String>();
set1.add("Mat");
set1.add("Sat");
set1.add("Cat");
The second set −
HashSet <String> set2 = new HashSet <String>();
set2.add("Mat");
set2.add("Cat");
set2.add("Fat");
set2.add("Hat");
Get the union −
set1.addAll(set2);
The following is an example −
Live Demo
import java.util.*;
public class Demo {
public static void main(String args[]) {
HashSet <String> set1 = new HashSet <String>();
HashSet <String> set2 = new HashSet <String>();
set1.add("Mat");
set1.add("Sat");
set1.add("Cat");
System.out.println("Set1 = "+ set1);
set2.add("Mat");
set2.add("Cat");
set2.add("Fat");
set2.add("Hat");
System.out.println("Set2 = "+ set2);
set1.addAll(set2);
System.out.println("Union = "+ set1);
}
}
Set1 = [Mat, Sat, Cat]
Set2 = [Mat, Cat, Fat, Hat]
Union = [Mat, Sat, Cat, Fat, Hat]
|
[
{
"code": null,
"e": 1117,
"s": 1062,
"text": "To get the union of two sets, use the addAll() method."
},
{
"code": null,
"e": 1133,
"s": 1117,
"text": "The first set −"
},
{
"code": null,
"e": 1232,
"s": 1133,
"text": "HashSet <String> set1 = new HashSet <String>();\nset1.add(\"Mat\");\nset1.add(\"Sat\");\nset1.add(\"Cat\");"
},
{
"code": null,
"e": 1249,
"s": 1232,
"text": "The second set −"
},
{
"code": null,
"e": 1365,
"s": 1249,
"text": "HashSet <String> set2 = new HashSet <String>();\nset2.add(\"Mat\");\nset2.add(\"Cat\");\nset2.add(\"Fat\");\nset2.add(\"Hat\");"
},
{
"code": null,
"e": 1381,
"s": 1365,
"text": "Get the union −"
},
{
"code": null,
"e": 1400,
"s": 1381,
"text": "set1.addAll(set2);"
},
{
"code": null,
"e": 1430,
"s": 1400,
"text": "The following is an example −"
},
{
"code": null,
"e": 1441,
"s": 1430,
"text": " Live Demo"
},
{
"code": null,
"e": 1956,
"s": 1441,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n HashSet <String> set1 = new HashSet <String>();\n HashSet <String> set2 = new HashSet <String>();\n set1.add(\"Mat\");\n set1.add(\"Sat\");\n set1.add(\"Cat\");\n System.out.println(\"Set1 = \"+ set1);\n set2.add(\"Mat\");\n set2.add(\"Cat\");\n set2.add(\"Fat\");\n set2.add(\"Hat\");\n System.out.println(\"Set2 = \"+ set2);\n set1.addAll(set2);\n System.out.println(\"Union = \"+ set1);\n }\n}"
},
{
"code": null,
"e": 2041,
"s": 1956,
"text": "Set1 = [Mat, Sat, Cat]\nSet2 = [Mat, Cat, Fat, Hat]\nUnion = [Mat, Sat, Cat, Fat, Hat]"
}
] |
What is 'void' Operator in JavaScript?
|
The void is an important keyword in JavaScript, which can be used as a unary operator that appears before its single operand, which may be of any type. This operator specifies an expression to be evaluated without returning a value.
The syntax of void can be either of the following two −
<head>
<script>
<!--
void func()
javascript:void func()
or:
void(func())
javascript:void(func())
//-->
</script>
</head>
The most common use of this operator is in a client-side javascript: URL, where it allows you to evaluate an expression for its side-effects without the browser displaying the value of the evaluated expression.
Here the expression alert ('Warning!!!') is evaluated but it is not loaded back into the current document.
<html>
<head>
<script>
<!--
//-->
</script>
</head>
<body>
<p>Clickthe following, This won't react at all...</p>
<ahref = "javascript:void(alert('Warning!!!'))">Clickme!</a>
</body>
</html>
|
[
{
"code": null,
"e": 1295,
"s": 1062,
"text": "The void is an important keyword in JavaScript, which can be used as a unary operator that appears before its single operand, which may be of any type. This operator specifies an expression to be evaluated without returning a value."
},
{
"code": null,
"e": 1351,
"s": 1295,
"text": "The syntax of void can be either of the following two −"
},
{
"code": null,
"e": 1535,
"s": 1351,
"text": "<head>\n <script>\n <!--\n void func()\n javascript:void func()\n or:\n void(func())\n javascript:void(func())\n //-->\n </script>\n</head>"
},
{
"code": null,
"e": 1746,
"s": 1535,
"text": "The most common use of this operator is in a client-side javascript: URL, where it allows you to evaluate an expression for its side-effects without the browser displaying the value of the evaluated expression."
},
{
"code": null,
"e": 1853,
"s": 1746,
"text": "Here the expression alert ('Warning!!!') is evaluated but it is not loaded back into the current document."
},
{
"code": null,
"e": 2098,
"s": 1853,
"text": "<html>\n <head>\n <script>\n <!--\n //-->\n </script>\n </head>\n\n <body>\n <p>Clickthe following, This won't react at all...</p>\n <ahref = \"javascript:void(alert('Warning!!!'))\">Clickme!</a>\n </body>\n</html>"
}
] |
How to use D3js with WebComponents | by Ruben Triviño | Towards Data Science
|
D3 is a fantastic open source library for data visualization developed originally by Mike Bostock. The great variety of tools it offers allow to make rare graphs from scratch or using pre-built templates. The possibilities offered by D3 are unlimited, you only need to have a look at their gallery.
If you have already worked with D3 you will know that apart from getting astonishing graphs you also end up with a bunch of scripts for formatting data, iterating over SVG elements, services to communicate with the server, models, etc.. All of these, probably, in the very middle of a project poorly related with the graphs itself, a real mess!
Luckily, the world of Web Components it is more accessible than ever and it is the perfect tool for creating your own graphic hub well encapsulated and reusable. On Custom Elements Everywhere you may check if Web Components are compatible with your preferred development framework.
Stencil is a Web Components, or more specifically Custom Elements, a compiler that uses the main features of the most known web development frameworks.
This tool has been developed by the IonicFramework to make it easy to make compatible components with multiple web development frameworks, towards an agnostic framework idea.
Thus, using D3 in a project based on the Web Components (Custom Components) standards using StencilJS is an elegant and easy to accomplish solution if you want to have a single reusable graphing project.
Firstly, install the latest version of StencilJS using npm for instance and initialize the base project:
npm install @stencil/core@latest --save-exactnpm init stencil
Choose component option with the arrow keys and set the project name. The CLI of Stencil will create a project folder where you would find src folder which contains the first component generated by default: my-component . The .tsx file of the component folder is the one containing the main logic of it.
Now check that everything is working properly by typing the start command from the root project folder on your console.
npm run start
A new browser window should open showing the HelloWorld! of Stencil, a bit dull to be honest.
Once you have launched the project, any update in the code will be rendered on the browser. Now, we only have to import D3 into the code of the component. First, we need to install it using npm :
npm install d3 --save
Usually, when we work with D3 in a Javascript code we import all reference at once on a d3 alias like this: import * from ‘d3.js' . However, since the last version and using Typescript we will have to import different modules individually. This is a bit tedious but it would help us to make the app light-weighted. In this case, we are using a pie chart so we will import the following modules:
import { select } from 'd3-selection'import { pie, arc } from 'd3-shape';import { scaleOrdinal } from 'd3-scale';import { quantize } from 'd3-interpolate';import { interpolateCool } from 'd3-scale-chromatic';
select operator allows getting reference of the html elements which we want to use or modify.
pie operator is responsible for generating the data structure and arc is the tool that allows us to generate the angles values and radio, needed to draw the chart.
scaleOrdinal, quantize andinterpolateCool operators help us to generate multiple colors depending on the value of each portion of the chart.
With this, we got all set and we only need to know where to place the D3 code. The basic structure of the component would be something like this:
Stencil API offers a bunch of decorators and methods that allow us to interact with the component and his lifecycle.
This decorator allows getting inputs from the outer world of the component. In our case, those will be the graph data. These inputs are provided when using our component in html.
In fact, if we look a the project files, src/index.html contains the components generated (only one in this case) and we may see that the instantiation of the component is done like this:
<my-component data='myData'></my-component>
Where myData is the data structure provided to our component so it can iterate over it and draw the chart.
This function is called just after the component is instantiated or modified and is responsible for generating the html tags that eventually will be rendered by the browser. Here we generate the html schema of our component and we will include the SVG element that we will use to generate all the pie chart elements.
This method is called once the elements are fully loaded preventing us from getting null references of the html elements of the component.
Logic associated with D3, which is for regenerating data structures and graphical elements, must be set inside this method so we can guarantee that we may reference the final html.
This decorator allows us access to the main component and thus iterate over its children html elements. In particular, this is the reference that we would use to use select function of D3 and obtain the SVG where we will inflate our chart. Due to the encapsulation of Stencil we will have to access through shadowRoot :
select(this.element.shadowRoot.querySelectorAll(".chart")[0]);
Once we get the reference of the SVG element we may forget all about Stencil and start to think about D3 exclusively. So we add the script to generate the pie chart (or other) and this is it, we would get our webcomponent ready:
With the previous code we would get a chart like this:
You may find a full code example in this GitHub link.
Once we get our chart ready to publish we just have to build it and use it in any other project that we may have. Fortunately, this process is so simple as checking package.json file for setting project name, version number, license, description, etc.. and launch build command:
npm run build
This will generate the WebComponent ready to distribute in the www/build folder. To use it in any other project you will only have to publish it into your account of npm and enjoy all its features:
npm loginnpm publish
Stencil allows creating a modular working environment, exportable and accessible for the main web development frameworks. This is a great opportunity to unify al graphical elements of multiple projects into one and standardize their use, code recycling, html, css, etc..
If you work in a development team that is in continuous contact with the UX/UI department Stencil is the perfect place to develop a sustainable Design System once for all and to make it easy for everyone.
|
[
{
"code": null,
"e": 471,
"s": 172,
"text": "D3 is a fantastic open source library for data visualization developed originally by Mike Bostock. The great variety of tools it offers allow to make rare graphs from scratch or using pre-built templates. The possibilities offered by D3 are unlimited, you only need to have a look at their gallery."
},
{
"code": null,
"e": 816,
"s": 471,
"text": "If you have already worked with D3 you will know that apart from getting astonishing graphs you also end up with a bunch of scripts for formatting data, iterating over SVG elements, services to communicate with the server, models, etc.. All of these, probably, in the very middle of a project poorly related with the graphs itself, a real mess!"
},
{
"code": null,
"e": 1098,
"s": 816,
"text": "Luckily, the world of Web Components it is more accessible than ever and it is the perfect tool for creating your own graphic hub well encapsulated and reusable. On Custom Elements Everywhere you may check if Web Components are compatible with your preferred development framework."
},
{
"code": null,
"e": 1250,
"s": 1098,
"text": "Stencil is a Web Components, or more specifically Custom Elements, a compiler that uses the main features of the most known web development frameworks."
},
{
"code": null,
"e": 1425,
"s": 1250,
"text": "This tool has been developed by the IonicFramework to make it easy to make compatible components with multiple web development frameworks, towards an agnostic framework idea."
},
{
"code": null,
"e": 1629,
"s": 1425,
"text": "Thus, using D3 in a project based on the Web Components (Custom Components) standards using StencilJS is an elegant and easy to accomplish solution if you want to have a single reusable graphing project."
},
{
"code": null,
"e": 1734,
"s": 1629,
"text": "Firstly, install the latest version of StencilJS using npm for instance and initialize the base project:"
},
{
"code": null,
"e": 1796,
"s": 1734,
"text": "npm install @stencil/core@latest --save-exactnpm init stencil"
},
{
"code": null,
"e": 2100,
"s": 1796,
"text": "Choose component option with the arrow keys and set the project name. The CLI of Stencil will create a project folder where you would find src folder which contains the first component generated by default: my-component . The .tsx file of the component folder is the one containing the main logic of it."
},
{
"code": null,
"e": 2220,
"s": 2100,
"text": "Now check that everything is working properly by typing the start command from the root project folder on your console."
},
{
"code": null,
"e": 2234,
"s": 2220,
"text": "npm run start"
},
{
"code": null,
"e": 2328,
"s": 2234,
"text": "A new browser window should open showing the HelloWorld! of Stencil, a bit dull to be honest."
},
{
"code": null,
"e": 2524,
"s": 2328,
"text": "Once you have launched the project, any update in the code will be rendered on the browser. Now, we only have to import D3 into the code of the component. First, we need to install it using npm :"
},
{
"code": null,
"e": 2546,
"s": 2524,
"text": "npm install d3 --save"
},
{
"code": null,
"e": 2941,
"s": 2546,
"text": "Usually, when we work with D3 in a Javascript code we import all reference at once on a d3 alias like this: import * from ‘d3.js' . However, since the last version and using Typescript we will have to import different modules individually. This is a bit tedious but it would help us to make the app light-weighted. In this case, we are using a pie chart so we will import the following modules:"
},
{
"code": null,
"e": 3150,
"s": 2941,
"text": "import { select } from 'd3-selection'import { pie, arc } from 'd3-shape';import { scaleOrdinal } from 'd3-scale';import { quantize } from 'd3-interpolate';import { interpolateCool } from 'd3-scale-chromatic';"
},
{
"code": null,
"e": 3244,
"s": 3150,
"text": "select operator allows getting reference of the html elements which we want to use or modify."
},
{
"code": null,
"e": 3408,
"s": 3244,
"text": "pie operator is responsible for generating the data structure and arc is the tool that allows us to generate the angles values and radio, needed to draw the chart."
},
{
"code": null,
"e": 3549,
"s": 3408,
"text": "scaleOrdinal, quantize andinterpolateCool operators help us to generate multiple colors depending on the value of each portion of the chart."
},
{
"code": null,
"e": 3695,
"s": 3549,
"text": "With this, we got all set and we only need to know where to place the D3 code. The basic structure of the component would be something like this:"
},
{
"code": null,
"e": 3812,
"s": 3695,
"text": "Stencil API offers a bunch of decorators and methods that allow us to interact with the component and his lifecycle."
},
{
"code": null,
"e": 3991,
"s": 3812,
"text": "This decorator allows getting inputs from the outer world of the component. In our case, those will be the graph data. These inputs are provided when using our component in html."
},
{
"code": null,
"e": 4179,
"s": 3991,
"text": "In fact, if we look a the project files, src/index.html contains the components generated (only one in this case) and we may see that the instantiation of the component is done like this:"
},
{
"code": null,
"e": 4223,
"s": 4179,
"text": "<my-component data='myData'></my-component>"
},
{
"code": null,
"e": 4330,
"s": 4223,
"text": "Where myData is the data structure provided to our component so it can iterate over it and draw the chart."
},
{
"code": null,
"e": 4647,
"s": 4330,
"text": "This function is called just after the component is instantiated or modified and is responsible for generating the html tags that eventually will be rendered by the browser. Here we generate the html schema of our component and we will include the SVG element that we will use to generate all the pie chart elements."
},
{
"code": null,
"e": 4786,
"s": 4647,
"text": "This method is called once the elements are fully loaded preventing us from getting null references of the html elements of the component."
},
{
"code": null,
"e": 4967,
"s": 4786,
"text": "Logic associated with D3, which is for regenerating data structures and graphical elements, must be set inside this method so we can guarantee that we may reference the final html."
},
{
"code": null,
"e": 5287,
"s": 4967,
"text": "This decorator allows us access to the main component and thus iterate over its children html elements. In particular, this is the reference that we would use to use select function of D3 and obtain the SVG where we will inflate our chart. Due to the encapsulation of Stencil we will have to access through shadowRoot :"
},
{
"code": null,
"e": 5350,
"s": 5287,
"text": "select(this.element.shadowRoot.querySelectorAll(\".chart\")[0]);"
},
{
"code": null,
"e": 5579,
"s": 5350,
"text": "Once we get the reference of the SVG element we may forget all about Stencil and start to think about D3 exclusively. So we add the script to generate the pie chart (or other) and this is it, we would get our webcomponent ready:"
},
{
"code": null,
"e": 5634,
"s": 5579,
"text": "With the previous code we would get a chart like this:"
},
{
"code": null,
"e": 5688,
"s": 5634,
"text": "You may find a full code example in this GitHub link."
},
{
"code": null,
"e": 5967,
"s": 5688,
"text": "Once we get our chart ready to publish we just have to build it and use it in any other project that we may have. Fortunately, this process is so simple as checking package.json file for setting project name, version number, license, description, etc.. and launch build command:"
},
{
"code": null,
"e": 5981,
"s": 5967,
"text": "npm run build"
},
{
"code": null,
"e": 6179,
"s": 5981,
"text": "This will generate the WebComponent ready to distribute in the www/build folder. To use it in any other project you will only have to publish it into your account of npm and enjoy all its features:"
},
{
"code": null,
"e": 6200,
"s": 6179,
"text": "npm loginnpm publish"
},
{
"code": null,
"e": 6471,
"s": 6200,
"text": "Stencil allows creating a modular working environment, exportable and accessible for the main web development frameworks. This is a great opportunity to unify al graphical elements of multiple projects into one and standardize their use, code recycling, html, css, etc.."
}
] |
numpy.nanpercentile() in Python
|
07 Jul, 2022
numpy.nanpercentile()function used to compute the nth percentile of the given data (array elements) along the specified axis ang ignores nan values.
Syntax :
numpy.nanpercentile(arr, q, axis=None, out=None)
Parameters :
arr :input array.
q : percentile value.
axis :axis along which we want to calculate the percentile value.Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row.
out : Different array in which we want to place the result. The array must have same dimensions as expected output.
Return :Percentile of the array (a scalar value if axis is none) or array with percentiles of values along specified axis.
Code #1 : Working
Python
# Python Program illustrating# numpy.nanpercentile() method import numpy as np # 1D arrayarr = [20, 2, 7, np.nan, 34]print("arr : ", arr)print("50th percentile of arr : ", np.percentile(arr, 50))print("25th percentile of arr : ", np.percentile(arr, 25))print("75th percentile of arr : ", np.percentile(arr, 75)) print("\n50th percentile of arr : ", np.nanpercentile(arr, 50))print("25th percentile of arr : ", np.nanpercentile(arr, 25))print("75th percentile of arr : ", np.nanpercentile(arr, 75))
Output :
arr : [20, 2, 7, nan, 34]
50th percentile of arr : nan
25th percentile of arr : nan
75th percentile of arr : nan
50th percentile of arr : 13.5
25th percentile of arr : 5.75
75th percentile of arr : 23.5
Code #2 :
Python
# Python Program illustrating# numpy.nanpercentile() method import numpy as np # 2D arrayarr = [[14, np.nan, 12, 33, 44], [15, np.nan, 27, 8, 19], [23, 2, np.nan, 1, 4, ]]print(& quot \narr: \n" , arr) # Percentile of the flattened arrayprint(& quot \n50th Percentile of arr, axis = None : & quot , np.percentile(arr, 50))print(& quot \n50th Percentile of arr, axis = None : & quot , np.nanpercentile(arr, 50))print(& quot 0th Percentile of arr, axis = None : & quot , np.nanpercentile(arr, 0)) # Percentile along the axis = 0print(& quot \n50th Percentile of arr, axis = 0 : & quot , np.nanpercentile(arr, 50, axis=0))print(& quot 0th Percentile of arr, axis = 0 : & quot , np.nanpercentile(arr, 0, axis=0)) # Percentile along the axis = 1print(& quot \n50th Percentile of arr, axis = 1 : & quot , np.nanpercentile(arr, 50, axis=1))print(& quot 0th Percentile of arr, axis = 1 : & quot , np.nanpercentile(arr, 0, axis=1)) print(& quot \n0th Percentile of arr, axis = 1: \n" , np.nanpercentile(arr, 50, axis=1, keepdims=True))print(& quot \n0th Percentile of arr, axis = 1: \n" , np.nanpercentile(arr, 0, axis=1, keepdims=True))
Output :
arr :
[[14, nan, 12, 33, 44], [15, nan, 27, 8, 19], [23, 2, nan, 1, 4]]
50th Percentile of arr, axis = None : nan
50th Percentile of arr, axis = None : 14.5
0th Percentile of arr, axis = None : 1.0
50th Percentile of arr, axis = 0 : [15. 2. 19.5 8. 19. ]
0th Percentile of arr, axis = 0 : [14. 2. 12. 1. 4.]
50th Percentile of arr, axis = 1 : [23.5 17. 3. ]
0th Percentile of arr, axis = 1 : [12. 8. 1.]
0th Percentile of arr, axis = 1 :
[[23.5]
[17. ]
[ 3. ]]
0th Percentile of arr, axis = 1 :
[[12.]
[ 8.]
[ 1.]]
Code #3:
Python
# Python Program illustrating# numpy.nanpercentile() method import numpy as np # 2D arrayarr = [[14, np.nan, 12, 33, 44], [15, np.nan, 27, 8, 19], [23, np.nan, np.nan, 1, 4, ]]print(& quot \narr: \n" , arr)# Percentile along the axis = 1print(& quot \n50th Percentile of arr, axis = 1 : & quot , np.nanpercentile(arr, 50, axis=1))print(& quot \n50th Percentile of arr, axis = 0 : & quot , np.nanpercentile(arr, 50, axis=0))
Output :
arr :
[[14, nan, 12, 33, 44], [15, nan, 27, 8, 19], [23, nan, nan, 1, 4]]
50th Percentile of arr, axis = 1 : [23.5 17. 4. ]
50th Percentile of arr, axis = 0 : [15. nan 19.5 8. 19. ]
RuntimeWarning: All-NaN slice encountered
overwrite_input, interpolation)
hamidullahbinol
daniel8l2l
Python numpy-Statistics Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 177,
"s": 28,
"text": "numpy.nanpercentile()function used to compute the nth percentile of the given data (array elements) along the specified axis ang ignores nan values."
},
{
"code": null,
"e": 187,
"s": 177,
"text": "Syntax : "
},
{
"code": null,
"e": 237,
"s": 187,
"text": "numpy.nanpercentile(arr, q, axis=None, out=None) "
},
{
"code": null,
"e": 251,
"s": 237,
"text": "Parameters : "
},
{
"code": null,
"e": 270,
"s": 251,
"text": "arr :input array. "
},
{
"code": null,
"e": 293,
"s": 270,
"text": "q : percentile value. "
},
{
"code": null,
"e": 505,
"s": 293,
"text": "axis :axis along which we want to calculate the percentile value.Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row. "
},
{
"code": null,
"e": 622,
"s": 505,
"text": "out : Different array in which we want to place the result. The array must have same dimensions as expected output. "
},
{
"code": null,
"e": 745,
"s": 622,
"text": "Return :Percentile of the array (a scalar value if axis is none) or array with percentiles of values along specified axis."
},
{
"code": null,
"e": 764,
"s": 745,
"text": "Code #1 : Working "
},
{
"code": null,
"e": 771,
"s": 764,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.nanpercentile() method import numpy as np # 1D arrayarr = [20, 2, 7, np.nan, 34]print(\"arr : \", arr)print(\"50th percentile of arr : \", np.percentile(arr, 50))print(\"25th percentile of arr : \", np.percentile(arr, 25))print(\"75th percentile of arr : \", np.percentile(arr, 75)) print(\"\\n50th percentile of arr : \", np.nanpercentile(arr, 50))print(\"25th percentile of arr : \", np.nanpercentile(arr, 25))print(\"75th percentile of arr : \", np.nanpercentile(arr, 75))",
"e": 1307,
"s": 771,
"text": null
},
{
"code": null,
"e": 1317,
"s": 1307,
"text": "Output : "
},
{
"code": null,
"e": 1528,
"s": 1317,
"text": "arr : [20, 2, 7, nan, 34]\n50th percentile of arr : nan\n25th percentile of arr : nan\n75th percentile of arr : nan\n\n50th percentile of arr : 13.5\n25th percentile of arr : 5.75\n75th percentile of arr : 23.5"
},
{
"code": null,
"e": 1541,
"s": 1528,
"text": " Code #2 : "
},
{
"code": null,
"e": 1548,
"s": 1541,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.nanpercentile() method import numpy as np # 2D arrayarr = [[14, np.nan, 12, 33, 44], [15, np.nan, 27, 8, 19], [23, 2, np.nan, 1, 4, ]]print(& quot \\narr: \\n\" , arr) # Percentile of the flattened arrayprint(& quot \\n50th Percentile of arr, axis = None : & quot , np.percentile(arr, 50))print(& quot \\n50th Percentile of arr, axis = None : & quot , np.nanpercentile(arr, 50))print(& quot 0th Percentile of arr, axis = None : & quot , np.nanpercentile(arr, 0)) # Percentile along the axis = 0print(& quot \\n50th Percentile of arr, axis = 0 : & quot , np.nanpercentile(arr, 50, axis=0))print(& quot 0th Percentile of arr, axis = 0 : & quot , np.nanpercentile(arr, 0, axis=0)) # Percentile along the axis = 1print(& quot \\n50th Percentile of arr, axis = 1 : & quot , np.nanpercentile(arr, 50, axis=1))print(& quot 0th Percentile of arr, axis = 1 : & quot , np.nanpercentile(arr, 0, axis=1)) print(& quot \\n0th Percentile of arr, axis = 1: \\n\" , np.nanpercentile(arr, 50, axis=1, keepdims=True))print(& quot \\n0th Percentile of arr, axis = 1: \\n\" , np.nanpercentile(arr, 0, axis=1, keepdims=True))",
"e": 2863,
"s": 1548,
"text": null
},
{
"code": null,
"e": 2873,
"s": 2863,
"text": "Output : "
},
{
"code": null,
"e": 3423,
"s": 2873,
"text": "arr : \n [[14, nan, 12, 33, 44], [15, nan, 27, 8, 19], [23, 2, nan, 1, 4]]\n\n50th Percentile of arr, axis = None : nan\n\n50th Percentile of arr, axis = None : 14.5\n0th Percentile of arr, axis = None : 1.0\n\n50th Percentile of arr, axis = 0 : [15. 2. 19.5 8. 19. ]\n0th Percentile of arr, axis = 0 : [14. 2. 12. 1. 4.]\n\n50th Percentile of arr, axis = 1 : [23.5 17. 3. ]\n0th Percentile of arr, axis = 1 : [12. 8. 1.]\n\n0th Percentile of arr, axis = 1 : \n [[23.5]\n [17. ]\n [ 3. ]]\n\n0th Percentile of arr, axis = 1 : \n [[12.]\n [ 8.]\n [ 1.]]"
},
{
"code": null,
"e": 3435,
"s": 3423,
"text": " Code #3: "
},
{
"code": null,
"e": 3442,
"s": 3435,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.nanpercentile() method import numpy as np # 2D arrayarr = [[14, np.nan, 12, 33, 44], [15, np.nan, 27, 8, 19], [23, np.nan, np.nan, 1, 4, ]]print(& quot \\narr: \\n\" , arr)# Percentile along the axis = 1print(& quot \\n50th Percentile of arr, axis = 1 : & quot , np.nanpercentile(arr, 50, axis=1))print(& quot \\n50th Percentile of arr, axis = 0 : & quot , np.nanpercentile(arr, 50, axis=0))",
"e": 3926,
"s": 3442,
"text": null
},
{
"code": null,
"e": 3936,
"s": 3926,
"text": "Output : "
},
{
"code": null,
"e": 4206,
"s": 3936,
"text": "arr : \n [[14, nan, 12, 33, 44], [15, nan, 27, 8, 19], [23, nan, nan, 1, 4]]\n\n50th Percentile of arr, axis = 1 : [23.5 17. 4. ]\n\n50th Percentile of arr, axis = 0 : [15. nan 19.5 8. 19. ]\nRuntimeWarning: All-NaN slice encountered\n overwrite_input, interpolation)"
},
{
"code": null,
"e": 4222,
"s": 4206,
"text": "hamidullahbinol"
},
{
"code": null,
"e": 4233,
"s": 4222,
"text": "daniel8l2l"
},
{
"code": null,
"e": 4267,
"s": 4233,
"text": "Python numpy-Statistics Functions"
},
{
"code": null,
"e": 4280,
"s": 4267,
"text": "Python-numpy"
},
{
"code": null,
"e": 4287,
"s": 4280,
"text": "Python"
},
{
"code": null,
"e": 4385,
"s": 4287,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4417,
"s": 4385,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4444,
"s": 4417,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4465,
"s": 4444,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4496,
"s": 4465,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4552,
"s": 4496,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4575,
"s": 4552,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4617,
"s": 4575,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4659,
"s": 4617,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4698,
"s": 4659,
"text": "Python | datetime.timedelta() function"
}
] |
Choose optimal number of epochs to train a neural network in Keras
|
08 Jun, 2020
One of the critical issues while training a neural network on the sample data is Overfitting. When the number of epochs used to train a neural network model is more than necessary, the training model learns patterns that are specific to sample data to a great extent. This makes the model incapable to perform well on a new dataset. This model gives high accuracy on the training set (sample data) but fails to achieve good accuracy on the test set. In other words, the model loses generalization capacity by overfitting to the training data.
To mitigate overfitting and to increase the generalization capacity of the neural network, the model should be trained for an optimal number of epochs. A part of training data is dedicated for validation of the model, to check the performance of the model after each epoch of training. Loss and accuracy on the training set as well as on validation set are monitored to look over the epoch number after which the model starts overfitting.
Either loss/accuracy values can be monitored by Early stopping call back function. If the loss is being monitored, training comes to halt when there is an increment observed in loss values. Or, If accuracy is being monitored, training comes to halt when there is decrement observed in accuracy values.
Syntax with default values:
keras.callbacks.callbacks.EarlyStopping(monitor=’val_loss’, min_delta=0, patience=0, verbose=0, mode=’auto’, baseline=None, restore_best_weights=False)
Understanding few important arguments:
monitor: The value to be monitored by the function should be assigned. It can be validation loss or validation accuracy.
mode: It is the mode in which change in the quantity monitored should be observed. This can be ‘min’ or ‘max’ or ‘auto’. When the monitored value is loss, its value is ‘min’. When the monitored value is accuracy, its value is ‘max’. When the mode is set is ‘auto’, the function automatically monitors with the suitable mode.
min_delta: The minimum value should be set for the change to be considered i.e., Change in the value being monitored should be higher than ‘min_delta’ value.
patience: Patience is the number of epochs for the training to be continued after the first halt. The model waits for patience number of epochs for any improvement in the model.
verbose: Verbose is an integer value-0, 1 or 2. This value is to select the way in which the progress is displayed while training.Verbose = 0: Silent mode-Nothing is displayed in this mode.Verbose = 1: A bar depicting the progress of training is displayed.Verbose = 2: In this mode, one line per epoch, showing the progress of training per epoch is displayed.
Verbose = 0: Silent mode-Nothing is displayed in this mode.
Verbose = 1: A bar depicting the progress of training is displayed.
Verbose = 2: In this mode, one line per epoch, showing the progress of training per epoch is displayed.
restore_best_weights: This is a boolean value. True value restores the weights which are optimal.
Finding the optimal number of epochs to avoid overfitting on MNIST dataset.
Step 1: Loading dataset and preprocessing
import kerasfrom keras.utils.np_utils import to_categoricalfrom keras.datasets import mnist # Loading data(train_images, train_labels), (test_images, test_labels)= mnist.load_data() # Reshaping data-Adding number of channels as 1 (Grayscale images)train_images = train_images.reshape((train_images.shape[0], train_images.shape[1], train_images.shape[2], 1)) test_images = test_images.reshape((test_images.shape[0], test_images.shape[1], test_images.shape[2], 1)) # Scaling down pixel valuestrain_images = train_images.astype('float32')/255test_images = test_images.astype('float32')/255 # Encoding labels to a binary class matrixy_train = to_categorical(train_labels)y_test = to_categorical(test_labels)
Step 2: Building a CNN model
from keras import modelsfrom keras import layers model = models.Sequential()model.add(layers.Conv2D(32, (3, 3), activation ="relu", input_shape =(28, 28, 1)))model.add(layers.MaxPooling2D(2, 2))model.add(layers.Conv2D(64, (3, 3), activation ="relu"))model.add(layers.MaxPooling2D(2, 2))model.add(layers.Flatten())model.add(layers.Dense(64, activation ="relu"))model.add(layers.Dense(10, activation ="softmax")) model.summary()
Output: Summary of the model
Step 4: Compiling the model with RMSprop optimizer, categorical cross entropy loss function and accuracy as success metric
model.compile(optimizer ="rmsprop", loss ="categorical_crossentropy", metrics =['accuracy'])
Step 5: Creating validation set and training set by partitioning the current training set
val_images = train_images[:10000]partial_images = train_images[10000:]val_labels = y_train[:10000]partial_labels = y_train[10000:]
Step 6: Initializing earlystopping callback and training the model
from keras import callbacksearlystopping = callbacks.EarlyStopping(monitor ="val_loss", mode ="min", patience = 5, restore_best_weights = True) history = model.fit(partial_images, partial_labels, batch_size = 128, epochs = 25, validation_data =(val_images, val_labels), callbacks =[earlystopping])
Training stopped at 11th epoch i.e., the model will start overfitting from 12th epoch. Therefore, the optimal number of epochs to train most dataset is 11.
Observing loss values without using Early Stopping call back function:Train the model up until 25 epochs and plot the training loss values and validation loss values against number of epochs. The plot looks like:
Inference:As the number of epochs increases beyond 11, training set loss decreases and becomes nearly zero. Whereas, validation loss increases depicting the overfitting of the model on training data.
References:
https://keras.io/callbacks/
https://keras.io/datasets/
Deep-Learning
Neural Network
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Support Vector Machine Algorithm
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 595,
"s": 52,
"text": "One of the critical issues while training a neural network on the sample data is Overfitting. When the number of epochs used to train a neural network model is more than necessary, the training model learns patterns that are specific to sample data to a great extent. This makes the model incapable to perform well on a new dataset. This model gives high accuracy on the training set (sample data) but fails to achieve good accuracy on the test set. In other words, the model loses generalization capacity by overfitting to the training data."
},
{
"code": null,
"e": 1034,
"s": 595,
"text": "To mitigate overfitting and to increase the generalization capacity of the neural network, the model should be trained for an optimal number of epochs. A part of training data is dedicated for validation of the model, to check the performance of the model after each epoch of training. Loss and accuracy on the training set as well as on validation set are monitored to look over the epoch number after which the model starts overfitting."
},
{
"code": null,
"e": 1336,
"s": 1034,
"text": "Either loss/accuracy values can be monitored by Early stopping call back function. If the loss is being monitored, training comes to halt when there is an increment observed in loss values. Or, If accuracy is being monitored, training comes to halt when there is decrement observed in accuracy values."
},
{
"code": null,
"e": 1364,
"s": 1336,
"text": "Syntax with default values:"
},
{
"code": null,
"e": 1516,
"s": 1364,
"text": "keras.callbacks.callbacks.EarlyStopping(monitor=’val_loss’, min_delta=0, patience=0, verbose=0, mode=’auto’, baseline=None, restore_best_weights=False)"
},
{
"code": null,
"e": 1555,
"s": 1516,
"text": "Understanding few important arguments:"
},
{
"code": null,
"e": 1676,
"s": 1555,
"text": "monitor: The value to be monitored by the function should be assigned. It can be validation loss or validation accuracy."
},
{
"code": null,
"e": 2001,
"s": 1676,
"text": "mode: It is the mode in which change in the quantity monitored should be observed. This can be ‘min’ or ‘max’ or ‘auto’. When the monitored value is loss, its value is ‘min’. When the monitored value is accuracy, its value is ‘max’. When the mode is set is ‘auto’, the function automatically monitors with the suitable mode."
},
{
"code": null,
"e": 2159,
"s": 2001,
"text": "min_delta: The minimum value should be set for the change to be considered i.e., Change in the value being monitored should be higher than ‘min_delta’ value."
},
{
"code": null,
"e": 2337,
"s": 2159,
"text": "patience: Patience is the number of epochs for the training to be continued after the first halt. The model waits for patience number of epochs for any improvement in the model."
},
{
"code": null,
"e": 2697,
"s": 2337,
"text": "verbose: Verbose is an integer value-0, 1 or 2. This value is to select the way in which the progress is displayed while training.Verbose = 0: Silent mode-Nothing is displayed in this mode.Verbose = 1: A bar depicting the progress of training is displayed.Verbose = 2: In this mode, one line per epoch, showing the progress of training per epoch is displayed."
},
{
"code": null,
"e": 2757,
"s": 2697,
"text": "Verbose = 0: Silent mode-Nothing is displayed in this mode."
},
{
"code": null,
"e": 2825,
"s": 2757,
"text": "Verbose = 1: A bar depicting the progress of training is displayed."
},
{
"code": null,
"e": 2929,
"s": 2825,
"text": "Verbose = 2: In this mode, one line per epoch, showing the progress of training per epoch is displayed."
},
{
"code": null,
"e": 3027,
"s": 2929,
"text": "restore_best_weights: This is a boolean value. True value restores the weights which are optimal."
},
{
"code": null,
"e": 3103,
"s": 3027,
"text": "Finding the optimal number of epochs to avoid overfitting on MNIST dataset."
},
{
"code": null,
"e": 3145,
"s": 3103,
"text": "Step 1: Loading dataset and preprocessing"
},
{
"code": "import kerasfrom keras.utils.np_utils import to_categoricalfrom keras.datasets import mnist # Loading data(train_images, train_labels), (test_images, test_labels)= mnist.load_data() # Reshaping data-Adding number of channels as 1 (Grayscale images)train_images = train_images.reshape((train_images.shape[0], train_images.shape[1], train_images.shape[2], 1)) test_images = test_images.reshape((test_images.shape[0], test_images.shape[1], test_images.shape[2], 1)) # Scaling down pixel valuestrain_images = train_images.astype('float32')/255test_images = test_images.astype('float32')/255 # Encoding labels to a binary class matrixy_train = to_categorical(train_labels)y_test = to_categorical(test_labels)",
"e": 3997,
"s": 3145,
"text": null
},
{
"code": null,
"e": 4026,
"s": 3997,
"text": "Step 2: Building a CNN model"
},
{
"code": "from keras import modelsfrom keras import layers model = models.Sequential()model.add(layers.Conv2D(32, (3, 3), activation =\"relu\", input_shape =(28, 28, 1)))model.add(layers.MaxPooling2D(2, 2))model.add(layers.Conv2D(64, (3, 3), activation =\"relu\"))model.add(layers.MaxPooling2D(2, 2))model.add(layers.Flatten())model.add(layers.Dense(64, activation =\"relu\"))model.add(layers.Dense(10, activation =\"softmax\")) model.summary()",
"e": 4484,
"s": 4026,
"text": null
},
{
"code": null,
"e": 4513,
"s": 4484,
"text": "Output: Summary of the model"
},
{
"code": null,
"e": 4636,
"s": 4513,
"text": "Step 4: Compiling the model with RMSprop optimizer, categorical cross entropy loss function and accuracy as success metric"
},
{
"code": "model.compile(optimizer =\"rmsprop\", loss =\"categorical_crossentropy\", metrics =['accuracy'])",
"e": 4773,
"s": 4636,
"text": null
},
{
"code": null,
"e": 4863,
"s": 4773,
"text": "Step 5: Creating validation set and training set by partitioning the current training set"
},
{
"code": "val_images = train_images[:10000]partial_images = train_images[10000:]val_labels = y_train[:10000]partial_labels = y_train[10000:]",
"e": 4994,
"s": 4863,
"text": null
},
{
"code": null,
"e": 5061,
"s": 4994,
"text": "Step 6: Initializing earlystopping callback and training the model"
},
{
"code": "from keras import callbacksearlystopping = callbacks.EarlyStopping(monitor =\"val_loss\", mode =\"min\", patience = 5, restore_best_weights = True) history = model.fit(partial_images, partial_labels, batch_size = 128, epochs = 25, validation_data =(val_images, val_labels), callbacks =[earlystopping])",
"e": 5480,
"s": 5061,
"text": null
},
{
"code": null,
"e": 5636,
"s": 5480,
"text": "Training stopped at 11th epoch i.e., the model will start overfitting from 12th epoch. Therefore, the optimal number of epochs to train most dataset is 11."
},
{
"code": null,
"e": 5849,
"s": 5636,
"text": "Observing loss values without using Early Stopping call back function:Train the model up until 25 epochs and plot the training loss values and validation loss values against number of epochs. The plot looks like:"
},
{
"code": null,
"e": 6049,
"s": 5849,
"text": "Inference:As the number of epochs increases beyond 11, training set loss decreases and becomes nearly zero. Whereas, validation loss increases depicting the overfitting of the model on training data."
},
{
"code": null,
"e": 6061,
"s": 6049,
"text": "References:"
},
{
"code": null,
"e": 6089,
"s": 6061,
"text": "https://keras.io/callbacks/"
},
{
"code": null,
"e": 6116,
"s": 6089,
"text": "https://keras.io/datasets/"
},
{
"code": null,
"e": 6130,
"s": 6116,
"text": "Deep-Learning"
},
{
"code": null,
"e": 6145,
"s": 6130,
"text": "Neural Network"
},
{
"code": null,
"e": 6162,
"s": 6145,
"text": "Machine Learning"
},
{
"code": null,
"e": 6169,
"s": 6162,
"text": "Python"
},
{
"code": null,
"e": 6186,
"s": 6169,
"text": "Machine Learning"
},
{
"code": null,
"e": 6284,
"s": 6186,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6325,
"s": 6284,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 6361,
"s": 6325,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 6394,
"s": 6361,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 6418,
"s": 6394,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 6469,
"s": 6418,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 6497,
"s": 6469,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 6547,
"s": 6497,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 6569,
"s": 6547,
"text": "Python map() function"
}
] |
Migration to Open JDK from Oracle JDK
|
09 Mar, 2021
Let us first discuss the need for migration. It is as follows as in the year 2018, Oracle announced that after January 2019, businesses will need to purchase a commercial license (i.e., from Oracle) in order to receive software updates. Keep Oracle Java and upgrade to supported patch level and pay the subscription costs. To give you an idea of the cost, each core of the server must be licensed, and it costs US $25 core per month. Also, if the server is in a virtualized environment, the entire cluster “cores” would be liable for license fee even if you have just one server with Java in the cluster.
1. Pre-requisite: Let us go through technical requirements prior to comparing Oracle Java v/s Open JDK.
Oracle has introduced a subscription fee for anything newer than Oracle Java JE 8 patch 211 and JDK 11, and it is not ideal to keep the version at an older, non-supported patch level from a security vulnerability point of view. Therefore, we must determine if Oracle Java JE or JDK installed are indeed necessary to run any of the applications on the server or not.
For each server that you own, we ask that you select the appropriate response as follows:
Uninstall the Oracle Java versions if it/they are not needed
Opt to go with Open source versions again if compatible with your need
Note: Some applications which require Oracle Java may have included this cost as a part of the main application license fee, please validate this with your application vendor.
Keep Oracle Java and upgrade to supported patch level and pay the subscription costs. To give you an idea of the cost, each core of the server must be licensed, and it costs the US $25 core per month. Also, if the server is in a virtualized environment, the entire cluster “cores” would be liable for license fee even if you have just one server with Java in the cluster.
2. Existing Implementation of Oracle JDK
As per Oracle support the last non-billable Java version Java 1.8.0.202 (64 bit) let us first go through the highlights.
The biggest difference between OpenJDK and Oracle JDK is licensing. OpenJDK is a completely open-source Java with a GNU General Public License. Oracle JDK requires a commercial license under the Oracle Binary Code License Agreement.
Since January 2019, businesses now need to purchase a commercial license (from Oracle) in order to receive software updates.
Historically, Oracle JDK has had better performance than OpenJDK. However, the performance of OpenJDK is growing. And the contributions of the OpenJDK community often outperform Oracle JDK.
OpenJDK is 99% the same code as Oracle JDK (depending on what provider you’re getting it from) so what this really boils down to is support.
3. OpenJDK Lifecycle Dates and RHEL versions
RHEL 5 Support Added RHEL 6 Support Added RHEL 7 Support Added RHEL 8 Support Added End of Support for OpenJDK version is as follows:
OpenJDK 6 (1.6) 5.3 6.0 7.0 N/A December 2016
OpenJDK 7 (1.7) 5.9 6.3 7.0 N/A June 2020
OpenJDK 8 (1.8) N/A 6.6 7.1 8.0 May 2026
OpenJDK 11 N/A N/A 7.6 8.0 October 2024
The Service Level Agreement (SLA) and Scope of Coverage (SoC) for OpenJDK is determined as below, for production deployments of OpenJDK on RHEL and Windows the SoC is defined (Production Support Scope of Coverage that is Red Hat Customer Portal) and the SLA is defined (Production Support Terms of Service — Red Hat Customer Portal).
4. Release Schedule
Oracle will deliver releases every three years, while OpenJDK will be released every six months
5. License
Oracle JDK was licensed under the Oracle Binary Code License Agreement, whereas OpenJDK has the GNU General Public License (GNU GPL) version 2 with a linking exception.
6. Performance
There is no real technical difference between the two since the build process for the Oracle JDK is based on that of OpenJDK. When it comes to performance, Oracle’s is much better regarding responsiveness and JVM performance. It puts more focus on stability due to the importance it gives to its enterprise customers. OpenJDK, in contrast, will deliver releases more often. As a result, we can encounter problems with instability.
7. Features
If we compare features and options, we’ll see that the Oracle product has Flight Recorder, Java Mission Control, and Application Class-Data Sharing features, while OpenJDK has the Font Renderer feature. Also, Oracle has more Garbage Collection options and better renderers.
8. Development and Popularity
Oracle JDK is fully developed by Oracle Corporation whereas the OpenJDK is developed by Oracle, OpenJDK, and the Java Community. However, top-notch companies like Red Hat, Azul Systems, IBM, Apple Inc., SAP AG also take an active part in its development.
9. Cost-Benefit Analysis
Keep Oracle Java and upgrade to supported patch level and pay the subscription costs. To give you an idea of the cost, each core of the server must be licensed, and it costs US $25 core per month. Also, if the server is in a virtualized environment, the entire cluster “cores” would be liable for license fee even if you have just one server with Java in the cluster.
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 Mar, 2021"
},
{
"code": null,
"e": 660,
"s": 53,
"text": "Let us first discuss the need for migration. It is as follows as in the year 2018, Oracle announced that after January 2019, businesses will need to purchase a commercial license (i.e., from Oracle) in order to receive software updates. Keep Oracle Java and upgrade to supported patch level and pay the subscription costs. To give you an idea of the cost, each core of the server must be licensed, and it costs US $25 core per month. Also, if the server is in a virtualized environment, the entire cluster “cores” would be liable for license fee even if you have just one server with Java in the cluster."
},
{
"code": null,
"e": 764,
"s": 660,
"text": "1. Pre-requisite: Let us go through technical requirements prior to comparing Oracle Java v/s Open JDK."
},
{
"code": null,
"e": 1132,
"s": 764,
"text": "Oracle has introduced a subscription fee for anything newer than Oracle Java JE 8 patch 211 and JDK 11, and it is not ideal to keep the version at an older, non-supported patch level from a security vulnerability point of view. Therefore, we must determine if Oracle Java JE or JDK installed are indeed necessary to run any of the applications on the server or not."
},
{
"code": null,
"e": 1222,
"s": 1132,
"text": "For each server that you own, we ask that you select the appropriate response as follows:"
},
{
"code": null,
"e": 1283,
"s": 1222,
"text": "Uninstall the Oracle Java versions if it/they are not needed"
},
{
"code": null,
"e": 1354,
"s": 1283,
"text": "Opt to go with Open source versions again if compatible with your need"
},
{
"code": null,
"e": 1530,
"s": 1354,
"text": "Note: Some applications which require Oracle Java may have included this cost as a part of the main application license fee, please validate this with your application vendor."
},
{
"code": null,
"e": 1904,
"s": 1530,
"text": "Keep Oracle Java and upgrade to supported patch level and pay the subscription costs. To give you an idea of the cost, each core of the server must be licensed, and it costs the US $25 core per month. Also, if the server is in a virtualized environment, the entire cluster “cores” would be liable for license fee even if you have just one server with Java in the cluster."
},
{
"code": null,
"e": 1946,
"s": 1904,
"text": " 2. Existing Implementation of Oracle JDK"
},
{
"code": null,
"e": 2067,
"s": 1946,
"text": "As per Oracle support the last non-billable Java version Java 1.8.0.202 (64 bit) let us first go through the highlights."
},
{
"code": null,
"e": 2300,
"s": 2067,
"text": "The biggest difference between OpenJDK and Oracle JDK is licensing. OpenJDK is a completely open-source Java with a GNU General Public License. Oracle JDK requires a commercial license under the Oracle Binary Code License Agreement."
},
{
"code": null,
"e": 2425,
"s": 2300,
"text": "Since January 2019, businesses now need to purchase a commercial license (from Oracle) in order to receive software updates."
},
{
"code": null,
"e": 2615,
"s": 2425,
"text": "Historically, Oracle JDK has had better performance than OpenJDK. However, the performance of OpenJDK is growing. And the contributions of the OpenJDK community often outperform Oracle JDK."
},
{
"code": null,
"e": 2756,
"s": 2615,
"text": "OpenJDK is 99% the same code as Oracle JDK (depending on what provider you’re getting it from) so what this really boils down to is support."
},
{
"code": null,
"e": 2801,
"s": 2756,
"text": "3. OpenJDK Lifecycle Dates and RHEL versions"
},
{
"code": null,
"e": 2935,
"s": 2801,
"text": "RHEL 5 Support Added RHEL 6 Support Added RHEL 7 Support Added RHEL 8 Support Added End of Support for OpenJDK version is as follows:"
},
{
"code": null,
"e": 3109,
"s": 2935,
"text": "OpenJDK 6 (1.6) 5.3 6.0 7.0 N/A December 2016\nOpenJDK 7 (1.7) 5.9 6.3 7.0 N/A June 2020\nOpenJDK 8 (1.8) N/A 6.6 7.1 8.0 May 2026\nOpenJDK 11 N/A N/A 7.6 8.0 October 2024"
},
{
"code": null,
"e": 3443,
"s": 3109,
"text": "The Service Level Agreement (SLA) and Scope of Coverage (SoC) for OpenJDK is determined as below, for production deployments of OpenJDK on RHEL and Windows the SoC is defined (Production Support Scope of Coverage that is Red Hat Customer Portal) and the SLA is defined (Production Support Terms of Service — Red Hat Customer Portal)."
},
{
"code": null,
"e": 3463,
"s": 3443,
"text": "4. Release Schedule"
},
{
"code": null,
"e": 3559,
"s": 3463,
"text": "Oracle will deliver releases every three years, while OpenJDK will be released every six months"
},
{
"code": null,
"e": 3570,
"s": 3559,
"text": "5. License"
},
{
"code": null,
"e": 3739,
"s": 3570,
"text": "Oracle JDK was licensed under the Oracle Binary Code License Agreement, whereas OpenJDK has the GNU General Public License (GNU GPL) version 2 with a linking exception."
},
{
"code": null,
"e": 3755,
"s": 3739,
"text": "6. Performance "
},
{
"code": null,
"e": 4186,
"s": 3755,
"text": "There is no real technical difference between the two since the build process for the Oracle JDK is based on that of OpenJDK. When it comes to performance, Oracle’s is much better regarding responsiveness and JVM performance. It puts more focus on stability due to the importance it gives to its enterprise customers. OpenJDK, in contrast, will deliver releases more often. As a result, we can encounter problems with instability."
},
{
"code": null,
"e": 4198,
"s": 4186,
"text": "7. Features"
},
{
"code": null,
"e": 4472,
"s": 4198,
"text": "If we compare features and options, we’ll see that the Oracle product has Flight Recorder, Java Mission Control, and Application Class-Data Sharing features, while OpenJDK has the Font Renderer feature. Also, Oracle has more Garbage Collection options and better renderers."
},
{
"code": null,
"e": 4502,
"s": 4472,
"text": "8. Development and Popularity"
},
{
"code": null,
"e": 4757,
"s": 4502,
"text": "Oracle JDK is fully developed by Oracle Corporation whereas the OpenJDK is developed by Oracle, OpenJDK, and the Java Community. However, top-notch companies like Red Hat, Azul Systems, IBM, Apple Inc., SAP AG also take an active part in its development."
},
{
"code": null,
"e": 4782,
"s": 4757,
"text": "9. Cost-Benefit Analysis"
},
{
"code": null,
"e": 5151,
"s": 4782,
"text": "Keep Oracle Java and upgrade to supported patch level and pay the subscription costs. To give you an idea of the cost, each core of the server must be licensed, and it costs US $25 core per month. Also, if the server is in a virtualized environment, the entire cluster “cores” would be liable for license fee even if you have just one server with Java in the cluster."
},
{
"code": null,
"e": 5175,
"s": 5151,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 5180,
"s": 5175,
"text": "Java"
},
{
"code": null,
"e": 5199,
"s": 5180,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5204,
"s": 5199,
"text": "Java"
}
] |
DoubleFunction Interface in Java with Examples
|
08 Oct, 2018
The DoubleFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and produces a result of type R.
This functional interface takes in only one generic, namely:-
R: denotes the type of the output of this function
The lambda expression assigned to an object of DoubleFunction type is used to define its apply() which eventually applies the given operation on its only argument. It is similar to using an object of type Function<Double, R>.
The DoubleFunction interface has only one function:
This method accepts a double-valued argument and gives a result of type R.
Syntax:
R apply(double value)
Parameters: This method takes in one parameter value which is a double-valued argument.
Returns: This method returns a value of type R.
Below is the code to illustrate apply() method:
Program
import java.util.function.DoubleFunction; public class Main { public static void main(String args[]) { DoubleFunction<Integer> ob = a -> (int)(a * 10); // Using apply() method System.out.println(ob.apply(3.2)); }}
32
Java - util package
Java 8
java-basics
java-interfaces
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Oct, 2018"
},
{
"code": null,
"e": 284,
"s": 28,
"text": "The DoubleFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and produces a result of type R."
},
{
"code": null,
"e": 346,
"s": 284,
"text": "This functional interface takes in only one generic, namely:-"
},
{
"code": null,
"e": 397,
"s": 346,
"text": "R: denotes the type of the output of this function"
},
{
"code": null,
"e": 623,
"s": 397,
"text": "The lambda expression assigned to an object of DoubleFunction type is used to define its apply() which eventually applies the given operation on its only argument. It is similar to using an object of type Function<Double, R>."
},
{
"code": null,
"e": 675,
"s": 623,
"text": "The DoubleFunction interface has only one function:"
},
{
"code": null,
"e": 750,
"s": 675,
"text": "This method accepts a double-valued argument and gives a result of type R."
},
{
"code": null,
"e": 758,
"s": 750,
"text": "Syntax:"
},
{
"code": null,
"e": 780,
"s": 758,
"text": "R apply(double value)"
},
{
"code": null,
"e": 868,
"s": 780,
"text": "Parameters: This method takes in one parameter value which is a double-valued argument."
},
{
"code": null,
"e": 916,
"s": 868,
"text": "Returns: This method returns a value of type R."
},
{
"code": null,
"e": 964,
"s": 916,
"text": "Below is the code to illustrate apply() method:"
},
{
"code": null,
"e": 972,
"s": 964,
"text": "Program"
},
{
"code": "import java.util.function.DoubleFunction; public class Main { public static void main(String args[]) { DoubleFunction<Integer> ob = a -> (int)(a * 10); // Using apply() method System.out.println(ob.apply(3.2)); }}",
"e": 1219,
"s": 972,
"text": null
},
{
"code": null,
"e": 1223,
"s": 1219,
"text": "32\n"
},
{
"code": null,
"e": 1243,
"s": 1223,
"text": "Java - util package"
},
{
"code": null,
"e": 1250,
"s": 1243,
"text": "Java 8"
},
{
"code": null,
"e": 1262,
"s": 1250,
"text": "java-basics"
},
{
"code": null,
"e": 1278,
"s": 1262,
"text": "java-interfaces"
},
{
"code": null,
"e": 1292,
"s": 1278,
"text": "Java Programs"
}
] |
Scala | reduce() Function
|
01 Jun, 2021
The reduce() method is a higher-order function that takes all the elements in a collection (Array, List, etc) and combines them using a binary operation to produce a single value. It is necessary to make sure that operations are commutative and associative. Anonymous functions are passed as parameter to the reduce function. Syntax:
val l = List(2, 5, 3, 6, 4, 7)
// returns the largest number from the collection
l.reduce((x, y) => x max y)
The order in which numbers are selected for operation by the reduce method is random. This is the reason why non-commutative and non-associative operations are not preferred. Example :
scala
// Scala program to// print maximum value// using reduce() // Creating objectobject GfG{ // Main methoddef main(args:Array[String]){ // source collection val collection = List(1, 3, 2, 5, 4, 7, 6) // finding the maximum valued element val res = collection.reduce((x, y) => x max y) println(res)}}
Output :
7
In the above program, the reduce method selects random pairs and finds out the maximum value in a particular pair. These values are again compared with each other until a single maximum valued element is obtained. We generally make use of the reduce() method along with the map() method while working with Resilient Distributed Datasets in Spark. The map() method helps us to transform a collection to another collection while the reduce() method allows us to perform some action.Finding average using map() and reduce(): Example :
scala
// Scala program to// print average// using map() and reduce() //Creating objectobject GfG{ // Main methoddef main(args:Array[String]){ // source collection val collection = List(1, 5, 7, 8) // converting every element to a pair of the form (x,1) // 1 is initial frequency of all elements val new_collection = collection.map(x => (x,1)) /* List((1, 1), (5, 1), (7, 1), (8, 1)) */ // adding elements at corresponding positions val res = new_collection.reduce( (a,b) => ( a._1 + b._1, a._2 + b._2 ) ) /* (21, 4) */ println(res) println("Average="+ res._1/res._2.toFloat)}}
Output:
(21, 4)
Average= 5.25
In the above program, all elements of the collection are transformed into tuples with two elements. First element of the tuple is the number itself and the second element is the counter. Initially all counters are set to 1. The output itself is a tuple with two elements: first value is the sum and the second value is the number of elements. Note: Type of output given by reduce() method is same as the type of elements of the collection.
simmytarika5
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 389,
"s": 53,
"text": "The reduce() method is a higher-order function that takes all the elements in a collection (Array, List, etc) and combines them using a binary operation to produce a single value. It is necessary to make sure that operations are commutative and associative. Anonymous functions are passed as parameter to the reduce function. Syntax: "
},
{
"code": null,
"e": 498,
"s": 389,
"text": "val l = List(2, 5, 3, 6, 4, 7)\n// returns the largest number from the collection\nl.reduce((x, y) => x max y)"
},
{
"code": null,
"e": 685,
"s": 498,
"text": "The order in which numbers are selected for operation by the reduce method is random. This is the reason why non-commutative and non-associative operations are not preferred. Example : "
},
{
"code": null,
"e": 691,
"s": 685,
"text": "scala"
},
{
"code": "// Scala program to// print maximum value// using reduce() // Creating objectobject GfG{ // Main methoddef main(args:Array[String]){ // source collection val collection = List(1, 3, 2, 5, 4, 7, 6) // finding the maximum valued element val res = collection.reduce((x, y) => x max y) println(res)}}",
"e": 1009,
"s": 691,
"text": null
},
{
"code": null,
"e": 1020,
"s": 1009,
"text": "Output : "
},
{
"code": null,
"e": 1022,
"s": 1020,
"text": "7"
},
{
"code": null,
"e": 1556,
"s": 1022,
"text": "In the above program, the reduce method selects random pairs and finds out the maximum value in a particular pair. These values are again compared with each other until a single maximum valued element is obtained. We generally make use of the reduce() method along with the map() method while working with Resilient Distributed Datasets in Spark. The map() method helps us to transform a collection to another collection while the reduce() method allows us to perform some action.Finding average using map() and reduce(): Example : "
},
{
"code": null,
"e": 1562,
"s": 1556,
"text": "scala"
},
{
"code": "// Scala program to// print average// using map() and reduce() //Creating objectobject GfG{ // Main methoddef main(args:Array[String]){ // source collection val collection = List(1, 5, 7, 8) // converting every element to a pair of the form (x,1) // 1 is initial frequency of all elements val new_collection = collection.map(x => (x,1)) /* List((1, 1), (5, 1), (7, 1), (8, 1)) */ // adding elements at corresponding positions val res = new_collection.reduce( (a,b) => ( a._1 + b._1, a._2 + b._2 ) ) /* (21, 4) */ println(res) println(\"Average=\"+ res._1/res._2.toFloat)}}",
"e": 2229,
"s": 1562,
"text": null
},
{
"code": null,
"e": 2239,
"s": 2229,
"text": "Output: "
},
{
"code": null,
"e": 2261,
"s": 2239,
"text": "(21, 4)\nAverage= 5.25"
},
{
"code": null,
"e": 2702,
"s": 2261,
"text": "In the above program, all elements of the collection are transformed into tuples with two elements. First element of the tuple is the number itself and the second element is the counter. Initially all counters are set to 1. The output itself is a tuple with two elements: first value is the sum and the second value is the number of elements. Note: Type of output given by reduce() method is same as the type of elements of the collection. "
},
{
"code": null,
"e": 2715,
"s": 2702,
"text": "simmytarika5"
},
{
"code": null,
"e": 2721,
"s": 2715,
"text": "Scala"
},
{
"code": null,
"e": 2734,
"s": 2721,
"text": "Scala-Method"
},
{
"code": null,
"e": 2740,
"s": 2734,
"text": "Scala"
}
] |
What is the difference between printf, sprintf and fprintf?
|
13 Dec, 2018
printf:printf function is used to print character stream of data on stdout console.
Syntax :
int printf(const char* str, ...);
Example :
// simple print on stdout #include<stdio.h>int main(){ printf("hello geeksquiz"); return 0;}
Output :
hello geeksquiz
sprintf:Syntax:
int sprintf(char *str, const char *string,...);
String print function instead of printing on console store it on char buffer which are specified in sprintf
Example :
// Example program to demonstrate sprintf()#include<stdio.h>int main(){ char buffer[50]; int a = 10, b = 20, c; c = a + b; sprintf(buffer, "Sum of %d and %d is %d", a, b, c); // The string "sum of 10 and 20 is 30" is stored // into buffer instead of printing on stdout printf("%s", buffer); return 0;}
Output :
Sum of 10 and 20 is 30
fprintf:fprintf is used to print the string content in file but not on stdout console.
int fprintf(FILE *fptr, const char *str, ...);
Example :
#include<stdio.h>int main(){ int i, n=2; char str[50]; //open file sample.txt in write mode FILE *fptr = fopen("sample.txt", "w"); if (fptr == NULL) { printf("Could not open file"); return 0; } for (i=0; i<n; i++) { puts("Enter a name"); gets(str); fprintf(fptr,"%d.%s\n", i, str); } fclose(fptr); return 0;}
Input: GeeksforGeeks
GeeksQuiz
Output : sample.txt file now having output as
0. GeeksforGeeks
1. GeeksQuiz
Thank you for reading, i will soon update with scanf, fscanf, sscanf keep tuned.
This article is contributed by Vankayala Karunakar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
mikerua
C-Input and Output Quiz
c-input-output
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Functions that cannot be overloaded in C++
Exception Handling in C++
Function Pointer in C
Command line arguments in C/C++
Different Methods to Reverse a String in C++
Structures in C
Switch Statement in C/C++
std::string class in C++
Functions in C/C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Dec, 2018"
},
{
"code": null,
"e": 136,
"s": 52,
"text": "printf:printf function is used to print character stream of data on stdout console."
},
{
"code": null,
"e": 145,
"s": 136,
"text": "Syntax :"
},
{
"code": null,
"e": 181,
"s": 145,
"text": " int printf(const char* str, ...); "
},
{
"code": null,
"e": 191,
"s": 181,
"text": "Example :"
},
{
"code": "// simple print on stdout #include<stdio.h>int main(){ printf(\"hello geeksquiz\"); return 0;}",
"e": 288,
"s": 191,
"text": null
},
{
"code": null,
"e": 297,
"s": 288,
"text": "Output :"
},
{
"code": null,
"e": 314,
"s": 297,
"text": " hello geeksquiz"
},
{
"code": null,
"e": 330,
"s": 314,
"text": "sprintf:Syntax:"
},
{
"code": null,
"e": 379,
"s": 330,
"text": "int sprintf(char *str, const char *string,...); "
},
{
"code": null,
"e": 487,
"s": 379,
"text": "String print function instead of printing on console store it on char buffer which are specified in sprintf"
},
{
"code": null,
"e": 497,
"s": 487,
"text": "Example :"
},
{
"code": "// Example program to demonstrate sprintf()#include<stdio.h>int main(){ char buffer[50]; int a = 10, b = 20, c; c = a + b; sprintf(buffer, \"Sum of %d and %d is %d\", a, b, c); // The string \"sum of 10 and 20 is 30\" is stored // into buffer instead of printing on stdout printf(\"%s\", buffer); return 0;}",
"e": 828,
"s": 497,
"text": null
},
{
"code": null,
"e": 837,
"s": 828,
"text": "Output :"
},
{
"code": null,
"e": 860,
"s": 837,
"text": "Sum of 10 and 20 is 30"
},
{
"code": null,
"e": 947,
"s": 860,
"text": "fprintf:fprintf is used to print the string content in file but not on stdout console."
},
{
"code": null,
"e": 994,
"s": 947,
"text": "int fprintf(FILE *fptr, const char *str, ...);"
},
{
"code": null,
"e": 1004,
"s": 994,
"text": "Example :"
},
{
"code": "#include<stdio.h>int main(){ int i, n=2; char str[50]; //open file sample.txt in write mode FILE *fptr = fopen(\"sample.txt\", \"w\"); if (fptr == NULL) { printf(\"Could not open file\"); return 0; } for (i=0; i<n; i++) { puts(\"Enter a name\"); gets(str); fprintf(fptr,\"%d.%s\\n\", i, str); } fclose(fptr); return 0;}",
"e": 1390,
"s": 1004,
"text": null
},
{
"code": null,
"e": 1506,
"s": 1390,
"text": "Input: GeeksforGeeks\n GeeksQuiz\nOutput : sample.txt file now having output as \n0. GeeksforGeeks\n1. GeeksQuiz"
},
{
"code": null,
"e": 1587,
"s": 1506,
"text": "Thank you for reading, i will soon update with scanf, fscanf, sscanf keep tuned."
},
{
"code": null,
"e": 1764,
"s": 1587,
"text": "This article is contributed by Vankayala Karunakar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1772,
"s": 1764,
"text": "mikerua"
},
{
"code": null,
"e": 1796,
"s": 1772,
"text": "C-Input and Output Quiz"
},
{
"code": null,
"e": 1811,
"s": 1796,
"text": "c-input-output"
},
{
"code": null,
"e": 1822,
"s": 1811,
"text": "C Language"
},
{
"code": null,
"e": 1920,
"s": 1822,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1937,
"s": 1920,
"text": "Substring in C++"
},
{
"code": null,
"e": 1980,
"s": 1937,
"text": "Functions that cannot be overloaded in C++"
},
{
"code": null,
"e": 2006,
"s": 1980,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 2028,
"s": 2006,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 2060,
"s": 2028,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 2105,
"s": 2060,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 2121,
"s": 2105,
"text": "Structures in C"
},
{
"code": null,
"e": 2147,
"s": 2121,
"text": "Switch Statement in C/C++"
},
{
"code": null,
"e": 2172,
"s": 2147,
"text": "std::string class in C++"
}
] |
MatSnackBar in Angular Material
|
23 Feb, 2021
Angular Material is a UI component library developed by Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have done it you can enter the below command and can download it. MatSnackBar is used to display information or text from bottom of the screen when performing any action.
Installation syntax:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatSnackBarModule’ from ‘@angular/material/snack-bar’ in the app.module.ts file.
First we need to create an instance for ‘MatSnackBar’. Then we need to invoke a function on button click.
Using this instance we get access to open() function which is in-built.
Now we need to mention the duration of the message.
Once done with the above steps then serve or start the project.
Code Implementation:
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import {MatSnackBarModule} from '@angular/material/snack-bar';import { MatButtonModule } from '@angular/material/button'; @NgModule({ imports: [ BrowserModule, FormsModule, MatButtonModule, MatSnackBarModule, BrowserAnimationsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
app.component.ts
import { Component } from '@angular/core';import {MatSnackBar} from '@angular/material/snack-bar'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent { constructor(private _snackBar: MatSnackBar) {} openSnackBar(message: string, action: string) { this._snackBar.open(message, action, { duration: 2000, }); }}
app.component.html:
HTML
<button mat-stroked-button (click)= "openSnackBar('GAME ONE','HURRAH !!!!!')"> Show snack-bar Message</button> <p> By Clicking on above button we can invoke the function and it will, render the message of snack-bar</p>
Output:
Angular-material
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 419,
"s": 28,
"text": "Angular Material is a UI component library developed by Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have done it you can enter the below command and can download it. MatSnackBar is used to display information or text from bottom of the screen when performing any action."
},
{
"code": null,
"e": 440,
"s": 419,
"text": "Installation syntax:"
},
{
"code": null,
"e": 465,
"s": 440,
"text": "ng add @angular/material"
},
{
"code": null,
"e": 475,
"s": 465,
"text": "Approach:"
},
{
"code": null,
"e": 546,
"s": 475,
"text": "First, install the angular material using the above-mentioned command."
},
{
"code": null,
"e": 670,
"s": 546,
"text": "After completing the installation, Import ‘MatSnackBarModule’ from ‘@angular/material/snack-bar’ in the app.module.ts file."
},
{
"code": null,
"e": 776,
"s": 670,
"text": "First we need to create an instance for ‘MatSnackBar’. Then we need to invoke a function on button click."
},
{
"code": null,
"e": 848,
"s": 776,
"text": "Using this instance we get access to open() function which is in-built."
},
{
"code": null,
"e": 900,
"s": 848,
"text": "Now we need to mention the duration of the message."
},
{
"code": null,
"e": 964,
"s": 900,
"text": "Once done with the above steps then serve or start the project."
},
{
"code": null,
"e": 985,
"s": 964,
"text": "Code Implementation:"
},
{
"code": null,
"e": 999,
"s": 985,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import {MatSnackBarModule} from '@angular/material/snack-bar';import { MatButtonModule } from '@angular/material/button'; @NgModule({ imports: [ BrowserModule, FormsModule, MatButtonModule, MatSnackBarModule, BrowserAnimationsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }",
"e": 1686,
"s": 999,
"text": null
},
{
"code": null,
"e": 1703,
"s": 1686,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core';import {MatSnackBar} from '@angular/material/snack-bar'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent { constructor(private _snackBar: MatSnackBar) {} openSnackBar(message: string, action: string) { this._snackBar.open(message, action, { duration: 2000, }); }}",
"e": 2120,
"s": 1703,
"text": null
},
{
"code": null,
"e": 2140,
"s": 2120,
"text": "app.component.html:"
},
{
"code": null,
"e": 2145,
"s": 2140,
"text": "HTML"
},
{
"code": "<button mat-stroked-button (click)= \"openSnackBar('GAME ONE','HURRAH !!!!!')\"> Show snack-bar Message</button> <p> By Clicking on above button we can invoke the function and it will, render the message of snack-bar</p>",
"e": 2382,
"s": 2145,
"text": null
},
{
"code": null,
"e": 2390,
"s": 2382,
"text": "Output:"
},
{
"code": null,
"e": 2409,
"s": 2392,
"text": "Angular-material"
},
{
"code": null,
"e": 2416,
"s": 2409,
"text": "Picked"
},
{
"code": null,
"e": 2426,
"s": 2416,
"text": "AngularJS"
},
{
"code": null,
"e": 2443,
"s": 2426,
"text": "Web Technologies"
},
{
"code": null,
"e": 2541,
"s": 2443,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2565,
"s": 2541,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 2600,
"s": 2565,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 2624,
"s": 2600,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 2677,
"s": 2624,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 2726,
"s": 2677,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 2759,
"s": 2726,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2821,
"s": 2759,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2882,
"s": 2821,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2932,
"s": 2882,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python | Rearrange Positive and Negative Elements
|
05 Sep, 2019
Sometimes, while working with Python lists, we can have a problem in which we need to perform a sort in list. There are many variations of sorting that might be required to perform. Once such variation can be to sort elements of list, but keeping in mind, positive elements appear before negative elements. Let’s discuss a way in which this task can be performed.
Method : Using sorted() + lambdaThis task can be performed using combination of above functions. In this, the logic we apply is computing inverse and negative of each number and then perform the sort using sorted(). The inversion makes sure that larger magnitude elements occur at middle and smaller at ends ( hill arrangement ) and negative takes care of making positives occur before negatives.
# Python3 code to demonstrate working of# Sort while keeping Positive elements before negatives# using sorted() + lambda # initialize listtest_list = [4, -8, -6, 3, -5, 8, 10, 5, -19] # printing original listprint("The original list is : " + str(test_list)) # Sort while keeping Positive elements before negatives# using sorted() + lambdares = sorted(test_list, key = lambda i: 0 if i == 0 else -1 / i) # printing resultprint("Result after performing sort operation : " + str(res))
The original list is : [4, -8, -6, 3, -5, 8, 10, 5, -19]
Result after performing sort operation : [3, 4, 5, 8, 10, -19, -8, -6, -5]
Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 392,
"s": 28,
"text": "Sometimes, while working with Python lists, we can have a problem in which we need to perform a sort in list. There are many variations of sorting that might be required to perform. Once such variation can be to sort elements of list, but keeping in mind, positive elements appear before negative elements. Let’s discuss a way in which this task can be performed."
},
{
"code": null,
"e": 789,
"s": 392,
"text": "Method : Using sorted() + lambdaThis task can be performed using combination of above functions. In this, the logic we apply is computing inverse and negative of each number and then perform the sort using sorted(). The inversion makes sure that larger magnitude elements occur at middle and smaller at ends ( hill arrangement ) and negative takes care of making positives occur before negatives."
},
{
"code": "# Python3 code to demonstrate working of# Sort while keeping Positive elements before negatives# using sorted() + lambda # initialize listtest_list = [4, -8, -6, 3, -5, 8, 10, 5, -19] # printing original listprint(\"The original list is : \" + str(test_list)) # Sort while keeping Positive elements before negatives# using sorted() + lambdares = sorted(test_list, key = lambda i: 0 if i == 0 else -1 / i) # printing resultprint(\"Result after performing sort operation : \" + str(res))",
"e": 1275,
"s": 789,
"text": null
},
{
"code": null,
"e": 1408,
"s": 1275,
"text": "The original list is : [4, -8, -6, 3, -5, 8, 10, 5, -19]\nResult after performing sort operation : [3, 4, 5, 8, 10, -19, -8, -6, -5]\n"
},
{
"code": null,
"e": 1429,
"s": 1408,
"text": "Python list-programs"
},
{
"code": null,
"e": 1436,
"s": 1429,
"text": "Python"
}
] |
How to convert C style strings to std::string and vice versa?
|
06 Jul, 2017
What are C style strings?These strings are array of characters terminating with a NULL character. C style strings can be declared in following ways:
Declaration and initialization
/* To demonstrate C style strings */#include<iostream>using namespace std;int main(){ /* Null character has to be added explicitly */ char str1[8] = {'H' , 'E' , 'L' , 'L' , 'O' , '-','1','\0' }; /* Compiler implicitly adds Null character */ char str2[] = "HELLO-2" ; /* Compiler implicitly adds Null character. Note that string literals are typically stored as read only */ const char *str3 = "HELLO-3" ; cout << str1 << endl << str2 << endl << str3; return 0;}
Output:
HELLO-1
HELLO-2
HELLO-3
C style strings are operated with very useful functions like strcpy(), strlen(), strpbrk(), strcat(), strstr() and many more!(All these functions are member functions of ‘cstring‘ header ).
What is a std::string?C++ standard library contains functions and classes. String is one of its classes. Here we deal with an object of string class. This std::string takes care of itself and manages its own memory.
Declaration and initialization
/* To demonstrate std::string */#include<iostream>#include<string> using namespace std;int main(){ /* s becomes object of class string. */ string s; /* Initializing with a value. */ s = "HELLO"; /* Printing the value */ cout << s; return 0;}
Output:
HELLO
Converting C-String to a std::string.But why do we need this transformation? From a C string to a std::string? It is because
Std::string manages its own space. So programmer don’t need to worry about memory , unlike C strings (Since they are array of characters)
They are easy to operate. ‘+’ operator for concatenation, ‘=’ for assignment, can be compared using regular operators.
string::find() and many other functions can be implemented on std::string and not on C-Strings so this becomes handy.
Iterators can be used in std::string and not in C-strings.
And many more! Here is the code for it:-
/* To demonstrate C style string to std::string */#include<bits/stdc++.h> using namespace std;int main(){ /*Initializing a C-String */ const char *a = "Testing"; cout << "This is a C-String : "<< a << endl; /* This is how std::string s is assigned though a C string ‘a’ */ string s(a); /* Now s is a std::string and a is a C-String */ cout << "This is a std::string : "<< s << endl; return 0;}
Output:
This is a C-String : Testing
This is a std::string : Testing
The above conversion also works for character array.
// Character array to std::string conversion
char a[] = "Testing";
string s(a);
Converting a std::string to a C style stringWhy do we need this transformation? From std::string to a C string?
It is because there are several powerful functions in header that makes our work very much easier.
atoi() , itoa() , and many more functions work with C strings only.
You can think of other reasons too!Here is the code for conversion:-
/* To demonstrate std::string to C style string */#include<iostream>#include<string> /* This header contains string class */using namespace std;int main(){ /* std::string initialized */ string s = "Testing"; cout << "This is a std::string : "<< s << endl; /* Address of first character of std::string is stored to char pointer a */ char *a = &(s[0]); /* Now 'a' has address of starting character of string */ printf("%s\n", a); return 0;}
Output:
This is a std::string : Testing
This is a C-String : Testing
std::string also has a function c_str() that can be used to get a null terminated character array.
/* To demonstrate std::string to C style string using c_str() */#include<bits/stdc++.h>using namespace std; int main(){ /* std::string initialized */ string s = "Testing"; cout << "This is a std::string : "<< s << endl; // c_str returns null terminated array of characters const char *a = s.c_str(); /* Now 'a' has address of starting character of string */ printf("%s\n", a); return 0;}
Output:
This is a std::string : Testing
This is a C-String : Testing
Both C strings and std::strings have their own advantages. One should know conversion between them, to solve problems easily and effectively.Related articles:C++ string class and its applications | Set 1C++ string class and its applications | Set 2
This article is contributed by Nishant. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-string
cpp-strings-library
STL
C Language
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Jul, 2017"
},
{
"code": null,
"e": 202,
"s": 53,
"text": "What are C style strings?These strings are array of characters terminating with a NULL character. C style strings can be declared in following ways:"
},
{
"code": null,
"e": 233,
"s": 202,
"text": "Declaration and initialization"
},
{
"code": "/* To demonstrate C style strings */#include<iostream>using namespace std;int main(){ /* Null character has to be added explicitly */ char str1[8] = {'H' , 'E' , 'L' , 'L' , 'O' , '-','1','\\0' }; /* Compiler implicitly adds Null character */ char str2[] = \"HELLO-2\" ; /* Compiler implicitly adds Null character. Note that string literals are typically stored as read only */ const char *str3 = \"HELLO-3\" ; cout << str1 << endl << str2 << endl << str3; return 0;} ",
"e": 767,
"s": 233,
"text": null
},
{
"code": null,
"e": 775,
"s": 767,
"text": "Output:"
},
{
"code": null,
"e": 800,
"s": 775,
"text": "HELLO-1\nHELLO-2\nHELLO-3\n"
},
{
"code": null,
"e": 990,
"s": 800,
"text": "C style strings are operated with very useful functions like strcpy(), strlen(), strpbrk(), strcat(), strstr() and many more!(All these functions are member functions of ‘cstring‘ header )."
},
{
"code": null,
"e": 1206,
"s": 990,
"text": "What is a std::string?C++ standard library contains functions and classes. String is one of its classes. Here we deal with an object of string class. This std::string takes care of itself and manages its own memory."
},
{
"code": null,
"e": 1237,
"s": 1206,
"text": "Declaration and initialization"
},
{
"code": "/* To demonstrate std::string */#include<iostream>#include<string> using namespace std;int main(){ /* s becomes object of class string. */ string s; /* Initializing with a value. */ s = \"HELLO\"; /* Printing the value */ cout << s; return 0;}",
"e": 1555,
"s": 1237,
"text": null
},
{
"code": null,
"e": 1563,
"s": 1555,
"text": "Output:"
},
{
"code": null,
"e": 1570,
"s": 1563,
"text": "HELLO\n"
},
{
"code": null,
"e": 1695,
"s": 1570,
"text": "Converting C-String to a std::string.But why do we need this transformation? From a C string to a std::string? It is because"
},
{
"code": null,
"e": 1833,
"s": 1695,
"text": "Std::string manages its own space. So programmer don’t need to worry about memory , unlike C strings (Since they are array of characters)"
},
{
"code": null,
"e": 1952,
"s": 1833,
"text": "They are easy to operate. ‘+’ operator for concatenation, ‘=’ for assignment, can be compared using regular operators."
},
{
"code": null,
"e": 2070,
"s": 1952,
"text": "string::find() and many other functions can be implemented on std::string and not on C-Strings so this becomes handy."
},
{
"code": null,
"e": 2129,
"s": 2070,
"text": "Iterators can be used in std::string and not in C-strings."
},
{
"code": null,
"e": 2170,
"s": 2129,
"text": "And many more! Here is the code for it:-"
},
{
"code": "/* To demonstrate C style string to std::string */#include<bits/stdc++.h> using namespace std;int main(){ /*Initializing a C-String */ const char *a = \"Testing\"; cout << \"This is a C-String : \"<< a << endl; /* This is how std::string s is assigned though a C string ‘a’ */ string s(a); /* Now s is a std::string and a is a C-String */ cout << \"This is a std::string : \"<< s << endl; return 0;}",
"e": 2606,
"s": 2170,
"text": null
},
{
"code": null,
"e": 2614,
"s": 2606,
"text": "Output:"
},
{
"code": null,
"e": 2676,
"s": 2614,
"text": "This is a C-String : Testing\nThis is a std::string : Testing\n"
},
{
"code": null,
"e": 2729,
"s": 2676,
"text": "The above conversion also works for character array."
},
{
"code": null,
"e": 2822,
"s": 2729,
"text": " // Character array to std::string conversion \n\tchar a[] = \"Testing\"; \n\tstring s(a); "
},
{
"code": null,
"e": 2934,
"s": 2822,
"text": "Converting a std::string to a C style stringWhy do we need this transformation? From std::string to a C string?"
},
{
"code": null,
"e": 3033,
"s": 2934,
"text": "It is because there are several powerful functions in header that makes our work very much easier."
},
{
"code": null,
"e": 3101,
"s": 3033,
"text": "atoi() , itoa() , and many more functions work with C strings only."
},
{
"code": null,
"e": 3170,
"s": 3101,
"text": "You can think of other reasons too!Here is the code for conversion:-"
},
{
"code": "/* To demonstrate std::string to C style string */#include<iostream>#include<string> /* This header contains string class */using namespace std;int main(){ /* std::string initialized */ string s = \"Testing\"; cout << \"This is a std::string : \"<< s << endl; /* Address of first character of std::string is stored to char pointer a */ char *a = &(s[0]); /* Now 'a' has address of starting character of string */ printf(\"%s\\n\", a); return 0;}",
"e": 3670,
"s": 3170,
"text": null
},
{
"code": null,
"e": 3678,
"s": 3670,
"text": "Output:"
},
{
"code": null,
"e": 3740,
"s": 3678,
"text": "This is a std::string : Testing\nThis is a C-String : Testing\n"
},
{
"code": null,
"e": 3839,
"s": 3740,
"text": "std::string also has a function c_str() that can be used to get a null terminated character array."
},
{
"code": "/* To demonstrate std::string to C style string using c_str() */#include<bits/stdc++.h>using namespace std; int main(){ /* std::string initialized */ string s = \"Testing\"; cout << \"This is a std::string : \"<< s << endl; // c_str returns null terminated array of characters const char *a = s.c_str(); /* Now 'a' has address of starting character of string */ printf(\"%s\\n\", a); return 0;}",
"e": 4282,
"s": 3839,
"text": null
},
{
"code": null,
"e": 4290,
"s": 4282,
"text": "Output:"
},
{
"code": null,
"e": 4352,
"s": 4290,
"text": "This is a std::string : Testing\nThis is a C-String : Testing\n"
},
{
"code": null,
"e": 4601,
"s": 4352,
"text": "Both C strings and std::strings have their own advantages. One should know conversion between them, to solve problems easily and effectively.Related articles:C++ string class and its applications | Set 1C++ string class and its applications | Set 2"
},
{
"code": null,
"e": 4896,
"s": 4601,
"text": "This article is contributed by Nishant. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 5021,
"s": 4896,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5032,
"s": 5021,
"text": "cpp-string"
},
{
"code": null,
"e": 5052,
"s": 5032,
"text": "cpp-strings-library"
},
{
"code": null,
"e": 5056,
"s": 5052,
"text": "STL"
},
{
"code": null,
"e": 5067,
"s": 5056,
"text": "C Language"
},
{
"code": null,
"e": 5071,
"s": 5067,
"text": "C++"
},
{
"code": null,
"e": 5075,
"s": 5071,
"text": "STL"
},
{
"code": null,
"e": 5079,
"s": 5075,
"text": "CPP"
}
] |
Built in & Custom Model Managers in Django
|
18 May, 2021
Django manager is a class that acts as an interface through which Django models interact with databases. Every model has at least one manager object. It has a lot of methods, attributes to ease working with databases. In fact, many beginner-level Django developers do not know that they use the Manager class object to extract or create desired model object/objects. The default Manager object that Django provides in models is “objects“.
Syntax :
To use the Django default manager object, you have to follow the below syntax –
model_name.objects.method
Here “objects” is the manager object that Django creates by default.
One basic example :
Let’s say we have a model class named Hospital –
class Hospital(models.Model):
name = models.CharField(max_length=50)
city = models.CharField(max_length=30)
def __str__(self):
return self.name
But it did not create any objects in the database yet. It only creates an empty table with the structure of hospital objects. To create these objects in the database we need to use our default Django manager object (As we have not to build any custom manager) –
Hospital.objects.create(name='AIIMS',city ='Delhi')
The ‘create’ method creates a new object. It takes field values that the model class wants. In the above code line, we created a hospital object by calling the ‘create’ method which takes field values as an argument.
Giving a custom name to the default manager :
Sometimes there is a need to give a custom name to the default manager. To do this you have to define a class attribute or field of type models.Manager(). Here is an example –
class Student(models.Model):
...
students = models.Manager() //now the default manager is named as students
After this, all the operation on the student database table have to be done using the “students” manager –
Student.students.filter(...) // here students manager is used
Any effort of using “objects” as manager for this class will lead to giving an error.
Methods of Manager class :
Manager objects have many in-build methods to ease the operations on the database. Some of the most popular methods are described here –
Example :
This following example uses python command shell.
>>> h1 = Hospital.objects.create(name="Calcutta Medical",city="kolkata")
>>> h2 = Hospital.objects.create(name="dummy",city="Chennai") #creating objects using create() and save all these new objects into database
>>> h3 = Hospital.objects.create(name="TATA cancer Hospital",city="Mumbai")
>>> h4 = Hospital.objects.create(name="AIIMS Delhi",city="Delhi")
>>> h5 = Hospital.objects.create(name='NRS hospital",city="kolkata")
...
>>> Hospital.objects.filter(city='kolkata') # returns queryset of objects whose city attribute is 'kolkata'
<QuerySet [<Hospital: Calcutta Medical>, <Hospital: NRS hospital>]>
>>> Hospital.objects.get(city='Delhi')
<Hospital: AIIMS Delhi>
>>> Hospital.objects.get(city='kolkata') # raise error as there are multiple objects
These are the most popular methods . However the number of such methods are huge. You can check django documentation for complete reference.
Creating custom managers :
Sometimes you may want django manager to work in a certain way which default manager don’t. In that case you can make your own custom managers. The procedure is easy. You have to make a class which inherits from Manager class. Here is an example –
Example :
Let’s talk about Hospital model. We are creating a custom manager called CustomManager which is similar to the default django manager except one thing. When we call all() method of CustomManager object we will not get all objects. Instead we will get all those objects that have city = ‘kolkata’ –
Python3
class CustomManager(models.Manager): '''first we get all objects from the database by calling the get_queryset method of the inherited class i.e. Manager class using super().get_queryset(). After that we are filtering objects having city attribute equal to kolkata and return the filtered objects''' get_queryset(self): return super().get_queryset().filter(city= 'kolkata')
Every manager class have a get_queryset method. It is used to get queryset of objects based on the properties it takes as arguments. If no argument is provided then it will return all the objects. In this example, we create a custom django manager by inheriting Manager class and overriding only the get_queryset method .
So we have defined a custom manager . Now all we have to do is we have to link this manager with Hospital model –
Python3
class Hospital(models.Model): name = models.CharField(max_length=50) city = models.CharField(max_length=30) objects = models.Manager() # our default django manager kolkata_hospitals = CustomManager() # creating our custom manager object def __str__(self): return self.name
Hospital model have two manager objects. Now if we call Hospital.objects.all() , we get all the hospital objects. But when we call Hospital.kolkata_hospitals.all() we will get only those objects whose city is kolkata.
Note that if you are using multiple manager objects in same model then you need to be careful about the order of the manager objects defined. The first defined manager object will be treated as default manager object. For example – In above example, “objects” is the default manager as it is defined first. Django uses default managers in some internal process. So, be careful about choosing your default manager or you may get some unexpected results. If you want to make a manager default and that manager object is not defined first then you can define it as default manager by setting default_manager_name of Meta class equal to that object name.
class Hospital(models.Models):
...
class Meta:
default_manager_name = 'kolkata_hospitals' # default manager is now kolkata_hospitals not objects
You can do anything you want with custom managers. You can define a new method to modify some data in database, or return something. It is not necessary that every manager method should return a queryset. In fact you can define methods that return nothing.
If you want to know more , checkout Django’s official documentation on manager – https://docs.djangoproject.com/en/3.0/topics/db/managers/
clintra
Python Django
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 May, 2021"
},
{
"code": null,
"e": 467,
"s": 28,
"text": "Django manager is a class that acts as an interface through which Django models interact with databases. Every model has at least one manager object. It has a lot of methods, attributes to ease working with databases. In fact, many beginner-level Django developers do not know that they use the Manager class object to extract or create desired model object/objects. The default Manager object that Django provides in models is “objects“."
},
{
"code": null,
"e": 476,
"s": 467,
"text": "Syntax :"
},
{
"code": null,
"e": 557,
"s": 476,
"text": "To use the Django default manager object, you have to follow the below syntax – "
},
{
"code": null,
"e": 583,
"s": 557,
"text": "model_name.objects.method"
},
{
"code": null,
"e": 652,
"s": 583,
"text": "Here “objects” is the manager object that Django creates by default."
},
{
"code": null,
"e": 672,
"s": 652,
"text": "One basic example :"
},
{
"code": null,
"e": 721,
"s": 672,
"text": "Let’s say we have a model class named Hospital –"
},
{
"code": null,
"e": 885,
"s": 721,
"text": "class Hospital(models.Model):\n name = models.CharField(max_length=50)\n city = models.CharField(max_length=30)\n def __str__(self):\n return self.name"
},
{
"code": null,
"e": 1148,
"s": 885,
"text": "But it did not create any objects in the database yet. It only creates an empty table with the structure of hospital objects. To create these objects in the database we need to use our default Django manager object (As we have not to build any custom manager) –"
},
{
"code": null,
"e": 1200,
"s": 1148,
"text": "Hospital.objects.create(name='AIIMS',city ='Delhi')"
},
{
"code": null,
"e": 1417,
"s": 1200,
"text": "The ‘create’ method creates a new object. It takes field values that the model class wants. In the above code line, we created a hospital object by calling the ‘create’ method which takes field values as an argument."
},
{
"code": null,
"e": 1463,
"s": 1417,
"text": "Giving a custom name to the default manager :"
},
{
"code": null,
"e": 1639,
"s": 1463,
"text": "Sometimes there is a need to give a custom name to the default manager. To do this you have to define a class attribute or field of type models.Manager(). Here is an example –"
},
{
"code": null,
"e": 1755,
"s": 1639,
"text": "class Student(models.Model):\n ...\n students = models.Manager() //now the default manager is named as students"
},
{
"code": null,
"e": 1863,
"s": 1755,
"text": "After this, all the operation on the student database table have to be done using the “students” manager – "
},
{
"code": null,
"e": 1925,
"s": 1863,
"text": "Student.students.filter(...) // here students manager is used"
},
{
"code": null,
"e": 2011,
"s": 1925,
"text": "Any effort of using “objects” as manager for this class will lead to giving an error."
},
{
"code": null,
"e": 2038,
"s": 2011,
"text": "Methods of Manager class :"
},
{
"code": null,
"e": 2176,
"s": 2038,
"text": "Manager objects have many in-build methods to ease the operations on the database. Some of the most popular methods are described here – "
},
{
"code": null,
"e": 2186,
"s": 2176,
"text": "Example :"
},
{
"code": null,
"e": 2237,
"s": 2186,
"text": "This following example uses python command shell. "
},
{
"code": null,
"e": 2994,
"s": 2237,
"text": ">>> h1 = Hospital.objects.create(name=\"Calcutta Medical\",city=\"kolkata\")\n>>> h2 = Hospital.objects.create(name=\"dummy\",city=\"Chennai\") #creating objects using create() and save all these new objects into database\n>>> h3 = Hospital.objects.create(name=\"TATA cancer Hospital\",city=\"Mumbai\")\n>>> h4 = Hospital.objects.create(name=\"AIIMS Delhi\",city=\"Delhi\")\n>>> h5 = Hospital.objects.create(name='NRS hospital\",city=\"kolkata\")\n...\n>>> Hospital.objects.filter(city='kolkata') # returns queryset of objects whose city attribute is 'kolkata'\n<QuerySet [<Hospital: Calcutta Medical>, <Hospital: NRS hospital>]>\n>>> Hospital.objects.get(city='Delhi')\n<Hospital: AIIMS Delhi>\n>>> Hospital.objects.get(city='kolkata') # raise error as there are multiple objects"
},
{
"code": null,
"e": 3135,
"s": 2994,
"text": "These are the most popular methods . However the number of such methods are huge. You can check django documentation for complete reference."
},
{
"code": null,
"e": 3162,
"s": 3135,
"text": "Creating custom managers :"
},
{
"code": null,
"e": 3411,
"s": 3162,
"text": "Sometimes you may want django manager to work in a certain way which default manager don’t. In that case you can make your own custom managers. The procedure is easy. You have to make a class which inherits from Manager class. Here is an example – "
},
{
"code": null,
"e": 3421,
"s": 3411,
"text": "Example :"
},
{
"code": null,
"e": 3722,
"s": 3421,
"text": "Let’s talk about Hospital model. We are creating a custom manager called CustomManager which is similar to the default django manager except one thing. When we call all() method of CustomManager object we will not get all objects. Instead we will get all those objects that have city = ‘kolkata’ – "
},
{
"code": null,
"e": 3730,
"s": 3722,
"text": "Python3"
},
{
"code": "class CustomManager(models.Manager): '''first we get all objects from the database by calling the get_queryset method of the inherited class i.e. Manager class using super().get_queryset(). After that we are filtering objects having city attribute equal to kolkata and return the filtered objects''' get_queryset(self): return super().get_queryset().filter(city= 'kolkata')",
"e": 4113,
"s": 3730,
"text": null
},
{
"code": null,
"e": 4436,
"s": 4113,
"text": "Every manager class have a get_queryset method. It is used to get queryset of objects based on the properties it takes as arguments. If no argument is provided then it will return all the objects. In this example, we create a custom django manager by inheriting Manager class and overriding only the get_queryset method . "
},
{
"code": null,
"e": 4551,
"s": 4436,
"text": "So we have defined a custom manager . Now all we have to do is we have to link this manager with Hospital model – "
},
{
"code": null,
"e": 4559,
"s": 4551,
"text": "Python3"
},
{
"code": "class Hospital(models.Model): name = models.CharField(max_length=50) city = models.CharField(max_length=30) objects = models.Manager() # our default django manager kolkata_hospitals = CustomManager() # creating our custom manager object def __str__(self): return self.name",
"e": 4840,
"s": 4559,
"text": null
},
{
"code": null,
"e": 5059,
"s": 4840,
"text": "Hospital model have two manager objects. Now if we call Hospital.objects.all() , we get all the hospital objects. But when we call Hospital.kolkata_hospitals.all() we will get only those objects whose city is kolkata."
},
{
"code": null,
"e": 5710,
"s": 5059,
"text": "Note that if you are using multiple manager objects in same model then you need to be careful about the order of the manager objects defined. The first defined manager object will be treated as default manager object. For example – In above example, “objects” is the default manager as it is defined first. Django uses default managers in some internal process. So, be careful about choosing your default manager or you may get some unexpected results. If you want to make a manager default and that manager object is not defined first then you can define it as default manager by setting default_manager_name of Meta class equal to that object name."
},
{
"code": null,
"e": 5871,
"s": 5710,
"text": "class Hospital(models.Models):\n ...\n class Meta:\n default_manager_name = 'kolkata_hospitals' # default manager is now kolkata_hospitals not objects"
},
{
"code": null,
"e": 6129,
"s": 5871,
"text": "You can do anything you want with custom managers. You can define a new method to modify some data in database, or return something. It is not necessary that every manager method should return a queryset. In fact you can define methods that return nothing. "
},
{
"code": null,
"e": 6269,
"s": 6129,
"text": "If you want to know more , checkout Django’s official documentation on manager – https://docs.djangoproject.com/en/3.0/topics/db/managers/"
},
{
"code": null,
"e": 6277,
"s": 6269,
"text": "clintra"
},
{
"code": null,
"e": 6291,
"s": 6277,
"text": "Python Django"
},
{
"code": null,
"e": 6315,
"s": 6291,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 6322,
"s": 6315,
"text": "Python"
},
{
"code": null,
"e": 6341,
"s": 6322,
"text": "Technical Scripter"
}
] |
Check if Matrix sum is prime or not - GeeksforGeeks
|
05 Apr, 2021
Given a matrix mat[][], the task is to check that the sum of the elements of the matrix is prime or not.Examples:
Input: mat[][] = {{1, 2}, {2, 1}} Output: NO Explanation: Sum of Matrix = 1 + 2 + 2 + 1 = 6 Since 6 is not prime. Therefore, output is NOInput: mat[][] = {{1, 2}, {2, 2}} Output: YES Explanation: Sum of matrix = 1 + 2 + 2 + 2 = 7 Since 7 is prime. Therefore, output is YES
Approach: The idea is to find the sum of the matrix using two nested loops and then finally check that the sum of the matrix is a prime or not. If yes then the output is YES otherwise the output is NO.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to check// if the sum of matrix// is prime or not #include <bits/stdc++.h>using namespace std; const int N = 4, M = 5; // Function to check// whether a number// is prime or notbool isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i <= sqrt(n); i++) if (n % i == 0) return false; return true;} // Function for to find the sum// of the given matrixint takeSum(int a[N][M]){ int s = 0; for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) s += a[i][j]; return s;} // Driver Codeint main(){ int a[N][M] = { { 1, 2, 3, 4, 2 }, { 0, 1, 2, 3, 34 }, { 0, 34, 21, 12, 12 }, { 1, 2, 3, 6, 6 } }; int sum = takeSum(a); if (isPrime(sum)) cout << "YES" << endl; else cout << "NO" << endl; return 0;}
// Java implementation to check if// the sum of matrix is prime or notclass GFG{ static int N = 4, M = 5; // Function to check whether// a number is prime or notstatic boolean isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for(int i = 2; i <= Math.sqrt(n); i++) if (n % i == 0) return false; return true;} // Function for to find the sum// of the given matrixstatic int takeSum(int a[][]){ int s = 0; for(int i = 0; i < N; i++) for(int j = 0; j < M; j++) s += a[i][j]; return s;} // Driver Codepublic static void main(String[] args){ int a[][] = { { 1, 2, 3, 4, 2 }, { 0, 1, 2, 3, 34 }, { 0, 34, 21, 12, 12 }, { 1, 2, 3, 6, 6 } }; int sum = takeSum(a); if (isPrime(sum)) System.out.print("YES" + "\n"); else System.out.print("NO" + "\n");}} // This code is contributed by PrinciRaj1992
# Python3 implementation to check if# the sum of matrix is prime or notimport math # Function to check whether a number# is prime or notdef isPrime(n): # Corner case if (n <= 1): return False; # Check from 2 to n-1 for i in range(2, (int)(math.sqrt(n)) + 1): if (n % i == 0): return False; return True; # Function for to find the sum# of the given matrixdef takeSum(a): s = 0 for i in range(0, 4): for j in range(0, 5): s += a[i][j] return s; # Driver Codea = [ [ 1, 2, 3, 4, 2 ], [ 0, 1, 2, 3, 34 ], [ 0, 34, 21, 12, 12 ], [ 1, 2, 3, 6, 6 ] ];sum = takeSum(a); if (isPrime(sum)): print("YES")else: print("NO") # This code is contributed by grand_master
// C# implementation to check if// the sum of matrix is prime or notusing System;class GFG{ static int N = 4, M = 5; // Function to check whether// a number is prime or notstatic Boolean isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for(int i = 2; i <= Math.Sqrt(n); i++) if (n % i == 0) return false; return true;} // Function for to find the sum// of the given matrixstatic int takeSum(int [][]a){ int s = 0; for(int i = 0; i < N; i++) for(int j = 0; j < M; j++) s += a[i][j]; return s;} // Driver Codepublic static void Main(String[] args){ int [][]a = new int[][] { new int[] { 1, 2, 3, 4, 2 }, new int[] { 0, 1, 2, 3, 34 }, new int[] { 0, 34, 21, 12, 12 }, new int[] { 1, 2, 3, 6, 6 } }; int sum = takeSum(a); if (isPrime(sum)) Console.Write("YES" + "\n"); else Console.Write("NO" + "\n");}} // This code is contributed by shivanisinghss2110
<script> // Javascript implementation to check // if the sum of matrix // is prime or not let N = 4, M = 5; // Function to check // whether a number // is prime or not function isPrime(n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (let i = 2; i <= Math.sqrt(n); i++) if (n % i == 0) return false; return true; } // Function for to find the sum // of the given matrix function takeSum(a) { let s = 0; for (let i = 0; i < N; i++) for (let j = 0; j < M; j++) s += a[i][j]; return s; } let a = [ [ 1, 2, 3, 4, 2 ], [ 0, 1, 2, 3, 34 ], [ 0, 34, 21, 12, 12 ], [ 1, 2, 3, 6, 6 ] ]; let sum = takeSum(a); if (isPrime(sum)) document.write("YES"); else document.write("NO"); </script>
YES
Time Complexity: O(N*M)
grand_master
princiraj1992
shivanisinghss2110
divyesh072019
palindrome
Mathematical
Matrix
School Programming
Mathematical
Matrix
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Modular multiplicative inverse
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Rat in a Maze | Backtracking-2
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
|
[
{
"code": null,
"e": 24692,
"s": 24664,
"text": "\n05 Apr, 2021"
},
{
"code": null,
"e": 24808,
"s": 24692,
"text": "Given a matrix mat[][], the task is to check that the sum of the elements of the matrix is prime or not.Examples: "
},
{
"code": null,
"e": 25083,
"s": 24808,
"text": "Input: mat[][] = {{1, 2}, {2, 1}} Output: NO Explanation: Sum of Matrix = 1 + 2 + 2 + 1 = 6 Since 6 is not prime. Therefore, output is NOInput: mat[][] = {{1, 2}, {2, 2}} Output: YES Explanation: Sum of matrix = 1 + 2 + 2 + 2 = 7 Since 7 is prime. Therefore, output is YES "
},
{
"code": null,
"e": 25338,
"s": 25085,
"text": "Approach: The idea is to find the sum of the matrix using two nested loops and then finally check that the sum of the matrix is a prime or not. If yes then the output is YES otherwise the output is NO.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25342,
"s": 25338,
"text": "C++"
},
{
"code": null,
"e": 25347,
"s": 25342,
"text": "Java"
},
{
"code": null,
"e": 25355,
"s": 25347,
"text": "Python3"
},
{
"code": null,
"e": 25358,
"s": 25355,
"text": "C#"
},
{
"code": null,
"e": 25369,
"s": 25358,
"text": "Javascript"
},
{
"code": "// C++ implementation to check// if the sum of matrix// is prime or not #include <bits/stdc++.h>using namespace std; const int N = 4, M = 5; // Function to check// whether a number// is prime or notbool isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i <= sqrt(n); i++) if (n % i == 0) return false; return true;} // Function for to find the sum// of the given matrixint takeSum(int a[N][M]){ int s = 0; for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) s += a[i][j]; return s;} // Driver Codeint main(){ int a[N][M] = { { 1, 2, 3, 4, 2 }, { 0, 1, 2, 3, 34 }, { 0, 34, 21, 12, 12 }, { 1, 2, 3, 6, 6 } }; int sum = takeSum(a); if (isPrime(sum)) cout << \"YES\" << endl; else cout << \"NO\" << endl; return 0;}",
"e": 26286,
"s": 25369,
"text": null
},
{
"code": "// Java implementation to check if// the sum of matrix is prime or notclass GFG{ static int N = 4, M = 5; // Function to check whether// a number is prime or notstatic boolean isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for(int i = 2; i <= Math.sqrt(n); i++) if (n % i == 0) return false; return true;} // Function for to find the sum// of the given matrixstatic int takeSum(int a[][]){ int s = 0; for(int i = 0; i < N; i++) for(int j = 0; j < M; j++) s += a[i][j]; return s;} // Driver Codepublic static void main(String[] args){ int a[][] = { { 1, 2, 3, 4, 2 }, { 0, 1, 2, 3, 34 }, { 0, 34, 21, 12, 12 }, { 1, 2, 3, 6, 6 } }; int sum = takeSum(a); if (isPrime(sum)) System.out.print(\"YES\" + \"\\n\"); else System.out.print(\"NO\" + \"\\n\");}} // This code is contributed by PrinciRaj1992",
"e": 27277,
"s": 26286,
"text": null
},
{
"code": "# Python3 implementation to check if# the sum of matrix is prime or notimport math # Function to check whether a number# is prime or notdef isPrime(n): # Corner case if (n <= 1): return False; # Check from 2 to n-1 for i in range(2, (int)(math.sqrt(n)) + 1): if (n % i == 0): return False; return True; # Function for to find the sum# of the given matrixdef takeSum(a): s = 0 for i in range(0, 4): for j in range(0, 5): s += a[i][j] return s; # Driver Codea = [ [ 1, 2, 3, 4, 2 ], [ 0, 1, 2, 3, 34 ], [ 0, 34, 21, 12, 12 ], [ 1, 2, 3, 6, 6 ] ];sum = takeSum(a); if (isPrime(sum)): print(\"YES\")else: print(\"NO\") # This code is contributed by grand_master",
"e": 28028,
"s": 27277,
"text": null
},
{
"code": "// C# implementation to check if// the sum of matrix is prime or notusing System;class GFG{ static int N = 4, M = 5; // Function to check whether// a number is prime or notstatic Boolean isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for(int i = 2; i <= Math.Sqrt(n); i++) if (n % i == 0) return false; return true;} // Function for to find the sum// of the given matrixstatic int takeSum(int [][]a){ int s = 0; for(int i = 0; i < N; i++) for(int j = 0; j < M; j++) s += a[i][j]; return s;} // Driver Codepublic static void Main(String[] args){ int [][]a = new int[][] { new int[] { 1, 2, 3, 4, 2 }, new int[] { 0, 1, 2, 3, 34 }, new int[] { 0, 34, 21, 12, 12 }, new int[] { 1, 2, 3, 6, 6 } }; int sum = takeSum(a); if (isPrime(sum)) Console.Write(\"YES\" + \"\\n\"); else Console.Write(\"NO\" + \"\\n\");}} // This code is contributed by shivanisinghss2110",
"e": 29123,
"s": 28028,
"text": null
},
{
"code": "<script> // Javascript implementation to check // if the sum of matrix // is prime or not let N = 4, M = 5; // Function to check // whether a number // is prime or not function isPrime(n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (let i = 2; i <= Math.sqrt(n); i++) if (n % i == 0) return false; return true; } // Function for to find the sum // of the given matrix function takeSum(a) { let s = 0; for (let i = 0; i < N; i++) for (let j = 0; j < M; j++) s += a[i][j]; return s; } let a = [ [ 1, 2, 3, 4, 2 ], [ 0, 1, 2, 3, 34 ], [ 0, 34, 21, 12, 12 ], [ 1, 2, 3, 6, 6 ] ]; let sum = takeSum(a); if (isPrime(sum)) document.write(\"YES\"); else document.write(\"NO\"); </script>",
"e": 30071,
"s": 29123,
"text": null
},
{
"code": null,
"e": 30075,
"s": 30071,
"text": "YES"
},
{
"code": null,
"e": 30102,
"s": 30077,
"text": "Time Complexity: O(N*M) "
},
{
"code": null,
"e": 30115,
"s": 30102,
"text": "grand_master"
},
{
"code": null,
"e": 30129,
"s": 30115,
"text": "princiraj1992"
},
{
"code": null,
"e": 30148,
"s": 30129,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 30162,
"s": 30148,
"text": "divyesh072019"
},
{
"code": null,
"e": 30173,
"s": 30162,
"text": "palindrome"
},
{
"code": null,
"e": 30186,
"s": 30173,
"text": "Mathematical"
},
{
"code": null,
"e": 30193,
"s": 30186,
"text": "Matrix"
},
{
"code": null,
"e": 30212,
"s": 30193,
"text": "School Programming"
},
{
"code": null,
"e": 30225,
"s": 30212,
"text": "Mathematical"
},
{
"code": null,
"e": 30232,
"s": 30225,
"text": "Matrix"
},
{
"code": null,
"e": 30243,
"s": 30232,
"text": "palindrome"
},
{
"code": null,
"e": 30341,
"s": 30243,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30373,
"s": 30341,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 30417,
"s": 30373,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 30442,
"s": 30417,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 30475,
"s": 30442,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 30506,
"s": 30475,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 30541,
"s": 30506,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 30585,
"s": 30541,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 30621,
"s": 30585,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 30652,
"s": 30621,
"text": "Rat in a Maze | Backtracking-2"
}
] |
JavaScript JSON stringify() Method - GeeksforGeeks
|
15 Nov, 2021
The JSON.stringify() method in Javascript is used to create a JSON string out of it. While developing an application using JavaScript, many times it is needed to serialize the data to strings for storing the data into a database or for sending the data to an API or web server. The data has to be in the form of strings. This conversion of an object to a string can be easily done with the help of the JSON.stringify() method.
Syntax:
JSON.stringify(value, replacer, space);
Parameters: This method accepts three parameters as mentioned above and described below:
value: It is the value that is to be converted into a JSON string.
replacer: It is an optional parameter. This parameter value can be an altering function or an array used as a selected filter for the stringify. If the value is empty or null then all properties of an object are included in a string.
space: It is also an optional parameter. This argument is used to control spacing in the final string generated using JSON.stringify() function. It can be a number or a string if it is a number then the specified number of spaces indented to the final string and if it is a string then that string is (up to 10 characters) used for indentation.
Return Value: It returns a string for a given value.
Example: The below example illustrates the JSON signify() method in JavaScript:
var value = { name: "Logan", age: 21, location: "London" };
var result = JSON.stringify(value);
Output:
{"name":"Logan", "age":21, "location":"London"}
Example: The below is the example of the JSON stringify() Method.
Javascript
<script> const value = { Company: "GeeksforGeeks", Estd: 2009, location: "Noida" }; const result = JSON.stringify(value); document.write("value of result = " + result + "<br>");</script>
Output:
value of result = {"Company":"GeeksforGeeks",
"Estd":2009,
"location":"Noida"}
More example codes for the above method are as follows:
Program 1: In the below code, the JavaScript object is being passed as a value in the function to convert it into a string.
Javascript
<script> var value = { name: "Logan", age: 21, location: "London" }; var result = JSON.stringify(value); document.write("value of result = " + result + "<br>"); document.write("type of result = " + typeof result);</script>
Output:
value of result = {"name":"Logan", "age":21, "location":"London"}
type of result = string
Program 2: In the below code, the JavaScript array can be passed as a value in the function to convert it into a string.
Javascript
<script> var value = ["Logan", 21, "Peter", 24]; var result = JSON.stringify(value); document.write("value of result = " + result + "<br>"); document.write("type of result = " + typeof result);</script>
Output:
value of result = ["Logan", 21, "Peter", 24]
type of result = string
Supported browsers:
Chrome 4.0
Firefox 3.5
Microsoft Edge 12.0
Opera 11.0
Internet Explorer 8.0
Safari 4.0
bhaskargeeksforgeeks
JavaScript-Methods
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Use the JavaScript Fetch API to Get Data?
How to read a local text file using JavaScript?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25017,
"s": 24989,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 25444,
"s": 25017,
"text": "The JSON.stringify() method in Javascript is used to create a JSON string out of it. While developing an application using JavaScript, many times it is needed to serialize the data to strings for storing the data into a database or for sending the data to an API or web server. The data has to be in the form of strings. This conversion of an object to a string can be easily done with the help of the JSON.stringify() method."
},
{
"code": null,
"e": 25452,
"s": 25444,
"text": "Syntax:"
},
{
"code": null,
"e": 25492,
"s": 25452,
"text": "JSON.stringify(value, replacer, space);"
},
{
"code": null,
"e": 25581,
"s": 25492,
"text": "Parameters: This method accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 25648,
"s": 25581,
"text": "value: It is the value that is to be converted into a JSON string."
},
{
"code": null,
"e": 25882,
"s": 25648,
"text": "replacer: It is an optional parameter. This parameter value can be an altering function or an array used as a selected filter for the stringify. If the value is empty or null then all properties of an object are included in a string."
},
{
"code": null,
"e": 26227,
"s": 25882,
"text": "space: It is also an optional parameter. This argument is used to control spacing in the final string generated using JSON.stringify() function. It can be a number or a string if it is a number then the specified number of spaces indented to the final string and if it is a string then that string is (up to 10 characters) used for indentation."
},
{
"code": null,
"e": 26280,
"s": 26227,
"text": "Return Value: It returns a string for a given value."
},
{
"code": null,
"e": 26360,
"s": 26280,
"text": "Example: The below example illustrates the JSON signify() method in JavaScript:"
},
{
"code": null,
"e": 26513,
"s": 26360,
"text": "var value = { name: \"Logan\", age: 21, location: \"London\" };\nvar result = JSON.stringify(value);\n\nOutput:\n{\"name\":\"Logan\", \"age\":21, \"location\":\"London\"}"
},
{
"code": null,
"e": 26580,
"s": 26513,
"text": "Example: The below is the example of the JSON stringify() Method. "
},
{
"code": null,
"e": 26591,
"s": 26580,
"text": "Javascript"
},
{
"code": "<script> const value = { Company: \"GeeksforGeeks\", Estd: 2009, location: \"Noida\" }; const result = JSON.stringify(value); document.write(\"value of result = \" + result + \"<br>\");</script>",
"e": 26811,
"s": 26591,
"text": null
},
{
"code": null,
"e": 26819,
"s": 26811,
"text": "Output:"
},
{
"code": null,
"e": 26936,
"s": 26819,
"text": "value of result = {\"Company\":\"GeeksforGeeks\",\n \"Estd\":2009,\n \"location\":\"Noida\"}"
},
{
"code": null,
"e": 26993,
"s": 26936,
"text": "More example codes for the above method are as follows: "
},
{
"code": null,
"e": 27117,
"s": 26993,
"text": "Program 1: In the below code, the JavaScript object is being passed as a value in the function to convert it into a string."
},
{
"code": null,
"e": 27128,
"s": 27117,
"text": "Javascript"
},
{
"code": "<script> var value = { name: \"Logan\", age: 21, location: \"London\" }; var result = JSON.stringify(value); document.write(\"value of result = \" + result + \"<br>\"); document.write(\"type of result = \" + typeof result);</script>",
"e": 27387,
"s": 27128,
"text": null
},
{
"code": null,
"e": 27395,
"s": 27387,
"text": "Output:"
},
{
"code": null,
"e": 27485,
"s": 27395,
"text": "value of result = {\"name\":\"Logan\", \"age\":21, \"location\":\"London\"}\ntype of result = string"
},
{
"code": null,
"e": 27606,
"s": 27485,
"text": "Program 2: In the below code, the JavaScript array can be passed as a value in the function to convert it into a string."
},
{
"code": null,
"e": 27617,
"s": 27606,
"text": "Javascript"
},
{
"code": "<script> var value = [\"Logan\", 21, \"Peter\", 24]; var result = JSON.stringify(value); document.write(\"value of result = \" + result + \"<br>\"); document.write(\"type of result = \" + typeof result);</script>",
"e": 27832,
"s": 27617,
"text": null
},
{
"code": null,
"e": 27840,
"s": 27832,
"text": "Output:"
},
{
"code": null,
"e": 27909,
"s": 27840,
"text": "value of result = [\"Logan\", 21, \"Peter\", 24]\ntype of result = string"
},
{
"code": null,
"e": 27929,
"s": 27909,
"text": "Supported browsers:"
},
{
"code": null,
"e": 27940,
"s": 27929,
"text": "Chrome 4.0"
},
{
"code": null,
"e": 27952,
"s": 27940,
"text": "Firefox 3.5"
},
{
"code": null,
"e": 27972,
"s": 27952,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 27983,
"s": 27972,
"text": "Opera 11.0"
},
{
"code": null,
"e": 28005,
"s": 27983,
"text": "Internet Explorer 8.0"
},
{
"code": null,
"e": 28016,
"s": 28005,
"text": "Safari 4.0"
},
{
"code": null,
"e": 28037,
"s": 28016,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 28056,
"s": 28037,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 28063,
"s": 28056,
"text": "Picked"
},
{
"code": null,
"e": 28074,
"s": 28063,
"text": "JavaScript"
},
{
"code": null,
"e": 28091,
"s": 28074,
"text": "Web Technologies"
},
{
"code": null,
"e": 28189,
"s": 28091,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28198,
"s": 28189,
"text": "Comments"
},
{
"code": null,
"e": 28211,
"s": 28198,
"text": "Old Comments"
},
{
"code": null,
"e": 28272,
"s": 28211,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28317,
"s": 28272,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28389,
"s": 28317,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28438,
"s": 28389,
"text": "How to Use the JavaScript Fetch API to Get Data?"
},
{
"code": null,
"e": 28486,
"s": 28438,
"text": "How to read a local text file using JavaScript?"
},
{
"code": null,
"e": 28542,
"s": 28486,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28575,
"s": 28542,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28637,
"s": 28575,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28680,
"s": 28637,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Replace an element at a specified index of the Vector in Java
|
An element in a Vector can be replaced at a specified index using the java.util.Vector.set() method. This method has two parameters i.e the index at which the Vector element is to be replaced and the element that it should be replaced with. Vector.set() method returns the element that was at the position specified at the index previously.
A program that demonstrates this is given as follows:
Live Demo
import java.util.Vector;
public class Demo {
public static void main(String args[]) {
Vector vec = new Vector(5);
vec.add(7);
vec.add(3);
vec.add(9);
vec.add(1);
vec.add(5);
System.out.println("The Vector elements are: " + vec);
vec.set(1, 6);
System.out.println("The Vector elements are: " + vec);
}
}
The output of the above program is as follows:
The Vector elements are: [7, 3, 9, 1, 5]
The Vector elements are: [7, 6, 9, 1, 5]
Now let us understand the above program.
The Vector is created. Then Vector.add() is used to add the elements to the Vector. Then Vector.set() is used to replace the element 3 with element 6 at index 1. Then the Vector is displayed. A code snippet which demonstrates this is as follows:
Vector vec = new Vector(5);
vec.add(7);
vec.add(3);
vec.add(9);
vec.add(1);
vec.add(5);
System.out.println("The Vector elements are: " + vec);
vec.set(1, 6);
System.out.println("The Vector elements are: " + vec);
|
[
{
"code": null,
"e": 1403,
"s": 1062,
"text": "An element in a Vector can be replaced at a specified index using the java.util.Vector.set() method. This method has two parameters i.e the index at which the Vector element is to be replaced and the element that it should be replaced with. Vector.set() method returns the element that was at the position specified at the index previously."
},
{
"code": null,
"e": 1457,
"s": 1403,
"text": "A program that demonstrates this is given as follows:"
},
{
"code": null,
"e": 1468,
"s": 1457,
"text": " Live Demo"
},
{
"code": null,
"e": 1831,
"s": 1468,
"text": "import java.util.Vector;\npublic class Demo {\n public static void main(String args[]) {\n Vector vec = new Vector(5);\n vec.add(7);\n vec.add(3);\n vec.add(9);\n vec.add(1);\n vec.add(5);\n System.out.println(\"The Vector elements are: \" + vec);\n vec.set(1, 6);\n System.out.println(\"The Vector elements are: \" + vec);\n }\n}"
},
{
"code": null,
"e": 1878,
"s": 1831,
"text": "The output of the above program is as follows:"
},
{
"code": null,
"e": 1960,
"s": 1878,
"text": "The Vector elements are: [7, 3, 9, 1, 5]\nThe Vector elements are: [7, 6, 9, 1, 5]"
},
{
"code": null,
"e": 2001,
"s": 1960,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2247,
"s": 2001,
"text": "The Vector is created. Then Vector.add() is used to add the elements to the Vector. Then Vector.set() is used to replace the element 3 with element 6 at index 1. Then the Vector is displayed. A code snippet which demonstrates this is as follows:"
},
{
"code": null,
"e": 2460,
"s": 2247,
"text": "Vector vec = new Vector(5);\nvec.add(7);\nvec.add(3);\nvec.add(9);\nvec.add(1);\nvec.add(5);\nSystem.out.println(\"The Vector elements are: \" + vec);\nvec.set(1, 6);\nSystem.out.println(\"The Vector elements are: \" + vec);"
}
] |
Context Manager in Python - GeeksforGeeks
|
26 Nov, 2018
Managing Resources : In any programming language, the usage of resources like file operations or database connections is very common. But these resources are limited in supply. Therefore, the main problem lies in making sure to release these resources after usage. If they are not released then it will lead to resource leakage and may cause the system to either slow down or crash. It would be very helpful if user have a mechanism for the automatic setup and teardown of resources.In Python, it can be achieved by the usage of context managers which facilitate the proper handling of resources. The most common way of performing file operations is by using the with keyword as shown below:
# Python program showing # a use of with keyword with open("test.txt") as f: data = f.read()
Let’s take the example of file management. When a file is opened, a file descriptor is consumed which is a limited resource. Only a certain number of files can be opened by a process at a time. The following program demonstrates it.
file_descriptors = []for x in range(100000): file_descriptors.append(open('test.txt', 'w'))
Output:
Traceback (most recent call last):
File "context.py", line 3, in
OSError: [Errno 24] Too many open files: 'test.txt'
An error message saying that too many files are open. The above example is a case of file descriptor leakage. It happens because there are too many open files and they are not closed. There might be chances where a programmer may forget to close an opened file.
Managing Resources using context manager :
Suppose a block of code raises an exception or if it has a complex algorithm with multiple return paths, it becomes cumbersome to close a file in all the places.Generally in other languages when working with files try-except-finally is used to ensure that the file resource is closed after usage even if there is an exception.Python provides an easy way to manage resources: Context Managers. The with keyword is used. When it gets evaluated it should result in an object that performs context management. Context managers can be written using classes or functions(with decorators).
Creating a Context Manager :
When creating context managers using classes, user need to ensure that the class has the methods: __enter__() and __exit__(). The __enter__() returns the resource that needs to be managed and the __exit__() does not return anything but performs the cleanup operations.First, lets create a simple class called ContextManager to understand the basic structure of creating context managers using classes, as shown below:
# Python program creating a# context manager class ContextManager(): def __init__(self): print('init method called') def __enter__(self): print('enter method called') return self def __exit__(self, exc_type, exc_value, exc_traceback): print('exit method called') with ContextManager() as manager: print('with statement block')
Output:
init method called
enter method called
with statement block
exit method called
In this case a ContextManager object is created. This is assigned to the variable after the as keyword i.e manager. On running the above program, the following get executed in sequence:
__init__()
__enter__()
statement body (code inside the with block)
__exit__()[the parameters in this method are used to manage exceptions]
File management using context manager :
Let’s apply the above concept to create a class that helps in file resource management.The FileManager class helps in opening a file, writing/reading contents and then closing it.
# Python program showing# file management using # context manager class FileManager(): def __init__(self, filename, mode): self.filename = filename self.mode = mode self.file = None def __enter__(self): self.file = open(self.filename, self.mode) return self.file def __exit__(self, exc_type, exc_value, exc_traceback): self.file.close() # loading a file with FileManager('test.txt', 'w') as f: f.write('Test') print(f.closed)
Output:
True
File management using context manager and with statement :
On executing the with block, the following operations happen in sequence:
A FileManager object is created with test.txt as the filename and w(write) as the mode when __init__ method is executed.
The __enter__ method opens the test.txt file in write mode(setup operation) and returns the FileManager object to variable f.
The text ‘Test’ is written into the file.
The __exit__ method takes care of closing the file on exiting the with block(teardown operation).When print(f.closed) is run, the output is True as the FileManager has already taken care of closing the file which otherwise needed to be explicitly done.
Database connection management using context manager :
Let’s create a simple database connection management system. The number of database connections that can be opened at a time is also limited(just like file descriptors). Therefore context managers are helpful in managing connections to the database as there could be chances that the programmer may forget to close the connection.
# Python program shows the# connection management # for MongoDB from pymongo import MongoClient class MongoDBConnectionManager(): def __init__(self, hostname, port): self.hostname = hostname self.port = port self.connection = None def __enter__(self): self.connection = MongoClient(self.hostname, self.port) return self def __exit__(self, exc_type, exc_value, exc_traceback): self.connection.close() # connecting with a localhostwith MongoDBConnectionManager('localhost', '27017') as mongo: collection = mongo.connection.SampleDb.test data = collection.find({'_id': 1}) print(data.get('name'))
Database connection management using context manager and with statement :
On executing the with block, the following operations happen in sequence:
A MongoDBConnectionManager object is created with localhost as the hostnamename and 27017 as the port when __init__ method is executed.
The __enter__ method opens the mongodb connection and returns the MongoDBConnectionManager object to variable mongo.
The test collection in SampleDb database is accessed and the document with _id=1 is retrieved. The name field of the document is printed.
The __exit__ method takes care of closing the connection on exiting the with block(teardown operation).
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
|
[
{
"code": null,
"e": 24298,
"s": 24270,
"text": "\n26 Nov, 2018"
},
{
"code": null,
"e": 24990,
"s": 24298,
"text": "Managing Resources : In any programming language, the usage of resources like file operations or database connections is very common. But these resources are limited in supply. Therefore, the main problem lies in making sure to release these resources after usage. If they are not released then it will lead to resource leakage and may cause the system to either slow down or crash. It would be very helpful if user have a mechanism for the automatic setup and teardown of resources.In Python, it can be achieved by the usage of context managers which facilitate the proper handling of resources. The most common way of performing file operations is by using the with keyword as shown below:"
},
{
"code": "# Python program showing # a use of with keyword with open(\"test.txt\") as f: data = f.read()",
"e": 25090,
"s": 24990,
"text": null
},
{
"code": null,
"e": 25323,
"s": 25090,
"text": "Let’s take the example of file management. When a file is opened, a file descriptor is consumed which is a limited resource. Only a certain number of files can be opened by a process at a time. The following program demonstrates it."
},
{
"code": "file_descriptors = []for x in range(100000): file_descriptors.append(open('test.txt', 'w'))",
"e": 25418,
"s": 25323,
"text": null
},
{
"code": null,
"e": 25426,
"s": 25418,
"text": "Output:"
},
{
"code": null,
"e": 25547,
"s": 25426,
"text": "Traceback (most recent call last):\n File \"context.py\", line 3, in \nOSError: [Errno 24] Too many open files: 'test.txt'\n"
},
{
"code": null,
"e": 25809,
"s": 25547,
"text": "An error message saying that too many files are open. The above example is a case of file descriptor leakage. It happens because there are too many open files and they are not closed. There might be chances where a programmer may forget to close an opened file."
},
{
"code": null,
"e": 25852,
"s": 25809,
"text": "Managing Resources using context manager :"
},
{
"code": null,
"e": 26435,
"s": 25852,
"text": "Suppose a block of code raises an exception or if it has a complex algorithm with multiple return paths, it becomes cumbersome to close a file in all the places.Generally in other languages when working with files try-except-finally is used to ensure that the file resource is closed after usage even if there is an exception.Python provides an easy way to manage resources: Context Managers. The with keyword is used. When it gets evaluated it should result in an object that performs context management. Context managers can be written using classes or functions(with decorators)."
},
{
"code": null,
"e": 26464,
"s": 26435,
"text": "Creating a Context Manager :"
},
{
"code": null,
"e": 26882,
"s": 26464,
"text": "When creating context managers using classes, user need to ensure that the class has the methods: __enter__() and __exit__(). The __enter__() returns the resource that needs to be managed and the __exit__() does not return anything but performs the cleanup operations.First, lets create a simple class called ContextManager to understand the basic structure of creating context managers using classes, as shown below:"
},
{
"code": "# Python program creating a# context manager class ContextManager(): def __init__(self): print('init method called') def __enter__(self): print('enter method called') return self def __exit__(self, exc_type, exc_value, exc_traceback): print('exit method called') with ContextManager() as manager: print('with statement block')",
"e": 27269,
"s": 26882,
"text": null
},
{
"code": null,
"e": 27277,
"s": 27269,
"text": "Output:"
},
{
"code": null,
"e": 27357,
"s": 27277,
"text": "init method called\nenter method called\nwith statement block\nexit method called\n"
},
{
"code": null,
"e": 27543,
"s": 27357,
"text": "In this case a ContextManager object is created. This is assigned to the variable after the as keyword i.e manager. On running the above program, the following get executed in sequence:"
},
{
"code": null,
"e": 27554,
"s": 27543,
"text": "__init__()"
},
{
"code": null,
"e": 27566,
"s": 27554,
"text": "__enter__()"
},
{
"code": null,
"e": 27610,
"s": 27566,
"text": "statement body (code inside the with block)"
},
{
"code": null,
"e": 27682,
"s": 27610,
"text": "__exit__()[the parameters in this method are used to manage exceptions]"
},
{
"code": null,
"e": 27722,
"s": 27682,
"text": "File management using context manager :"
},
{
"code": null,
"e": 27902,
"s": 27722,
"text": "Let’s apply the above concept to create a class that helps in file resource management.The FileManager class helps in opening a file, writing/reading contents and then closing it."
},
{
"code": "# Python program showing# file management using # context manager class FileManager(): def __init__(self, filename, mode): self.filename = filename self.mode = mode self.file = None def __enter__(self): self.file = open(self.filename, self.mode) return self.file def __exit__(self, exc_type, exc_value, exc_traceback): self.file.close() # loading a file with FileManager('test.txt', 'w') as f: f.write('Test') print(f.closed)",
"e": 28401,
"s": 27902,
"text": null
},
{
"code": null,
"e": 28409,
"s": 28401,
"text": "Output:"
},
{
"code": null,
"e": 28415,
"s": 28409,
"text": "True\n"
},
{
"code": null,
"e": 28475,
"s": 28415,
"text": " File management using context manager and with statement :"
},
{
"code": null,
"e": 28549,
"s": 28475,
"text": "On executing the with block, the following operations happen in sequence:"
},
{
"code": null,
"e": 28670,
"s": 28549,
"text": "A FileManager object is created with test.txt as the filename and w(write) as the mode when __init__ method is executed."
},
{
"code": null,
"e": 28796,
"s": 28670,
"text": "The __enter__ method opens the test.txt file in write mode(setup operation) and returns the FileManager object to variable f."
},
{
"code": null,
"e": 28838,
"s": 28796,
"text": "The text ‘Test’ is written into the file."
},
{
"code": null,
"e": 29091,
"s": 28838,
"text": "The __exit__ method takes care of closing the file on exiting the with block(teardown operation).When print(f.closed) is run, the output is True as the FileManager has already taken care of closing the file which otherwise needed to be explicitly done."
},
{
"code": null,
"e": 29146,
"s": 29091,
"text": "Database connection management using context manager :"
},
{
"code": null,
"e": 29477,
"s": 29146,
"text": "Let’s create a simple database connection management system. The number of database connections that can be opened at a time is also limited(just like file descriptors). Therefore context managers are helpful in managing connections to the database as there could be chances that the programmer may forget to close the connection."
},
{
"code": "# Python program shows the# connection management # for MongoDB from pymongo import MongoClient class MongoDBConnectionManager(): def __init__(self, hostname, port): self.hostname = hostname self.port = port self.connection = None def __enter__(self): self.connection = MongoClient(self.hostname, self.port) return self def __exit__(self, exc_type, exc_value, exc_traceback): self.connection.close() # connecting with a localhostwith MongoDBConnectionManager('localhost', '27017') as mongo: collection = mongo.connection.SampleDb.test data = collection.find({'_id': 1}) print(data.get('name'))",
"e": 30138,
"s": 29477,
"text": null
},
{
"code": null,
"e": 30213,
"s": 30138,
"text": " Database connection management using context manager and with statement :"
},
{
"code": null,
"e": 30287,
"s": 30213,
"text": "On executing the with block, the following operations happen in sequence:"
},
{
"code": null,
"e": 30423,
"s": 30287,
"text": "A MongoDBConnectionManager object is created with localhost as the hostnamename and 27017 as the port when __init__ method is executed."
},
{
"code": null,
"e": 30540,
"s": 30423,
"text": "The __enter__ method opens the mongodb connection and returns the MongoDBConnectionManager object to variable mongo."
},
{
"code": null,
"e": 30678,
"s": 30540,
"text": "The test collection in SampleDb database is accessed and the document with _id=1 is retrieved. The name field of the document is printed."
},
{
"code": null,
"e": 30782,
"s": 30678,
"text": "The __exit__ method takes care of closing the connection on exiting the with block(teardown operation)."
},
{
"code": null,
"e": 30803,
"s": 30782,
"text": "python-file-handling"
},
{
"code": null,
"e": 30810,
"s": 30803,
"text": "Python"
},
{
"code": null,
"e": 30908,
"s": 30810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30926,
"s": 30908,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30958,
"s": 30926,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31000,
"s": 30958,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31026,
"s": 31000,
"text": "Python String | replace()"
},
{
"code": null,
"e": 31063,
"s": 31026,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 31107,
"s": 31063,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 31136,
"s": 31107,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 31178,
"s": 31136,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 31234,
"s": 31178,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Returning an Array from a Method in Java
|
A method may also return an array. For example, the following method returns an array that is the reversal of another array -
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
|
[
{
"code": null,
"e": 1188,
"s": 1062,
"text": "A method may also return an array. For example, the following method returns an array that is the reversal of another array -"
},
{
"code": null,
"e": 1393,
"s": 1188,
"text": "public static int[] reverse(int[] list) {\n int[] result = new int[list.length];\n for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {\n result[j] = list[i];\n }\n return result;\n}"
}
] |
How to find K in K-Means? | by Ankit Goel | Jul, 2020 | Towards Data Science
|
K-Means is the most used clustering algorithm in unsupervised Machine Learning problems and it is really useful to find similar data points and to determine the structure of the data. In this article, I assume that you have a basic understanding of K-Means and will focus more on how you can-
Find the value of K (number of clusters) using different methods like the Elbow curve, Sillhouette curve, and Intercluster distances.
A great visualization library YellowBrick which can help you to plot these curves with just 1 line of code.
Different Scikit-Learn tips to improve your K-Means model.
If you are a newbie, there are many great articles on the internet that can help you to understand K-Means. I would recommend going through blogs from Imad Dabbura “K-means Clustering: Algorithm, Applications, Evaluation Methods, and Drawbacks” and Azika Amelia “K-Means Clustering: From A to Z” which covers most of it. You can refer to Scikit-Learn documentation for clustering as well which lay out it pretty nicely.
Let’s start and see how it can be done.
To use K-Means, we need to specify the value of K that is the number of clusters we want to group our data into. Most of the time, we are not aware of the number of groups that would be present in our data and it becomes challenging to find the optimal value for K. Thankfully, different ways can help us to find the right value.
I will go through 4 different ways here.
Elbow Curve.Silhouette Curve.Intercluster Distance Maps.Using other clustering algorithms.
Elbow Curve.
Silhouette Curve.
Intercluster Distance Maps.
Using other clustering algorithms.
To best demonstrate, I will create a dataset using make_blobs API from Scikit-Learn which is used to create multiclass datasets by allocating each class to one or more normally-distributed clusters of points.
Have a look at the notebook I created which have more details, feel free to download and import it in your environment and play around-
github.com
Here, we created a dataset with 10 centers using make_blobs.
from sklearn.datasets import make_blobs# Generate synthetic dataset with 10 random clusters in 2 dimensional spaceX, y = make_blobs(n_samples=1000, n_features=2, centers=10, random_state=42)
Although we created 10 random clusters, the plot below shows there is an overlap between some and we will see how Elbow method can tell us the exact number of clusters for which we have maximum gain.
As stated in Wikipedia-
The elbow method is a heuristic used in determining the number of clusters in a data set. The method consists of plotting the explained variation as a function of the number of clusters, and picking the elbow of the curve as the number of clusters to use.
The intuition behind the Elbow curve is that the explained variation changes rapidly until the number of groups you have in the data and then it slows down leading to an elbow formation in the graph as shown below. The Elbow point is the number of clusters you should use for your K-Means algorithm.
Recently I discovered a library named Yellowbrick which can help us to plot the Elbow curve with just 1 line of code. It is a wrapper around Scikit-Learn and hence integrate well with it.
# Import ElbowVisualizerfrom yellowbrick.cluster import KElbowVisualizermodel = KMeans()# k is range of number of clusters.visualizer = KElbowVisualizer(model, k=(4,12), timings=False)visualizer.fit(X) # Fit the data to the visualizervisualizer.show() # Finalize and render the figure
The above code will generate this nice graph with all details. By default, it uses Distortion Score as a metric that computes the sum of squared distances from each point to its assigned center. You can try other metrics mentioned here as well.
Some clustering problems might not result in elbow formation and can result in a continuously decreasing graph which makes it difficult to select the value of K. We can use other methods in this case as mentioned in the next sub-section.
Generally, we don’t have ground truth (label) in clustering problems, evaluation needs to be done using the model itself. The silhouette coefficient calculates the density of the cluster by generating a score for each sample based on the difference between the average intra-cluster distance and the mean nearest-cluster distance for that sample normalized by the maximum value. We can find the optimal value of K by generating plots for different values of K and selecting the one with the best score depending on the cluster’s assignment.
Below, I plotted Silhouette plots for K = 6, 7, 8, 9 and you can see that we got the highest score for K = 7 as we got using the Elbow method. This also helps us to identify class imbalance as the width of the clusters shows the number of samples in that cluster and if you see the graph for K=9, we have many small clusters.
I used Yellowbrick to generate the above plot. The code below will generate a single Sillhouette graph for K=7, you can refer my notebook on how you can loop through it to generate multiple plots.
model = KMeans(7, random_state=42)visualizer = SilhouetteVisualizer(model, colors='yellowbrick')visualizer.fit(X) # Fit the data to the visualizervisualizer.show() # Finalize and render the figure
Although this might not help directly to find the number of clusters. It helps in evaluating the K-Means algorithm as it gives a sense of relative importance of clusters. By default, Yellowbrick uses MDS (multidimensional scaling) as an embedding algorithm to embed into 2-dimensional space. You can read more about it here.
model = KMeans(7)visualizer = InterclusterDistance(model, random_state=0)visualizer.fit(X) # Fit the data to the visualizervisualizer.show() # Finalize and render the figure
The above code would generate below plot-
Another thing we can try is to use other clustering algorithms like Affinity Propagation which doesn’t require you to supply the value of K and make it a part of the learning process. These algorithms might not work for large datasets. So, in some cases, we need to try them on a subset of data and then use the value in K-Means. The Below code predicted 10 clusters that match the number of centers we have used.
from sklearn.cluster import AffinityPropagation# Creating Affinity Propagation model instanceaffinity_propagation = AffinityPropagation(random_state=None, damping=0.90)# number of clusters found by Affinity propagationlen(affinity_propagation.cluster_centers_indices_)
Now, as we evaluated using different methods, the optimal value for K which we got is 7. Let’s apply the K-Means algorithm with K=7 and see how it clusters our data points.
model = KMeans(n_clusters=7)# fit Xmodel.fit(X)# predict labels data['y_pred'] = model.predict(X)# plot resultssns.scatterplot(x='feature1', y='feature2', hue='y_pred', data=data)
Scikit-learn provides different configurations for K-Means which we can utilize. You can find the complete list here. I will go through a few of them which can help in improving our model.
K-Means algorithm depends largely on how you have initialized centroids (center of the clusters). Scikit-Learn provides different values of init which can be used but in general k-means++ stands out from others as it tries to initializes the centroids to be (generally) distant from each other, leading to provably better results.
K-Means uses Euclidean distance to calculate the distance between points. It is observed that in very high dimensional space, Euclidean distances tend to blow up and don’t work well. So, if you have a large number of features, using dimensionality reduction algorithms like PCA before k-means can overcome this issue and speed up the computation.
For large datasets, K-Means can take a lot of time to converge. As stated in Scikit-Learn documentation-
The MiniBatchKMeans is a variant of the KMeans algorithm which uses mini-batches to reduce the computation time, while still attempting to optimise the same objective function. Mini-batches are subsets of the input data, randomly sampled in each training iteration. These mini-batches drastically reduce the amount of computation required to converge to a local solution. In contrast to other algorithms that reduce the convergence time of k-means, mini-batch k-means produces results that are generally only slightly worse than the standard algorithm.
So, if you have a large dataset, do check out MiniBatchKmeans.
Most of the people who start Machine Learning knows about metrics like accuracy, precision, and recall. We tend to think that if there is no label then how we can measure the results. Scikit-Learn provides different metrics for clustering like homogeneity, completeness, v-measure, or silhouette coefficient which we discussed here. These metrics can help us to evaluate the model. While some of these follow a semi-supervised learning approach and require you to have target labels for a few data points at least others works without any labels. Do check out all the metrics available in Scikit-Learn for clustering here.
You must scale the dataset before applying k-means as it can impact the distance calculations.
Due to the way K-Means works, it is normally suitable for clusters that have even shapes like spherical. If you know you have data that follows uneven shapes then it is better to use other clustering algorithms like DBSCAN that works for uneven clusters.
K-Means is a powerful and simple algorithm that works for most of the unsupervised Machine Learning problems and provides considerably good results. I hope this article will help you with your clustering problems and would save your time for future clustering project. Also, Are you using Pipeline in Scikit-Learn? If not, do check out my other article here which can help you improve your machine learning workflows.
Stay Safe !!! Keep Learning !!!
|
[
{
"code": null,
"e": 465,
"s": 172,
"text": "K-Means is the most used clustering algorithm in unsupervised Machine Learning problems and it is really useful to find similar data points and to determine the structure of the data. In this article, I assume that you have a basic understanding of K-Means and will focus more on how you can-"
},
{
"code": null,
"e": 599,
"s": 465,
"text": "Find the value of K (number of clusters) using different methods like the Elbow curve, Sillhouette curve, and Intercluster distances."
},
{
"code": null,
"e": 707,
"s": 599,
"text": "A great visualization library YellowBrick which can help you to plot these curves with just 1 line of code."
},
{
"code": null,
"e": 766,
"s": 707,
"text": "Different Scikit-Learn tips to improve your K-Means model."
},
{
"code": null,
"e": 1186,
"s": 766,
"text": "If you are a newbie, there are many great articles on the internet that can help you to understand K-Means. I would recommend going through blogs from Imad Dabbura “K-means Clustering: Algorithm, Applications, Evaluation Methods, and Drawbacks” and Azika Amelia “K-Means Clustering: From A to Z” which covers most of it. You can refer to Scikit-Learn documentation for clustering as well which lay out it pretty nicely."
},
{
"code": null,
"e": 1226,
"s": 1186,
"text": "Let’s start and see how it can be done."
},
{
"code": null,
"e": 1556,
"s": 1226,
"text": "To use K-Means, we need to specify the value of K that is the number of clusters we want to group our data into. Most of the time, we are not aware of the number of groups that would be present in our data and it becomes challenging to find the optimal value for K. Thankfully, different ways can help us to find the right value."
},
{
"code": null,
"e": 1597,
"s": 1556,
"text": "I will go through 4 different ways here."
},
{
"code": null,
"e": 1688,
"s": 1597,
"text": "Elbow Curve.Silhouette Curve.Intercluster Distance Maps.Using other clustering algorithms."
},
{
"code": null,
"e": 1701,
"s": 1688,
"text": "Elbow Curve."
},
{
"code": null,
"e": 1719,
"s": 1701,
"text": "Silhouette Curve."
},
{
"code": null,
"e": 1747,
"s": 1719,
"text": "Intercluster Distance Maps."
},
{
"code": null,
"e": 1782,
"s": 1747,
"text": "Using other clustering algorithms."
},
{
"code": null,
"e": 1991,
"s": 1782,
"text": "To best demonstrate, I will create a dataset using make_blobs API from Scikit-Learn which is used to create multiclass datasets by allocating each class to one or more normally-distributed clusters of points."
},
{
"code": null,
"e": 2127,
"s": 1991,
"text": "Have a look at the notebook I created which have more details, feel free to download and import it in your environment and play around-"
},
{
"code": null,
"e": 2138,
"s": 2127,
"text": "github.com"
},
{
"code": null,
"e": 2199,
"s": 2138,
"text": "Here, we created a dataset with 10 centers using make_blobs."
},
{
"code": null,
"e": 2390,
"s": 2199,
"text": "from sklearn.datasets import make_blobs# Generate synthetic dataset with 10 random clusters in 2 dimensional spaceX, y = make_blobs(n_samples=1000, n_features=2, centers=10, random_state=42)"
},
{
"code": null,
"e": 2590,
"s": 2390,
"text": "Although we created 10 random clusters, the plot below shows there is an overlap between some and we will see how Elbow method can tell us the exact number of clusters for which we have maximum gain."
},
{
"code": null,
"e": 2614,
"s": 2590,
"text": "As stated in Wikipedia-"
},
{
"code": null,
"e": 2870,
"s": 2614,
"text": "The elbow method is a heuristic used in determining the number of clusters in a data set. The method consists of plotting the explained variation as a function of the number of clusters, and picking the elbow of the curve as the number of clusters to use."
},
{
"code": null,
"e": 3170,
"s": 2870,
"text": "The intuition behind the Elbow curve is that the explained variation changes rapidly until the number of groups you have in the data and then it slows down leading to an elbow formation in the graph as shown below. The Elbow point is the number of clusters you should use for your K-Means algorithm."
},
{
"code": null,
"e": 3358,
"s": 3170,
"text": "Recently I discovered a library named Yellowbrick which can help us to plot the Elbow curve with just 1 line of code. It is a wrapper around Scikit-Learn and hence integrate well with it."
},
{
"code": null,
"e": 3657,
"s": 3358,
"text": "# Import ElbowVisualizerfrom yellowbrick.cluster import KElbowVisualizermodel = KMeans()# k is range of number of clusters.visualizer = KElbowVisualizer(model, k=(4,12), timings=False)visualizer.fit(X) # Fit the data to the visualizervisualizer.show() # Finalize and render the figure"
},
{
"code": null,
"e": 3902,
"s": 3657,
"text": "The above code will generate this nice graph with all details. By default, it uses Distortion Score as a metric that computes the sum of squared distances from each point to its assigned center. You can try other metrics mentioned here as well."
},
{
"code": null,
"e": 4140,
"s": 3902,
"text": "Some clustering problems might not result in elbow formation and can result in a continuously decreasing graph which makes it difficult to select the value of K. We can use other methods in this case as mentioned in the next sub-section."
},
{
"code": null,
"e": 4681,
"s": 4140,
"text": "Generally, we don’t have ground truth (label) in clustering problems, evaluation needs to be done using the model itself. The silhouette coefficient calculates the density of the cluster by generating a score for each sample based on the difference between the average intra-cluster distance and the mean nearest-cluster distance for that sample normalized by the maximum value. We can find the optimal value of K by generating plots for different values of K and selecting the one with the best score depending on the cluster’s assignment."
},
{
"code": null,
"e": 5007,
"s": 4681,
"text": "Below, I plotted Silhouette plots for K = 6, 7, 8, 9 and you can see that we got the highest score for K = 7 as we got using the Elbow method. This also helps us to identify class imbalance as the width of the clusters shows the number of samples in that cluster and if you see the graph for K=9, we have many small clusters."
},
{
"code": null,
"e": 5204,
"s": 5007,
"text": "I used Yellowbrick to generate the above plot. The code below will generate a single Sillhouette graph for K=7, you can refer my notebook on how you can loop through it to generate multiple plots."
},
{
"code": null,
"e": 5415,
"s": 5204,
"text": "model = KMeans(7, random_state=42)visualizer = SilhouetteVisualizer(model, colors='yellowbrick')visualizer.fit(X) # Fit the data to the visualizervisualizer.show() # Finalize and render the figure"
},
{
"code": null,
"e": 5740,
"s": 5415,
"text": "Although this might not help directly to find the number of clusters. It helps in evaluating the K-Means algorithm as it gives a sense of relative importance of clusters. By default, Yellowbrick uses MDS (multidimensional scaling) as an embedding algorithm to embed into 2-dimensional space. You can read more about it here."
},
{
"code": null,
"e": 5928,
"s": 5740,
"text": "model = KMeans(7)visualizer = InterclusterDistance(model, random_state=0)visualizer.fit(X) # Fit the data to the visualizervisualizer.show() # Finalize and render the figure"
},
{
"code": null,
"e": 5970,
"s": 5928,
"text": "The above code would generate below plot-"
},
{
"code": null,
"e": 6384,
"s": 5970,
"text": "Another thing we can try is to use other clustering algorithms like Affinity Propagation which doesn’t require you to supply the value of K and make it a part of the learning process. These algorithms might not work for large datasets. So, in some cases, we need to try them on a subset of data and then use the value in K-Means. The Below code predicted 10 clusters that match the number of centers we have used."
},
{
"code": null,
"e": 6653,
"s": 6384,
"text": "from sklearn.cluster import AffinityPropagation# Creating Affinity Propagation model instanceaffinity_propagation = AffinityPropagation(random_state=None, damping=0.90)# number of clusters found by Affinity propagationlen(affinity_propagation.cluster_centers_indices_)"
},
{
"code": null,
"e": 6826,
"s": 6653,
"text": "Now, as we evaluated using different methods, the optimal value for K which we got is 7. Let’s apply the K-Means algorithm with K=7 and see how it clusters our data points."
},
{
"code": null,
"e": 7006,
"s": 6826,
"text": "model = KMeans(n_clusters=7)# fit Xmodel.fit(X)# predict labels data['y_pred'] = model.predict(X)# plot resultssns.scatterplot(x='feature1', y='feature2', hue='y_pred', data=data)"
},
{
"code": null,
"e": 7195,
"s": 7006,
"text": "Scikit-learn provides different configurations for K-Means which we can utilize. You can find the complete list here. I will go through a few of them which can help in improving our model."
},
{
"code": null,
"e": 7526,
"s": 7195,
"text": "K-Means algorithm depends largely on how you have initialized centroids (center of the clusters). Scikit-Learn provides different values of init which can be used but in general k-means++ stands out from others as it tries to initializes the centroids to be (generally) distant from each other, leading to provably better results."
},
{
"code": null,
"e": 7873,
"s": 7526,
"text": "K-Means uses Euclidean distance to calculate the distance between points. It is observed that in very high dimensional space, Euclidean distances tend to blow up and don’t work well. So, if you have a large number of features, using dimensionality reduction algorithms like PCA before k-means can overcome this issue and speed up the computation."
},
{
"code": null,
"e": 7978,
"s": 7873,
"text": "For large datasets, K-Means can take a lot of time to converge. As stated in Scikit-Learn documentation-"
},
{
"code": null,
"e": 8531,
"s": 7978,
"text": "The MiniBatchKMeans is a variant of the KMeans algorithm which uses mini-batches to reduce the computation time, while still attempting to optimise the same objective function. Mini-batches are subsets of the input data, randomly sampled in each training iteration. These mini-batches drastically reduce the amount of computation required to converge to a local solution. In contrast to other algorithms that reduce the convergence time of k-means, mini-batch k-means produces results that are generally only slightly worse than the standard algorithm."
},
{
"code": null,
"e": 8594,
"s": 8531,
"text": "So, if you have a large dataset, do check out MiniBatchKmeans."
},
{
"code": null,
"e": 9217,
"s": 8594,
"text": "Most of the people who start Machine Learning knows about metrics like accuracy, precision, and recall. We tend to think that if there is no label then how we can measure the results. Scikit-Learn provides different metrics for clustering like homogeneity, completeness, v-measure, or silhouette coefficient which we discussed here. These metrics can help us to evaluate the model. While some of these follow a semi-supervised learning approach and require you to have target labels for a few data points at least others works without any labels. Do check out all the metrics available in Scikit-Learn for clustering here."
},
{
"code": null,
"e": 9312,
"s": 9217,
"text": "You must scale the dataset before applying k-means as it can impact the distance calculations."
},
{
"code": null,
"e": 9567,
"s": 9312,
"text": "Due to the way K-Means works, it is normally suitable for clusters that have even shapes like spherical. If you know you have data that follows uneven shapes then it is better to use other clustering algorithms like DBSCAN that works for uneven clusters."
},
{
"code": null,
"e": 9985,
"s": 9567,
"text": "K-Means is a powerful and simple algorithm that works for most of the unsupervised Machine Learning problems and provides considerably good results. I hope this article will help you with your clustering problems and would save your time for future clustering project. Also, Are you using Pipeline in Scikit-Learn? If not, do check out my other article here which can help you improve your machine learning workflows."
}
] |
Firebase - Filtering Data
|
Firebase offers several ways to filter data.
Let us understand what limit to first and last is.
limitToFirst method returns the specified number of items beginning from the first one.
limitToFirst method returns the specified number of items beginning from the first one.
limitToLast method returns a specified number of items beginning from the last one.
limitToLast method returns a specified number of items beginning from the last one.
Our example is showing how this works. Since we only have two players in database, we will limit queries to one player.
Let us consider the following example.
var firstPlayerRef = firebase.database().ref("players/").limitToFirst(1);
var lastPlayerRef = firebase.database().ref('players/').limitToLast(1);
firstPlayerRef.on("value", function(data) {
console.log(data.val());
}, function (error) {
console.log("Error: " + error.code);
});
lastPlayerRef.on("value", function(data) {
console.log(data.val());
}, function (error) {
console.log("Error: " + error.code);
});
Our console will log the first player from the first query, and the last player from the second query.
We can also use other Firebase filtering methods. The startAt(), endAt() and the equalTo() can be combined with ordering methods. In our example, we will combine it with the orderByChild() method.
Let us consider the following example.
var playersRef = firebase.database().ref("players/");
playersRef.orderByChild("name").startAt("Amanda").on("child_added", function(data) {
console.log("Start at filter: " + data.val().name);
});
playersRef.orderByChild("name").endAt("Amanda").on("child_added", function(data) {
console.log("End at filter: " + data.val().name);
});
playersRef.orderByChild("name").equalTo("John").on("child_added", function(data) {
console.log("Equal to filter: " + data.val().name);
});
playersRef.orderByChild("age").startAt(20).on("child_added", function(data) {
console.log("Age filter: " + data.val().name);
});
The first query will order elements by name and filter from the player with the name Amanda. The console will log both players. The second query will log "Amanda" since we are ending query with this name. The third one will log "John" since we are searching for a player with that name.
The fourth example is showing how we can combine filters with "age" value. Instead of string, we are passing the number inside the startAt() method since age is represented by a number value.
60 Lectures
5 hours
University Code
28 Lectures
2.5 hours
Appeteria
85 Lectures
14.5 hours
Appeteria
46 Lectures
2.5 hours
Gautham Vijayan
13 Lectures
1.5 hours
Nishant Kumar
85 Lectures
16.5 hours
Rahul Agarwal
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2211,
"s": 2166,
"text": "Firebase offers several ways to filter data."
},
{
"code": null,
"e": 2262,
"s": 2211,
"text": "Let us understand what limit to first and last is."
},
{
"code": null,
"e": 2350,
"s": 2262,
"text": "limitToFirst method returns the specified number of items beginning from the first one."
},
{
"code": null,
"e": 2438,
"s": 2350,
"text": "limitToFirst method returns the specified number of items beginning from the first one."
},
{
"code": null,
"e": 2522,
"s": 2438,
"text": "limitToLast method returns a specified number of items beginning from the last one."
},
{
"code": null,
"e": 2606,
"s": 2522,
"text": "limitToLast method returns a specified number of items beginning from the last one."
},
{
"code": null,
"e": 2726,
"s": 2606,
"text": "Our example is showing how this works. Since we only have two players in database, we will limit queries to one player."
},
{
"code": null,
"e": 2765,
"s": 2726,
"text": "Let us consider the following example."
},
{
"code": null,
"e": 3189,
"s": 2765,
"text": "var firstPlayerRef = firebase.database().ref(\"players/\").limitToFirst(1);\n\nvar lastPlayerRef = firebase.database().ref('players/').limitToLast(1);\n\nfirstPlayerRef.on(\"value\", function(data) {\n console.log(data.val());\n}, function (error) {\n console.log(\"Error: \" + error.code);\n});\n\nlastPlayerRef.on(\"value\", function(data) {\n console.log(data.val());\n}, function (error) {\n console.log(\"Error: \" + error.code);\n});"
},
{
"code": null,
"e": 3292,
"s": 3189,
"text": "Our console will log the first player from the first query, and the last player from the second query."
},
{
"code": null,
"e": 3489,
"s": 3292,
"text": "We can also use other Firebase filtering methods. The startAt(), endAt() and the equalTo() can be combined with ordering methods. In our example, we will combine it with the orderByChild() method."
},
{
"code": null,
"e": 3528,
"s": 3489,
"text": "Let us consider the following example."
},
{
"code": null,
"e": 4144,
"s": 3528,
"text": "var playersRef = firebase.database().ref(\"players/\");\n\nplayersRef.orderByChild(\"name\").startAt(\"Amanda\").on(\"child_added\", function(data) {\n console.log(\"Start at filter: \" + data.val().name);\n});\n\nplayersRef.orderByChild(\"name\").endAt(\"Amanda\").on(\"child_added\", function(data) {\n console.log(\"End at filter: \" + data.val().name);\n});\n\nplayersRef.orderByChild(\"name\").equalTo(\"John\").on(\"child_added\", function(data) {\n console.log(\"Equal to filter: \" + data.val().name);\n});\n\nplayersRef.orderByChild(\"age\").startAt(20).on(\"child_added\", function(data) {\n console.log(\"Age filter: \" + data.val().name);\n});"
},
{
"code": null,
"e": 4431,
"s": 4144,
"text": "The first query will order elements by name and filter from the player with the name Amanda. The console will log both players. The second query will log \"Amanda\" since we are ending query with this name. The third one will log \"John\" since we are searching for a player with that name."
},
{
"code": null,
"e": 4623,
"s": 4431,
"text": "The fourth example is showing how we can combine filters with \"age\" value. Instead of string, we are passing the number inside the startAt() method since age is represented by a number value."
},
{
"code": null,
"e": 4656,
"s": 4623,
"text": "\n 60 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4673,
"s": 4656,
"text": " University Code"
},
{
"code": null,
"e": 4708,
"s": 4673,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4719,
"s": 4708,
"text": " Appeteria"
},
{
"code": null,
"e": 4755,
"s": 4719,
"text": "\n 85 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 4766,
"s": 4755,
"text": " Appeteria"
},
{
"code": null,
"e": 4801,
"s": 4766,
"text": "\n 46 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4818,
"s": 4801,
"text": " Gautham Vijayan"
},
{
"code": null,
"e": 4853,
"s": 4818,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4868,
"s": 4853,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 4904,
"s": 4868,
"text": "\n 85 Lectures \n 16.5 hours \n"
},
{
"code": null,
"e": 4919,
"s": 4904,
"text": " Rahul Agarwal"
},
{
"code": null,
"e": 4926,
"s": 4919,
"text": " Print"
},
{
"code": null,
"e": 4937,
"s": 4926,
"text": " Add Notes"
}
] |
Python Program Exit handlers (atexit)
|
The atexit module in the standard distribution of Python has two functions – register() and unregister(). Both functions take some existing function as an argument. Registered functions are executed automatically when the interpreter session is terminated normally.
If more than one functions are registered, their execution is in the reverse order of registration. It means, functions f1(), f2() and f3() are registered one after other, their order of execution will be f3(), f2() and f1().
The unregister() function removes the specified function from list of functions to be automatically invoked.
Following code shows how a function is registered for automatic execution upon termination of code. (Note: This code has to be executed from a command line and not through IDLE). The program asks a user to input numbers successively and adds them. When the loop is over, the registered function savetotal() is called automatically to save the addition to a file.
import atexit
sum = 0
def savetotal():
fo = open("atexit.txt","w")
fo.write(str(sum))
print ("sum written to file")
fo.close()
atexit.register(savetotal)
while True:
n = int(input("enter a number. -1 to exit"))
if n == -1:
break
sum = sum + n
print (sum)
Save above code as atexit-example.py and run from command line. Successive numbers input are added and the total is written to atexit.txt at the end.
C:\python36>python atexit-example.py
enter a number. -1 to exit4
enter a number. -1 to exit6
enter a number. -1 to exit3
enter a number. -1 to exit5
enter a number. -1 to exit2
enter a number. -1 to exit-1
20
sum written to file
The atexit.txt file will be created in current directory and it will store the total (20 in this case).
It is also possible to register a function with different arguments. In that case, function with each argument will be registered independently and will be executed in reverse order of registration.
import atexit
names = ['Ashok', 'Radha', 'Abdul', 'John']
def hello(name):
print ("Hello",name)
for name in names:
atexit.register(hello,name)
Output
C:\python36>python atexit-example2.py
Hello John
Hello Abdul
Hello Radha
Hello Ashok
atexit.unregister(hello) will remove all copies of hello() with various parameters from the list of functions.
A convenient alternative to register a function is to use register() function as a decorator.
import atexit
@atexit.register
def hello():
print('Hello World!')
print('Say Hello')
C:\python36>python atexit-example3.py
Say Hello
Hello World!
The registered functions will not be invoked automatically if program terminates abruptly or os.exit() function is called.
The atexit module is useful in automatically performing clean operations like closing databases and files, freeing up resources etc.
|
[
{
"code": null,
"e": 1328,
"s": 1062,
"text": "The atexit module in the standard distribution of Python has two functions – register() and unregister(). Both functions take some existing function as an argument. Registered functions are executed automatically when the interpreter session is terminated normally."
},
{
"code": null,
"e": 1554,
"s": 1328,
"text": "If more than one functions are registered, their execution is in the reverse order of registration. It means, functions f1(), f2() and f3() are registered one after other, their order of execution will be f3(), f2() and f1()."
},
{
"code": null,
"e": 1663,
"s": 1554,
"text": "The unregister() function removes the specified function from list of functions to be automatically invoked."
},
{
"code": null,
"e": 2026,
"s": 1663,
"text": "Following code shows how a function is registered for automatic execution upon termination of code. (Note: This code has to be executed from a command line and not through IDLE). The program asks a user to input numbers successively and adds them. When the loop is over, the registered function savetotal() is called automatically to save the addition to a file."
},
{
"code": null,
"e": 2281,
"s": 2026,
"text": "import atexit\nsum = 0\ndef savetotal():\nfo = open(\"atexit.txt\",\"w\")\nfo.write(str(sum))\nprint (\"sum written to file\")\nfo.close()\natexit.register(savetotal)\nwhile True:\nn = int(input(\"enter a number. -1 to exit\"))\nif n == -1:\nbreak\nsum = sum + n\nprint (sum)"
},
{
"code": null,
"e": 2431,
"s": 2281,
"text": "Save above code as atexit-example.py and run from command line. Successive numbers input are added and the total is written to atexit.txt at the end."
},
{
"code": null,
"e": 2660,
"s": 2431,
"text": "C:\\python36>python atexit-example.py\nenter a number. -1 to exit4\nenter a number. -1 to exit6\nenter a number. -1 to exit3\nenter a number. -1 to exit5\nenter a number. -1 to exit2\nenter a number. -1 to exit-1\n20\nsum written to file"
},
{
"code": null,
"e": 2764,
"s": 2660,
"text": "The atexit.txt file will be created in current directory and it will store the total (20 in this case)."
},
{
"code": null,
"e": 2963,
"s": 2764,
"text": "It is also possible to register a function with different arguments. In that case, function with each argument will be registered independently and will be executed in reverse order of registration."
},
{
"code": null,
"e": 3106,
"s": 2963,
"text": "import atexit\nnames = ['Ashok', 'Radha', 'Abdul', 'John']\ndef hello(name):\nprint (\"Hello\",name)\nfor name in names:\natexit.register(hello,name)"
},
{
"code": null,
"e": 3113,
"s": 3106,
"text": "Output"
},
{
"code": null,
"e": 3198,
"s": 3113,
"text": "C:\\python36>python atexit-example2.py\nHello John\nHello Abdul\nHello Radha\nHello Ashok"
},
{
"code": null,
"e": 3309,
"s": 3198,
"text": "atexit.unregister(hello) will remove all copies of hello() with various parameters from the list of functions."
},
{
"code": null,
"e": 3403,
"s": 3309,
"text": "A convenient alternative to register a function is to use register() function as a decorator."
},
{
"code": null,
"e": 3488,
"s": 3403,
"text": "import atexit\n@atexit.register\ndef hello():\nprint('Hello World!')\nprint('Say Hello')"
},
{
"code": null,
"e": 3549,
"s": 3488,
"text": "C:\\python36>python atexit-example3.py\nSay Hello\nHello World!"
},
{
"code": null,
"e": 3672,
"s": 3549,
"text": "The registered functions will not be invoked automatically if program terminates abruptly or os.exit() function is called."
},
{
"code": null,
"e": 3805,
"s": 3672,
"text": "The atexit module is useful in automatically performing clean operations like closing databases and files, freeing up resources etc."
}
] |
Interactive Topic Modeling with BERTopic | Towards Data Science
|
Every day, businesses deal with large volumes of unstructured text. From customer interactions in emails to online feedback and reviews. To deal with this large amount of text, we look towards topic modeling. A technique to automatically extract meaning from documents by identifying recurrent topics.
A few months ago, I wrote an article on leveraging BERT for topic modeling. It blew up unexpectedly and I was surprised by the positive feedback I had gotten!
towardsdatascience.com
I decided to focus on further developing the topic modeling technique the article was based on, namely BERTopic.
BERTopic is a topic modeling technique that leverages BERT embeddings and a class-based TF-IDF to create dense clusters allowing for easily interpretable topics whilst keeping important words in the topic descriptions.
I am now at a point where BERTopic has gotten enough traction and development that I feel confident it can replace or complement other topic modeling techniques, such as LDA.
github.com
The main purpose of this article is to give you an in-depth overview of BERTopic’s features and tutorials on how to best apply this for your own projects.
As always, we start by installing the package via pypi:
pip install bertopic
To use the visualization options, install BERTopic as follows:
pip install bertopic[visualization]
Using BERTopic out-of-the-box is quite straightforward. You load in your documents as a list of strings and simply pass it to the fit_transform method.
To give you an example, below we will be using the 20 newsgroups dataset:
There are two outputs generated, topics and probabilities. A value in topics simply represents the topic it is assigned to. Probabilities on the other hand demonstrate the likelihood of a document falling into any of the possible topics.
Next, we can access the topics that were generated by their relative frequency:
In the output above, it seems that Topic -1 is the largest. -1 refers to all outliers which do not have a topic assigned. Forcing documents in a topic could lead to poor performance. Thus, we ignore Topic -1.
Instead, let us take a look at the second most frequent topic that was generated, namely Topic 49:
Since I created this model, I am obviously biased, but to me, this does seem like a coherent and easily interpretable topic!
Under the hood, BERTopic is using sentence-transformers to create embeddings for the documents you pass it. As a default, BERTopic is set to using an English model but is supports any language for which an embedding model exists.
You can choose the language by simply setting the language parameter in BERTopic:
When you select a language, the corresponding sentence-transformers model will be loaded. This is typically a multilingual model that supports many languages.
Having said that, if you have a mixture of language in your documents you can use BERTopic(language="multilingual") to select a model that supports over 50 languages!
To chose a different pre-trained embedding model, we simply pass it through BERTopic by pointing the variable embedding_model towards the corresponding sentence-transformers model:
Click here for a list of supported sentence transformers models.
We can easily save a trained BERTopic model by calling save:
Then, we can load the model in one line:
Now that we have covered the basics and generated our topics, we visualize them! Having an overall picture of the topics allows us to generate an internal perception of the topic model’s quality.
To visualize our topics I took inspiration from LDAvis which is a framework for visualizing LDA topic models. It allows you to interactively explore topics and the words that describe them.
To achieve a similar effect in BERTopic, I embedded our class-based TF-IDF representation of the topics in 2D using Umap. Then, it was a simple matter of visualizing the dimensions using Plotly to create an interactive view.
To do this, simply call model.visualize_topics() in order to visualize our topics:
An interactive Plotly figure will be generated which can be used as indicated in the animation above. Each circle indicates a topic and its size is the frequency of the topic across all documents.
To try it out yourself, take a look at the documentation here where you can find an interactive version!
For each document, we can also visualize the probability of that document belong to each possible topic. To do so, we use the variable probabilities after running BERTopic to understand how confident the model is for that instance.
Since there are too many topics to visualize, we visualize the probability distribution of the most probable topics:
It seems that for this document, the model had some more difficulty choosing the correct topic as they were multiple topics very similar to each other.
As we have seen before, hundreds of topics could be generated. At times, this might simply be too much for you to explore or a too fine-grained solution.
Fortunately, we can reduce the number of topics by merging pairs of topics that are most similar to each other, as indicated by the cosine similarity between c-TF-IDF vectors.
Below, I will go into three methods for reducing the number of topics that result from BERTopic.
When initiating your BERTopic model, you might already have a feeling of the number of topics that could reside in your documents.
By setting the nr_topics variable, BERTopic will find the most similar pairs of topics and merge them, starting from the least frequent topic, until we reach the value of nr_topics:
It is advised, however, to keep a decently high value, such as 50 to prevent topics from being merged that should not.
As indicated above, if you merge topics to a low nr_topics topics will be forced to merge even though they might not actually be that similar to each other.
Instead, we can reduce the number of topics iteratively as long as a pair of topics is found that exceeds a minimum similarity of 0.9.
To use this option, we simply set nr_topics to "auto" before training our model:
What if you are left with too many topics after training which took many hours? It would be a shame to have to re-train your model just to experiment with the number of topics.
Fortunately, we can reduce the number of topics after having trained a BERTopic model. Another advantage of doing so is that you can decide the number of topics after knowing how many are actually created:
Using the code above, we reduce the number of topics to 30 after having trained the model. This allows you to play around with the number of topics that suit your use-case!
Topics are typically represented by a set of words. In BERTopic, these words are extracted from the documents using a class-based TF-IDF.
At times, you might not be happy with the representation of the topics that were created. This is possible when you selected to have only 1-gram words as representation. Perhaps you want to try out a different n-gram range or you have a custom vectorizer that you want to use.
To update the topic representation after training, we can use the function update_topics to update the topic representation with new parameters for c-TF-IDF:
We can also use a custom CountVectorizer instead:
Why limit ourselves to publicly available pre-trained embeddings? You might have very specific data for which you have created an embedding model that you could not have found pre-trained available.
To use any embedding model that you trained yourself, you will only have to embed your documents with that model. You can then pass in the embeddings and BERTopic will do the rest:
As you can see above, we used a SentenceTransformer model to create the embedding. You could also have used 🤗 transformers, Doc2Vec, or any other embedding method.
While we are at it, why limit ourselves to transformer models? There is a reason why statistical models, such as TF-IDF, are still around. They work great out-of-the-box without much tuning!
As you might have guessed, it is also possible to use TF-IDF on the documents and use them as input for BERTopic. We simply create a TF-IDF matrix and pass it through fit_transform:
Here, you will probably notice that creating the embeddings is quite fast whereas fit_transform is quite slow. This is to be expected as reducing the dimensionality of a large sparse matrix takes some time. The inverse of using transformer embeddings is true: creating the embeddings is slow whereas fit_transform is quite fast.
If you are, like me, passionate about AI, Data Science, or Psychology, please feel free to add me on LinkedIn or follow me on Twitter.
You can find BERTopic, as well as its documentation, below:
|
[
{
"code": null,
"e": 473,
"s": 171,
"text": "Every day, businesses deal with large volumes of unstructured text. From customer interactions in emails to online feedback and reviews. To deal with this large amount of text, we look towards topic modeling. A technique to automatically extract meaning from documents by identifying recurrent topics."
},
{
"code": null,
"e": 632,
"s": 473,
"text": "A few months ago, I wrote an article on leveraging BERT for topic modeling. It blew up unexpectedly and I was surprised by the positive feedback I had gotten!"
},
{
"code": null,
"e": 655,
"s": 632,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 768,
"s": 655,
"text": "I decided to focus on further developing the topic modeling technique the article was based on, namely BERTopic."
},
{
"code": null,
"e": 987,
"s": 768,
"text": "BERTopic is a topic modeling technique that leverages BERT embeddings and a class-based TF-IDF to create dense clusters allowing for easily interpretable topics whilst keeping important words in the topic descriptions."
},
{
"code": null,
"e": 1162,
"s": 987,
"text": "I am now at a point where BERTopic has gotten enough traction and development that I feel confident it can replace or complement other topic modeling techniques, such as LDA."
},
{
"code": null,
"e": 1173,
"s": 1162,
"text": "github.com"
},
{
"code": null,
"e": 1328,
"s": 1173,
"text": "The main purpose of this article is to give you an in-depth overview of BERTopic’s features and tutorials on how to best apply this for your own projects."
},
{
"code": null,
"e": 1384,
"s": 1328,
"text": "As always, we start by installing the package via pypi:"
},
{
"code": null,
"e": 1405,
"s": 1384,
"text": "pip install bertopic"
},
{
"code": null,
"e": 1468,
"s": 1405,
"text": "To use the visualization options, install BERTopic as follows:"
},
{
"code": null,
"e": 1504,
"s": 1468,
"text": "pip install bertopic[visualization]"
},
{
"code": null,
"e": 1656,
"s": 1504,
"text": "Using BERTopic out-of-the-box is quite straightforward. You load in your documents as a list of strings and simply pass it to the fit_transform method."
},
{
"code": null,
"e": 1730,
"s": 1656,
"text": "To give you an example, below we will be using the 20 newsgroups dataset:"
},
{
"code": null,
"e": 1968,
"s": 1730,
"text": "There are two outputs generated, topics and probabilities. A value in topics simply represents the topic it is assigned to. Probabilities on the other hand demonstrate the likelihood of a document falling into any of the possible topics."
},
{
"code": null,
"e": 2048,
"s": 1968,
"text": "Next, we can access the topics that were generated by their relative frequency:"
},
{
"code": null,
"e": 2257,
"s": 2048,
"text": "In the output above, it seems that Topic -1 is the largest. -1 refers to all outliers which do not have a topic assigned. Forcing documents in a topic could lead to poor performance. Thus, we ignore Topic -1."
},
{
"code": null,
"e": 2356,
"s": 2257,
"text": "Instead, let us take a look at the second most frequent topic that was generated, namely Topic 49:"
},
{
"code": null,
"e": 2481,
"s": 2356,
"text": "Since I created this model, I am obviously biased, but to me, this does seem like a coherent and easily interpretable topic!"
},
{
"code": null,
"e": 2711,
"s": 2481,
"text": "Under the hood, BERTopic is using sentence-transformers to create embeddings for the documents you pass it. As a default, BERTopic is set to using an English model but is supports any language for which an embedding model exists."
},
{
"code": null,
"e": 2793,
"s": 2711,
"text": "You can choose the language by simply setting the language parameter in BERTopic:"
},
{
"code": null,
"e": 2952,
"s": 2793,
"text": "When you select a language, the corresponding sentence-transformers model will be loaded. This is typically a multilingual model that supports many languages."
},
{
"code": null,
"e": 3119,
"s": 2952,
"text": "Having said that, if you have a mixture of language in your documents you can use BERTopic(language=\"multilingual\") to select a model that supports over 50 languages!"
},
{
"code": null,
"e": 3300,
"s": 3119,
"text": "To chose a different pre-trained embedding model, we simply pass it through BERTopic by pointing the variable embedding_model towards the corresponding sentence-transformers model:"
},
{
"code": null,
"e": 3365,
"s": 3300,
"text": "Click here for a list of supported sentence transformers models."
},
{
"code": null,
"e": 3426,
"s": 3365,
"text": "We can easily save a trained BERTopic model by calling save:"
},
{
"code": null,
"e": 3467,
"s": 3426,
"text": "Then, we can load the model in one line:"
},
{
"code": null,
"e": 3663,
"s": 3467,
"text": "Now that we have covered the basics and generated our topics, we visualize them! Having an overall picture of the topics allows us to generate an internal perception of the topic model’s quality."
},
{
"code": null,
"e": 3853,
"s": 3663,
"text": "To visualize our topics I took inspiration from LDAvis which is a framework for visualizing LDA topic models. It allows you to interactively explore topics and the words that describe them."
},
{
"code": null,
"e": 4078,
"s": 3853,
"text": "To achieve a similar effect in BERTopic, I embedded our class-based TF-IDF representation of the topics in 2D using Umap. Then, it was a simple matter of visualizing the dimensions using Plotly to create an interactive view."
},
{
"code": null,
"e": 4161,
"s": 4078,
"text": "To do this, simply call model.visualize_topics() in order to visualize our topics:"
},
{
"code": null,
"e": 4358,
"s": 4161,
"text": "An interactive Plotly figure will be generated which can be used as indicated in the animation above. Each circle indicates a topic and its size is the frequency of the topic across all documents."
},
{
"code": null,
"e": 4463,
"s": 4358,
"text": "To try it out yourself, take a look at the documentation here where you can find an interactive version!"
},
{
"code": null,
"e": 4695,
"s": 4463,
"text": "For each document, we can also visualize the probability of that document belong to each possible topic. To do so, we use the variable probabilities after running BERTopic to understand how confident the model is for that instance."
},
{
"code": null,
"e": 4812,
"s": 4695,
"text": "Since there are too many topics to visualize, we visualize the probability distribution of the most probable topics:"
},
{
"code": null,
"e": 4964,
"s": 4812,
"text": "It seems that for this document, the model had some more difficulty choosing the correct topic as they were multiple topics very similar to each other."
},
{
"code": null,
"e": 5118,
"s": 4964,
"text": "As we have seen before, hundreds of topics could be generated. At times, this might simply be too much for you to explore or a too fine-grained solution."
},
{
"code": null,
"e": 5294,
"s": 5118,
"text": "Fortunately, we can reduce the number of topics by merging pairs of topics that are most similar to each other, as indicated by the cosine similarity between c-TF-IDF vectors."
},
{
"code": null,
"e": 5391,
"s": 5294,
"text": "Below, I will go into three methods for reducing the number of topics that result from BERTopic."
},
{
"code": null,
"e": 5522,
"s": 5391,
"text": "When initiating your BERTopic model, you might already have a feeling of the number of topics that could reside in your documents."
},
{
"code": null,
"e": 5704,
"s": 5522,
"text": "By setting the nr_topics variable, BERTopic will find the most similar pairs of topics and merge them, starting from the least frequent topic, until we reach the value of nr_topics:"
},
{
"code": null,
"e": 5823,
"s": 5704,
"text": "It is advised, however, to keep a decently high value, such as 50 to prevent topics from being merged that should not."
},
{
"code": null,
"e": 5980,
"s": 5823,
"text": "As indicated above, if you merge topics to a low nr_topics topics will be forced to merge even though they might not actually be that similar to each other."
},
{
"code": null,
"e": 6115,
"s": 5980,
"text": "Instead, we can reduce the number of topics iteratively as long as a pair of topics is found that exceeds a minimum similarity of 0.9."
},
{
"code": null,
"e": 6196,
"s": 6115,
"text": "To use this option, we simply set nr_topics to \"auto\" before training our model:"
},
{
"code": null,
"e": 6373,
"s": 6196,
"text": "What if you are left with too many topics after training which took many hours? It would be a shame to have to re-train your model just to experiment with the number of topics."
},
{
"code": null,
"e": 6579,
"s": 6373,
"text": "Fortunately, we can reduce the number of topics after having trained a BERTopic model. Another advantage of doing so is that you can decide the number of topics after knowing how many are actually created:"
},
{
"code": null,
"e": 6752,
"s": 6579,
"text": "Using the code above, we reduce the number of topics to 30 after having trained the model. This allows you to play around with the number of topics that suit your use-case!"
},
{
"code": null,
"e": 6890,
"s": 6752,
"text": "Topics are typically represented by a set of words. In BERTopic, these words are extracted from the documents using a class-based TF-IDF."
},
{
"code": null,
"e": 7167,
"s": 6890,
"text": "At times, you might not be happy with the representation of the topics that were created. This is possible when you selected to have only 1-gram words as representation. Perhaps you want to try out a different n-gram range or you have a custom vectorizer that you want to use."
},
{
"code": null,
"e": 7325,
"s": 7167,
"text": "To update the topic representation after training, we can use the function update_topics to update the topic representation with new parameters for c-TF-IDF:"
},
{
"code": null,
"e": 7375,
"s": 7325,
"text": "We can also use a custom CountVectorizer instead:"
},
{
"code": null,
"e": 7574,
"s": 7375,
"text": "Why limit ourselves to publicly available pre-trained embeddings? You might have very specific data for which you have created an embedding model that you could not have found pre-trained available."
},
{
"code": null,
"e": 7755,
"s": 7574,
"text": "To use any embedding model that you trained yourself, you will only have to embed your documents with that model. You can then pass in the embeddings and BERTopic will do the rest:"
},
{
"code": null,
"e": 7919,
"s": 7755,
"text": "As you can see above, we used a SentenceTransformer model to create the embedding. You could also have used 🤗 transformers, Doc2Vec, or any other embedding method."
},
{
"code": null,
"e": 8110,
"s": 7919,
"text": "While we are at it, why limit ourselves to transformer models? There is a reason why statistical models, such as TF-IDF, are still around. They work great out-of-the-box without much tuning!"
},
{
"code": null,
"e": 8292,
"s": 8110,
"text": "As you might have guessed, it is also possible to use TF-IDF on the documents and use them as input for BERTopic. We simply create a TF-IDF matrix and pass it through fit_transform:"
},
{
"code": null,
"e": 8621,
"s": 8292,
"text": "Here, you will probably notice that creating the embeddings is quite fast whereas fit_transform is quite slow. This is to be expected as reducing the dimensionality of a large sparse matrix takes some time. The inverse of using transformer embeddings is true: creating the embeddings is slow whereas fit_transform is quite fast."
},
{
"code": null,
"e": 8756,
"s": 8621,
"text": "If you are, like me, passionate about AI, Data Science, or Psychology, please feel free to add me on LinkedIn or follow me on Twitter."
}
] |
MySQL - Multiplication Operator (*)
|
This operator is used to multiply two numbers in MySQL.
Following is an example of the "*" operator −
mysql> SELECT 4156456*56445;
+---------------+
| 4156456*56445 |
+---------------+
| 234611158920 |
+---------------+
1 row in set (0.00 sec)
Let us see another example −
mysql> SELECT 547.5478*657.3547*5475;
+------------------------+
| 547.5478*657.3547*5475 |
+------------------------+
| 1970633830.93051350 |
+------------------------+
1 row in set (0.00 sec)
You can also have negative values as operands for this operator −
mysql> SELECT 4445*-533;
+-----------+
| 4445*-533 |
+-----------+
| -2369185 |
+-----------+
1 row in set (0.00 sec)
Assume we have created a table in MySQL using the following quires −
CREATE TABLE student (Name VARCHAR(100), Math INT, English INT, Science INT, History INT);
INSERT INTO student values('Raman', 95, 89, 85, 81);
INSERT INTO student values('Rahul' , 90, 87, 86, 81);
INSERT INTO student values('Mohit', 90, 85, 86, 81);
Following query calculates displays the percentage of each student −
mysql> SELECT name, (Math + English + Science + History)/400*100 as Percentage FROM student;
+-------+------------+
| name | Percentage |
+-------+------------+
| Raman | 87.5000 |
| Rahul | 86.0000 |
| Mohit | 85.5000 |
+-------+------------+
3 rows in set (0.00 sec)
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": 2389,
"s": 2333,
"text": "This operator is used to multiply two numbers in MySQL."
},
{
"code": null,
"e": 2435,
"s": 2389,
"text": "Following is an example of the \"*\" operator −"
},
{
"code": null,
"e": 2578,
"s": 2435,
"text": "mysql> SELECT 4156456*56445;\n+---------------+\n| 4156456*56445 |\n+---------------+\n| 234611158920 |\n+---------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2607,
"s": 2578,
"text": "Let us see another example −"
},
{
"code": null,
"e": 2804,
"s": 2607,
"text": "mysql> SELECT 547.5478*657.3547*5475;\n+------------------------+\n| 547.5478*657.3547*5475 |\n+------------------------+\n| 1970633830.93051350 |\n+------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2870,
"s": 2804,
"text": "You can also have negative values as operands for this operator −"
},
{
"code": null,
"e": 2989,
"s": 2870,
"text": "mysql> SELECT 4445*-533;\n+-----------+\n| 4445*-533 |\n+-----------+\n| -2369185 |\n+-----------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 3058,
"s": 2989,
"text": "Assume we have created a table in MySQL using the following quires −"
},
{
"code": null,
"e": 3309,
"s": 3058,
"text": "CREATE TABLE student (Name VARCHAR(100), Math INT, English INT, Science INT, History INT);\nINSERT INTO student values('Raman', 95, 89, 85, 81);\nINSERT INTO student values('Rahul' , 90, 87, 86, 81);\nINSERT INTO student values('Mohit', 90, 85, 86, 81);"
},
{
"code": null,
"e": 3378,
"s": 3309,
"text": "Following query calculates displays the percentage of each student −"
},
{
"code": null,
"e": 3657,
"s": 3378,
"text": "mysql> SELECT name, (Math + English + Science + History)/400*100 as Percentage FROM student;\n+-------+------------+\n| name | Percentage |\n+-------+------------+\n| Raman | 87.5000 |\n| Rahul | 86.0000 |\n| Mohit | 85.5000 |\n+-------+------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3690,
"s": 3657,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3718,
"s": 3690,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3753,
"s": 3718,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3770,
"s": 3753,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3804,
"s": 3770,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3839,
"s": 3804,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3873,
"s": 3839,
"text": "\n 60 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3901,
"s": 3873,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 3934,
"s": 3901,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3954,
"s": 3934,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 3987,
"s": 3954,
"text": "\n 25 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4005,
"s": 3987,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 4012,
"s": 4005,
"text": " Print"
},
{
"code": null,
"e": 4023,
"s": 4012,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.