title stringlengths 3 221 | text stringlengths 17 477k | parsed listlengths 0 3.17k |
|---|---|---|
C# Program to Check a Specified Type is a Primitive Data Type or Not - GeeksforGeeks | 16 Nov, 2021
In C#, data types are used to specify the type of data that a variable can hold. There are two types of data types available in C# that is, primitive and non-primitive data types. Primitive data types are predefined data types such as Byte, SByte, Boolean, Int16, UInt16, Int32, UInt32, Char, Double, Int64, UInt64, Single, etc. Whereas non-primitive data types are user-defined data types such as enum, class, etc. In this article, we will learn how to check a specified type is a primitive data type or not. So, to do this task we use the IsPrimitive property of the Type class. This property is used to check whether the type of the specified data is one of the primitive types or not. It returns true if the given data type is primitive otherwise it will return false.
Syntax:
public bool IsPrimitive{ get; }
Example:
C#
// C# program to check a specified type // is a primitive data type or notusing System;using System.Reflection; class GFG{ static void Main(){ // Check the int is an primitiva or not if (typeof(int).IsPrimitive == true) { Console.WriteLine("Primitive data type"); } else { Console.WriteLine("Not a primitive data type"); } // Check the float is an primitiva or not if (typeof(float).IsPrimitive == true) { Console.WriteLine("Primitive data type"); } else { Console.WriteLine("Not a primitive data type"); } // Check the int is an primitiva or not if (typeof(double).IsPrimitive == true) { Console.WriteLine("Primitive data type"); } else { Console.WriteLine("Not a primitive data type"); }}}
Output:
Primitive data type
Primitive data type
Primitive data type
CSharp-data-types
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Switch Statement in C#
Convert String to Character Array in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Socket Programming in C#
Program to find absolute value of a given number | [
{
"code": null,
"e": 24400,
"s": 24372,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 25173,
"s": 24400,
"text": "In C#, data types are used to specify the type of data that a variable can hold. There are two types of data types available in C# that is, primitive and non-primi... |
__subclasscheck__ and __subclasshook__ in Python - GeeksforGeeks | 30 Jan, 2020
Class is a collection of data (variables and methods). It bundles data and functionality together. It provides all standard features of object-oriented programming. Basically it is a blueprint for creating objects. Creating a new class creates a new type of object, allowing new instances of that type to be made.
Example:
# class 'A' definedclass A(object): # Calling Constructor def __init__(self, a): self.a = a print("The value of a:", self.a) # Driver's codec = A(7)
Output:
The value of a: 7
__subclasscheck__ is one of the methods to customize the result of issubclass() built-in function. It is a method to check whether a class is a subclass or not and returns True if the class is considered as a subclass(direct or indirect) of another class, otherwise, returns False. It cannot be defined as a class method in the actual/real class. It is implemented in the metaclass, as it is not for ordinary classes. Consider the below example for better understanding.
Example: Consider a situation where you want to check if a certain value is present as an attribute inside a class using the issubclass() method.
# Python program to demonstrate# subclasscheck class A(type): # __subclasscheck__() defined def __subclasscheck__(cls, sub): # Getting the L attribute of # subclass attr = getattr(cls, 'L', []) # Checking if the subclass # is present in the L attribute # of subclass or not if sub in attr: return True return False class B(metaclass = A): # L Attribute L = [1, 2, 3, 4, 5] class C(metaclass = A): # L Attribute L = ["Geeks", "For"] # Driver's codeprint(issubclass(1, B))print(issubclass("Geeks", B))print(issubclass("Geeks", C))
Output:
True
False
True
Abstract class can override __subclasshook__() method to customize issubclass(). It returns True when a class is found to be subclass of a ABC class, it returns False if it is not and returns NotImplemented if the subclass check is continued with the usual mechanism. This method is defined in the ABC class with some conditions. Classes that follow those conditions are considered to be a subclass.
Note: It must be defined as a class method.
Example:
# Python program to demonstrate# subclasshook from abc import ABCMeta class A(metaclass = ABCMeta): @classmethod def __subclasshook__(cls, C): if cls is A: # condition to check if the # function anyfun() is present # in any sub class or not if any("__anyfun__" in Q.__dict__ for Q in C.__mro__): return True return False class P(object): pass class Q(object): def __anyfun__(self): return 0 # Driver's codeprint(issubclass(Q, A) ) print(issubclass(P, A) )
Output:
True
False
Python-OOP
python-oop-concepts
Technical Scripter 2019
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list | [
{
"code": null,
"e": 25673,
"s": 25645,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 25987,
"s": 25673,
"text": "Class is a collection of data (variables and methods). It bundles data and functionality together. It provides all standard features of object-oriented programming... |
Espresso Testing Framework - Quick Guide | In general, mobile automation testing is a difficult and challenging task. Android availability for different devices and platforms makes it things tedious for mobile automation testing. To make it easier, Google took on the challenge and developed Espresso framework. It provides a very simple, consistent and flexible API to automate and test the user interfaces in an android application. Espresso tests can be written in both Java and Kotlin, a modern programming language to develop android application.
The Espresso API is simple and easy to learn. You can easily perform Android UI tests without the complexity of multi-threaded testing. Google Drive, Maps and some other applications are currently using Espresso.
Some the salient features supported by Espresso are as follow,
Very simple API and so, easy to learn.
Very simple API and so, easy to learn.
Highly scalable and flexible.
Highly scalable and flexible.
Provides separate module to test Android WebView component.
Provides separate module to test Android WebView component.
Provides separate module to validate as well as mock Android Intents.
Provides separate module to validate as well as mock Android Intents.
Provides automatic synchronization between your application and tests.
Provides automatic synchronization between your application and tests.
Let us now what the benefits of Espresso are.
Backward compatibility
Backward compatibility
Easy to setup.
Easy to setup.
Highly stable test cycle.
Highly stable test cycle.
Supports testing activities outside application as well.
Supports testing activities outside application as well.
Supports JUnit4
Supports JUnit4
UI automation suitable for writing black box tests.
UI automation suitable for writing black box tests.
In this chapter, let us understand how to install espresso framework, configure it to write espresso tests and execute it in our android application.
Espresso is a user interface-testing framework for testing android application developed in Java / Kotlin language using Android SDK. Therefore, espresso’s only requirement is to develop the application using Android SDK in either Java or Kotlin and it is advised to have the latest Android Studio.
The list of items to be configured properly before we start working in espresso framework is as follows −
Install latest Java JDK and configure JAVA_HOME environment variable.
Install latest Java JDK and configure JAVA_HOME environment variable.
Install latest Android Studio (version 3.2. or higher).
Install latest Android Studio (version 3.2. or higher).
Install latest Android SDK using SDK Manager and configure ANDROID_HOME environment variable.
Install latest Android SDK using SDK Manager and configure ANDROID_HOME environment variable.
Install latest Gradle Build Tool and configure GRADLE_HOME environment variable.
Install latest Gradle Build Tool and configure GRADLE_HOME environment variable.
Initially, espresso testing framework is provided as part of the Android Support library. Later, the Android team provides a new Android library, AndroidX and moves the latest espresso testing framework development into the library. Latest development (Android 9.0, API level 28 or higher) of espresso testing framework will be done in AndroidX library.
Including espresso testing framework in a project is as simple as setting the espresso testing framework as a dependency in the application gradle file, app/build.gradle. The complete configuration is as follow,
Using Android support library,
android {
defaultConfig {
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espressocore:3.0.2'
}
Using AndroidX library,
android {
defaultConfig {
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
}
dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.androidx.test:runner:1.0.2'
androidTestImplementation 'com.androidx.espresso:espresso-core:3.0.2'
}
testInstrumentationRunner in the android/defaultConfig sets AndroidJUnitRunner class to run the instrumentation tests. The first line in the dependencies includes the JUnit testing framework, the second line in the dependencies includes the test runner library to run the test cases and finally the third line in the dependencies includes the espresso testing framework.
By default, Android studio sets the espresso testing framework (Android support library) as a dependency while creating the android project and gradle will download the necessary library from the Maven repository. Let us create a simple Hello world android application and check whether the espresso testing framework is configured properly.
The steps to create a new Android application are described below −
Start Android Studio.
Start Android Studio.
Select File → New → New Project.
Select File → New → New Project.
Enter Application Name (HelloWorldApp) and Company domain (espressosamples.tutorialspoint.com) and then click Next.
Enter Application Name (HelloWorldApp) and Company domain (espressosamples.tutorialspoint.com) and then click Next.
To create Android Project,
Select minimum API as API 15: Android 4.0.3 (IceCreamSandwich) and then click Next.
Select minimum API as API 15: Android 4.0.3 (IceCreamSandwich) and then click Next.
To target Android Devices,
Select Empty Activity and then click Next.
Select Empty Activity and then click Next.
To add an activity to Mobile,
Enter name for main activity and then click Finish.
Enter name for main activity and then click Finish.
To configure Activity,
Once, a new project is created, open the app/build.gradle file and check its content. The content of the file is specified below,
Once, a new project is created, open the app/build.gradle file and check its content. The content of the file is specified below,
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.tutorialspoint.espressosamples.helloworldapp"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espressocore:3.0.2'
}
The last line specifies the espresso testing framework dependency. By default, Android support library is configured. We can reconfigure the application to use AndroidX library by clicking Refactor → Migrate to AndroidX in the menu.
To migrate to Androidx,
Now, the app/build.gradle changes as specified below,
Now, the app/build.gradle changes as specified below,
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.tutorialspoint.espressosamples.helloworldapp"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
Now, the last line includes espresso testing framework from AndroidX library.
During testing, it is recommended to turn off the animation on the Android device, which is used for testing. This will reduce the confusions while checking ideling resources.
Let us see how to disable animation on Android devices – (Settings → Developer options),
Window animation scale
Window animation scale
Transition animation scale
Transition animation scale
Animator duration scale
Animator duration scale
If Developer options menu is not available in the Settings screen, then click Build Number available inside the About Phone option several times. This enables the Developer Option menu.
In this chapter, let us see how to run tests using Android studio.
Every android application has two type of tests −
Functional / Unit tests
Functional / Unit tests
Instrumentation tests
Instrumentation tests
Functional test does not need the actual android application to be installed and launched in the device or emulator and test the functionality. It can be launched in the console itself without invoking the actual application. However, instrumentation tests need the actual application to be launched to test the functionality like user interface and user interaction. By default, Unit tests are written in src/test/java/ folder and Instrumentation tests are written in src/androidTest/java/ folder. Android studio provides Run context menu for the test classes to run the test written in the selected test classes. By default, an Android application has two classes − ExampleUnitTest in src/test folder and ExampleInstrumentedTest in src/androidTest folder.
To run the default unit test, select ExampleUnitTest in the Android studio, right-click on it and then click the Run 'ExampleUnitTest' as shown below,
This will run the unit test and show the result in the console as in the following screenshot −
To run the default instrumentation test, select ExampleInstrumentationTest in the android studio, right-click it and then click the Run 'ExampleInstrumentationTest' as shown below,
This will run the unit test by launching the application in either device or emulator and show the result in the console as in the following screenshot −
The instrumentation test ran successful.
In this chapter, let us understand the basics of JUnit, the popular unit-testing framework developed by the Java community upon which the espresso testing framework is build.
JUnit is the de facto standard for unit testing a Java application. Even though, it is popular for unit testing, it has complete support and provision for instrumentation testing as well. Espresso testing library extends the necessary JUnit classes to support the Android based instrumentation testing.
Let us create a Java class, Computation (Computation.java) and write simple mathematical operation, Summation and Multiplication. Then, we will write test cases using JUnit and check it by running the test cases.
Start Android Studio.
Start Android Studio.
Open HelloWorldApp created in the previous chapter.
Open HelloWorldApp created in the previous chapter.
Create a file, Computation.java in app/src/main/java/com/tutorialspoint/espressosamples/helloworldapp/ and write two functions – Sum and Multiply as specified below,
Create a file, Computation.java in app/src/main/java/com/tutorialspoint/espressosamples/helloworldapp/ and write two functions – Sum and Multiply as specified below,
package com.tutorialspoint.espressosamples.helloworldapp;
public class Computation {
public Computation() {}
public int Sum(int a, int b) {
return a + b;
}
public int Multiply(int a, int b) {
return a * b;
}
}
Create a file, ComputationUnitTest.java in app/src/test/java/com/tutorialspoint/espressosamples/helloworldapp and write unit test cases to test Sum and Multiply functionality as specified below
Create a file, ComputationUnitTest.java in app/src/test/java/com/tutorialspoint/espressosamples/helloworldapp and write unit test cases to test Sum and Multiply functionality as specified below
package com.tutorialspoint.espressosamples.helloworldapp;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ComputationUnitTest {
@Test
public void sum_isCorrect() {
Computation computation = new Computation();
assertEquals(4, computation.Sum(2,2));
}
@Test
public void multiply_isCorrect() {
Computation computation = new Computation();
assertEquals(4, computation.Multiply(2,2));
}
}
Here, we have used two new terms – @Test and assertEquals. In general, JUnit uses Java annotation to identify the test cases in a class and information on how to execute the test cases. @Test is one such Java annotation, which specifies that the particular function is a junit test case. assertEquals is a function to assert that the first argument (expected value) and the second argument (computed value) are equal and same. JUnit provides a number of assertion methods for different test scenarios.
Now, run the ComputationUnitTest in the Android studio by right-clicking the class and invoking the Run 'ComputationUnitTest' option as explained in the previous chapter. This will run the unit test cases and report success.
Now, run the ComputationUnitTest in the Android studio by right-clicking the class and invoking the Run 'ComputationUnitTest' option as explained in the previous chapter. This will run the unit test cases and report success.
Result of computation unit test is as shown below −
The JUnit framework uses annotation extensively. Some of the important annotations are as follows −
@Test
@Test
@Before
@Before
@After
@After
@BeforeClass
@BeforeClass
@AfterClass
@AfterClass
@Rule
@Rule
@Test is the very important annotation in the JUnit framework. @Test is used to differentiate a normal method from the test case method. Once a method is decorated with @Test annotation, then that particular method is considered as a Test case and will be run by JUnit Runner. JUnit Runner is a special class, which is used to find and run the JUnit test cases available inside the java classes. For now, we are using Android Studio’s build in option to run the unit tests (which in turn run the JUnit Runner). A sample code is as follows,
package com.tutorialspoint.espressosamples.helloworldapp;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ComputationUnitTest {
@Test
public void multiply_isCorrect() {
Computation computation = new Computation();
assertEquals(4, computation.Multiply(2,2));
}
}
@Before annotation is used to refer a method, which needs to be invoked before running any test method available in a particular test class. For example in our sample, the Computation object can be created in a separate method and annotated with @Before so that it will run before both sum_isCorrect and multiply_isCorrect test case. The complete code is as follows,
package com.tutorialspoint.espressosamples.helloworldapp;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ComputationUnitTest {
Computation computation = null;
@Before
public void CreateComputationObject() {
this.computation = new Computation();
}
@Test
public void sum_isCorrect() {
assertEquals(4, this.computation.Sum(2,2));
}
@Test
public void multiply_isCorrect() {
assertEquals(4, this.computation.Multiply(2,2));
}
}
@After is similar to @Before, but the method annotated with @After will be called or executed after each test case is run. The sample code is as follows,
package com.tutorialspoint.espressosamples.helloworldapp;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ComputationUnitTest {
Computation computation = null;
@Before
public void CreateComputationObject() {
this.computation = new Computation();
}
@After
public void DestroyComputationObject() {
this.computation = null;
}
@Test
public void sum_isCorrect() {
assertEquals(4, this.computation.Sum(2,2));
}
@Test
public void multiply_isCorrect() {
assertEquals(4, this.computation.Multiply(2,2));
}
}
@BeforeClass is similar to @Before, but the method annotated with @BeforeClass will be called or executed only once before running all test cases in a particular class. It is useful to create resource intensive object like database connection object. This will reduce the time to execute a collection of test cases. This method needs to be static in order to work properly. In our sample, we can create the computation object once before running all test cases as specified below,
package com.tutorialspoint.espressosamples.helloworldapp;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ComputationUnitTest {
private static Computation computation = null;
@BeforeClass
public static void CreateComputationObject() {
computation = new Computation();
}
@Test
public void sum_isCorrect() {
assertEquals(4, computation.Sum(2,2));
}
@Test
public void multiply_isCorrect() {
assertEquals(4, computation.Multiply(2,2));
}
}
@AfterClass is similar to @BeforeClass, but the method annotated with @AfterClass will be called or executed only once after all test cases in a particular class are run. This method also needs to be static to work properly. The sample code is as follows −
package com.tutorialspoint.espressosamples.helloworldapp;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ComputationUnitTest {
private static Computation computation = null;
@BeforeClass
public static void CreateComputationObject() {
computation = new Computation();
}
@AfterClass
public static void DestroyComputationObject() {
computation = null;
}
@Test
public void sum_isCorrect() {
assertEquals(4, computation.Sum(2,2));
}
@Test
public void multiply_isCorrect() {
assertEquals(4, computation.Multiply(2,2));
}
}
@Rule annotation is one of the highlights of JUnit. It is used to add behavior to the test cases. We can only annotate the fields of type TestRule. It actually provides feature set provided by @Before and @After annotation but in an efficient and reusable way. For example, we may need a temporary folder to store some data during a test case. Normally, we need to create a temporary folder before running the test case (using either @Before or @BeforeClass annotation) and destroy it after the test case is run (using either @After or @AfterClass annotation). Instead, we can use TemporaryFolder (of type TestRule) class provided by JUnit framework to create a temporary folder for all our test cases and the temporary folder will be deleted as and when the test case is run. We need to create a new variable of type TemporaryFolder and need to annotate with @Rule as specified below,
package com.tutorialspoint.espressosamples.helloworldapp;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals;
public class ComputationUnitTest {
private static Computation computation = null;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void file_isCreated() throws IOException {
folder.newFolder("MyTestFolder");
File testFile = folder.newFile("MyTestFile.txt");
assertTrue(testFile.exists());
}
@BeforeClass
public static void CreateComputationObject() {
computation = new Computation();
}
@AfterClass
public static void DestroyComputationObject() {
computation = null;
}
@Test
public void sum_isCorrect() {
assertEquals(4, computation.Sum(2,2));
}
@Test
public void multiply_isCorrect() {
assertEquals(4, computation.Multiply(2,2));
}
}
In JUnit, the methods annotated with different annotation will be executed in specific order as shown below,
@BeforeClass
@BeforeClass
@Rule
@Rule
@Before
@Before
@Test
@Test
@After
@After
@AfterClass
@AfterClass
Assertion is a way of checking whether the expected value of the test case matches the actual value of the test case result. JUnit provides assertion for different scenario; a few important assertions are listed below −
fail() − To explicitly make a test case fail.
fail() − To explicitly make a test case fail.
assertTrue(boolean test_condition) − Checks that the test_condition is true
assertTrue(boolean test_condition) − Checks that the test_condition is true
assertFalse(boolean test_condition) − Checks that the test_condition is false
assertFalse(boolean test_condition) − Checks that the test_condition is false
assertEquals(expected, actual) − Checks that both values are equal
assertEquals(expected, actual) − Checks that both values are equal
assertNull(object) − Checks that the object is null
assertNull(object) − Checks that the object is null
assertNotNull(object) − Checks that the object is not null
assertNotNull(object) − Checks that the object is not null
assertSame(expected, actual) − Checks that both refers same object.
assertSame(expected, actual) − Checks that both refers same object.
assertNotSame(expected, actual) − Checks that both refers different object.
assertNotSame(expected, actual) − Checks that both refers different object.
In this chapter, let us learn the terms of espresso testing framework, how to write a simple espresso test case and the complete workflow or architecture of the espresso testing framework.
Espresso provides a large number of classes to test user interface and the user interaction of an android application. They can be grouped into five categories as specified below −
Android testing framework provides a runner, AndroidJUnitRunner to run the espresso test cases written in JUnit3 and JUnit4 style test cases. It is specific to android application and it transparently handles loading the espresso test cases and the application under test both in actual device or emulator, execute the test cases and report the result of the test cases. To use AndroidJUnitRunner in the test case, we need to annotate the test class using @RunWith annotation and then pass the AndroidJUnitRunner argument as specified below −
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
}
Android testing framework provides a rule, ActivityTestRule to launch an android activity before executing the test cases. It launches the activity before each method annotated with @Test` and @Before. It will terminate the activity after method annotated with @After. A sample code is as follows,
@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
Here, MainActivity is the activity to be launched before running a test case and destroyed after the particular test case is run.
Espresso provides large number of view matcher classes (in androidx.test.espresso.matcher.ViewMatchers package) to match and find UI elements / views in an android activity screen’s view hierarchy. Espresso’s method onView takes a single argument of type Matcher (View matchers), finds the corresponding UI view and returns corresponding ViewInteraction object. ViewInteraction object returned by onView method can be further used to invoke actions like click on the matched view or can be used to assert the matched view. A sample code to find the view with text, “Hello World!” is as follows,
ViewInteraction viewInteraction = Espresso.onView(withText("Hello World!"));
Here, withText is a matcher, which can be used to match UI view having text “Hello World!”
Espresso provides large number of view action classes (in androidx.test.espresso.action.ViewActions) to invoke the different action on the selected / matched view. Once onView matches and returns ViewInteraction object, any action can be invoked by calling “perform” method of ViewInteraction object and pass it with proper view actions. A sample code to click the matched view is as follows,
ViewInteraction viewInteraction = Espresso.onView(withText("Hello World!"));
viewInteraction.perform(click());
Here, the click action of the matched view will be invoked.
Similar to view matchers and view actions, Espresso provides a large number of view assertion (in androidx.test.espresso.assertion.ViewAssertions package) to assert the matched view is what we expected. Once onView matches and returns the ViewInteraction object, any assert can be checked using check method of ViewInteraction by passing it with proper view assertion. A sample code to assert that the matched view is as follows,
ViewInteraction viewInteraction = Espresso.onView(withText("Hello World!"));
viewInteraction.check(matches(withId(R.id.text_view)));
Here, matches accept the view matcher and return view assertion, which can be checked by check method of ViewInteraction.
Let us understand how the espresso testing framework works and how it provides options to do any kind of user interaction in a simple and flexible way. Workflow of an espresso test case is as described below,
As we learned earlier, Android JUnit runner, AndroidJUnit4 will run the android test cases. The espresso test cases need to be marked with @RunWith(AndroidJUnut.class). First, AndroidJUnit4 will prepare the environment to run the test cases. It starts either the connected android device or emulator, installs the application and makes sure the application to be tested is in ready state. It will run the test cases and report the results.
As we learned earlier, Android JUnit runner, AndroidJUnit4 will run the android test cases. The espresso test cases need to be marked with @RunWith(AndroidJUnut.class). First, AndroidJUnit4 will prepare the environment to run the test cases. It starts either the connected android device or emulator, installs the application and makes sure the application to be tested is in ready state. It will run the test cases and report the results.
Espresso needs at least a single JUnit rule of type ActivityTestRule to specify the activity. Android JUnit runner will start the activity to be launched using ActivityTestRule.
Espresso needs at least a single JUnit rule of type ActivityTestRule to specify the activity. Android JUnit runner will start the activity to be launched using ActivityTestRule.
Every test case needs a minimum of single onView or onDate (used to find data based views like AdapterView) method invocation to match and find the desired view. onView or onData returns ViewInteraction object.
Every test case needs a minimum of single onView or onDate (used to find data based views like AdapterView) method invocation to match and find the desired view. onView or onData returns ViewInteraction object.
Once ViewInteraction object is returned, we can either invoke an action of the selected view or check the view for our expected view using assertion.
Once ViewInteraction object is returned, we can either invoke an action of the selected view or check the view for our expected view using assertion.
Action can be invoked using perform method of ViewInteraction object by passing any one of the available view actions.
Action can be invoked using perform method of ViewInteraction object by passing any one of the available view actions.
Assertion can be invoked using check method of ViewInteraction object by passing any one of the available view assertions.
Assertion can be invoked using check method of ViewInteraction object by passing any one of the available view assertions.
The diagram representation of the Workflow is as follows,
Let us write a simple test case to find the text view having “Hello World!” text in our “HelloWorldApp” application and then assert it using view assertion. The complete code is as follows,
package com.tutorialspoint.espressosamples.helloworldapp;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.matcher.ViewMatchers.withText;;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
@Test
public void view_isCorrect() {
onView(withText("Hello World!")).check(matches(isDisplayed()));
}
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.tutorialspoint.espressosamples.helloworldapp", appContext.getPackageName());
}
}
Here, we have used withText view matchers to find the text view having “Hello World!” text and matches view assertion to assert that the text view is properly displayed. Once the test case is invoked in Android Studio, it will run the test case and report the success message as below.
Espresso framework provides many view matchers. The purpose of the matcher is to match a view using different attributes of the view like Id, Text, and availability of child view. Each matcher matches a particular attributes of the view and applies to particular type of view. For example, withId matcher matches the Id property of the view and applies to all view, whereas withText matcher matches the Text property of the view and applies to TextView only.
In this chapter, let us learn the different matchers provided by espresso testing framework as well as learn the Hamcrest library upon which the espresso matchers are built.
Hamcrest library is an important library in the scope of espresso testing framework. Hamcrest is itself a framework for writing matcher objects. Espresso framework extensively uses the Hamcrest library and extend it whenever necessary to provide simple and extendable matchers.
Hamcrest provides a simple function assertThat and a collection of matchers to assert any objects. assertThat has three arguments and they are as shown below −
String (description of the test, optional)
String (description of the test, optional)
Object (actual)
Object (actual)
Matcher (expected)
Matcher (expected)
Let us write a simple example to test whether a list object has expected value.
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
@Test
public void list_hasValue() {
ArrayList<String> list = new ArrayList<String>();
list.add("John");
assertThat("Is list has John?", list, hasItem("John"));
}
Here, hasItem returns a matcher, which checks whether the actual list has specified value as one of the item.
Hamcrest has a lot of built-in matchers and also options to create new matchers. Some of the important built-in matchers useful in espresso testing framework are as follows −
Logical based matchers
allOf − accept any number of matchers and matches only if all matchers are succeeded.
allOf − accept any number of matchers and matches only if all matchers are succeeded.
anyOf − accept any number of matchers and matches if any one matcher succeeded.
anyOf − accept any number of matchers and matches if any one matcher succeeded.
not − accept one matcher and matches only if the matcher failed and vice versa.
not − accept one matcher and matches only if the matcher failed and vice versa.
equalToIgnoringCase − used to test whether the actual input equals the expected string ignoring case.
equalToIgnoringCase − used to test whether the actual input equals the expected string ignoring case.
equalToIgnoringWhiteSpace − used to test whether the actual input equals the specified string ignoring case and white spaces.
equalToIgnoringWhiteSpace − used to test whether the actual input equals the specified string ignoring case and white spaces.
containsString − used to test whether the actual input contains specified string.
containsString − used to test whether the actual input contains specified string.
endsWith − used to test whether the actual input starts with specified string.
endsWith − used to test whether the actual input starts with specified string.
startsWith − used to test whether actual the input ends with specified string.
startsWith − used to test whether actual the input ends with specified string.
closeTo − used to test whether the actual input is close to the expected number.
closeTo − used to test whether the actual input is close to the expected number.
greaterThan − used to test whether the actual input is greater than the expected number.
greaterThan − used to test whether the actual input is greater than the expected number.
greaterThanOrEqualTo − used to test whether the actual input is greater than or equal to the expected number.
greaterThanOrEqualTo − used to test whether the actual input is greater than or equal to the expected number.
lessThan − used to test whether the actual input is less than the expected number.
lessThan − used to test whether the actual input is less than the expected number.
lessThanOrEqualTo − used to test whether the actual input is less than or equal to the expected number.
lessThanOrEqualTo − used to test whether the actual input is less than or equal to the expected number.
equalTo − used to test whether the actual input is equals to the expected object
equalTo − used to test whether the actual input is equals to the expected object
hasToString − used to test whether the actual input has toString method.
hasToString − used to test whether the actual input has toString method.
instanceOf − used to test whether the actual input is the instance of expected class.
instanceOf − used to test whether the actual input is the instance of expected class.
isCompatibleType − used to test whether the actual input is compatible with the expected type.
isCompatibleType − used to test whether the actual input is compatible with the expected type.
notNullValue − used to test whether the actual input is not null.
notNullValue − used to test whether the actual input is not null.
sameInstance − used to test whether the actual input and expected are of same instance.
sameInstance − used to test whether the actual input and expected are of same instance.
hasProperty − used to test whether the actual input has the expected property
hasProperty − used to test whether the actual input has the expected property
Espresso provides the onView() method to match and find the views. It accepts view matchers and returns ViewInteraction object to interact with the matched view. The frequently used list of view matchers are described below −
withId() accepts an argument of type int and the argument refers the id of the view. It returns a matcher, which matches the view using the id of the view. The sample code is as follows,
onView(withId(R.id.testView))
withText() accepts an argument of type string and the argument refers the value of the view’s text property. It returns a matcher, which matches the view using the text value of the view. It applies to TextView only. The sample code is as follows,
onView(withText("Hello World!"))
withContentDescription() accepts an argument of type string and the argument refers the value of the view’s content description property. It returns a matcher, which matches the view using the description of the view. The sample code is as follows,
onView(withContentDescription("blah"))
We can also pass the resource id of the text value instead of the text itself.
onView(withContentDescription(R.id.res_id_blah))
hasContentDescription() has no argument. It returns a matcher, which matches the view that has any content description. The sample code is as follows,
onView(allOf(withId(R.id.my_view_id), hasContentDescription()))
withTagKey() accepts an argument of type string and the argument refers the view’s tag key. It returns a matcher, which matches the view using its tag key. The sample code is as follows,
onView(withTagKey("blah"))
We can also pass the resource id of the tag name instead of the tag name itself.
onView(withTagKey(R.id.res_id_blah))
withTagValue() accepts an argument of type Matcher <Object> and the argument refers the view’s tag value. It returns a matcher, which matches the view using its tag value. The sample code is as follows,
onView(withTagValue(is((Object) "blah")))
Here, is is Hamcrest matcher.
withClassName() accepts an argument of type Matcher<String> and the argument refers the view’s class name value. It returns a matcher, which matches the view using its class name. The sample code is as follows,
onView(withClassName(endsWith("EditText")))
Here, endsWith is Hamcrest matcher and return Matcher<String>
withHint() accepts an argument of type Matcher<String> and the argument refers the view’s hint value. It returns a matcher, which matches the view using the hint of the view. The sample code is as follows,
onView(withClassName(endsWith("Enter name")))
withInputType() accepts an argument of type int and the argument refers the input type of the view. It returns a matcher, which matches the view using its input type. The sample code is as follows,
onView(withInputType(TYPE_CLASS_DATETIME))
Here, TYPE_CLASS_DATETIME refers edit view supporting dates and times.
withResourceName() accepts an argument of type Matcher<String> and the argument refers the view’s class name value. It returns a matcher, which matches the view using resource name of the view. The sample code is as follows,
onView(withResourceName(endsWith("res_name")))
It accepts string argument as well. The sample code is as follows,
onView(withResourceName("my_res_name"))
withAlpha() accepts an argument of type float and the argument refers the alpha value of the view. It returns a matcher, which matches the view using the alpha value of the view. The sample code is as follows,
onView(withAlpha(0.8))
withEffectiveVisibility() accepts an argument of type ViewMatchers.Visibility and the argument refers the effective visibility of the view. It returns a matcher, which matches the view using the visibility of the view. The sample code is as follows,
onView(withEffectiveVisibility(withEffectiveVisibility.INVISIBLE))
withSpinnerText() accepts an argument of type Matcher<String> and the argument refers the Spinner’s current selected view’s value. It returns a matcher, which matches the the spinner based on it’s selected item’s toString value. The sample code is as follows,
onView(withSpinnerText(endsWith("USA")))
It accepts string argument or resource id of the string as well. The sample code is as follows,
onView(withResourceName("USA"))
onView(withResourceName(R.string.res_usa))
withSubString() is similar to withText() except it helps to test substring of the text value of the view.
onView(withSubString("Hello"))
hasLinks() has no arguments and it returns a matcher, which matches the view having links. It applies to TextView only. The sample code is as follows,
onView(allOf(withSubString("Hello"), hasLinks()))
Here, allOf is a Hamcrest matcher. allOf returns a matcher, which matches all the passed in matchers and here, it is used to match a view as well as check whether the view has links in its text value.
hasTextColor() accepts a single argument of type int and the argument refers the resource id of the color. It returns a matcher, which matches the TextView based on its color. It applies to TextView only. The sample code is as follows,
onView(allOf(withSubString("Hello"), hasTextColor(R.color.Red)))
hasEllipsizedText() has no argument. It returns a matcher, which matches the TextView that has long text and either ellipsized (first.. ten.. last) or cut off (first...). The sample code is as follows,
onView(allOf(withId(R.id.my_text_view_id), hasEllipsizedText()))
hasMultilineText() has no argument. It returns a matcher, which matches the TextView that has any multi line text. The sample code is as follows,
onView(allOf(withId(R.id.my_test_view_id), hasMultilineText()))
hasBackground() accepts a single argument of type int and the argument refers the resource id of the background resource. It returns a matcher, which matches the view based on its background resources. The sample code is as follows,
onView(allOf(withId("image"), hasBackground(R.drawable.your_drawable)))
hasErrorText() accepts an argument of type Matcher<String> and the argument refers the view’s (EditText) error string value. It returns a matcher, which matches the view using error string of the view. This applies to EditText only. The sample code is as follows,
onView(allOf(withId(R.id.editText_name), hasErrorText(is("name is required"))))
It accepts string argument as well. The sample code is as follows,
onView(allOf(withId(R.id.editText_name), hasErrorText("name is required")))
hasImeAction() accepts an argument of type Matcher<Integer> and the argument refers the view’s (EditText) supported input methods. It returns a matcher, which matches the view using supported input method of the view. This applies to EditText only. The sample code is as follows,
onView(allOf(withId(R.id.editText_name),
hasImeAction(is(EditorInfo.IME_ACTION_GO))))
Here, EditorInfo.IME_ACTION_GO is on of the input methods options. hasImeAction() accepts integer argument as well. The sample code is as follows,
onView(allOf(withId(R.id.editText_name),
hasImeAction(EditorInfo.IME_ACTION_GO)))
supportsInputMethods() has no argument. It returns a matcher, which matches the view if it supports input methods. The sample code is as follows,
onView(allOf(withId(R.id.editText_name), supportsInputMethods()))
isRoot() has no argument. It returns a matcher, which matches the root view. The sample code is as follows,
onView(allOf(withId(R.id.my_root_id), isRoot()))
isDisplayed() has no argument. It returns a matcher, which matches the view that are currently displayed. The sample code is as follows,
onView(allOf(withId(R.id.my_view_id), isDisplayed()))
isDisplayingAtLeast() accepts a single argument of type int. It returns a matcher, which matches the view that are current displayed at least the specified percentage. The sample code is as follows,
onView(allOf(withId(R.id.my_view_id), isDisplayingAtLeast(75)))
isCompletelyDisplayed() has no argument. It returns a matcher, which matches the view that are currently displayed completely on the screen. The sample code is as follows,
onView(allOf(withId(R.id.my_view_id), isCompletelyDisplayed()))
isEnabled() has no argument. It returns a matcher, which matches the view that is enabled. The sample code is as follows,
onView(allOf(withId(R.id.my_view_id), isEnabled()))
isFocusable() has no argument. It returns a matcher, which matches the view that has focus option. The sample code is as follows,
onView(allOf(withId(R.id.my_view_id), isFocusable()))
hasFocus() has no argument. It returns a matcher, which matches the view that is currently focused. The sample code is as follows,
onView(allOf(withId(R.id.my_view_id), hasFocus()))
isClickable() has no argument. It returns a matcher, which matches the view that is click option. The sample code is as follows,
onView(allOf(withId(R.id.my_view_id), isClickable()))
isSelected() has no argument. It returns a matcher, which matches the view that is currently selected. The sample code is as follows,
onView(allOf(withId(R.id.my_view_id), isSelected()))
isChecked() has no argument. It returns a matcher, which matches the view that is of type CompoundButton (or subtype of it) and is in checked state. The sample code is as follows,
onView(allOf(withId(R.id.my_view_id), isChecked()))
isNotChecked() is just opposite to isChecked. The sample code is as *follows,
onView(allOf(withId(R.id.my_view_id), isNotChecked()))
isJavascriptEnabled() has no argument. It returns a matcher, which matches the WebView that is evaluating JavaScript. The sample code is as follows,
onView(allOf(withId(R.id.my_webview_id), isJavascriptEnabled()))
withParent() accepts one argument of type Matcher<View>. The argument refers a view. It returns a matcher, which matches the view that specified view is parent view. The sample code is as follows,
onView(allOf(withId(R.id.childView), withParent(withId(R.id.parentView))))
hasSibling() accepts one argument of type Matcher>View<. The argument refers a view. It returns a matcher, which matches the view that passed-in view is one of its sibling view. The sample code is as follows,
onView(hasSibling(withId(R.id.siblingView)))
withChild() accepts one argument of type Matcher<View>. The argument refers a view. It returns a matcher, which matches the view that passed-in view is child view. The sample code is as follows,
onView(allOf(withId(R.id.parentView), withChild(withId(R.id.childView))))
hasChildCount() accepts one argument of type int. The argument refers the child count of a view. It returns a matcher, which matches the view that has exactly the same number of child view as specified in the argument. The sample code is as follows,
onView(hasChildCount(4))
hasMinimumChildCount() accepts one argument of type int. The argument refers the child count of a view. It returns a matcher, which matches the view that has at least the number of child view as specified in the argument. The sample code is as follows,
onView(hasMinimumChildCount(4))
hasDescendant() accepts one argument of type Matcher<View>. The argument refers a view. It returns a matcher, which matches the view that passed-in view is one of the descendant view in the view hierarchy. The sample code is as follows,
onView(hasDescendant(withId(R.id.descendantView)))
isDescendantOfA() accepts one argument of type Matcher<View>. The argument refers a view. It returns a matcher, which matches the view that passed-in view is one of the ancestor view in the view hierarchy. The sample code is as follows,
onView(allOf(withId(R.id.myView), isDescendantOfA(withId(R.id.parentView))))
Espresso provides various options to create our own custom view matchers and it is based on Hamcrest matchers. Custom matcher is a very powerful concept to extend the framework and also to customize the framework to our taste. Some of the advantages of writing custom matchers are as follows,
To exploit the unique feature of our own custom views
To exploit the unique feature of our own custom views
Custom matcher helps in the AdapterView based test cases to match with the different type of underlying data.
Custom matcher helps in the AdapterView based test cases to match with the different type of underlying data.
To simplify the current matchers by combining features of multiple matcher
To simplify the current matchers by combining features of multiple matcher
We can create new matcher as and when the demand arises and it is quite easy. Let us create a new custom matcher, which returns a matcher to test both id and text of a TextView.
Espresso provides the following two classes to write new matchers −
TypeSafeMatcher
TypeSafeMatcher
BoundedMatcher
BoundedMatcher
Both classes are similar in nature except that the BoundedMatcher transparently handles the casting of the object to correct type without manually checking for the correct type. We will create a new matcher, withIdAndText using BoundedMatcher class. Let us check the steps to write new matchers.
Add the below dependency in the app/build.gradle file and sync it.
Add the below dependency in the app/build.gradle file and sync it.
dependencies {
implementation 'androidx.test.espresso:espresso-core:3.1.1'
}
Create a new class to include our matchers (methods) and mark it as final
Create a new class to include our matchers (methods) and mark it as final
public final class MyMatchers {
}
Declare a static method inside the new class with the necessary arguments and set Matcher<View> as return type.
Declare a static method inside the new class with the necessary arguments and set Matcher<View> as return type.
public final class MyMatchers {
@NonNull
public static Matcher<View> withIdAndText(final Matcher<Integer>
integerMatcher, final Matcher<String> stringMatcher) {
}
}
Create a new BoundedMatcher object (return value as well) with the below signature inside the static method,
Create a new BoundedMatcher object (return value as well) with the below signature inside the static method,
public final class MyMatchers {
@NonNull
public static Matcher<View> withIdAndText(final Matcher<Integer>
integerMatcher, final Matcher<String> stringMatcher) {
return new BoundedMatcher<View, TextView>(TextView.class) {
};
}
}
Override describeTo and matchesSafely methods in the BoundedMatcher object. describeTo has single argument of type Description with no return type and it is used to error information regarding matchers. matchesSafely has a single argument of type TextView with return type boolean and it is used to match the view.
Override describeTo and matchesSafely methods in the BoundedMatcher object. describeTo has single argument of type Description with no return type and it is used to error information regarding matchers. matchesSafely has a single argument of type TextView with return type boolean and it is used to match the view.
The final version of the code is as follows,
public final class MyMatchers {
@NonNull
public static Matcher<View> withIdAndText(final Matcher<Integer>
integerMatcher, final Matcher<String> stringMatcher) {
return new BoundedMatcher<View, TextView>(TextView.class) {
@Override
public void describeTo(final Description description) {
description.appendText("error text: ");
stringMatcher.describeTo(description);
integerMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(final TextView textView) {
return stringMatcher.matches(textView.getText().toString()) &&
integerMatcher.matches(textView.getId());
}
};
}
}
Finally, We can use our mew matcher to write the test case as sown below,
Finally, We can use our mew matcher to write the test case as sown below,
@Test
public void view_customMatcher_isCorrect() {
onView(withIdAndText(is((Integer) R.id.textView_hello), is((String) "Hello World!")))
.check(matches(withText("Hello World!")));
}
As discussed earlier, view assertion is used to assert that both the actual view (found using view matchers) and expected views are the same. A sample code is as follows,
onView(withId(R.id.my_view)) .check(matches(withText("Hello")))
Here,
onView() returns ViewInteration object corresponding to matched view. ViewInteraction is used to interact with matched view.
onView() returns ViewInteration object corresponding to matched view. ViewInteraction is used to interact with matched view.
withId(R.id.my_view) returns a view matcher that will match with the view (actual) having id attributes equals to my_view.
withId(R.id.my_view) returns a view matcher that will match with the view (actual) having id attributes equals to my_view.
withText(“Hello”) also returns a view matcher that will match with the view (expected) having text attributes equals to Hello.
withText(“Hello”) also returns a view matcher that will match with the view (expected) having text attributes equals to Hello.
check is a method which accepts an argument of type ViewAssertion and do assertion using passed in ViewAssertion object.
check is a method which accepts an argument of type ViewAssertion and do assertion using passed in ViewAssertion object.
matches(withText(“Hello”)) returns a view assertion, which will do the real job of asserting that both actual view (found using withId) and expected view (found using withText) are one and the same.
matches(withText(“Hello”)) returns a view assertion, which will do the real job of asserting that both actual view (found using withId) and expected view (found using withText) are one and the same.
Let us learn some of the methods provided by espresso testing framework to assert view objects.
Returns a view assertion, which ensures that the view matcher does not find any matching view.
onView(withText("Hello")) .check(doesNotExist());
Here, the test case ensures that there is no view with text Hello.
Accepts a target view matcher and returns a view assertion, which ensures that the view matcher (actual) exists and matches with the view matched by the target view matcher.
onView(withId(R.id.textView_hello)) .check(matches(withText("Hello World!")));
Here, the test case ensures that the view having id, R.id.textView_hello exists and matches with the target view with text Hello World!
Accepts a target view matcher and returns a view assertion, which ensures that the view matcher (actual) exists and is bottom aligned with the target view matcher.
onView(withId(R.id.view)) .check(isBottomAlignedWith(withId(R.id.target_view)))
Here, the test case ensures that the view having id, R.id.view exists and is bottom aligned with view having id, R.id.target_view.
Accepts a target view matcher and returns a view assertion, which ensures that the view matcher (actual) exists and is positioned completely above the target view matcher.
onView(withId(R.id.view)) .check(isCompletelyAbove(withId(R.id.target_view)))
Here, the test case ensures that the view having id, R.id.view exists and is positioned completely above the view having id, R.id.target_view
Accepts a target view matcher and returns a view assertion, which ensures that the view matcher (actual) exists and is positioned completely below the target view matcher.
onView(withId(R.id.view)) .check(isCompletelyBelow(withId(R.id.target_view)))
Here, the test case ensures that the view having id, R.id.view exists and is positioned completely below the view having id, R.id.target_view.
Accepts a target view matcher and returns a view assertion, which ensures that the view matcher (actual) exists and is positioned completely left of the target view matcher.
onView(withId(R.id.view)) .check(isCompletelyLeftOf(withId(R.id.target_view)))
Here, the test case ensures that the view having id, R.id.view exists and is positioned completely left of view having id, R.id.target_view
Accepts a target view matcher and returns a view assertion, which ensures that the view matcher (actual) exists and is positioned completely right of the target view matcher.
onView(withId(R.id.view)) .check(isCompletelyRightOf(withId(R.id.target_view)))
Here, the test case ensures that the view having id, R.id.view exists and is positioned completely right of the view having id, R.id.target_view.
Accepts a target view matcher and returns a view assertion, which ensures that the view matcher (actual) exists and is left aligned with the target view matcher.
onView(withId(R.id.view)) .check(isLeftAlignedWith(withId(R.id.target_view)))
Here, the test case ensures that the view having id, R.id.view exists and is left aligned with view having id, R.id.target_view
Accepts a target view matcher and returns a view assertion, which ensures that the view matcher (actual) exists and is positioned partially above the target view matcher.
onView(withId(R.id.view)) .check(isPartiallyAbove(withId(R.id.target_view)))
Here, the test case ensures that the view having id, R.id.view exists and is positioned partially above the view having id, R.id.target_view
Accepts a target view matcher and returns a view assertion, which ensures that the view matcher (actual) exists and is positioned partially below the target view matcher.
onView(withId(R.id.view)) .check(isPartiallyBelow(withId(R.id.target_view)))
Here, the test case ensures that the view having id, R.id.view exists and is positioned partially below the view having id, R.id.target_view.
Accepts a target view matcher and returns a view assertion, which ensures that the view matcher (actual) exists and is positioned partially left of the target view matcher.
onView(withId(R.id.view)) .check(isPartiallyLeftOf(withId(R.id.target_view)))
Here, the test case ensures that the view having id, R.id.view exists and is positioned partially left of view having id, R.id.target_view.
Accepts a target view matcher and returns a view assertion, which ensures that the view matcher (actual) exists and is positioned partially right of the target view matcher
onView(withId(R.id.view)) .check(isPartiallyRightOf(withId(R.id.target_view)))
Here, the test case ensures that the view having id, R.id.view exists and is positioned partially right of view having id, R.id.target_view.
Accepts a target view matcher and returns a view assertion, which ensures that the view matcher (actual) exists and is right aligned with the target view matcher.
onView(withId(R.id.view)) .check(isRightAlignedWith(withId(R.id.target_view)))
Here, the test case ensures that the view having id, R.id.view exists and is right aligned with view having id, R.id.target_view.
Accepts a target view matcher and returns a view assertion, which ensures that the view matcher (actual) exists and is top aligned with the target view matcher.
onView(withId(R.id.view)) .check(isTopAlignedWith(withId(R.id.target_view)))
Here, the test case ensures that the view having id, R.id.view exists and is top aligned with view having id, R.id.target_view
Returns a view assertion, which ensures that the view hierarchy does not contain ellipsized or cut off text views.
onView(withId(R.id.view)) .check(noEllipsizedText());
Returns a view assertion, which ensures that the view hierarchy does not contain multi line buttons.
onView(withId(R.id.view)) .check(noMultilineButtons());
Returns a view assertion, which ensures that the descendant object assignable to TextView or ImageView does not overlap each other. It has another option, which accepts a target view matcher and returns a view assertion, which ensures that the descendant view matching the target view do not overlap.
As learned earlier, view actions automate all the possible actions performable by users in an android application. Espresso onView and “onData” provides the perform method, which accepts view actions and invokes/automates the corresponding user actions in the test environment. For example, “click()” is a view action, which when passed to the onView(R.id.myButton).perform(click()) method, will fire the click event of the button (with id: “myButton”) in the testing environment.
In this chapter, let us learn about the view actions provided by espresso testing framework.
typeText() accepts one argument (text) of type String and returns a view action. The returned view action types the provided text into the view. Before placing the text, it taps the view once. The content may be placed at arbitrary position if it contains text already.
onView(withId(R.id.text_view)).perform(typeText("Hello World!"))
typeTextIntoFocusedView() is similar to typeText() except that it places the text right next to the cursor position in the view.
onView(withId(R.id.text_view)).perform(typeTextIntoFocusedView("Hello World!"))
replaceText() is similar to typeText() except that it replaces the content of the view.
onView(withId(R.id.text_view)).perform(typeTextIntoFocusedView("Hello World!"))
clearText() has no arguments and returns a view action, which will clear the text in the view.
onView(withId(R.id.text_view)).perform(clearText())
pressKey() accepts key code (e.g KeyEvent.KEYCODE_ENTER) and returns a view action, which will press the key corresponds to the key code.
onView(withId(R.id.text_view)).perform(typeText(
"Hello World!", pressKey(KeyEvent.KEYCODE_ENTER))
pressMenuKey() has no arguments and returns a view action, which will press the hardware menu key.
onView(withId(R.id.text_view)).perform(typeText(
"Hello World!", pressKey(KeyEvent.KEYCODE_ENTER), pressMenuKey())
closeSoftKeyboard() has no arguments and returns a view action, which will close the keyboard, if one is opened.
onView(withId(R.id.text_view)).perform(typeText(
"Hello World!", closeSoftKeyboard())
click() has no arguments and returns a view action, which will invoke the click action of the view.
onView(withId(R.id.button)).perform(click())
doubleClick() has no arguments and returns a view action, which will invoke the double click action of the view.
onView(withId(R.id.button)).perform(doubleClick())
longClick() has no arguments and returns a view action, which will invoke the long click action of the view.
onView(withId(R.id.button)).perform(longClick())
pressBack() has no arguments and returns a view action, which will click the back button.
onView(withId(R.id.button)).perform(pressBack())
pressBackUnconditionally() has no arguments and returns a view action, which will click the back button and does not throw an exception if the back button action exits the application itself.
onView(withId(R.id.button)).perform(pressBack())
openLink() has two arguments. The first argument (link text) is of type Matcher and refers the text of the HTML anchor tag. The second argument (url) is of the type Matcher and refers the url of the HTML anchor tag. It is applicable for TextView only. It returns a view action, which collects all the HTML anchor tags available in the content of the text view, finds the anchor tag matching the first argument (link text) and the second argument (url) and finally opens the corresponding url. Let us consider a text view having the content as −
<a href="http://www.google.com/">copyright</a>
Then, the link can be opened and tested using the below test case,
onView(withId(R.id.text_view)).perform(openLink(is("copyright"),
is(Uri.parse("http://www.google.com/"))))
Here, openLink will get the content of the text view, find the link having copyright as text, www.google.com as url and open the url in a browser.
openLinkWithText() has one argument, which may be either of type **String* or Matcher. It is simply a short cut to the openLink *method.
onView(withId(R.id.text_view)).perform(openLinkWithText("copyright"))
openLinkWithUri() has one argument, which may be either of type String or Matcher. It is simply a short cut to the openLink* method.
onView(withId(R.id.text_view)).perform(openLinkWithUri("http://www.google.com/"))
pressImeActionButton() has no arguments and returns a view action, which will execute the action set in android:imeOptions configuration. For example, if the android:imeOptions equals actionNext, this will move the cursor to next possible EditText view in the screen.
onView(withId(R.id.text_view)).perform(pressImeActionButton())
scrollTo() has no arguments and returns a view action, which will scroll the matched scrollView on the screen.
onView(withId(R.id.scrollView)).perform(scrollTo())
swipeDown() has no arguments and returns a view action, which will fire swipe down action on the screen.
onView(withId(R.id.root)).perform(swipeDown())
swipeUp() has no arguments and returns a view action, which will fire swipe up action on the screen.
onView(withId(R.id.root)).perform(swipeUp())
swipeRight() has no arguments and returns a view action, which will fire swipe right action on the screen.
onView(withId(R.id.root)).perform(swipeRight())
swipeLeft() has no arguments and returns a view action, which will fire swipe left action on the screen.
onView(withId(R.id.root)).perform(swipeLeft())
AdapterView is a special kind of view specifically designed to render a collection of similar information like product list and user contacts fetched from an underlying data source using Adapter. The data source may be simple list to complex database entries. Some of the view derived from AdapterView are ListView, GridView and Spinner.
AdapterView renders the user interface dynamically depending on the amount of data available in the underlying data source. In addition, AdapterView renders only the minimum necessary data, which can be rendered in the available visible area of the screen. AdapterView does this to conserve memory and to make the user interface look smooth even if the underlying data is large.
Upon analysis, the nature of the AdapterView architecture makes the onView option and its view matchers irrelevant because the particular view to be tested may not be rendered at all in the first place. Luckily, espresso provides a method, onData(), which accepts hamcrest matchers (relevant to the data type of the underlying data) to match the underlying data and returns object of type DataInteraction corresponding to the view o the matched data. A sample code is as follows,
onData(allOf(is(instanceOf(String.class)), startsWith("Apple"))).perform(click())
Here, onData() matches entry “Apple”, if it is available in the underlying data (array list) and returns DataInteraction object to interact with the matched view (TextView corresponding to “Apple” entry).
DataInteraction provides the below methods to interact with the view,
This accepts view actions and fires the passed in view actions.
onData(allOf(is(instanceOf(String.class)), startsWith("Apple"))).perform(click())
This accepts view assertions and checks the passed in view assertions.
onData(allOf(is(instanceOf(String.class)), startsWith("Apple")))
.check(matches(withText("Apple")))
This accepts view matchers. It selects the particular AdapterView based on the passed in view matchers and returns DataInteraction object to interact with the matched AdapterView
onData(allOf())
.inAdapterView(withId(R.id.adapter_view))
.atPosition(5)
.perform(click())
This accepts an argument of type integer and refers the position of the item in the underlying data. It selects the view corresponding to the passed in positional value of the data and returns DataInteraction object to interact with the matched view. It will be useful, if we know the correct order of the underlying data.
onData(allOf())
.inAdapterView(withId(R.id.adapter_view))
.atPosition(5)
.perform(click())
This accepts view matchers and matches the view inside the specific child view. For example, we can interact with specific items like Buy button in a product list based AdapterView.
onData(allOf(is(instanceOf(String.class)), startsWith("Apple")))
.onChildView(withId(R.id.buy_button))
.perform(click())
Follow the steps shown below to write a simple application based on AdapterView and write a test case using the onData() method.
Start Android studio.
Start Android studio.
Create new project as discussed earlier and name it, MyFruitApp.
Create new project as discussed earlier and name it, MyFruitApp.
Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu.
Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu.
Remove default design in the main activity and add ListView. The content of the activity_main.xml is as follows,
Remove default design in the main activity and add ListView. The content of the activity_main.xml is as follows,
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<ListView
android:id = "@+id/listView"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</RelativeLayout>
Add new layout resource, item.xml to specify the item template of the list view. The content of the item.xml is as follows,
Add new layout resource, item.xml to specify the item template of the list view. The content of the item.xml is as follows,
<?xml version = "1.0" encoding = "utf-8"?>
<TextView xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/name"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:padding = "8dp"
/>
Now, create an adapter having fruit array as underlying data and set it to the list view. This needs to be done in the onCreate() of MainActivity as specified below,
Now, create an adapter having fruit array as underlying data and set it to the list view. This needs to be done in the onCreate() of MainActivity as specified below,
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find fruit list view
final ListView listView = (ListView) findViewById(R.id.listView);
// Initialize fruit data
String[] fruits = new String[]{
"Apple",
"Banana",
"Cherry",
"Dates",
"Elderberry",
"Fig",
"Grapes",
"Grapefruit",
"Guava",
"Jack fruit",
"Lemon",
"Mango",
"Orange",
"Papaya",
"Pears",
"Peaches",
"Pineapple",
"Plums",
"Raspberry",
"Strawberry",
"Watermelon"
};
// Create array list of fruits
final ArrayList<String> fruitList = new ArrayList<String>();
for (int i = 0; i < fruits.length; ++i) {
fruitList.add(fruits[i]);
}
// Create Array adapter
final ArrayAdapter adapter = new ArrayAdapter(this, R.layout.item, fruitList);
// Set adapter in list view
listView.setAdapter(adapter);
}
Now, compile the code and run the application. The screenshot of the My Fruit App is as follows,
Now, compile the code and run the application. The screenshot of the My Fruit App is as follows,
Now, open ExampleInstrumentedTest.java file and add ActivityTestRule as specified below,
Now, open ExampleInstrumentedTest.java file and add ActivityTestRule as specified below,
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<MainActivity>(MainActivity.class);
Also, make sure the test configuration is done in app/build.gradle −
dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test:rules:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
Add a new test case to test the list view as below,
Add a new test case to test the list view as below,
@Test
public void listView_isCorrect() {
// check list view is visible
onView(withId(R.id.listView)).check(matches(isDisplayed()));
onData(allOf(is(instanceOf(String.class)), startsWith("Apple"))).perform(click());
onData(allOf(is(instanceOf(String.class)), startsWith("Apple")))
.check(matches(withText("Apple")));
// click a child item
onData(allOf())
.inAdapterView(withId(R.id.listView))
.atPosition(10)
.perform(click());
}
Finally, run the test case using android studio’s context menu and check whether all test cases are succeeding.
Finally, run the test case using android studio’s context menu and check whether all test cases are succeeding.
WebView is a special view provided by android to display web pages inside the application. WebView does not provide all the features of a full-fledged browser application like chrome and firefox. However, it provides complete control over the content to be shown and exposes all the android features to be invoked inside the web pages. It enables WebView and provides a special environment where the UI can be easily designed using HTML technology and native features like camera and dial a contact. This feature set enables a WebView to provide a new kind of application called Hybrid application, where the UI is done in HTML and business logic is done in either JavaScript or through an external API endpoint.
Normally, testing a WebView needs to be a challenge because it uses HTML technology for its user interface elements rather than native user interface/views. Espresso excels in this area by providing a new set to web matchers and web assertions, which is intentionally similar to native view matchers and view assertions. At the same time, it provides a wellbalanced approach by including a web technology based testing environment as well.
Espresso web is built upon WebDriver Atom framework, which is used to find and manipulate web elements. Atom is similar to view actions. Atom will do all the interaction inside a web page. WebDriver exposes a predefined set of methods, like findElement(), getElement() to find web elements and returns the corresponding atoms (to do action in the web page).
A standard web testing statement looks like the below code,
onWebView()
.withElement(Atom)
.perform(Atom)
.check(WebAssertion)
Here,
onWebView() − Similar to onView(), it exposes a set of API to test a WebView.
onWebView() − Similar to onView(), it exposes a set of API to test a WebView.
withElement() − One of the several methods used to locate web elements inside a web page using Atom and returns WebInteration object, which is similar to ViewInteraction.
withElement() − One of the several methods used to locate web elements inside a web page using Atom and returns WebInteration object, which is similar to ViewInteraction.
perform() − Executes the action inside a web page using Atom and returns WebInteraction.
perform() − Executes the action inside a web page using Atom and returns WebInteraction.
check() − This does the necessary assertion using WebAssertion.
check() − This does the necessary assertion using WebAssertion.
A sample web testing code is as follows,
onWebView()
.withElement(findElement(Locator.ID, "apple"))
.check(webMatches(getText(), containsString("Apple")))
Here,
findElement() locate a element and returns an Atom
findElement() locate a element and returns an Atom
webMatches is similar to matches method
webMatches is similar to matches method
Let us write a simple application based on WebView and write a test case using the onWebView() method. Follow these steps to write a sample application −
Start Android studio.
Start Android studio.
Create new project as discussed earlier and name it, MyWebViewApp.
Create new project as discussed earlier and name it, MyWebViewApp.
Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu.
Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu.
Add the below configuration option in the AndroidManifest.xml file to give permission to access Internet.
Add the below configuration option in the AndroidManifest.xml file to give permission to access Internet.
<uses-permission android:name = "android.permission.INTERNET" />
Espresso web is provided as a separate plugin. So, add the dependency in the app/build.gradle and sync it.
Espresso web is provided as a separate plugin. So, add the dependency in the app/build.gradle and sync it.
dependencies {
androidTestImplementation 'androidx.test:rules:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-web:3.1.1'
}
Remove default design in the main activity and add WebView. The content of the activity_main.xml is as follows,
Remove default design in the main activity and add WebView. The content of the activity_main.xml is as follows,
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<WebView
android:id = "@+id/web_view_test"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent" />
</RelativeLayout>
Create a new class, ExtendedWebViewClient extending WebViewClient and override shouldOverrideUrlLoading method to load link action in the same WebView; otherwise, it will open a new browser window outside the application. Place it in MainActivity.java.
Create a new class, ExtendedWebViewClient extending WebViewClient and override shouldOverrideUrlLoading method to load link action in the same WebView; otherwise, it will open a new browser window outside the application. Place it in MainActivity.java.
private class ExtendedWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Now, add the below code in the onCreate method of MainActivity. The purpose of the code is to find the WebView, properly configure it and then finally load the target url.
Now, add the below code in the onCreate method of MainActivity. The purpose of the code is to find the WebView, properly configure it and then finally load the target url.
// Find web view
WebView webView = (WebView) findViewById(R.id.web_view_test);
// set web view client
webView.setWebViewClient(new ExtendedWebViewClient());
// Clear cache
webView.clearCache(true);
// load Url
webView.loadUrl("http://<your domain or IP>/index.html");
Here,
The content of index.html is as follows −
The content of index.html is as follows −
<html>
<head>
<title>Android Web View Sample</title>
</head>
<body>
<h1>Fruits</h1>
<ol>
<li><a href = "apple.html" id = "apple">Apple</a></li>
<li><a href = "banana.html" id = "banana">Banana</a></li>
</ol>
</body>
</html>
The content of the apple.html file referred in index.html is as follows −
The content of the apple.html file referred in index.html is as follows −
<html>
<head>
<title>Android Web View Sample</title>
</head>
<body>
<h1>Apple</h1>
</body>
</html>
The content of the banana.html file referred in banana.html is as follows,
The content of the banana.html file referred in banana.html is as follows,
<html>
<head>
<title>Android Web View Sample</title>
</head>
<body>
<h1>Banana</h1>
</body>
</html>
Place index.html, apple.html and banana.html in a web server
Place index.html, apple.html and banana.html in a web server
Replace the url in loadUrl method with your configured url.
Replace the url in loadUrl method with your configured url.
Now, run the application and manually check if everything is fine. Below is the screenshot of the WebView sample application −
Now, run the application and manually check if everything is fine. Below is the screenshot of the WebView sample application −
Now, open the ExampleInstrumentedTest.java file and add the below rule −
Now, open the ExampleInstrumentedTest.java file and add the below rule −
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<MainActivity>(MainActivity.class, false, true) {
@Override
protected void afterActivityLaunched() {
onWebView(withId(R.id.web_view_test)).forceJavascriptEnabled();
}
};
Here, we found the WebView and enabled JavaScript of the WebView because espresso web testing framework works exclusively through JavaScript engine to identify and manipulate web element.
Now, add the test case to test our WebView and its behavior.
Now, add the test case to test our WebView and its behavior.
@Test
public void webViewTest(){
onWebView()
.withElement(findElement(Locator.ID, "apple"))
.check(webMatches(getText(), containsString("Apple")))
.perform(webClick())
.withElement(findElement(Locator.TAG_NAME, "h1"))
.check(webMatches(getText(), containsString("Apple")));
}
Here, the testing was done in the following order,
found the link, apple using its id attribute through findElement() method and Locator.ID enumeration.
found the link, apple using its id attribute through findElement() method and Locator.ID enumeration.
checks the text of the link using webMatches() method
checks the text of the link using webMatches() method
performs click action on the link. It opens the apple.html page.
performs click action on the link. It opens the apple.html page.
again found the h1 element using findElement() methods and Locator.TAG_NAME enumeration.
again found the h1 element using findElement() methods and Locator.TAG_NAME enumeration.
finally again checks the text of the h1 tag using webMatches() method.
finally again checks the text of the h1 tag using webMatches() method.
Finally, run the test case using android studio context menu.
Finally, run the test case using android studio context menu.
In this chapter, we will learn how to test asynchronous operations using Espresso Idling Resources.
One of the challenges of the modern application is to provide smooth user experience. Providing smooth user experience involves lot of work in the background to make sure that the application process does not take longer than few milliseconds. Background task ranges from the simple one to costly and complex task of fetching data from remote API / database. To encounter the challenge in the past, a developer used to write costly and long running task in a background thread and sync up with the main UIThread once background thread is completed.
If developing a multi-threaded application is complex, then writing test cases for it is even more complex. For example, we should not test an AdapterView before the necessary data is loaded from the database. If fetching the data is done in a separate thread, the test needs to wait until the thread completes. So, the test environment should be synced between background thread and UI thread. Espresso provides an excellent support for testing the multi-threaded application. An application uses thread in the following ways and espresso supports every scenario.
It is internally used by android SDK to provide smooth user experience with complex UI elements. Espresso supports this scenario transparently and does not need any configuration and special coding.
Modern programming languages support async programming to do light weight threading without the complexity of thread programming. Async task is also supported transparently by espresso framework.
A developer may start a new thread to fetch complex or large data from database. To support this scenario, espresso provides idling resource concept.
Let use learn the concept of idling resource and how to to it in this chapter.
The concept of idling resource is very simple and intuitive. The basic idea is to create a variable (boolean value) whenever a long running process is started in a separate thread to identify whether the process is running or not and register it in the testing environment. During testing, the test runner will check the registered variable, if any found and then find its running status. If the running status is true, test runner will wait until the status become false.
Espresso provides an interface, IdlingResources for the purpose of maintaining the running status. The main method to implement is isIdleNow(). If isIdleNow() returns true, espresso will resume the testing process or else wait until isIdleNow() returns false. We need to implement IdlingResources and use the derived class. Espresso also provides some of the built-in IdlingResources implementation to ease our workload. They are as follows,
This maintains an internal counter of running task. It exposes increment() and decrement() methods. increment() adds one to the counter and decrement() removes one from the counter. isIdleNow() returns true only when no task is active.
This is similar to CounintIdlingResource except that the counter needs to be zero for extended period to take the network latency as well.
This is a custom implementation of ThreadPoolExecutor to maintain the number active running task in the current thread pool.
This is similar to IdlingThreadPoolExecutor, but it schedules a task as well and a custom implementation of ScheduledThreadPoolExecutor.
If any one of the above implementation of IdlingResources or a custom one is used in the application, we need to register it to the testing environment as well before testing the application using IdlingRegistry class as below,
IdlingRegistry.getInstance().register(MyIdlingResource.getIdlingResource());
Moreover, it can be removed once testing is completed as below −
IdlingRegistry.getInstance().unregister(MyIdlingResource.getIdlingResource());
Espresso provides this functionality in a separate package, and the package needs to be configured as below in the app.gradle.
dependencies {
implementation 'androidx.test.espresso:espresso-idling-resource:3.1.1'
androidTestImplementation "androidx.test.espresso.idling:idlingconcurrent:3.1.1"
}
Let us create a simple application to list the fruits by fetching it from a web service in a separate thread and then, test it using idling resource concept.
Start Android studio.
Start Android studio.
Create new project as discussed earlier and name it, MyIdlingFruitApp
Create new project as discussed earlier and name it, MyIdlingFruitApp
Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu.
Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu.
Add espresso idling resource library in the app/build.gradle (and sync it) as specified below,
Add espresso idling resource library in the app/build.gradle (and sync it) as specified below,
dependencies {
implementation 'androidx.test.espresso:espresso-idling-resource:3.1.1'
androidTestImplementation "androidx.test.espresso.idling:idlingconcurrent:3.1.1"
}
Remove the default design in the main activity and add ListView. The content of the activity_main.xml is as follows,
Remove the default design in the main activity and add ListView. The content of the activity_main.xml is as follows,
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<ListView
android:id = "@+id/listView"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</RelativeLayout>
Add new layout resource, item.xml to specify the item template of the list view. The content of the item.xml is as follows,
Add new layout resource, item.xml to specify the item template of the list view. The content of the item.xml is as follows,
<?xml version = "1.0" encoding = "utf-8"?>
<TextView xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/name"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:padding = "8dp"
/>
Create a new class – MyIdlingResource. MyIdlingResource is used to hold our IdlingResource in one place and fetch it whenever necessary. We are going to use CountingIdlingResource in our example.
Create a new class – MyIdlingResource. MyIdlingResource is used to hold our IdlingResource in one place and fetch it whenever necessary. We are going to use CountingIdlingResource in our example.
package com.tutorialspoint.espressosamples.myidlingfruitapp;
import androidx.test.espresso.IdlingResource;
import androidx.test.espresso.idling.CountingIdlingResource;
public class MyIdlingResource {
private static CountingIdlingResource mCountingIdlingResource =
new CountingIdlingResource("my_idling_resource");
public static void increment() {
mCountingIdlingResource.increment();
}
public static void decrement() {
mCountingIdlingResource.decrement();
}
public static IdlingResource getIdlingResource() {
return mCountingIdlingResource;
}
}
Declare a global variable, mIdlingResource of type CountingIdlingResource in the MainActivity class as below,
Declare a global variable, mIdlingResource of type CountingIdlingResource in the MainActivity class as below,
@Nullable
private CountingIdlingResource mIdlingResource = null;
Write a private method to fetch fruit list from the web as below,
Write a private method to fetch fruit list from the web as below,
private ArrayList<String> getFruitList(String data) {
ArrayList<String> fruits = new ArrayList<String>();
try {
// Get url from async task and set it into a local variable
URL url = new URL(data);
Log.e("URL", url.toString());
// Create new HTTP connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set HTTP connection method as "Get"
conn.setRequestMethod("GET");
// Do a http request and get the response code
int responseCode = conn.getResponseCode();
// check the response code and if success, get response content
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
JSONArray jsonArray = new JSONArray(response.toString());
Log.e("HTTPResponse", response.toString());
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = String.valueOf(jsonObject.getString("name"));
fruits.add(name);
}
} else {
throw new IOException("Unable to fetch data from url");
}
conn.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return fruits;
}
Create a new task in the onCreate() method to fetch the data from the web using our getFruitList method followed by the creation of a new adapter and setting it out to list view. Also, decrement the idling resource once our work is completed in the thread. The code is as follows,
Create a new task in the onCreate() method to fetch the data from the web using our getFruitList method followed by the creation of a new adapter and setting it out to list view. Also, decrement the idling resource once our work is completed in the thread. The code is as follows,
// Get data
class FruitTask implements Runnable {
ListView listView;
CountingIdlingResource idlingResource;
FruitTask(CountingIdlingResource idlingRes, ListView listView) {
this.listView = listView;
this.idlingResource = idlingRes;
}
public void run() {
//code to do the HTTP request
final ArrayList<String> fruitList = getFruitList("http://<your domain or IP>/fruits.json");
try {
synchronized (this){
runOnUiThread(new Runnable() {
@Override
public void run() {
// Create adapter and set it to list view
final ArrayAdapter adapter = new
ArrayAdapter(MainActivity.this, R.layout.item, fruitList);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(adapter);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
if (!MyIdlingResource.getIdlingResource().isIdleNow()) {
MyIdlingResource.decrement(); // Set app as idle.
}
}
}
Here, the fruit url is considered as http://<your domain or IP/fruits.json and it is formated as JSON. The content is as follows,
[
{
"name":"Apple"
},
{
"name":"Banana"
},
{
"name":"Cherry"
},
{
"name":"Dates"
},
{
"name":"Elderberry"
},
{
"name":"Fig"
},
{
"name":"Grapes"
},
{
"name":"Grapefruit"
},
{
"name":"Guava"
},
{
"name":"Jack fruit"
},
{
"name":"Lemon"
},
{
"name":"Mango"
},
{
"name":"Orange"
},
{
"name":"Papaya"
},
{
"name":"Pears"
},
{
"name":"Peaches"
},
{
"name":"Pineapple"
},
{
"name":"Plums"
},
{
"name":"Raspberry"
},
{
"name":"Strawberry"
},
{
"name":"Watermelon"
}
]
Note − Place the file in your local web server and use it.
Now, find the view, create a new thread by passing FruitTask, increment the idling resource and finally start the task.
Now, find the view, create a new thread by passing FruitTask, increment the idling resource and finally start the task.
// Find list view
ListView listView = (ListView) findViewById(R.id.listView);
Thread fruitTask = new Thread(new FruitTask(this.mIdlingResource, listView));
MyIdlingResource.increment();
fruitTask.start();
The complete code of MainActivity is as follows,
The complete code of MainActivity is as follows,
package com.tutorialspoint.espressosamples.myidlingfruitapp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.app.AppCompatActivity;
import androidx.test.espresso.idling.CountingIdlingResource;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Nullable
private CountingIdlingResource mIdlingResource = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get data
class FruitTask implements Runnable {
ListView listView;
CountingIdlingResource idlingResource;
FruitTask(CountingIdlingResource idlingRes, ListView listView) {
this.listView = listView;
this.idlingResource = idlingRes;
}
public void run() {
//code to do the HTTP request
final ArrayList<String> fruitList = getFruitList(
"http://<yourdomain or IP>/fruits.json");
try {
synchronized (this){
runOnUiThread(new Runnable() {
@Override
public void run() {
// Create adapter and set it to list view
final ArrayAdapter adapter = new ArrayAdapter(
MainActivity.this, R.layout.item, fruitList);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
if (!MyIdlingResource.getIdlingResource().isIdleNow()) {
MyIdlingResource.decrement(); // Set app as idle.
}
}
}
// Find list view
ListView listView = (ListView) findViewById(R.id.listView);
Thread fruitTask = new Thread(new FruitTask(this.mIdlingResource, listView));
MyIdlingResource.increment();
fruitTask.start();
}
private ArrayList<String> getFruitList(String data) {
ArrayList<String> fruits = new ArrayList<String>();
try {
// Get url from async task and set it into a local variable
URL url = new URL(data);
Log.e("URL", url.toString());
// Create new HTTP connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set HTTP connection method as "Get"
conn.setRequestMethod("GET");
// Do a http request and get the response code
int responseCode = conn.getResponseCode();
// check the response code and if success, get response content
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
JSONArray jsonArray = new JSONArray(response.toString());
Log.e("HTTPResponse", response.toString());
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = String.valueOf(jsonObject.getString("name"));
fruits.add(name);
}
} else {
throw new IOException("Unable to fetch data from url");
}
conn.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return fruits;
}
}
Now, add below configuration in the application manifest file, AndroidManifest.xml
Now, add below configuration in the application manifest file, AndroidManifest.xml
<uses-permission android:name = "android.permission.INTERNET" />
Now, compile the above code and run the application. The screenshot of the My Idling Fruit App is as follows,
Now, compile the above code and run the application. The screenshot of the My Idling Fruit App is as follows,
Now, open the ExampleInstrumentedTest.java file and add ActivityTestRule as specified below,
Now, open the ExampleInstrumentedTest.java file and add ActivityTestRule as specified below,
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<MainActivity>(MainActivity.class);
Also, make sure the test configuration is done in app/build.gradle
dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test:rules:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
implementation 'androidx.test.espresso:espresso-idling-resource:3.1.1'
androidTestImplementation "androidx.test.espresso.idling:idlingconcurrent:3.1.1"
}
Add a new test case to test the list view as below,
Add a new test case to test the list view as below,
@Before
public void registerIdlingResource() {
IdlingRegistry.getInstance().register(MyIdlingResource.getIdlingResource());
}
@Test
public void contentTest() {
// click a child item
onData(allOf())
.inAdapterView(withId(R.id.listView))
.atPosition(10)
.perform(click());
}
@After
public void unregisterIdlingResource() {
IdlingRegistry.getInstance().unregister(MyIdlingResource.getIdlingResource());
}
Finally, run the test case using android studio’s context menu and check whether all test cases are succeeding.
Finally, run the test case using android studio’s context menu and check whether all test cases are succeeding.
Android Intent is used to open new activity, either internal (opening a product detail screen from product list screen) or external (like opening a dialer to make a call). Internal intent activity is handled transparently by the espresso testing framework and it does not need any specific work from the user side. However, invoking external activity is really a challenge because it goes out of our scope, the application under test. Once the user invokes an external application and goes out of the application under test, then the chances of user coming back to the application with predefined sequence of action is rather less. Therefore, we need to assume the user action before testing the application. Espresso provides two options to handle this situation. They are as follows,
This allows the user to make sure the correct intent is opened from the application under test.
This allows the user to mock an external activity like take a photo from the camera, dialing a number from the contact list, etc., and return to the application with predefined set of values (like predefined image from the camera instead of actual image).
Espresso supports the intent option through a plugin library and the library needs to be configured in the application’s gradle file. The configuration option is as follows,
dependencies {
// ...
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.1.1'
}
Espresso intent plugin provides special matchers to check whether the invoked intent is the expected intent. The provided matchers and the purpose of the matchers are as follows,
This accepts the intent action and returns a matcher, which matches the specified intent.
This accepts the data and returns a matcher, which matches the data provided to the intent while invoking it.
This accepts the intent package name and returns a matcher, which matches the package name of the invoked intent.
Now, let us create a new application and test the application for external activity using intended() to understand the concept.
Start Android studio.
Start Android studio.
Create a new project as discussed earlier and name it, IntentSampleApp.
Create a new project as discussed earlier and name it, IntentSampleApp.
Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu.
Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu.
Create a text box, a button to open contact list and another one to dial a call by changing the activity_main.xml as shown below,
Create a text box, a button to open contact list and another one to dial a call by changing the activity_main.xml as shown below,
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<EditText
android:id = "@+id/edit_text_phone_number"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_centerHorizontal = "true"
android:text = ""
android:autofillHints = "@string/phone_number"/>
<Button
android:id = "@+id/call_contact_button"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_centerHorizontal = "true"
android:layout_below = "@id/edit_text_phone_number"
android:text = "@string/call_contact"/>
<Button
android:id = "@+id/button"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_centerHorizontal = "true"
android:layout_below = "@id/call_contact_button"
android:text = "@string/call"/>
</RelativeLayout>
Also, add the below item in strings.xml resource file,
Also, add the below item in strings.xml resource file,
<string name = "phone_number">Phone number</string>
<string name = "call">Call</string>
<string name = "call_contact">Select from contact list</string>
Now, add the below code in the main activity (MainActivity.java) under the onCreate method.
Now, add the below code in the main activity (MainActivity.java) under the onCreate method.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// ... code
// Find call from contact button
Button contactButton = (Button) findViewById(R.id.call_contact_button);
contactButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Uri uri = Uri.parse("content://contacts");
Intent contactIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
contactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(contactIntent, REQUEST_CODE);
}
});
// Find edit view
final EditText phoneNumberEditView = (EditText)
findViewById(R.id.edit_text_phone_number);
// Find call button
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(phoneNumberEditView.getText() != null) {
Uri number = Uri.parse("tel:" + phoneNumberEditView.getText());
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
startActivity(callIntent);
}
}
});
}
// ... code
}
Here, we have programmed the button with id, call_contact_button to open the contact list and button with id, button to dial the call.
Add a static variable REQUEST_CODE in MainActivity class as shown below,
Add a static variable REQUEST_CODE in MainActivity class as shown below,
public class MainActivity extends AppCompatActivity {
// ...
private static final int REQUEST_CODE = 1;
// ...
}
Now, add the onActivityResult method in the MainActivity class as below,
Now, add the onActivityResult method in the MainActivity class as below,
public class MainActivity extends AppCompatActivity {
// ...
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Bundle extras = data.getExtras();
// String phoneNumber = extras.get("data").toString();
Uri uri = data.getData();
Log.e("ACT_RES", uri.toString());
String[] projection = {
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
cursor.moveToFirst();
int numberColumnIndex =
cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(numberColumnIndex);
int nameColumnIndex = cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String name = cursor.getString(nameColumnIndex);
Log.d("MAIN_ACTIVITY", "Selected number : " + number +" , name : "+name);
// Find edit view
final EditText phoneNumberEditView = (EditText)
findViewById(R.id.edit_text_phone_number);
phoneNumberEditView.setText(number);
}
}
};
// ...
}
Here, onActivityResult will be invoked when a user returns to the application after opening the contact list using the call_contact_button button and selecting a contact. Once the onActivityResult method is invoked, it gets the user selected contact, find the contact number and set it into the text box.
Run the application and make sure everything is fine. The final look of the Intent sample Application is as shown below,
Run the application and make sure everything is fine. The final look of the Intent sample Application is as shown below,
Now, configure the espresso intent in the application’s gradle file as shown below,
Now, configure the espresso intent in the application’s gradle file as shown below,
dependencies {
// ...
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.1.1'
}
Click the Sync Now menu option provided by the Android Studio. This will download the intent test library and configure it properly.
Click the Sync Now menu option provided by the Android Studio. This will download the intent test library and configure it properly.
Open ExampleInstrumentedTest.java file and add the IntentsTestRule instead of normally used AndroidTestRule. IntentTestRule is a special rule to handle intent testing.
Open ExampleInstrumentedTest.java file and add the IntentsTestRule instead of normally used AndroidTestRule. IntentTestRule is a special rule to handle intent testing.
public class ExampleInstrumentedTest {
// ... code
@Rule
public IntentsTestRule<MainActivity> mActivityRule =
new IntentsTestRule<>(MainActivity.class);
// ... code
}
Add two local variables to set the test phone number and dialer package name as below,
Add two local variables to set the test phone number and dialer package name as below,
public class ExampleInstrumentedTest {
// ... code
private static final String PHONE_NUMBER = "1 234-567-890";
private static final String DIALER_PACKAGE_NAME = "com.google.android.dialer";
// ... code
}
Fix the import issues by using Alt + Enter option provided by android studio or else include the below import statements,
Fix the import issues by using Alt + Enter option provided by android studio or else include the below import statements,
import android.content.Context;
import android.content.Intent;
import androidx.test.InstrumentationRegistry;
import androidx.test.espresso.intent.rule.IntentsTestRule;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.intent.Intents.intended;
import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction;
import static androidx.test.espresso.intent.matcher.IntentMatchers.hasData;
import static androidx.test.espresso.intent.matcher.IntentMatchers.toPackage;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static org.hamcrest.core.AllOf.allOf;
import static org.junit.Assert.*;
Add the below test case to test whether the dialer is properly called,
Add the below test case to test whether the dialer is properly called,
public class ExampleInstrumentedTest {
// ... code
@Test
public void validateIntentTest() {
onView(withId(R.id.edit_text_phone_number))
.perform(typeText(PHONE_NUMBER), closeSoftKeyboard());
onView(withId(R.id.button)) .perform(click());
intended(allOf(
hasAction(Intent.ACTION_DIAL),
hasData("tel:" + PHONE_NUMBER),
toPackage(DIALER_PACKAGE_NAME)));
}
// ... code
}
Here, hasAction, hasData and toPackage matchers are used along with allOf matcher to succeed only if all matchers are passed.
Now, run the ExampleInstrumentedTest through content menu in Android studio.
Now, run the ExampleInstrumentedTest through content menu in Android studio.
Espresso provides a special method – intending() to mock an external intent action. intending() accept the package name of the intent to be mocked and provides a method respondWith to set how the mocked intent needs to be responded with as specified below,
intending(toPackage("com.android.contacts")).respondWith(result);
Here, respondWith() accepts intent result of type Instrumentation.ActivityResult. We can create new stub intent and manually set the result as specified below,
// Stub intent
Intent intent = new Intent();
intent.setData(Uri.parse("content://com.android.contacts/data/1"));
Instrumentation.ActivityResult result =
new Instrumentation.ActivityResult(Activity.RESULT_OK, intent);
The complete code to test whether a contact application is properly opened is as follows,
@Test
public void stubIntentTest() {
// Stub intent
Intent intent = new Intent();
intent.setData(Uri.parse("content://com.android.contacts/data/1"));
Instrumentation.ActivityResult result =
new Instrumentation.ActivityResult(Activity.RESULT_OK, intent);
intending(toPackage("com.android.contacts")).respondWith(result);
// find the button and perform click action
onView(withId(R.id.call_contact_button)).perform(click());
// get context
Context targetContext2 = InstrumentationRegistry.getInstrumentation().getTargetContext();
// get phone number
String[] projection = { ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME };
Cursor cursor =
targetContext2.getContentResolver().query(Uri.parse("content://com.android.cont
acts/data/1"), projection, null, null, null);
cursor.moveToFirst();
int numberColumnIndex =
cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(numberColumnIndex);
// now, check the data
onView(withId(R.id.edit_text_phone_number))
.check(matches(withText(number)));
}
Here, we have created a new intent and set the return value (when invoking the intent) as the first entry of the contact list, content://com.android.contacts/data/1. Then we have set the intending method to mock the newly created intent in place of contact list. It sets and calls our newly created intent when the package, com.android.contacts is invoked and the default first entry of the list is returned. Then, we fired the click() action to start the mock intent and finally checks whether the phone number from invoking the mock intent and number of the first entry in the contact list are same.
It there is any missing import issue, then fix those import issues by using Alt + Enter option provided by android studio or else include the below import statements,
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import androidx.test.InstrumentationRegistry;
import androidx.test.espresso.ViewInteraction;
import androidx.test.espresso.intent.rule.IntentsTestRule;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.intent.Intents.intended;
import static androidx.test.espresso.intent.Intents.intending;
import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction;
import static androidx.test.espresso.intent.matcher.IntentMatchers.hasData;
import static androidx.test.espresso.intent.matcher.IntentMatchers.toPackage;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.core.AllOf.allOf;
import static org.junit.Assert.*;
Add the below rule in the test class to provide permission to read contact list −
@Rule
public GrantPermissionRule permissionRule =
GrantPermissionRule.grant(Manifest.permission.READ_CONTACTS);
Add the below option in the application manifest file, AndroidManifest.xml −
<uses-permission android:name = "android.permission.READ_CONTACTS" />
Now, make sure the contact list has at least one entry and then run the test using context menu of the Android Studio.
Android supports user interface testing that involves more than one application. Let us consider our application have an option to move from our application to messaging application to send a message and then comes back to our application. In this scenario, UI automator testing framework helps us to test the application. UI automator can be considered as a good companion for espresso testing framework. We can exploit the intending() option in espresso testing framework before opting for UI automator.
Android provides UI automator as a separate plugin. It needs to be configured in the app/build.gradle as specified below,
dependencies {
...
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
}
Let us understand how to write a UI Automator based test case,
Get UiDevice object by calling the getInstance() method and passing the Instrumentation object.
Get UiDevice object by calling the getInstance() method and passing the Instrumentation object.
myDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
myDevice.pressHome();
Get UiObject object using the findObject() method. Before using this method, we can open the uiautomatorviewer application to inspect the target application UI components since understanding the target application enables us to write better test cases.
Get UiObject object using the findObject() method. Before using this method, we can open the uiautomatorviewer application to inspect the target application UI components since understanding the target application enables us to write better test cases.
UiObject button = myDevice.findObject(new UiSelector()
.text("Run")
.className("android.widget.Button"));
Simulate user interaction by calling UiObject’s method. For example, setText() to edit a text field and click() to fire a click event of a button.
Simulate user interaction by calling UiObject’s method. For example, setText() to edit a text field and click() to fire a click event of a button.
if(button.exists() && button.isEnabled()) {
button.click();
}
Finally, we check whether the UI reflects the expected state.
Finally, we check whether the UI reflects the expected state.
Writing test case is a tedious job. Even though espresso provides very easy and flexible API, writing test cases may be a lazy and time-consuming task. To overcome this, Android studio provides a feature to record and generate espresso test cases. Record Espresso Test is available under the Run menu.
Let us record a simple test case in our HelloWorldApp by following the steps described below,
Open the Android studio followed by HelloWorldApp application.
Open the Android studio followed by HelloWorldApp application.
Click Run → Record Espresso test and select MainActivity.
Click Run → Record Espresso test and select MainActivity.
The Recorder screenshot is as follows,
The Recorder screenshot is as follows,
Click Add Assertion. It will open the application screen as shown below,
Click Add Assertion. It will open the application screen as shown below,
Click Hello World!. The Recorder screen to Select text view is as follows,
Click Hello World!. The Recorder screen to Select text view is as follows,
Again click Save Assertion This will save the assertion and show it as follows,
Again click Save Assertion This will save the assertion and show it as follows,
Click OK. It will open a new window and ask the name of the test case. The default name is MainActivityTest
Click OK. It will open a new window and ask the name of the test case. The default name is MainActivityTest
Change the test case name, if necessary.
Change the test case name, if necessary.
Again, click OK. This will generate a file, MainActivityTest with our recorded test case. The complete coding is as follows,
Again, click OK. This will generate a file, MainActivityTest with our recorded test case. The complete coding is as follows,
package com.tutorialspoint.espressosamples.helloworldapp;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import androidx.test.espresso.ViewInteraction;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
@Test
public void mainActivityTest() {
ViewInteraction textView = onView(
allOf(withId(R.id.textView_hello), withText("Hello World!"),
childAtPosition(childAtPosition(withId(android.R.id.content),
0),0),isDisplayed()));
textView.check(matches(withText("Hello World!")));
}
private static Matcher<View> childAtPosition(
final Matcher<View> parentMatcher, final int position) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("Child at position " + position + " in parent ");
parentMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(View view) {
ViewParent parent = view.getParent();
return parent instanceof ViewGroup &&
parentMatcher.matches(parent)&& view.equals(((ViewGroup)
parent).getChildAt(position));
}
};
}
}
Finally, run the test using context menu and check whether the test case run.
Finally, run the test using context menu and check whether the test case run.
Positive User experience plays a very important role in the success of an application. User experience not only involves beautiful user interfaces but also how fast those beautiful user interfaces are rendered and what is the frame per second rate. User interface needs to run consistently at 60 frames per second to give good user experience.
Let us learn some of the option available in the android to analyze UI performance in this chapter.
dumpsys is an in-built tool available in the android device. It outputs current information about the system services. dumpsys has the option to dump information about particular category. Passing gfxinfo will provide animation information of the supplied package. The command is as follows,
> adb shell dumpsys gfxinfo <PACKAGE_NAME>
framestats is an option of the dumpsys command. Once dumpsys is invoked with framestats, it will dump detailed frame timing information of recent frames. The command is as follows,
> adb shell dumpsys gfxinfo <PACKAGE_NAME> framestats
It outputs the information as CSV (comma separated values). The output in CSV format helps to easily push the data into excel and subsequently extract useful information through excel formulas and charts.
systrace is also an in-build tool available in the android device. It captures and displays execution times of the application processes. systrace can be run using the below command in the android studio’s terminal,
python %ANDROID_HOME%/platform-tools/systrace/systrace.py --time=10 -o
my_trace_output.html gfx view res
Accessibility feature is one of the key features for any application. The application developed by a vendor should support minimum accessibility guideline set by the android SDK to be a successful and useful application. Following the accessibility standard is very important and it is not an easy task. Android SDK provides great support by providing properly designed views to create accessible user interfaces.
Similarly, Espresso testing framework does a great favour for both developer and end user by transparently supporting the accessibility testing features into the core-testing engine.
In Espresso, a developer can enable and configure accessibility testing through the AccessibilityChecks class. The sample code is as follows,
AccessibilityChecks.enable();
By default, the accessibility checks run when you perform any view action. The check includes the view on which the action is performed as well as all descendant views. You can check the entire view hierarchy of a screen using the following code −
AccessibilityChecks.enable().setRunChecksFromRootView(true);
Espresso is a great tool for android developers to test their application completely in a very easy way and without putting extra efforts normally required by a testing framework. It even has recorder to create test case without writing the code manually. In addition, it supports all types of user interface testing. By using espresso testing framework, an android developer can confidently develop a great looking application as well as a successful application without any issues in a short period of time.
17 Lectures
1.5 hours
Anuja Jain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2485,
"s": 1976,
"text": "In general, mobile automation testing is a difficult and challenging task. Android availability for different devices and platforms makes it things tedious for mobile automation testing. To make it easier, Google took on the challenge and developed Espr... |
How to change font size with HTML in Java Swing JEditorPane? | Use HTMLEditorKitt to change the font size with HTML. With that, use the JEditorPane setText() method to set HTML:
HTMLEditorKit kit = new HTMLEditorKit();
editorPane.setEditorKit(kit);
editorPane.setSize(size);
editorPane.setOpaque(true);
editorPane.setText("<b><font face=\"Verdana\" size=\"30\"> This is a demo text with a different font!</font></b>");
The following is an example to change font size with HTML in Java Swing JEditorPane:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.html.HTMLEditorKit;
public class SwingDemo extends JFrame {
public static void main(String[] args) {
SwingDemo s = new SwingDemo();
s.setSize(600, 300);
Container container = s.getContentPane();
s.demo(container, container.getSize());
s.setVisible(true);
}
public void demo(Container container, Dimension size) {
JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
HTMLEditorKit kit = new HTMLEditorKit();
editorPane.setEditorKit(kit);
editorPane.setSize(size);
editorPane.setOpaque(true);
editorPane.setText("<b><font face=\"Verdana\" size=\"30\"> This is a demo text with a different font!</font></b>");
container.add(editorPane, BorderLayout.CENTER);
}
} | [
{
"code": null,
"e": 1177,
"s": 1062,
"text": "Use HTMLEditorKitt to change the font size with HTML. With that, use the JEditorPane setText() method to set HTML:"
},
{
"code": null,
"e": 1418,
"s": 1177,
"text": "HTMLEditorKit kit = new HTMLEditorKit();\neditorPane.setEditorKit(k... |
Different Methods to find Prime Number in Python Program | In this tutorial, we are going to explore different methods to find whether a given number is valid or not. Let's start without further due.
It's a general method to find prime numbers.
If the number is less than or equal to one, return False.
If the number is less than or equal to one, return False.
If the number is divisible by any number, then the function will return False.
If the number is divisible by any number, then the function will return False.
After the loop, return True.
After the loop, return True.
Live Demo
# checking for prime
def is_prime(n):
if n <= 1:
return False
else:
for i in range(2, n):
# checking for factor
if n % i == 0:
# return False
return False
# returning True
return True
print(f"Is 2 prime: {is_prime(2)}")
print(f"Is 4 prime: {is_prime(4)}")
print(f"Is 7 prime: {is_prime(7)}")
If you run the above code, then you will get the following result.
Is 2 prime: True
Is 4 prime: False
Is 7 prime: True
In this method, we are reducing the number of iterations by cutting them to the square root of n.Let's see the code.
Live Demo
import math
# checking for prime
def is_prime(n):
if n <= 1:
return False
else:
# iterating loop till square root of n
for i in range(2, int(math.sqrt(n)) + 1):
# checking for factor
if n % i == 0:
# return False
return False
# returning True
return True
print(f"Is 2 prime: {is_prime(2)}")
print(f"Is 4 prime: {is_prime(4)}")
print(f"Is 7 prime: {is_prime(7)}")
If you run the above code, then you will get the following result.
Is 2 prime: True
Is 4 prime: False
Is 7 prime: True
In the previous method, we have checked for the even numbers. We all know that even numbers
can't be prime except two. So, in this method, we will remove all evens to reduce the time.
Live Demo
import math
# checking for prime
def is_prime(n):
# checking for less than 1
if n <= 1:
return False
# checking for 2
elif n == 2:
return True
elif n > 2 and n % 2 == 0:
return False
else:
# iterating loop till square root of n
for i in range(3, int(math.sqrt(n)) + 1, 2):
# checking for factor
if n % i == 0:
# return False
return False
# returning True
return True
print(f"Is 2 prime: {is_prime(2)}")
print(f"Is 4 prime: {is_prime(4)}")
print(f"Is 7 prime: {is_prime(7)}")
If you run the above code, then you will get the following result.
Is 2 prime: True
Is 4 prime: False
Is 7 prime: True
If you have doubts in the tutorial, mention them in the comment section. | [
{
"code": null,
"e": 1203,
"s": 1062,
"text": "In this tutorial, we are going to explore different methods to find whether a given number is valid or not. Let's start without further due."
},
{
"code": null,
"e": 1248,
"s": 1203,
"text": "It's a general method to find prime numbe... |
Providence Interview Experience (On-Campus) - GeeksforGeeks | 09 Oct, 2020
Online Round: Around 250 candidates turned up for this round. The exam contained 3 sections:
Technical MCQ(24 questions)Coding Questions(2 easy-medium)SQL Query(1 Question)
Technical MCQ(24 questions)
Coding Questions(2 easy-medium)
SQL Query(1 Question)
This round was very easy. Basically, you have to be sure almost all MCQ is correct in order to enter for the interview.2 hrs time was there.
29 got Shortlisted from this round.
Round 1 (Face to Face): Introduction about self. This round was to understand what you have done until now. Basically, we discussed the major projects I have worked upon. Was having a deep conversation on what technologies, what methods, and so on.
So she was interested in knowing the boosting algorithm which I told her I implemented from scratch. She said she was not familiar with the concept and asked me to teach it. So I explained to her how boosting works and also wrote a pseudo code.
Asked me to explain OOPS concepts that I know.
Just asked me to write a code on how to merge 2 sorted lists.
Was asking about how familiar I was with python and asked a few simple questions like
Tell me difference between range(),xrange(), arange()
Are arrays and lists the same in python?
Inner join, Outer join, Self joins.
Then asked a few situational questions like
The Hardest problems faced in the project
A situation where I have done something which I did not expect.
Situations where I have helped my teammates even if it was not my part.
18 got shortlisted from this round.
Round 2 (Face to Face): This round was very cool. Some very senior people interviewed me. He was so cool and was so casual he asked what I am comfortable with and had a discussion only on those.
In this round, we had that elevator design problem where we have to accommodate the OOPS concept.
Then he casually asked me what subject to talk about. I casually said we can talk about sports and said about my Nationals experience and engaged him for 5 mins. He then politely said, “I asked about something technical”. We both laughed for a second.
Then I said competitive coding, and then he asked how will you implement a product like a tiny URL. Then I gave a solution he gave a mixed response. So when I added a few features which made it scalable he was quite happy.
Then an easy pattern printing question like this
*
* *
* * *
* * * *
Done with this and finally, he asked me any questions for me
Since we were having a very friendly discussion and I was not quite prepared to ask a one
I unknowingly said “Aiyoo I didn’t prepare any question”
Then we again had laughter then I asked him about work-life or some question of that sort.
8 got shortlisted from this round!. After finishing the round only I came to know that last round I made a huge mistake for the last question. However, luckily I got selected.
HR Round: She again was very friendly and asked to introduce myself.
My family members know what they are doing.
Am I ready to relocate?
Why Providence? (Unfortunately, I didn’t answer it in a satisfactory manner and also made an answer like I was happy with the benefits).
Then asked about the internship experience
Strength and Weakness.
Any questions for me ?(This time I prepared well for asking a question LOL!!)
The interview was over and they declared the results from the 8 they selected 5 .
Unfortunately I didn’t make it through even though I was so confident I almost cleared it.
Tips :
Stay calm and positive during interview.(Don’t talk with peers before the interview)
If you have enough time try to read as many interview experience as possible in GFG as it will be really helpful in technical rounds on how to go about.
At last if unfortunately, If you are turned down don’t worry keep the same spirit throughout the process(I was rejected during the interview of other 6 good companies even at hr levels but finally got what I wanted). It is a test of time, patience, and faith. Keep yourself positive and confident.
Thank you GFG!
Marketing
On-Campus
Providence Global Centre
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience
Amazon Interview Experience for SDE-1 (On-Campus)
Microsoft Interview Experience for Internship (Via Engage)
Directi Interview | Set 7 (Programming Questions)
Zoho Interview | Set 3 (Off-Campus)
Amazon Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1(Off-Campus)
Amazon Interview Experience for SDE-1 (Off-Campus) | [
{
"code": null,
"e": 25008,
"s": 24980,
"text": "\n09 Oct, 2020"
},
{
"code": null,
"e": 25101,
"s": 25008,
"text": "Online Round: Around 250 candidates turned up for this round. The exam contained 3 sections:"
},
{
"code": null,
"e": 25181,
"s": 25101,
"text"... |
How to Check if an element is a child of a parent using JavaScript? - GeeksforGeeks | 31 Oct, 2019
Method 1: Using the Node.contains() methodThe Node.contains() method is used to check if a given node is the descendant of another node at any level. The descendant may be directly the child’s parent or further up the chain. It returns a boolean value of the result.This method is used on the parent element and the parameter passed in the method is the child element to be checked. It returns true if the child is a descendant of the parent. This means that the element is a child of the parent.Syntax:function checkParent(parent, child) { if (parent.contains(child)) return true; return false;}Example:<html> <head> <title> How to Check if an element is a child of a parent using JavaScript? </title> <style> .parent, .child, .non-child { border: 2px solid; padding: 5px; margin: 5px; } </style></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b> How to Check if an element is a child of a parent using JavaScript? </b> <div class="parent">This is the parent div. <div class="child">This is the child div. </div> </div> <div class="non-child"> This is outside the parent div. </div> <p>Click on the button to check if the elements are child of a parent.</p> <p>Child has parent: <span class="output-child"></span> </p> <p>Non-Child has parent: <span class="output-non-child"></span> </p> <button onclick="checkElements()"> Check elements </button> <script> function checkParent(parent, child) { if (parent.contains(child)) return true; return false; } function checkElements() { parent = document.querySelector('.parent'); child = document.querySelector('.child'); non_child = document.querySelector('.non-child'); output_child = checkParent(parent, child); output_non_child = checkParent(parent, non_child); document.querySelector('.output-child').textContent = output_child; document.querySelector('.output-non-child').textContent = output_non_child; } </script></body> </html>Output:Before clicking the button:After clicking the button:
This method is used on the parent element and the parameter passed in the method is the child element to be checked. It returns true if the child is a descendant of the parent. This means that the element is a child of the parent.
Syntax:
function checkParent(parent, child) { if (parent.contains(child)) return true; return false;}
Example:
<html> <head> <title> How to Check if an element is a child of a parent using JavaScript? </title> <style> .parent, .child, .non-child { border: 2px solid; padding: 5px; margin: 5px; } </style></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b> How to Check if an element is a child of a parent using JavaScript? </b> <div class="parent">This is the parent div. <div class="child">This is the child div. </div> </div> <div class="non-child"> This is outside the parent div. </div> <p>Click on the button to check if the elements are child of a parent.</p> <p>Child has parent: <span class="output-child"></span> </p> <p>Non-Child has parent: <span class="output-non-child"></span> </p> <button onclick="checkElements()"> Check elements </button> <script> function checkParent(parent, child) { if (parent.contains(child)) return true; return false; } function checkElements() { parent = document.querySelector('.parent'); child = document.querySelector('.child'); non_child = document.querySelector('.non-child'); output_child = checkParent(parent, child); output_non_child = checkParent(parent, non_child); document.querySelector('.output-child').textContent = output_child; document.querySelector('.output-non-child').textContent = output_non_child; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Method 2: Looping through the parents of the given childThe child can be checked to have the given parent by continuously looping through the element’s parents one by one. The parent of each node is found by accessing the parentNode property which returns the parent node if any.A while loop is used until the parent required is found or no more parent elements exist. Inside this loop, each element’s parent node is found in every iteration. If the parent node matches the given one in any iteration, it means that the element is a child of the parent.Syntax:function checkParent(parent, child) { let node = child.parentNode; // keep iterating unless null while (node != null) { if (node == parent) { return true; } node = node.parentNode; } return false;}Example:<html> <head> <title> How to Check if an element is a child of a parent using JavaScript? </title> <style> .parent, .child, .non-child { border: 2px solid; padding: 5px; margin: 5px; } </style></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b> How to Check if an element is a child of a parent using JavaScript? </b> <div class="parent">This is the parent div. <div class="child">This is the child div. </div> </div> <div class="non-child"> This is outside the parent div. </div> <p>Click on the button to check if the elements are child of a parent.</p> <p>Child has parent: <span class="output-child"></span> </p> <p>Non-Child has parent: <span class="output-non-child"></span> </p> <button onclick="checkElements()"> Check elements </button> <script> function checkParent(parent, child) { let node = child.parentNode; // keep iterating unless null while (node != null) { if (node == parent) { return true; } node = node.parentNode; } return false; } function checkElements() { parent = document.querySelector('.parent'); child = document.querySelector('.child'); non_child = document.querySelector('.non-child'); output_child = checkParent(parent, child); output_non_child = checkParent(parent, non_child); document.querySelector('.output-child').textContent = output_child; document.querySelector('.output-non-child').textContent = output_non_child; } </script></body> </html>Output:Before clicking the button:After clicking the button:
A while loop is used until the parent required is found or no more parent elements exist. Inside this loop, each element’s parent node is found in every iteration. If the parent node matches the given one in any iteration, it means that the element is a child of the parent.
Syntax:
function checkParent(parent, child) { let node = child.parentNode; // keep iterating unless null while (node != null) { if (node == parent) { return true; } node = node.parentNode; } return false;}
Example:
<html> <head> <title> How to Check if an element is a child of a parent using JavaScript? </title> <style> .parent, .child, .non-child { border: 2px solid; padding: 5px; margin: 5px; } </style></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b> How to Check if an element is a child of a parent using JavaScript? </b> <div class="parent">This is the parent div. <div class="child">This is the child div. </div> </div> <div class="non-child"> This is outside the parent div. </div> <p>Click on the button to check if the elements are child of a parent.</p> <p>Child has parent: <span class="output-child"></span> </p> <p>Non-Child has parent: <span class="output-non-child"></span> </p> <button onclick="checkElements()"> Check elements </button> <script> function checkParent(parent, child) { let node = child.parentNode; // keep iterating unless null while (node != null) { if (node == parent) { return true; } node = node.parentNode; } return false; } function checkElements() { parent = document.querySelector('.parent'); child = document.querySelector('.child'); non_child = document.querySelector('.non-child'); output_child = checkParent(parent, child); output_non_child = checkParent(parent, non_child); document.querySelector('.output-child').textContent = output_child; document.querySelector('.output-non-child').textContent = output_non_child; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
JavaScript-Misc
Picked
JavaScript
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
How to execute PHP code using command line ? | [
{
"code": null,
"e": 25364,
"s": 25336,
"text": "\n31 Oct, 2019"
},
{
"code": null,
"e": 27709,
"s": 25364,
"text": "Method 1: Using the Node.contains() methodThe Node.contains() method is used to check if a given node is the descendant of another node at any level. The descendan... |
Implementation of Bit Stuffing and Bit Destuffing - GeeksforGeeks | 31 Dec, 2021
Bit Stuffing is a process of inserting an extra bit as 0, once the frame sequence encountered 5 consecutive 1’s. Given an array, arr[] of size N consisting of 0’s and 1’s, the task is to return an array after the bit stuffing.
Examples:
Input: N = 6, arr[] = {1, 1, 1, 1, 1, 1}Output: 1111101Explanation: During the traversal of the array, 5 consecutive 1’s are encountered after the 4th index of the given array. Hence, a zero bit has been inserted into the stuffed array after the 4th index
Input: N = 6, arr[] = {1, 0, 1, 0, 1, 0}Output: 101010
Approach: The idea is to check if the given array consists of 5 consecutive 1’s. Follow the steps below to solve the problem:
Initialize the array brr[] which stores the stuffed array. Also, create a variable count which maintains the count of the consecutive 1’s.
Traverse in a while loop using a variable i in the range [0, N) and perform the following tasks:If arr[i] is 1 then check for the next 4 bits if they are set bits as well. If they are, then insert a 0 bit after inserting all the 5 set bits into the array brr[].Otherwise, insert the value of arr[i] into the array brr[].
If arr[i] is 1 then check for the next 4 bits if they are set bits as well. If they are, then insert a 0 bit after inserting all the 5 set bits into the array brr[].
Otherwise, insert the value of arr[i] into the array brr[].
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>#include <iostream>using namespace std; // Function for bit stuffingvoid bitStuffing(int N, int arr[]){ // Stores the stuffed array int brr[30]; // Variables to traverse arrays int i, j, k; i = 0; j = 0; // Stores the count of consecutive ones int count = 1; // Loop to traverse in the range [0, N) while (i < N) { // If the current bit is a set bit if (arr[i] == 1) { // Insert into array brr[] brr[j] = arr[i]; // Loop to check for // next 5 bits for(k = i + 1; arr[k] == 1 && k < N && count < 5; k++) { j++; brr[j] = arr[k]; count++; // If 5 consecutive set bits // are found insert a 0 bit if (count == 5) { j++; brr[j] = 0; } i = k; } } // Otherwise insert arr[i] into // the array brr[] else { brr[j] = arr[i]; } i++; j++; } // Print Answer for(i = 0; i < j; i++) cout << brr[i];} // Driver codeint main(){ int N = 6; int arr[] = { 1, 1, 1, 1, 1, 1 }; bitStuffing(N, arr);; return 0;} // This code is contributed by target_2
// C program for the above approach#include <stdio.h>#include <string.h> // Function for bit stuffingvoid bitStuffing(int N, int arr[]){ // Stores the stuffed array int brr[30]; // Variables to traverse arrays int i, j, k; i = 0; j = 0; // Stores the count of consecutive ones int count = 1; // Loop to traverse in the range [0, N) while (i < N) { // If the current bit is a set bit if (arr[i] == 1) { // Insert into array brr[] brr[j] = arr[i]; // Loop to check for // next 5 bits for (k = i + 1; arr[k] == 1 && k < N && count < 5; k++) { j++; brr[j] = arr[k]; count++; // If 5 consecutive set bits // are found insert a 0 bit if (count == 5) { j++; brr[j] = 0; } i = k; } } // Otherwise insert arr[i] into // the array brr[] else { brr[j] = arr[i]; } i++; j++; } // Print Answer for (i = 0; i < j; i++) printf("%d", brr[i]);} // Driver Codeint main(){ int N = 6; int arr[] = { 1, 1, 1, 1, 1, 1 }; bitStuffing(N, arr); return 0;}
// Java program for the above approachclass GFG{ // Function for bit stuffingstatic void bitStuffing(int N, int arr[]){ // Stores the stuffed array int []brr = new int[30]; // Variables to traverse arrays int i, j, k; i = 0; j = 0; // Stores the count of consecutive ones int count = 1; // Loop to traverse in the range [0, N) while (i < N) { // If the current bit is a set bit if (arr[i] == 1) { // Insert into array brr[] brr[j] = arr[i]; // Loop to check for // next 5 bits for (k = i + 1; k < N && arr[k] == 1 && count < 5; k++) { j++; brr[j] = arr[k]; count++; // If 5 consecutive set bits // are found insert a 0 bit if (count == 5) { j++; brr[j] = 0; } i = k; } } // Otherwise insert arr[i] into // the array brr[] else { brr[j] = arr[i]; } i++; j++; } // Print Answer for (i = 0; i < j; i++) System.out.printf("%d", brr[i]);} // Driver Codepublic static void main(String[] args){ int N = 6; int arr[] = { 1, 1, 1, 1, 1, 1 }; bitStuffing(N, arr); }} // This code is contributed by shikhasingrajput
# Python3 program for the above approach # Function for bit stuffingdef bitStuffing(N, arr): # Stores the stuffed array brr = [0 for _ in range(30)] # Variables to traverse arrays k = 0 i = 0 j = 0 # Stores the count of consecutive ones count = 1 # Loop to traverse in the range [0, N) while (i < N): # If the current bit is a set bit if (arr[i] == 1): # Insert into array brr[] brr[j] = arr[i] # Loop to check for # next 5 bits k = i + 1 while True: if not (k < N and arr[k] == 1 and count < 5): break j += 1 brr[j] = arr[k] count += 1 # If 5 consecutive set bits # are found insert a 0 bit if (count == 5): j += 1 brr[j] = 0 i = k k += 1 # Otherwise insert arr[i] into # the array brr[] else: brr[j] = arr[i] i += 1 j += 1 # Print Answer for i in range(0, j): print(brr[i], end = "") # Driver Codeif __name__ == "__main__": N = 6 arr = [ 1, 1, 1, 1, 1, 1 ] bitStuffing(N, arr) # This code is contributed by rakeshsahni
// C# program for the above approachusing System; class GFG{ // Function for bit stuffingstatic void bitStuffing(int N, int[] arr){ // Stores the stuffed array int[] brr = new int[30]; // Variables to traverse arrays int i, j, k; i = 0; j = 0; // Stores the count of consecutive ones int count = 1; // Loop to traverse in the range [0, N) while (i < N) { // If the current bit is a set bit if (arr[i] == 1) { // Insert into array brr[] brr[j] = arr[i]; // Loop to check for // next 5 bits k = i + 1; while (k < N && arr[k] == 1 && count < 5) { j++; brr[j] = arr[k]; count++; // If 5 consecutive set bits // are found insert a 0 bit if (count == 5) { j++; brr[j] = 0; } i = k; k++; } } // Otherwise insert arr[i] into // the array brr[] else { brr[j] = arr[i]; } i++; j++; } // Print Answer for(i = 0; i < j; i++) Console.Write(brr[i]);} // Driver Codepublic static void Main(){ int N = 6; int[] arr = { 1, 1, 1, 1, 1, 1 }; bitStuffing(N, arr);}} // This code is contributed by ukasp
<script> // JavaScript Program to implement // the above approach // Function for bit stuffing function bitStuffing(N, arr) { // Stores the stuffed array let brr = new Array(30); // Variables to traverse arrays let i, j, k; i = 0; j = 0; // Stores the count of consecutive ones let count = 1; // Loop to traverse in the range [0, N) while (i < N) { // If the current bit is a set bit if (arr[i] == 1) { // Insert into array brr[] brr[j] = arr[i]; // Loop to check for // next 5 bits for (k = i + 1; arr[k] == 1 && k < N && count < 5; k++) { j++; brr[j] = arr[k]; count++; // If 5 consecutive set bits // are found insert a 0 bit if (count == 5) { j++; brr[j] = 0; } i = k; } } // Otherwise insert arr[i] into // the array brr[] else { brr[j] = arr[i]; } i++; j++; } // Print Answer for (i = 0; i < j; i++) document.write(brr[i] + " "); } // Driver Code let N = 6; let arr = [1, 1, 1, 1, 1, 1]; bitStuffing(N, arr); // This code is contributed by Potta Lokesh </script>
1111101
Time Complexity: O(N)Auxiliary Space: O(N)
Bit Destuffing or Bit Unstuffing is a process of undoing the changes in the array made during the bit stuffing process i.e, removing the extra 0 bit after encountering 5 consecutive 1’s.
Examples:
Input: N = 7, arr[] = {1, 1, 1, 1, 1, 0, 1}Output: 111111Explanation: During the traversal of the array, 5 consecutive 1’s are encountered after the 4th index of the given array. Hence, the next 0 bit must be removed to de-stuffed array.
Input: N = 6, arr[] = {1, 0, 1, 0, 1, 0}Output: 101010
Approach: This problem can be solved similarly to the bit stuffing problem. The only required change in the above-discussed approach is whenever 5 consecutive 1’s are encountered, skip the next bit in the array arr[] in place of inserting a 0 bit in the array brr[].
Below is the implementation of the above approach:
C
Java
Python3
C#
Javascript
// C program for the above approach#include <stdio.h>#include <string.h> // Function for bit de-stuffingvoid bitDestuffing(int N, int arr[]){ // Stores the de-stuffed array int brr[30]; // Variables to traverse the arrays int i, j, k; i = 0; j = 0; // Stores the count of consecutive ones int count = 1; // Loop to traverse in the range [0, N) while (i < N) { // If the current bit is a set bit if (arr[i] == 1) { // Insert into array brr[] brr[j] = arr[i]; // Loop to check for // the next 5 bits for (k = i + 1; arr[k] == 1 && k < N && count < 5; k++) { j++; brr[j] = arr[k]; count++; // If 5 consecutive set // bits are found skip the // next bit in arr[] if (count == 5) { k++; } i = k; } } // Otherwise insert arr[i] into // the array brr else { brr[j] = arr[i]; } i++; j++; } // Print Answer for (i = 0; i < j; i++) printf("%d", brr[i]);} // Driver Codeint main(){ int N = 7; int arr[] = { 1, 1, 1, 1, 1, 0, 1 }; bitDestuffing(N, arr); return 0;}
// Java program for the above approachclass GFG{ // Function for bit de-stuffingstatic void bitDestuffing(int N, int arr[]){ // Stores the de-stuffed array int []brr = new int[30]; // Variables to traverse the arrays int i, j, k; i = 0; j = 0; // Stores the count of consecutive ones int count = 1; // Loop to traverse in the range [0, N) while (i < N) { // If the current bit is a set bit if (arr[i] == 1) { // Insert into array brr[] brr[j] = arr[i]; // Loop to check for // the next 5 bits for (k = i + 1; k<N && arr[k] == 1 && count < 5; k++) { j++; brr[j] = arr[k]; count++; // If 5 consecutive set // bits are found skip the // next bit in arr[] if (count == 5) { k++; } i = k; } } // Otherwise insert arr[i] into // the array brr else { brr[j] = arr[i]; } i++; j++; } // Print Answer for (i = 0; i < j; i++) System.out.printf("%d", brr[i]);} // Driver Codepublic static void main(String[] args){ int N = 7; int arr[] = { 1, 1, 1, 1, 1, 0, 1 }; bitDestuffing(N, arr);}} // This code is contributed by shikhasingrajput
# Python program for the above approach # Function for bit de-stuffingdef bitDestuffing(N, arr): # Stores the de-stuffed array brr = [0 for i in range(30)]; # Variables to traverse the arrays k = 0; i = 0; j = 0; # Stores the count of consecutive ones count = 1; # Loop to traverse in the range [0, N) while (i < N): # If the current bit is a set bit if (arr[i] == 1): # Insert into array brr brr[j] = arr[i]; # Loop to check for # the next 5 bits for k in range(i + 1, k < N and arr[k] == 1 and count < 5,1): j += 1; brr[j] = arr[k]; count += 1; # If 5 consecutive set # bits are found skip the # next bit in arr if (count == 5): k += 1; i = k; # Otherwise insert arr[i] into # the array brr else: brr[j] = arr[i]; i += 1; j += 1; # PrAnswer for i in range(0, j): print(brr[i],end=""); # Driver Codeif __name__ == '__main__': N = 7; arr = [1, 1, 1, 1, 1, 0, 1]; bitDestuffing(N, arr); # This code contributed by shikhasingrajput
// C# program for the above approachusing System; class GFG{ // Function for bit de-stuffingstatic void bitDestuffing(int N, int[] arr){ // Stores the de-stuffed array int []brr = new int[30]; // Variables to traverse the arrays int i, j, k; i = 0; j = 0; // Stores the count of consecutive ones int count = 1; // Loop to traverse in the range [0, N) while (i < N) { // If the current bit is a set bit if (arr[i] == 1) { // Insert into array brr[] brr[j] = arr[i]; // Loop to check for // the next 5 bits for (k = i + 1; k<N && arr[k] == 1 && count < 5; k++) { j++; brr[j] = arr[k]; count++; // If 5 consecutive set // bits are found skip the // next bit in arr[] if (count == 5) { k++; } i = k; } } // Otherwise insert arr[i] into // the array brr else { brr[j] = arr[i]; } i++; j++; } // Print Answer for (i = 0; i < j; i++) Console.Write(brr[i]);} // Driver Codepublic static void Main(){ int N = 7; int[] arr = { 1, 1, 1, 1, 1, 0, 1 }; bitDestuffing(N, arr);}} // This code is contributed by gfgking
<script>// javascript program for the above approach// Function for bit de-stuffingfunction bitDestuffing(N , arr){ // Stores the de-stuffed array var brr = Array.from({length: 30}, (_, i) => 0); // Variables to traverse the arrays var i, j, k; i = 0; j = 0; // Stores the count of consecutive ones var count = 1; // Loop to traverse in the range [0, N) while (i < N) { // If the current bit is a set bit if (arr[i] == 1) { // Insert into array brr brr[j] = arr[i]; // Loop to check for // the next 5 bits for (k = i + 1; k<N && arr[k] == 1 && count < 5; k++) { j++; brr[j] = arr[k]; count++; // If 5 consecutive set // bits are found skip the // next bit in arr if (count == 5) { k++; } i = k; } } // Otherwise insert arr[i] into // the array brr else { brr[j] = arr[i]; } i++; j++; } // Print Answer for (i = 0; i < j; i++) document.write(brr[i]);} // Driver Codevar N = 7;var arr = [ 1, 1, 1, 1, 1, 0, 1 ]; bitDestuffing(N, arr); // This code is contributed by 29AjayKumar</script>
1111101
Time Complexity: O(N)Auxiliary Space: O(N)
lokeshpotta20
ukasp
rakeshsahni
shikhasingrajput
gfgking
29AjayKumar
surinderdawra388
target_2
Algorithms
Bit Magic
Computer Networks
Bit Magic
Algorithms
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to write a Pseudo Code?
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
How to swap two numbers without using a temporary variable? | [
{
"code": null,
"e": 25625,
"s": 25597,
"text": "\n31 Dec, 2021"
},
{
"code": null,
"e": 25852,
"s": 25625,
"text": "Bit Stuffing is a process of inserting an extra bit as 0, once the frame sequence encountered 5 consecutive 1’s. Given an array, arr[] of size N consisting of 0’s ... |
Output of Java programs | Set 10 (Garbage Collection) - GeeksforGeeks | 28 Jun, 2021
Prerequisite – Garbage Collection in Java
Difficulty level : IntermediateIn Java, object destruction is taken care by the Garbage Collector module and the objects which do not have any references to them are eligible for garbage collection. Below are some important output questions on Garbage collection.Predict the output of following Java Programs:
Program 1 :public class Test{ public static void main(String[] args) throws InterruptedException { String str = new String("GeeksForGeeks"); // making str eligible for gc str = null; // calling garbage collector System.gc(); // waiting for gc to complete Thread.sleep(1000); System.out.println("end of main"); } @Override protected void finalize() { System.out.println("finalize method called"); }}Output:end of main
Explanation : We know that finalize() method is called by Garbage Collector on an object before destroying it. But here, the trick is that the str is String class object, not the Test class. Therefore, finalize() method of String class(if overridden in String class) is called on str. If a class doesn’t override finalize method, then by default Object class finalize() method is called.
public class Test{ public static void main(String[] args) throws InterruptedException { String str = new String("GeeksForGeeks"); // making str eligible for gc str = null; // calling garbage collector System.gc(); // waiting for gc to complete Thread.sleep(1000); System.out.println("end of main"); } @Override protected void finalize() { System.out.println("finalize method called"); }}
Output:
end of main
Explanation : We know that finalize() method is called by Garbage Collector on an object before destroying it. But here, the trick is that the str is String class object, not the Test class. Therefore, finalize() method of String class(if overridden in String class) is called on str. If a class doesn’t override finalize method, then by default Object class finalize() method is called.
Program 2 :public class Test{ public static void main(String[] args) throws InterruptedException { Test t = new Test(); // making t eligible for garbage collection t = null; // calling garbage collector System.gc(); // waiting for gc to complete Thread.sleep(1000); System.out.println("end main"); } @Override protected void finalize() { System.out.println("finalize method called"); System.out.println(10/0); } }Output:finalize method called
end main
Explanation :When Garbage Collector calls finalize() method on an object, it ignores all the exceptions raised in the method and program will terminate normally.
public class Test{ public static void main(String[] args) throws InterruptedException { Test t = new Test(); // making t eligible for garbage collection t = null; // calling garbage collector System.gc(); // waiting for gc to complete Thread.sleep(1000); System.out.println("end main"); } @Override protected void finalize() { System.out.println("finalize method called"); System.out.println(10/0); } }
Output:
finalize method called
end main
Explanation :When Garbage Collector calls finalize() method on an object, it ignores all the exceptions raised in the method and program will terminate normally.
Program 3 :public class Test{ static Test t ; static int count =0; public static void main(String[] args) throws InterruptedException { Test t1 = new Test(); // making t1 eligible for garbage collection t1 = null; // line 12 // calling garbage collector System.gc(); // line 15 // waiting for gc to complete Thread.sleep(1000); // making t eligible for garbage collection, t = null; // line 21 // calling garbage collector System.gc(); // line 24 // waiting for gc to complete Thread.sleep(1000); System.out.println("finalize method called "+count+" times"); } @Override protected void finalize() { count++; t = this; // line 38 } }Output:finalize method called 1 times
Explanation :After execution of line 12, t1 becomes eligible for garbage collection. So when we call garbage collector at line 15, Garbage Collector will call finalize() method on t1 before destroying it. But in finalize method, in line 38, we are again referencing the same object by t, so after execution of line 38,this object is no longer eligible for garbage collection. Hence, Garbage Collector will not destroy the object.Now again in line 21, we are making same object eligible for garbage collection one more time. Here, we have to clear about one fact about Garbage Collector i.e. it will call finalize() method on a particular object exactly one time. Since on this object, finalize() method is already called, so now Garbage Collector will destroy it without calling finalize() method again.
public class Test{ static Test t ; static int count =0; public static void main(String[] args) throws InterruptedException { Test t1 = new Test(); // making t1 eligible for garbage collection t1 = null; // line 12 // calling garbage collector System.gc(); // line 15 // waiting for gc to complete Thread.sleep(1000); // making t eligible for garbage collection, t = null; // line 21 // calling garbage collector System.gc(); // line 24 // waiting for gc to complete Thread.sleep(1000); System.out.println("finalize method called "+count+" times"); } @Override protected void finalize() { count++; t = this; // line 38 } }
Output:
finalize method called 1 times
Explanation :After execution of line 12, t1 becomes eligible for garbage collection. So when we call garbage collector at line 15, Garbage Collector will call finalize() method on t1 before destroying it. But in finalize method, in line 38, we are again referencing the same object by t, so after execution of line 38,this object is no longer eligible for garbage collection. Hence, Garbage Collector will not destroy the object.
Now again in line 21, we are making same object eligible for garbage collection one more time. Here, we have to clear about one fact about Garbage Collector i.e. it will call finalize() method on a particular object exactly one time. Since on this object, finalize() method is already called, so now Garbage Collector will destroy it without calling finalize() method again.
Program 4 :public class Test{ public static void main(String[] args) { // How many objects are eligible for // garbage collection after this line? m1(); // Line 5 } static void m1() { Test t1 = new Test(); Test t2 = new Test(); } }Question :How many objects are eligible for garbage collection after execution of line 5 ?Answer :2
Explanation :Since t1 and t2 are local objects of m1() method, so they become eligible for garbage collection after complete execution of method unless any of them is returned.
public class Test{ public static void main(String[] args) { // How many objects are eligible for // garbage collection after this line? m1(); // Line 5 } static void m1() { Test t1 = new Test(); Test t2 = new Test(); } }
Question :How many objects are eligible for garbage collection after execution of line 5 ?Answer :
2
Explanation :Since t1 and t2 are local objects of m1() method, so they become eligible for garbage collection after complete execution of method unless any of them is returned.
Program 5 :public class Test{ public static void main(String [] args) { Test t1 = new Test(); Test t2 = m1(t1); // line 6 Test t3 = new Test(); t2 = t3; // line 8 } static Test m1(Test temp) { temp = new Test(); return temp; }}Question :How many objects are eligible for garbage collection after execution of line 8?Answer :1
Explanation :By the time line 8 has executed, the only object without a reference is the one generated i.e as a result of line 6. Remember that “Java is strictly pass by value” so the reference variable t1 is not affected by the m1() method. We can check it using finalize() method. The statement “System.out.println(this.hashcode())” in finalize() method print the object hashcode value on which finalize() method is called,and then just compare the value with other objects hashcode values created in main method.
public class Test{ public static void main(String [] args) { Test t1 = new Test(); Test t2 = m1(t1); // line 6 Test t3 = new Test(); t2 = t3; // line 8 } static Test m1(Test temp) { temp = new Test(); return temp; }}
Question :How many objects are eligible for garbage collection after execution of line 8?Answer :
1
Explanation :By the time line 8 has executed, the only object without a reference is the one generated i.e as a result of line 6. Remember that “Java is strictly pass by value” so the reference variable t1 is not affected by the m1() method. We can check it using finalize() method. The statement “System.out.println(this.hashcode())” in finalize() method print the object hashcode value on which finalize() method is called,and then just compare the value with other objects hashcode values created in main method.
This article is contributed by Gaurav Miglani. 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.
java-garbage-collection
Java-Output
Java
Program Output
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Arrow operator -> in C/C++ with Examples
delete keyword in C++
Output of Java Program | Set 1
Output of C Programs | Set 1
Output of C++ programs | Set 34 (File Handling) | [
{
"code": null,
"e": 25693,
"s": 25665,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25735,
"s": 25693,
"text": "Prerequisite – Garbage Collection in Java"
},
{
"code": null,
"e": 26045,
"s": 25735,
"text": "Difficulty level : IntermediateIn Java, object d... |
Flag register of 8086 microprocessor - GeeksforGeeks | 22 May, 2018
Prerequisite – Flag register in 8085 microprocessorThe Flag register is a Special Purpose Register. Depending upon the value of result after any arithmetic and logical operation the flag bits become set (1) or reset (0).
Figure – Format of flag registerThere are total 9 flags in 8086 and the flag register is divided into two types:
(a) Status Flags – There are 6 flag registers in 8086 microprocessor which become set(1) or reset(0) depending upon condition after either 8-bit or 16-bit operation. These flags are conditional/status flags. 5 of these flags are same as in case of 8085 microprocessor and their working is also same as in 8085 microprocessor. The sixth one is the overflow flag.
The 6 status flags are:
Sign Flag (S)Zero Flag (Z)Auxiliary Cary Flag (AC)Parity Flag (P)Carry Flag (CY)These first five flags are defined hereOverflow Flag (O) – This flag will be set (1) if the result of a signed operation is too large to fit in the number of bits available to represent it, otherwise reset (0). After any operation, if D[6] generates any carry and passes to D[7] OR if D[6] does not generates carry but D[7] generates, overflow flag becomes set, i.e., 1. If D[6] and D[7] both generate carry or both do not generate any carry, then overflow flag becomes reset, i.e., 0.Example: On adding bytes 100 + 50 (result is not in range -128...127), so overflow flag will set.MOV AL, 50 (50 is 01010000 which is positive)
MOV BL, 32 (32 is 00110010 which is positive)
ADD AL, BL (82 is 10000010 which is negative)
Overflow flag became set as we added 2 +ve numbers and we got a -ve number.
Sign Flag (S)
Zero Flag (Z)
Auxiliary Cary Flag (AC)
Parity Flag (P)
Carry Flag (CY)These first five flags are defined here
Overflow Flag (O) – This flag will be set (1) if the result of a signed operation is too large to fit in the number of bits available to represent it, otherwise reset (0). After any operation, if D[6] generates any carry and passes to D[7] OR if D[6] does not generates carry but D[7] generates, overflow flag becomes set, i.e., 1. If D[6] and D[7] both generate carry or both do not generate any carry, then overflow flag becomes reset, i.e., 0.Example: On adding bytes 100 + 50 (result is not in range -128...127), so overflow flag will set.MOV AL, 50 (50 is 01010000 which is positive)
MOV BL, 32 (32 is 00110010 which is positive)
ADD AL, BL (82 is 10000010 which is negative)
Overflow flag became set as we added 2 +ve numbers and we got a -ve number.
Example: On adding bytes 100 + 50 (result is not in range -128...127), so overflow flag will set.
MOV AL, 50 (50 is 01010000 which is positive)
MOV BL, 32 (32 is 00110010 which is positive)
ADD AL, BL (82 is 10000010 which is negative)
Overflow flag became set as we added 2 +ve numbers and we got a -ve number.
(b) Control Flags – The control flags enable or disable certain operations of the microprocessor. There are 3 control flags in 8086 microprocessor and these are:
Directional Flag (D) – This flag is specifically used in string instructions.If directional flag is set (1), then access the string data from higher memory location towards lower memory location.If directional flag is reset (0), then access the string data from lower memory location towards higher memory location.Interrupt Flag (I) – This flag is for interrupts.If interrupt flag is set (1), the microprocessor will recognize interrupt requests from the peripherals.If interrupt flag is reset (0), the microprocessor will not recognize any interrupt requests and will ignore them.Trap Flag (T) – This flag is used for on-chip debugging. Setting trap flag puts the microprocessor into single step mode for debugging. In single stepping, the microprocessor executes a instruction and enters into single step ISR.If trap flag is set (1), the CPU automatically generates an internal interrupt after each instruction, allowing a program to be inspected as it executes instruction by instruction.If trap flag is reset (0), no function is performed.
Directional Flag (D) – This flag is specifically used in string instructions.If directional flag is set (1), then access the string data from higher memory location towards lower memory location.If directional flag is reset (0), then access the string data from lower memory location towards higher memory location.
Interrupt Flag (I) – This flag is for interrupts.If interrupt flag is set (1), the microprocessor will recognize interrupt requests from the peripherals.If interrupt flag is reset (0), the microprocessor will not recognize any interrupt requests and will ignore them.
Trap Flag (T) – This flag is used for on-chip debugging. Setting trap flag puts the microprocessor into single step mode for debugging. In single stepping, the microprocessor executes a instruction and enters into single step ISR.If trap flag is set (1), the CPU automatically generates an internal interrupt after each instruction, allowing a program to be inspected as it executes instruction by instruction.If trap flag is reset (0), no function is performed.
Shivi_Aggarwal
microprocessor
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Memory Hierarchy Design and its Characteristics
Computer Organization | RISC and CISC
Direct Access Media (DMA) Controller in Computer Architecture
Interrupts
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Programmable peripheral interface 8255
Computer Organization | Von Neumann architecture
Architecture of 8085 microprocessor
Write Through and Write Back in Cache | [
{
"code": null,
"e": 25931,
"s": 25903,
"text": "\n22 May, 2018"
},
{
"code": null,
"e": 26152,
"s": 25931,
"text": "Prerequisite – Flag register in 8085 microprocessorThe Flag register is a Special Purpose Register. Depending upon the value of result after any arithmetic and log... |
How to Build a News App Using WebView Controller in Android Studio? - GeeksforGeeks | 05 Aug, 2021
In this article, we are going to make a News App with help of a WebView Controller in Android Studio. By making this application we will learn how to access Internet Permission in our android application and how to use WebView with its class named WebView Controller. After making this application you will also be aware of Navigation Drawer activity in android studio. So, let us start!
In this application, we are going to use the Navigation Drawer activity and set different fragments of different newspapers in it. In the fragments of navigation drawer, we will use WebView to access the websites of the different news channels and at last, we will make a class WebView Controller so that, we can show all these websites in our own application rather than going to the browser. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
Open Android Studio and create a new project by selecting Navigation Drawer Activity. You will get many default files but you have to make changes only in those where we have to work.
Step 2: Working with XML files
Open layout > nav_header_main.xml file to design the header of our navigation drawer. For that use the following code in it-
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" android:layout_width="match_parent" android:layout_height="@dimen/nav_header_height" android:background="#201E1E" android:gravity="bottom" android:orientation="vertical" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:theme="@style/ThemeOverlay.AppCompat.Dark"> <ImageView android:id="@+id/imageView" android:layout_width="130dp" android:layout_height="110dp" android:layout_gravity="center" android:contentDescription="@string/nav_header_desc" android:foregroundGravity="center" android:paddingTop="@dimen/nav_header_vertical_spacing" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.0" app:srcCompat="@drawable/news_app_img" /> <TextView android:layout_width="wrap_content" android:layout_height="51dp" android:layout_gravity="center" android:gravity="center" android:paddingTop="@dimen/nav_header_vertical_spacing" android:text="News App" android:textAppearance="@style/TextAppearance.AppCompat.Body1" android:textColor="#F6F8CA" android:textSize="24sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.501" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="@+id/imageView" app:layout_constraintVertical_bias="1.0" /> </androidx.constraintlayout.widget.ConstraintLayout>
After implementing the above code UI of the header file will be like:
Open menu > activity_main_drawer.xml file and use the following code in it so that we can add different items to our navigation drawer and use their fragments.
XML
<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"> <group android:checkableBehavior="single"> <item android:id="@+id/nav_home" android:icon="@drawable/z" android:menuCategory="secondary" android:title="Zee News" /> <item android:id="@+id/nav_gallery" android:icon="@drawable/t1" android:menuCategory="secondary" android:title="Times Of India" /> <item android:id="@+id/nav_slideshow" android:icon="@drawable/h" android:menuCategory="secondary" android:title="Hindustan Times" /> </group> </menu>
After implementation of the following code design of the activity_main_drawer.xml file looks like
Change the color of the ActionBar to “#201E1E” so that it can match the color code of logo of our application and our UI can become more attractive. If you do not know how to change the color of the action bar then you can click here to learn it. Go to layout > activity_main.xml and use the following code in it.
XML
<?xml version="1.0" encoding="utf-8"?> <!-- DrawerLayout acts as top level container for window content that allows for interactive “drawer” views to be pulled out from one or both vertical edges of the window--> <androidx.drawerlayout.widget.DrawerLayout 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:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:openDrawer="start"> <!-- To reuse layouts include tag is used --> <include layout="@layout/app_bar_main" android:layout_width="match_parent" android:layout_height="match_parent" /> <!-- Navigation view to make navigation drawer --> <com.google.android.material.navigation.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:background="#FDF2D5" android:fitsSystemWindows="true" app:headerLayout="@layout/nav_header_main" app:menu="@menu/activity_main_drawer" /> </androidx.drawerlayout.widget.DrawerLayout>
After implementing the above code our UI looks like this
Go to the navigation > mobile_navigation.xml file and use the following code in it so that we can specify the title and label of our items and can easily use them in java files.
XML
<?xml version="1.0" encoding="utf-8"?><navigation 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:id="@+id/mobile_navigation" app:startDestination="@+id/nav_home"> <!--These fragments are made to work on all the items listed in navigation drawer so that there java files can be managed separately --> <!-- Fragment for Zee News--> <fragment android:id="@+id/nav_home" android:name="com.example.newsapp.ui.Home.HomeFragment" android:label="Zee News" tools:layout="@layout/fragment_home" /> <!-- Fragment for Times Of India--> <fragment android:id="@+id/nav_gallery" android:name="com.example.newsapp.ui.Gallery.GalleryFragment" android:label="Times Of India" tools:layout="@layout/fragment_gallery" /> <!-- Fragment for Hindustan Times--> <fragment android:id="@+id/nav_slideshow" android:name="com.example.newsapp.ui.Slideshow.SlideshowFragment" android:label="Hindustan Times" tools:layout="@layout/fragment_slideshow" /> </navigation>
Now it’s time to insert WebView in all the fragments. Open fragment_home, fragment_gallery, fragment_slideshow XML files and use the code respectively.
XML
XML
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".ui.Home.HomeFragment"> <!--WebView is added on full screen so that application interface can be interactive and user can the web content is visible on full screen --> <WebView android:id="@+id/web_view_zee" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
<?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=".ui.Gallery.GalleryFragment"> <WebView android:id="@+id/web_view_toi" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
<?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=".ui.Slideshow.SlideshowFragment"> <WebView android:id="@+id/web_view_hindustan" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Add internet permission in the manifest file
Now we have add a piece of code to take permission for access to the internet so that our WebView can work easily. Go to the manifests > AndroidManifest.xml file and add the following code to it.
<uses-permission android:name="android.permission.INTERNET" />
Step 4: Working with the java files
Create a new java class as shown below and name it as “WebViewController“
Use the following code in the WebViewController.java file so that code to use the URL of a website can be executed.
Java
import android.webkit.WebView;import android.webkit.WebViewClient; // class is extended to WebViewClient to access the WebView public class WebViewController extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // loadurl function will load the // url we will provide to our webview view.loadUrl(url); return true; }}
Now it’s time to work on java files of fragments. Open HomeFragment, GalleryFragment, SlideshowFragment java files and use the code respectively.
Java
Java
Java
package com.example.newsapp.ui.Home; import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.webkit.WebView; import androidx.annotation.NonNull;import androidx.fragment.app.Fragment;import androidx.lifecycle.ViewModelProvider; import com.example.newsapp.R;import com.example.newsapp.WebViewController; public class HomeFragment extends Fragment { private HomeViewModel homeViewModel; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class); View root = inflater.inflate(R.layout.fragment_home, container, false); // Created a WebView and used the loadurl method // to give url to WebView Controller class WebView webView = root.findViewById(R.id.web_view_zee); // Url of website is passed here webView.loadUrl("https://zeenews.india.com/"); // WebViewController is used webView.setWebViewClient(new WebViewController()); return root; }}
import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.webkit.WebView; import androidx.annotation.NonNull;import androidx.fragment.app.Fragment;import androidx.lifecycle.ViewModelProvider; import com.example.newsapp.R;import com.example.newsapp.WebViewController; public class GalleryFragment extends Fragment { private GalleryViewModel galleryViewModel; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { galleryViewModel = new ViewModelProvider(this).get(GalleryViewModel.class); View root = inflater.inflate(R.layout.fragment_gallery, container, false); WebView webView = root.findViewById(R.id.web_view_toi); webView.loadUrl("https://timesofindia.indiatimes.com/"); webView.setWebViewClient(new WebViewController()); return root; }}
import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.webkit.WebView; import androidx.annotation.NonNull;import androidx.fragment.app.Fragment;import androidx.lifecycle.ViewModelProvider; import com.example.newsapp.R;import com.example.newsapp.WebViewController; public class SlideshowFragment extends Fragment { private SlideshowViewModel slideshowViewModel; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { slideshowViewModel = new ViewModelProvider(this).get(SlideshowViewModel.class); View root = inflater.inflate(R.layout.fragment_slideshow, container, false); WebView webView = root.findViewById(R.id.web_view_hindustan); webView.loadUrl("https://www.hindustantimes.com/"); webView.setWebViewClient(new WebViewController()); return root; }}
Congratulations!! You have successfully completed this news application. You can also add more number fragments for more news channels(a small task for you as learning from this article) and make the app more informative. Here is the output of our application.
Output:
If you want to take help or import the project then you can visit the GitHub link: https://github.com/Karan-Jangir/News_app/tree/master
Hence, we made a news application that uses WebViewController to access the news channels’ websites and show them in our application very easily.
Android
GBlog
Java
Project
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
DSA Sheet by Love Babbar
Socket Programming in C/C++
GET and POST requests using Python
Must Do Coding Questions for Product Based Companies | [
{
"code": null,
"e": 26407,
"s": 26379,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 26795,
"s": 26407,
"text": "In this article, we are going to make a News App with help of a WebView Controller in Android Studio. By making this application we will learn how to access Intern... |
Python | Skipping Test Failures - GeeksforGeeks | 12 Jun, 2019
Problem – To skip or mark selected tests as an anticipated failure in the unit tests.
The unittest module has decorators that can be applied to selected test methods to control their handling as shown in the code given below.
Code #1 :
import unittestimport osimport platform class Tests(unittest.TestCase): def test_0(self): self.assertTrue(True) @unittest.skip('skipped test') def test_1(self): self.fail('should have failed !') @unittest.skipIf(os.name =='posix', 'Not supported on Unix') def test_2(self): import winreg @unittest.skipUnless(platform.system() == 'Darwin', 'Mac specific test') def test_3(self): self.assertTrue(True) @unittest.expectedFailure def test_4(self): self.assertEqual(2 + 2, 5) if __name__ == '__main__': unittest.main()
Output:
bash % python3 testsample.py -v
test_0 (__main__.Tests) ... ok
test_1 (__main__.Tests) ... skipped 'skipped test'
test_2 (__main__.Tests) ... skipped 'Not supported on Unix'
test_3 (__main__.Tests) ... ok
test_4 (__main__.Tests) ... expected failure
----------------------------------------------------------------------
Ran 5 tests in 0.002s
OK (skipped = 2, expected failures = 1)
How it works :
The skip() decorator can be used to skip over a test that need not be run at all.
skipIf() and skipUnless() can be a useful way to write tests that only apply to certain platforms or Python versions, or which have other dependencies.
Use the @expectedFailure decorator to mark tests that are known failures, but for which the test framework need not report more information.
Code #2 : Applying decorators for skipping methods to entire testing classes
@unittest.skipUnless(platform.system() == 'Darwin', 'Mac specific tests')class DarwinTests(unittest.TestCase): ...
python-utility
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
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n12 Jun, 2019"
},
{
"code": null,
"e": 25623,
"s": 25537,
"text": "Problem – To skip or mark selected tests as an anticipated failure in the unit tests."
},
{
"code": null,
"e": 25763,
"s": 25623,
"text": "The ... |
N-th multiple in sorted list of multiples of two numbers - GeeksforGeeks | 10 May, 2022
Given three positive integers a, b and n. Consider a list that has all multiples of ‘a’ and ‘b’. the list is sorted and duplicates are removed. The task is to find n-th element of the list.Examples :
Input : a = 3, b = 5, n = 5
Output : 10
a = 3 b = 5, Multiple of 3 are 3, 6, 9, 12, 15,... and
multiples of 5 are 5, 10, 15, 20,....
After deleting duplicate element and sorting:
3, 5, 6, 9, 10, 12, 15, 18, 20,....
The 5th element in the sequence is 10.
Input : n = 6, a = 2, b = 3
Output : 9
Method 1: (Brute Force) Generate the first ‘n’ multiple of ‘a’. Now, generate first ‘n’ multiple of b such that it do not belong to the first n multiple of ‘a’. This can be done using Binary Search.
C++
Java
Python3
C#
Javascript
PHP
// C++ program to find n-th number in the sorted// list of multiples of two numbers.#include<bits/stdc++.h>using namespace std; // Return the n-th number in the sorted// list of multiples of two numbers.int nthElement(int a, int b, int n){ vector<int> seq; // Generating first n multiple of a. for (int i = 1; i <= n; i++) seq.push_back(a*i); // Sorting the sequence. sort(seq.begin(), seq.end()); // Generating and storing first n multiple of b // and storing if not present in the sequence. for (int i = 1, k = n; i <= n && k; i++) { // If not present in the sequence if (!binary_search(seq.begin(), seq.end(), b*i)) { // Storing in the sequence. seq.push_back(b*i); sort(seq.begin(), seq.end()); k--; } } return seq[n - 1];} // Driven Programint main(){ int a = 3, b = 5, n = 5; cout << nthElement(a, b, n) << endl; return 0;}
// Java program to find n-th number// in the sorted list of multiples// of two numbers.import java.io.*;import java.util.*;class GFG{// Return the n-th number in the sorted// list of multiples of two numbers.static int nthElement(int a, int b, int n){ ArrayList<Integer> seq = new ArrayList<Integer>(n * n + 1); // Generating first n multiple of a. for (int i = 1; i <= n; i++) seq.add(a * i); // Sorting the sequence. Collections.sort(seq); // Generating and storing first n // multiple of b and storing if // not present in the sequence. for (int i = 1, k = n; i <= n && k > 0; i++) { // If not present in the sequence if (seq.indexOf(b * i) == -1) { // Storing in the sequence. seq.add(b * i); Collections.sort(seq); k--; } } return seq.get(n - 1);} // Driver Codepublic static void main(String[] args){ int a = 3, b = 5, n = 5; System.out.println(nthElement(a, b, n));}} // This code is contributed by mits
# Python3 program to find n-th# number in the sorted list of# multiples of two numbers. # Return the n-th number in the# sorted list of multiples of# two numbers.def nthElement(a, b, n): seq = []; # Generating first n # multiple of a. for i in range(1, n + 1): seq.append(a * i); # Sorting the sequence. seq.sort(); # Generating and storing first # n multiple of b and storing # if not present in the sequence. i = 1; k = n; while(i <= n and k > 0): # If not present in the sequence try: z = seq.index(b * i); except ValueError: # Storing in the sequence. seq.append(b * i); seq.sort(); k -= 1; i += 1; return seq[n - 1]; # Driver Codea = 3;b = 5;n = 5;print(nthElement(a, b, n)); # This code is contributed by mits
// C# program to find n-th number// in the sorted list of multiples// of two numbers.using System;using System.Collections; class GFG{// Return the n-th number in the sorted// list of multiples of two numbers.static int nthElement(int a, int b, int n){ ArrayList seq = new ArrayList(); // Generating first n multiple of a. for (int i = 1; i <= n; i++) seq.Add(a * i); // Sorting the sequence. seq.Sort(); // Generating and storing first n // multiple of b and storing if // not present in the sequence. for (int i = 1, k = n; i <= n && k > 0; i++) { // If not present in the sequence if (!seq.Contains(b * i)) { // Storing in the sequence. seq.Add(b * i); seq.Sort(); k--; } } return (int)seq[n - 1];} // Driver Codestatic void Main(){ int a = 3, b = 5, n = 5; Console.WriteLine(nthElement(a, b, n));}} // This code is contributed by mits
<script> // Javascript program to find n-th number // in the sorted list of multiples // of two numbers. // Return the n-th number in the sorted // list of multiples of two numbers. function nthElement(a, b, n) { let seq = []; // Generating first n multiple of a. for (let i = 1; i <= n; i++) seq.push(a * i); // Sorting the sequence. seq.sort(function(a, b){return a - b}); // Generating and storing first n // multiple of b and storing if // not present in the sequence. for (let i = 1, k = n; i <= n && k > 0; i++) { // If not present in the sequence if (!seq.includes(b * i)) { // Storing in the sequence. seq.push(b * i); seq.sort(function(a, b){return a - b}); k--; } } return seq[n - 1]; } let a = 3, b = 5, n = 5; document.write(nthElement(a, b, n)); // This code is contributed by decode2207.</script>
<?php// PHP program to find n-th number// in the sorted list of multiples// of two numbers. // Return the n-th number in the sorted// list of multiples of two numbers.function nthElement($a, $b, $n){ $seq = array(); // Generating first n multiple of a. for ($i = 1; $i <= $n; $i++) array_push($seq, $a * $i); // Sorting the sequence. sort($seq); // Generating and storing first // n multiple of b and storing // if not present in the sequence. for ($i = 1, $k = $n; $i <= $n && $k > 0; $i++) { // If not present in the sequence if (array_search($b * $i, $seq) == 0) { // Storing in the sequence. array_push($seq, $b * $i); sort($seq); $k--; } } return $seq[$n - 1];} // Driver Code$a = 3;$b = 5;$n = 5;echo nthElement($a, $b, $n); // This code is contributed by mits?>
Output:
10
Method 2: (Efficient Approach) The idea is to use the fact that common multiple of a and b are removed using LCM(a, b). Let f(a, b, x) be a function which calculates the count of number that are less than x and multiples of a and b. Now, using the inclusion-exclusion principle we can say,
f(a, b, x) : Count of number that are less than x
and multiples of a and b
f(a, b, x) = (x/a) + (x/b) - (x/lcm(a, b))
where (x/a) define number of multiples of a
(x/b) define number of multiple of b
(x/lcm(a, b)) define the number of common multiples
of a and b.
Observe, a and b are constant. As x increases, f(a, b, x) will also increase. Therefore we can apply Binary Search to find the minimum value of x such that f(a, b, x) >= n. The lower bound of the function is the required answer.The upper bound for n-th term would be min(a, b)*n. Note that we get the largest value n-th term when there are no common elements in multiples of a and b.Below are the implementations of above approach:
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to find n-th number in the// sorted list of multiples of two numbers.#include<bits/stdc++.h>using namespace std; // Return the Nth number in the sorted// list of multiples of two numbers.int nthElement(int a, int b, int n){ // Finding LCM of a and b. int lcm = (a * b)/__gcd(a,b); // Binary Search. int l = 1, r = min(a, b)*n; while (l <= r) { // Finding the middle element. int mid = (l + r)>>1; // count of number that are less than // mid and multiples of a and b int val = mid/a + mid/b - mid/lcm; if (val == n) return max((mid/a)*a, (mid/b)*b); if (val < n) l = mid + 1; else r = mid - 1; }} // Driven Programint main(){ int a = 5, b = 3, n = 5; cout << nthElement(a, b, n) << endl; return 0;}
// Java program to find n-th number in the// sorted list of multiples of two numbers.import java.io.*; public class GFG{ // Recursive function to return// gcd of a and bstatic int __gcd(int a, int b){ // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a);} // Return the Nth number in the sorted// list of multiples of two numbers.static int nthElement(int a, int b, int n){ // Finding LCM of a and b. int lcm = (a * b) / __gcd(a, b); // Binary Search. int l = 1, r = Math.min(a, b) * n; while (l <= r) { // Finding the middle element. int mid = (l + r) >> 1; // count of number that are less than // mid and multiples of a and b int val = mid / a + mid / b - mid / lcm; if (val == n) return Math.max((mid / a) * a, (mid / b) * b); if (val < n) l = mid + 1; else r = mid - 1; } return 0;} // Driver Codestatic public void main (String[] args){ int a = 5, b = 3, n = 5; System.out.println(nthElement(a, b, n));}} // This code is contributed by vt_m.
# Python 3 program to find n-th number# in the sorted list of multiples of# two numbers.import math # Return the Nth number in the sorted# list of multiples of two numbers.def nthElement(a, b, n): # Finding LCM of a and b. lcm = (a * b) / int(math.gcd(a, b)) # Binary Search. l = 1 r = min(a, b) * n while (l <= r): # Finding the middle element. mid = (l + r) >> 1 # count of number that are less # than mid and multiples of a # and b val = (int(mid / a) + int(mid / b) - int(mid / lcm)) if (val == n): return int( max(int(mid / a) * a, int(mid / b) * b) ) if (val < n): l = mid + 1 else: r = mid - 1 # Driven Programa = 5b = 3n = 5print(nthElement(a, b, n)) # This code is contributed by Smitha.
// C# program to find n-th number in the// sorted list of multiples of two numbers.using System; public class GFG{ // Recursive function to return// gcd of a and bstatic int __gcd(int a, int b){ // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a);} // Return the Nth number in the sorted// list of multiples of two numbers.static int nthElement(int a, int b, int n){ // Finding LCM of a and b. int lcm = (a * b) / __gcd(a, b); // Binary Search. int l = 1, r = Math.Min(a, b) * n; while (l <= r) { // Finding the middle element. int mid = (l + r) >> 1; // count of number that are less than // mid and multiples of a and b int val = mid / a + mid / b - mid / lcm; if (val == n) return Math.Max((mid / a) * a, (mid / b) * b); if (val < n) l = mid + 1; else r = mid - 1; } return 0;} // Driver Code static public void Main (String []args) { int a = 5, b = 3, n = 5; Console.WriteLine(nthElement(a, b, n)); }} // This code is contributed by vt_m.
<?php// PHP program to find n-th number// in a sorted list of multiples// of two numbers. // function to calculate gcdfunction gcd($a, $b){ return ($a % $b) ? gcd($b, $a % $b) : $b;} // Return the Nth number in the sorted// list of multiples of two numbers.function nthElement($a, $b, $n){ // Finding LCM of a and b. $lcm = (int)(($a * $b) / gcd($a, $b)); // Binary Search. $l = 1; $r = min($a, $b) * $n; while ($l <= $r) { // Finding the middle element. $mid = ($l + $r) >> 1; // count of number that are // less than mid and multiples // of a and b $val = (int)($mid / $a) + (int)($mid / $b) - (int)($mid / $lcm); if ($val == $n) return max((int)(($mid / $a)) * $a, (int)(($mid / $b)) * $b); if ($val < $n) $l = $mid + 1; else $r = $mid - 1; }} // Driver code$a = 5;$b = 3;$n = 5;echo nthElement($a, $b, $n); // This code is contributed by mits?>
<script> // Javascript program to find n-th number in the// sorted list of multiples of two numbers. // Recursive function to return// gcd of a and bfunction __gcd(a , b){ // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a);} // Return the Nth number in the sorted// list of multiples of two numbers.function nthElement(a , b , n){ // Finding LCM of a and b. var lcm = parseInt((a * b) / __gcd(a, b)); // Binary Search. var l = 1, r = Math.min(a, b) * n; while (l <= r) { // Finding the middle element. var mid = (l + r) >> 1; // count of number that are less than // mid and multiples of a and b var val = parseInt(mid / a) + parseInt(mid / b) - parseInt(mid / lcm); if (val == n) return Math.max(parseInt(mid / a) * a, parseInt(mid / b) * b); if (val < n) l = mid + 1; else r = mid - 1; } return 0;} // Driver Codevar a = 5, b = 3, n = 5;document.write(nthElement(a, b, n)); // This code contributed by shikhasingrajput </script>
Output:
10
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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.
vt_m
Smitha Dinesh Semwal
Mithun Kumar
shikhasingrajput
decode2207
simmytarika5
surinderdawra388
GCD-LCM
Mathematical
Mathematical
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
Prime Numbers
Print all possible combinations of r elements in a given array of size n
The Knight's tour problem | Backtracking-1
Operators in C / C++
Program for factorial of a number
Find minimum number of coins that make a given value
Program to find sum of elements in a given array
Minimum number of jumps to reach end | [
{
"code": null,
"e": 25929,
"s": 25901,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 26132,
"s": 25929,
"text": "Given three positive integers a, b and n. Consider a list that has all multiples of ‘a’ and ‘b’. the list is sorted and duplicates are removed. The task is to fin... |
Minimize the difference between minimum and maximum elements - GeeksforGeeks | 13 May, 2021
Given an array of integers and an integer . It is allowed to modify an element either by increasing or decreasing them by k (only once).The task is to minimize and print the maximum difference between the shortest and longest towers.Examples:
Input: arr[] = {1, 10, 8, 5}, k = 2
Output : Max height difference = 5
Explanation:
modified arr[]={3, 8, 6, 7}
max difference: 5
Input: arr[] = {3, 16, 12, 9, 20}, k = 3
Output : Max height difference: 11
Approach:
Find the max and min elements present in the array.Check whether the difference between the max and min element is less than or equal to k or not: If yes, then return the difference between the max and min element.otherwise, go to step 3.Calculate the average of the max and min elements of the array.Traverse the array and do the following operations: If the array element is greater than the average then decrease it by k.If the array element is smaller than the average then increase it by k.Return the difference between the max and min elements of the modified array.
Find the max and min elements present in the array.
Check whether the difference between the max and min element is less than or equal to k or not: If yes, then return the difference between the max and min element.otherwise, go to step 3.
If yes, then return the difference between the max and min element.
otherwise, go to step 3.
Calculate the average of the max and min elements of the array.
Traverse the array and do the following operations: If the array element is greater than the average then decrease it by k.If the array element is smaller than the average then increase it by k.
If the array element is greater than the average then decrease it by k.
If the array element is smaller than the average then increase it by k.
Return the difference between the max and min elements of the modified array.
Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to minimize the difference between// minimum and maximum elements #include <bits/stdc++.h>using namespace std; // Function to minimize the difference between// minimum and maximum elementsint minimizeDiff(int* arr, int n, int k){ // Find max and min elements of the array int max = *(max_element(arr, arr + n)); int min = *(min_element(arr, arr + n)); // Check whether the difference between // the max and min element is less than // or equal to k or not if ((max - min) <= k) { return (max - min); } // Calculate average of max and min int avg = (max + min) / 2; for (int i = 0; i < n; i++) { // If the array element is greater than the // average then decrease it by k if (arr[i] > avg) arr[i] -= k; // If the array element is smaller than the // average then increase it by k else arr[i] += k; } // Find max and min of the modified array max = *(max_element(arr, arr + n)); min = *(min_element(arr, arr + n)); // return the new difference return (max - min);} // Driver codeint main(){ int arr[] = { 3, 16, 12, 9, 20 }; int n = 5; int k = 3; cout << "Max height difference = " << minimizeDiff(arr, n, k) << endl; return 0;}
// Java program to minimize the difference between// minimum and maximum elementsimport java.util.*; class GFG{ // Function to minimize the difference between // minimum and maximum elements static int minimizeDiff(int[] arr, int n, int k) { // Find max and min elements of the array int max = Arrays.stream(arr).max().getAsInt(); int min = Arrays.stream(arr).min().getAsInt(); // Check whether the difference between // the max and min element is less than // or equal to k or not if ((max - min) <= k) { return (max - min); } // Calculate average of max and min int avg = (max + min) / 2; for (int i = 0; i < n; i++) { // If the array element is greater than the // average then decrease it by k if (arr[i] > avg) { arr[i] -= k; } // If the array element is smaller than the // average then increase it by k else { arr[i] += k; } } // Find max and min of the modified array max = Arrays.stream(arr).max().getAsInt(); min = Arrays.stream(arr).min().getAsInt(); // return the new difference return (max - min); } // Driver code public static void main(String[] args) { int arr[] = {3, 16, 12, 9, 20}; int n = 5; int k = 3; System.out.println("Max height difference = " + minimizeDiff(arr, n, k)); }} // This code has been contributed by 29AjayKumar
# Python 3 program to minimize the# difference between minimum and# maximum elements # Function to minimize the difference# between minimum and maximum elementsdef minimizeDiff(arr, n, k) : # Find max and min elements # of the array max_element = max(arr) min_element = min(arr) # Check whether the difference between # the max and min element is less than # or equal to k or not if ((max_element - min_element) <= k) : return (max_element - min_element) # Calculate average of max and min avg = (max_element + min_element) // 2 for i in range(n): # If the array element is greater than # the average then decrease it by k if (arr[i] > avg) : arr[i] -= k # If the array element is smaller than # the average then increase it by k else : arr[i] += k # Find max and min of the # modified array max_element = max(arr) min_element = min(arr) # return the new difference return (max_element - min_element); # Driver codeif __name__ == "__main__" : arr = [ 3, 16, 12, 9, 20 ] n = 5 k = 3 print("Max height difference =", minimizeDiff(arr, n, k)) # This code is contributed by Ryuga
// C# program to minimize the difference between// minimum and maximum elementsusing System;using System.Linq; class GFG{ // Function to minimize the difference between // minimum and maximum elements static int minimizeDiff(int[] arr, int n, int k) { // Find max and min elements of the array int max = arr.Max(); int min = arr.Min(); // Check whether the difference between // the max and min element is less than // or equal to k or not if ((max - min) <= k) { return (max - min); } // Calculate average of max and min int avg = (max + min) / 2; for (int i = 0; i < n; i++) { // If the array element is greater than the // average then decrease it by k if (arr[i] > avg) { arr[i] -= k; } // If the array element is smaller than the // average then increase it by k else { arr[i] += k; } } // Find max and min of the modified array max = arr.Max(); min = arr.Min(); // return the new difference return (max - min); } // Driver code public static void Main() { int []arr = {3, 16, 12, 9, 20}; int n = 5; int k = 3; Console.WriteLine("Max height difference = " + minimizeDiff(arr, n, k)); }} /* This code contributed by PrinciRaj1992 */
<?php// PHP program to minimize the difference// between minimum and maximum elements // Function to minimize the difference// between minimum and maximum elementsfunction minimizeDiff(&$arr, $n, $k){ // Find max and min elements // of the array $max = max($arr); $min = min($arr); // Check whether the difference between // the max and min element is less than // or equal to k or not if (($max - $min) <= $k) { return ($max - $min); } // Calculate average of max and min $avg = ($max + $min) / 2; for ($i = 0; $i < $n; $i++) { // If the array element is greater than // the average then decrease it by k if ($arr[$i] > $avg) $arr[$i] -= $k; // If the array element is smaller than // the average then increase it by k else $arr[$i] += $k; } // Find max and min of the // modified array $max = max($arr); $min = min($arr); // return the new difference return ($max - $min);} // Driver code$arr = array( 3, 16, 12, 9, 20 );$n = 5;$k = 3; echo "Max height difference = " . minimizeDiff($arr, $n, $k). "\n"; // This code is contributed by ita_c?>
<script> // Javascript program to minimize// the difference between// minimum and maximum elements // Function to minimize the difference between // minimum and maximum elements function minimizeDiff(arr,n,k) { // Find max and min elements of the array let max = Math.max(...arr); let min = Math.min(...arr); // Check whether the difference between // the max and min element is less than // or equal to k or not if ((max - min) <= k) { return (max - min); } // Calculate average of max and min let avg = Math.floor((max + min) / 2); for (let i = 0; i < n; i++) { // If the array element is greater than the // average then decrease it by k if (arr[i] > avg) { arr[i] -= k; } // If the array element is smaller than the // average then increase it by k else { arr[i] += k; } } // Find max and min of the modified array max = Math.max(...arr); min = Math.min(...arr); // return the new difference return (max - min); } // Driver code let arr=[3, 16, 12, 9, 20]; let n = 5; let k = 3; document.write("Max height difference = " + minimizeDiff(arr, n, k)); // This code is contributed by avanitrachhadiya2155 </script>
Max height difference = 11
Time Complexity: O( N )
ankthon
ukasp
29AjayKumar
princiraj1992
avanitrachhadiya2155
Technical Scripter 2018
Arrays
Greedy
Technical Scripter
Arrays
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3 | [
{
"code": null,
"e": 26121,
"s": 26093,
"text": "\n13 May, 2021"
},
{
"code": null,
"e": 26366,
"s": 26121,
"text": "Given an array of integers and an integer . It is allowed to modify an element either by increasing or decreasing them by k (only once).The task is to minimize and... |
Python del to delete objects - GeeksforGeeks | 29 Apr, 2020
The del keyword in python is primarily used to delete objects in Python. Since everything in python represents an object in one way or another, The del keyword can also be used to delete a list, slice a list, delete a dictionaries, remove key-value pairs from a dictionary, delete variables, etc.
Syntax: del object_name
Below are various examples that show-case various use-cases of the del keyword:
1. del keyword for deleting objects
Example:In the program below we will deleted Sample_class using del Sample_class statement.
class Sample_class: some_variable = 20 # method of the class def my_method(self): print("GeeksForGeeks") # check if class existsprint(Sample_class) # delete the class using del keyworddel Sample_class # check if class existsprint(Sample_class)
Output:
class '__main__.Sample_class'
NameError:name 'Sample_class' is not defined
1. del keyword for deleting variables
Example:In the program below we will delete a variable using del keyword.
my_variable1 = 20my_variable2 = "GeeksForGeeks" # check if my_variable1 and my_variable2 existsprint(my_variable1)print(my_variable2) # delete both the variablesdel my_variable1del my_variable2 # check if my_variable1 and my_variable2 existsprint(my_variable1)print(my_variable2)
Output:
20
GeeksForGeeks
20
NameError: name 'my_variable2' is not defined
1. del keyword for deleting list and list slicing
Example:In the program below we will delete a list and slice another list using del keyword.
my_list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]my_list2 =["Geeks", "For", "Geek"] # check if my_list1 and my_list2 existsprint(my_list1)print(my_list2) # delete second element of my_list1del my_list1[1] # check if the second element in my_list1 is deletedprint(my_list1) # slice my_list1 from index 3 to 5del my_list1[3:5] # check if the elements from index 3 to 5 in my_list1 is deletedprint(my_list1) # delete my_list2del my_list2 # check if my_list2 existsprint(my_list2)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
['Geeks', 'For', 'Geek']
[1, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 4, 7, 8, 9]
NameError: name 'my_list2' is not defined
1. del keyword for deleting dictionaries and removing key-value pairs
Example:In the program below we will delete a dictionary and remove few key-value pairs using del keyword.
my_dict1 = {"small": "big", "black": "white", "up": "down"}my_dict2 = {"dark": "light", "fat": "thin", "sky": "land"} # check if my_dict1 and my_dict2 existsprint(my_dict1)print(my_dict2) # delete key-value pair with key "black" from my_dict1del my_dict1["black"] # check if the key-value pair with key "black" from my_dict1 is deletedprint(my_dict1) # delete my_dict2del my_dict2 # check if my_dict2 existsprint(my_dict2)
Output:
{'small': 'big', 'black': 'white', 'up': 'down'}
{'dark': 'light', 'fat': 'thin', 'sky': 'land'}
{'small': 'big', 'up': 'down'}
NameError: name 'my_dict2' is not defined
Please refer delattr() and del() for more details.
python-basics
Python-Data Type
Python-datatype
Python
Write From Home
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
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python | [
{
"code": null,
"e": 25357,
"s": 25329,
"text": "\n29 Apr, 2020"
},
{
"code": null,
"e": 25654,
"s": 25357,
"text": "The del keyword in python is primarily used to delete objects in Python. Since everything in python represents an object in one way or another, The del keyword can... |
turtle.turtlesize() function in Python - GeeksforGeeks | 26 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to return or set the pen’s attributes x or y-stretchfactors and outline.
Syntax :
turtle.turtlesize(stretch_wid=None, stretch_len=None, outline=None)
Parameters:
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle # set turtleturtle.speed(1)turtle.shape("turtle")turtle.fillcolor("blue") # loop for motionfor i in range(4): # set turtle width turtle.turtlesize(stretch_wid=(i+1)*0.5) turtle.forward(100) turtle.right(90)
Output :
Example 2 :
Python3
# import packageimport turtle # set turtleturtle.speed(1)turtle.shape("turtle")turtle.fillcolor("blue") # loop for motionfor i in range(4): # set turtle length turtle.turtlesize(stretch_len=(i+1)*0.5) turtle.forward(100) turtle.right(90)
Output :
Example 3 :
Python3
# import packageimport turtle # set turtleturtle.speed(1)turtle.shape("turtle")turtle.fillcolor("blue") # loop for motionfor i in range(4): # set turtle outline turtle.turtlesize(outline=i+1) turtle.forward(100) turtle.right(90)
Output :
Example 4 :
Python3
# import packageimport turtle # set turtleturtle.speed(1)turtle.shape("turtle")turtle.fillcolor("blue") # loop for motionfor i in range(4): # set turtlesize properties all together turtle.turtlesize(stretch_wid=(i+1)*0.5, stretch_len=(i+1)*0.5, outline=(i+1) ) turtle.forward(100) turtle.right(90)
Output :
Python-turtle
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": "\n26 Jul, 2020"
},
{
"code": null,
"e": 25754,
"s": 25537,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it... |
Find the sum of Eigen Values of the given N*N matrix - GeeksforGeeks | 10 May, 2021
Given an N*N matrix mat[][], the task is to find the sum of Eigen values of the given matrix.Examples:
Input: mat[][] = { {2, -1, 0}, {-1, 2, -1}, {0, -1, 2}} Output: 6Input: mat[][] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} Output: 34
Approach: The sum of Eigen values of a matrix is equal to the trace of the matrix. The trace of an n × n square matrix A is defined to be the sum of the elements on the main diagonal (the diagonal from the upper left to the lower right) of A.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;#define N 4 // Function to return the sum of eigen// values of the given matrixint sumEigen(int mat[N][N]){ int sum = 0; // Calculate the sum of // the diagonal elements for (int i = 0; i < N; i++) sum += (mat[i][i]); return sum;} // Driver codeint main(){ int mat[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; cout << sumEigen(mat); return 0;}
// Java implementation of the approachimport java.io.*; class GFG{ static int N = 4; // Function to return the sum of eigen// values of the given matrixstatic int sumEigen(int mat[][]){ int sum = 0; // Calculate the sum of // the diagonal elements for (int i = 0; i < N; i++) sum += (mat[i][i]); return sum;} // Driver codepublic static void main (String[] args){ int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; System.out.println (sumEigen(mat));}} // The code is contributed by Tushil..
# Python3 implementation of the approach N=4 # Function to return the sum of eigen# values of the given matrixdef sumEigen(mat): sum = 0 # Calculate the sum of # the diagonal elements for i in range(N): sum += (mat[i][i]) return sum # Driver codemat= [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ] print(sumEigen(mat)) # This code is contributed by mohit kumar 29
// C# implementation of the approachusing System; class GFG{ static int N = 4; // Function to return the sum of eigen// values of the given matrixstatic int sumEigen(int [,]mat){ int sum = 0; // Calculate the sum of // the diagonal elements for (int i = 0; i < N; i++) sum += (mat[i,i]); return sum;} // Driver codestatic public void Main (){ int [,]mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; Console.Write(sumEigen(mat));}} // The code is contributed by ajit...
<script> // Javascript implementation of the approachvar N = 4; // Function to return the sum of eigen// values of the given matrixfunction sumEigen(mat){ var sum = 0; // Calculate the sum of // the diagonal elements for (var i = 0; i < N; i++) sum += (mat[i][i]); return sum;} // Driver codevar mat = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ];document.write( sumEigen(mat)); </script>
34
mohit kumar 29
jit_t
rutvik_56
school-programming
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Efficiently compute sums of diagonals of a matrix
Flood fill Algorithm - how to implement fill() in paint?
Zigzag (or diagonal) traversal of Matrix
Mathematics | L U Decomposition of a System of Linear Equations
Python program to add two Matrices
Unique paths in a Grid with Obstacles
A Boolean Matrix Question
Breadth First Traversal ( BFS ) on a 2D array
Implementation of BFS using adjacency matrix
Check for possible path in 2D matrix | [
{
"code": null,
"e": 26141,
"s": 26113,
"text": "\n10 May, 2021"
},
{
"code": null,
"e": 26246,
"s": 26141,
"text": "Given an N*N matrix mat[][], the task is to find the sum of Eigen values of the given matrix.Examples: "
},
{
"code": null,
"e": 26406,
"s": 26246... |
How to Design Digital Clock using JavaScript ? - GeeksforGeeks | 30 Jul, 2021
Clocks are useful element for any UI if used in a proper way. Clocks can be used in sites where time is the main concern like some booking sites or some app showing arriving times of train, buses, flights, etc. Clock is basically of two types, Analog and Digital. We will be looking at making a digital one.
Approach: The approach is to use the date object to get time on every secondand then re-rendering time on the browser using the new time that we got by calling the same function each second.
HTML Code: In this section, we have a dummy time in the format of “HH:MM:SS” wrapped inside a “div” tag.
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Digital Clock</title> <link rel="stylesheet" href="clock2.css"></head><body> <div id="clock">8:10:45</div> <script src="clock2.js"></script></body></html>
CSS Code: For CSS, we have just aligned our clock to the center of the page. Other than that, it is just some font-size and width which you can adjust according to your need.
#clock { font-size: 175px; width: 900px; margin: 200px; text-align: center; border: 2px solid black; border-radius: 20px;}
JavaScript Code: For JavaScript, follow the below given steps.
Step 1: Create a function “showTime”.
Step 2: Create an instance of the Date object.
Step 3: Using the methods of Date object get “hours”, “minute” and “seconds”.
Step 4: Set AM/PM depending on the hour value. The Date object works on 24-hour format so we change hour back to 1 when it get’s larger than 12. The AM/PM also changes according to that.
Step 5: Now make a string using the same HH:MM:SS format changing the hour, minute, and second value with the values, we get from Date object methods.
Step 6: Now replace the string variable in the “div” using innerHTML property.
Step 7: To call the function every second use setInterval() method and set time-interval as 1000ms which is equal to 1s.
Step 8: Now call the function at the end to start function at exact reloading/rendering time as setInterval() will call first after 1s of rendering.
Note: You can use digital fonts available online to make the clock look more beautiful. For that, you have to download their file into your project and then use the “font-face” property to use that custom font.
setInterval(showTime, 1000);function showTime() { let time = new Date(); let hour = time.getHours(); let min = time.getMinutes(); let sec = time.getSeconds(); am_pm = "AM"; if (hour > 12) { hour -= 12; am_pm = "PM"; } if (hour == 0) { hr = 12; am_pm = "AM"; } hour = hour < 10 ? "0" + hour : hour; min = min < 10 ? "0" + min : min; sec = sec < 10 ? "0" + sec : sec; let currentTime = hour + ":" + min + ":" + sec + am_pm; document.getElementById("clock") .innerHTML = currentTime;}showTime();
Complete Code: It is the combination of the above three sections of code.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title>Digital Clock</title> <style> #clock { font-size: 175px; width: 900px; margin: 200px; text-align: center; border: 2px solid black; border-radius: 20px; } </style></head> <body> <div id="clock">8:10:45</div> <script> setInterval(showTime, 1000); function showTime() { let time = new Date(); let hour = time.getHours(); let min = time.getMinutes(); let sec = time.getSeconds(); am_pm = "AM"; if (hour > 12) { hour -= 12; am_pm = "PM"; } if (hour == 0) { hr = 12; am_pm = "AM"; } hour = hour < 10 ? "0" + hour : hour; min = min < 10 ? "0" + min : min; sec = sec < 10 ? "0" + sec : sec; let currentTime = hour + ":" + min + ":" + sec + am_pm; document.getElementById("clock") .innerHTML = currentTime; } showTime(); </script></body> </html>
Output:
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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 ?
Types of CSS (Cascading Style Sheet)
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": 37892,
"s": 37864,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 38200,
"s": 37892,
"text": "Clocks are useful element for any UI if used in a proper way. Clocks can be used in sites where time is the main concern like some booking sites or some app showin... |
JSON with Python | This chapter covers how to encode and decode JSON objects using Python programming language. Let's start with preparing the environment to start our programming with Python for JSON.
Before you start with encoding and decoding JSON using Python, you need to install any of the JSON modules available. For this tutorial we have downloaded and installed Demjson as follows −
$tar xvfz demjson-1.6.tar.gz
$cd demjson-1.6
$python setup.py install
Python encode() function encodes the Python object into a JSON string representation.
demjson.encode(self, obj, nest_level=0)
The following example shows arrays under JSON with Python.
#!/usr/bin/python
import demjson
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
json = demjson.encode(data)
print json
While executing, this will produce the following result −
[{"a":1,"b":2,"c":3,"d":4,"e":5}]
Python can use demjson.decode() function for decoding JSON. This function returns the value decoded from json to an appropriate Python type.
demjson.decode(self, txt)
The following example shows how Python can be used to decode JSON objects.
#!/usr/bin/python
import demjson
json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
text = demjson.decode(json)
print text
On executing, it will produce the following result −
{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}
20 Lectures
1 hours
Laurence Svekis
16 Lectures
1 hours
Laurence Svekis
10 Lectures
1 hours
Laurence Svekis
23 Lectures
2.5 hours
Laurence Svekis
9 Lectures
48 mins
Nilay Mehta
18 Lectures
2.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1963,
"s": 1780,
"text": "This chapter covers how to encode and decode JSON objects using Python programming language. Let's start with preparing the environment to start our programming with Python for JSON."
},
{
"code": null,
"e": 2153,
"s": 1963,
"text": ... |
Machine Learning with Python: Easy and robust method to fit nonlinear data | by Tirthajyoti Sarkar | Towards Data Science | Nonlinear data modeling is a routine task in data science and analytics domain. It is extremely rare to find a natural process whose outcome varies linearly with the independent variables. Therefore, we need an easy and robust methodology to quickly fit a measured data set against a set of variables assuming that the measured data could be a complex nonlinear function. This should be a fairly common tool in the repertoire of a data scientist or machine learning engineer.
There are a few pertinent questions to consider:
How do I decide what order of polynomial to try to fit? Do I need to include cross-coupling terms for multivariate regression? Is there an easy way to automate the process?
How to ensure I don’t overfit to the data?
Is my machine learning model robust against measurement noise?
Is my model easily scalable to higher dimensions and/or to bigger data set?
“Can I plot the data and take a quick peek?”
That is OK only when one can visualize the data clearly (feature dimension is 1 or 2). It is a lot tougher for feature dimensions 3 or higher. And it’s a complete waste of time if there is cross-coupling within the features influencing the outcome. Let me show this by plots,
It is easy to see that plotting only takes you so far. For a high-dimensional mutually-interacting data set, you can draw completely wrong conclusion if you try to look at the output vs. one input variable plot at a time. And, there is no easy way to visualize more than 2 variables at a time. So, we must resort to some kind of machine learning technique to fir a multi-dimensional dataset.
Actually, there are quite a few nice solutions out there.
Linear regression should be the first tool to look up and before you scream “...but these are highly nonlinear data sets...”, let us remember that the ‘LINEAR’ in linear regression model refers to the coefficients, and not to the degree of the features. Features (or independent variables) can be of any degree or even transcendental functions like exponential, logarithmic, sinusoidal. And, a surprisingly large body of natural phenomena can be modeled (approximately) using these transformations and linear model.
So, let’s say we get the following data set which has a single output and 3 features. We show the plots again, but, as expected, they don’t help much.
Therefore, we decide to learn a linear model with up to some high degree polynomial terms to fit a data set. Few questions immediately spring up:
— how to decide up to what polynomials are necessary
— when to stop if we start by incorporating 1st degree, 2nd degree, 3rd-degree terms one by one?
— how to decide if any of the cross-coupled terms are important i.e. do we only need X12, X23 or X1.X2 and X12.X3 terms also?
— And finally, do we have to manually write equations/functions for all these polynomial transformations and add them to the data set?
Fortunately, scikit-learn, the awesome machine learning library, offers ready-made classes/objects to answer all of the above questions in an easy and robust way.
Here is a simple video of the overview of linear regression using scikit-learn and here is a nice Medium article for your review. But we are going to cover much more than a simple linear fit in this article, so please read on. Entire boilerplate code for this article is available here on my GitHub repo.
We start by importing few relevant classes from scikit-learn,
# Import function to create training and test set splitsfrom sklearn.cross_validation import train_test_split# Import function to automatically create polynomial features! from sklearn.preprocessing import PolynomialFeatures# Import Linear Regression and a regularized regression functionfrom sklearn.linear_model import LinearRegressionfrom sklearn.linear_model import LassoCV# Finally, import function to make a machine learning pipelinefrom sklearn.pipeline import make_pipeline
Let us quickly define/recap the required concepts which we are going to use/implement next.
Train/Test split: This means creating two data sets from the single set we have. One of them (Training set) will be used to construct the model and another one (Test set) will be solely used to test the accuracy and robustness of the model. This is essential for any machine learning task, so that we don’t create model with all of our data and think the model is highly accurate (because it has ‘seen’ all the data and fitted nicely) but it performs badly when confronted with new (‘unseen’) data in the real world. Accuracy on the test set matters much more than the accuracy on training set. Here is a nice Medium article on this whole topic for your review. And below you can watch Google Car pioneer Sebastian Thrun talking about this concept.
Automatic polynomial feature generation: Scikit-learn offers a neat way to generate polynomial features from a set of linear features. All you have to do is to pass on the linear features in a list and specify the maximum degree up to which you want the polynomial degree terms to be generated. It also gives you choice to generate all the cross-coupling interaction terms or only the polynomial degrees of the main features. Here is an example Python code description.
Regularized regression: Importance of regularization cannot be overstated as it is a central concept in machine learning. In a linear regression setting, the basic idea is to penalize the model coefficients such that they don’t grow too big and overfit the data i.e. make the model extremely sensitive to noise in the data. There are two types of widely used regularization methods, of which we are using a method called LASSO. Here is a nice overview on both type of regularization methods.
Machine learning pipeline: A machine learning project is (almost) never a single modeling task. In its most common form, it consists of data generation/ingestion, data cleaning and transformation, model(s) fitting, cross-validation, model accuracy testing, and final deployment. Here is a Quora answer nicely summarizing the concept. Or, here is a related Medium article. Or, another nice article discussing the importance of pipeline practice. Scikit-learn offers a pipeline feature which can stack multiple models and data pre-processing classes together and turn your raw data into usable models.
If you have time, watch this long (1 hour +) video from PyData conference (Dallas, 2015) to see all of it in action.
So, here is the boilerplate code snapshot. You must modify it to run properly for your data set.
# Alpha (regularization strength) of LASSO regressionlasso_eps = 0.0001lasso_nalpha=20lasso_iter=5000# Min and max degree of polynomials features to considerdegree_min = 2degree_max = 8# Test/train splitX_train, X_test, y_train, y_test = train_test_split(df['X'], df['y'],test_size=test_set_fraction)# Make a pipeline model with polynomial transformation and LASSO regression with cross-validation, run it for increasing degree of polynomial (complexity of the model)for degree in range(degree_min,degree_max+1): model = make_pipeline(PolynomialFeatures(degree, interaction_only=False), LassoCV(eps=lasso_eps,n_alphas=lasso_nalpha,max_iter=lasso_iter,normalize=True,cv=5)) model.fit(X_train,y_train) test_pred = np.array(model.predict(X_test)) RMSE=np.sqrt(np.sum(np.square(test_pred-y_test))) test_score = model.score(X_test,y_test)
But hey, a code is for machines! For the mere human, we need sticky notes. So, here is the annotated version of the same with notes and comments :)
To distill it down further, here is the flow in more formal terms...
For all the models, we also capture the test error, train error (root-mean-square), and the customary R2 coefficient as the measure of model accuracy. Here is how they look like after we plot,
These plots are answering two of our earlier questions:
We do need 4th or 5th-degree polynomial to model this phenomena. Linear, quadratic, or even cubic models are not sufficiently complex for fitting the data.
However, we should not need to go beyond the 5th degree and over-complicate the model. Think this of an Occam’s Razor boundary for our model.
But, hey, where is the familiar bias/variance trade-off (aka underfit/overfit) shape in this curve? Why doesn’t the test error go up sharply for overly complex models?
The answer lies in the fact that using LASSO regression, we are essentially eliminating the higher-order terms in the more complex models. For more details, and some fantastic intuitive reasoning of why that happens, please read this article or watch the following video. This is, in fact, one of the key advantages of LASSO regression or L1-norm penalty, that it sets some of the model coefficients to exactly zero instead of just shrinking them. Effectively, this does the ‘automatic feature selection’ for you i.e. lets you automatically ignore the unimportant features even if you start with a highly complex model to fit the data.
We can easily test this by NOT doing the regularization and using a simple linear regression model class from scikit-learn. Here is the result in that case. The familiar bias-variance shape is showing up for the model complexity vs. error plot.
You can download my code and try changing the noise_magnitude parameter to see the impact of adding noise to the data set. Noise makes it hard for the model to be bias-free and it also pushes the model towards overfitting because the model tries to make sense of the noisy data patterns and instead of discovering the real pattern, it fits itself to the noise. Basically, the simple linear regression model (w/o regularization) can fail miserably in this condition. The regularized model still fares well but the bias-variance trade-off starts showing up for even the regularized model performance. Here is the summary,
So, in short, we discussed a methodical way to fit multi-variate regression models to a data set with highly non-linear and mutually coupled terms, in the presence of noise. We saw how we can take advantage of Python machine learning library to generate polynomial features, normalize the data, fit the model, keep the coefficients from becoming too large thereby maintaining bias-variance trade-off, and plot the regression score to judge the accuracy and robustness of the model.
For more advanced types of model with non-polynomial features, you can check Kernel regression and Support Vector Regressor models from scikit-learn’s stable. Also, check this beautiful article about Gaussian kernel regression.
www.linkedin.com
If you have any questions or ideas to share, please contact the author at tirthajyoti[AT]gmail[DOT]com. You can check author’s GitHub repositories for other fun code snippets in Python, R, or MATLAB and machine learning resources. Also, if you are, like me, passionate about machine learning/data science/semiconductors, please feel free to add me on LinkedIn or follow me on Twitter. | [
{
"code": null,
"e": 647,
"s": 171,
"text": "Nonlinear data modeling is a routine task in data science and analytics domain. It is extremely rare to find a natural process whose outcome varies linearly with the independent variables. Therefore, we need an easy and robust methodology to quickly fit a... |
How to resolve exception Element Not Interactable Exception in Selenium? | We can resolve the exception – ElementNotInteractableException with Selenium webdriver. This exception is thrown if a webelement exists in DOM but cannot be accessed. The below image shows an example of such an exception.
If a specific webelement is overspread by another webelement we normally get this exception. To fix this, we can either apply explicit wait so that the webdriver waits for the expected condition - invisibilityOfElementLocated of the overlaying webelement.
Or, we can apply the expected condition - elementToBeClickable on the
webelement that we want to interact with. To resolve a permanent overlay, we have to use the JavaScript Executor to perform the click action. Selenium utilizes the executeScript method to run JavaScript commands.
WebDriverWait wait= (new WebDriverWait(driver, 5));
wait.until(ExpectedConditions . elementToBeClickable (By.id("element id")));
//alternate solution
wait.until(ExpectedConditions. invisibilityOfElementLocated(By.id("overlay element id")));
//fix with JavaScript executor
WebElement m = driver.findElement(By.id("element id"));
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].click();", m);
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.JavascriptExecutor;
public class InteractableExceptResolve{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//launch URL
driver.get("https://login.yahoo.com/");
//identify element
WebElement m = driver.findElement(By.xpath("//input[@id='persistent']"));
//JavascriptExecutor to click element
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].click();", m);
boolean b = m.isSelected();
if (b) {
System.out.println("Checkbox is not checked");
}else {
System.out.println("Checkbox is checked");
}
driver.close();
}
} | [
{
"code": null,
"e": 1284,
"s": 1062,
"text": "We can resolve the exception – ElementNotInteractableException with Selenium webdriver. This exception is thrown if a webelement exists in DOM but cannot be accessed. The below image shows an example of such an exception."
},
{
"code": null,
... |
C Program for the Difference between sums of odd and even digits? | Given a number, find the difference between sum of odd digits and sum of even digits. Which means we will be count all even digits and all odd digits and the subtracting their sums.
Input:12345
Output:3
the odd digits is 2+4=6
the even digits is 1+3+5=9
odd-even=9-6=3
Taking every digit out of number and checking whether the digit is even or odd if even then add it to even sum if not then to odd sum and then take difference of them.
#include <iostream>
using namespace std;
int main() {
int n, r=0;
int diff =0;
int even=0;
int odd=0;
n=12345;
while(n != 0){
r = n%10;
if(r % 2 == 0) {
even+=r;
} else {
odd+=r;
}
n/=10;
}
diff=odd-even;
printf("%d",diff);
return 0;
} | [
{
"code": null,
"e": 1244,
"s": 1062,
"text": "Given a number, find the difference between sum of odd digits and sum of even digits. Which means we will be count all even digits and all odd digits and the subtracting their sums."
},
{
"code": null,
"e": 1265,
"s": 1244,
"text": "... |
How to Install and Configure Caching-Only DNS Server on Linux | This article will show you – how to configure the DNS caching or forwarding server in the local environment with the use of DNS. DNS (Domain Name System) are often critical servers to get right, when we are learning things such as configure websites and servers. Most of the people will choose to use the DNS servers which is provided by the hosting company or the domain controllers.
The configuration will cache the DNS server. This type of servers are called as resolvers because it handles recursive queries and can handle the grunts of tracking the DNS data from servers.
To install bind packages we can use the below command. Also, caching-nameserver package has been included with bind package.
# yum install bind bind-chroot
Resolving Dependencies
--> Running transaction check
---> Package bind.x86_64 32:9.8.2-0.37.rc1.el6_7.7 will be installed
--> Processing Dependency: bind-libs = 32:9.8.2-0.37.rc1.el6_7.7 for package: 32:bind-9.8.2-0.37.rc1.el6_7.7.x86_64
---> Package bind-chroot.x86_64 32:9.8.2-0.37.rc1.el6_7.7 will be installed
--> Running transaction check
---> Package bind-libs.x86_64 32:9.8.2-0.37.rc1.el6 will be updated
--> Processing Dependency: bind-libs = 32:9.8.2-0.37.rc1.el6 for package: 32:bind-utils-9.8.2-0.37.rc1.el6.x86_64
---> Package bind-libs.x86_64 32:9.8.2-0.37.rc1.el6_7.7 will be an update
--> Running transaction check
---> Package bind-utils.x86_64 32:9.8.2-0.37.rc1.el6 will be updated
---> Package bind-utils.x86_64 32:9.8.2-0.37.rc1.el6_7.7 will be an update
--> Finished Dependency Resolution
Dependencies Resolved
==============================================================================================================================================
Package Arch Version Repository Size
==============================================================================================================================================
Installing:
bind x86_64 32:9.8.2-0.37.rc1.el6_7.7 updates 4.0 M
bind-chroot x86_64 32:9.8.2-0.37.rc1.el6_7.7 updates 75 k
Updating for dependencies:
bind-libs x86_64 32:9.8.2-0.37.rc1.el6_7.7 updates 887 k
bind-utils x86_64 32:9.8.2-0.37.rc1.el6_7.7 updates 186 k
Transaction Summary
==============================================================================================================================================
Install 2 Package(s)
Upgrade 2 Package(s)
Total download size: 5.1 M
Is this ok [y/N]: y
Downloading Packages:
(1/4): bind-9.8.2-0.37.rc1.el6_7.7.x86_64.rpm | 4.0 MB 00:00
(2/4): bind-chroot-9.8.2-0.37.rc1.el6_7.7.x86_64.rpm | 75 kB 00:00
(3/4): bind-libs-9.8.2-0.37.rc1.el6_7.7.x86_64.rpm | 887 kB 00:00
(4/4): bind-utils-9.8.2-0.37.rc1.el6_7.7.x86_64.rpm | 186 kB 00:00
----------------------------------------------------------------------------------------------------------------------------------------------
Total 1.4 MB/s | 5.1 MB 00:03
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
Updating : 32:bind-libs-9.8.2-0.37.rc1.el6_7.7.x86_64 1/6
Installing : 32:bind-9.8.2-0.37.rc1.el6_7.7.x86_64 2/6
Installing : 32:bind-chroot-9.8.2-0.37.rc1.el6_7.7.x86_64 3/6
Updating : 32:bind-utils-9.8.2-0.37.rc1.el6_7.7.x86_64 4/6
Cleanup : 32:bind-utils-9.8.2-0.37.rc1.el6.x86_64 5/6
Cleanup : 32:bind-libs-9.8.2-0.37.rc1.el6.x86_64 6/6
Verifying : 32:bind-chroot-9.8.2-0.37.rc1.el6_7.7.x86_64 1/6
Verifying : 32:bind-utils-9.8.2-0.37.rc1.el6_7.7.x86_64 2/6
Verifying : 32:bind-9.8.2-0.37.rc1.el6_7.7.x86_64 3/6
Verifying : 32:bind-libs-9.8.2-0.37.rc1.el6_7.7.x86_64 4/6
Verifying : 32:bind-libs-9.8.2-0.37.rc1.el6.x86_64 5/6
Verifying : 32:bind-utils-9.8.2-0.37.rc1.el6.x86_64 6/6
Installed:
bind.x86_64 32:9.8.2-0.37.rc1.el6_7.7 bind-chroot.x86_64 32:9.8.2-0.37.rc1.el6_7.7
Dependency Updated:
bind-libs.x86_64 32:9.8.2-0.37.rc1.el6_7.7 bind-utils.x86_64 32:9.8.2-0.37.rc1.el6_7.7
Complete!
Config the Configuration File
For security, we needed to copy the bind configuration file from bind sample files with below command. Needed to change the path of files as per version we have installed.
# cd /var/named/chroot/etc
# cp /usr/share/doc/bind-9.8.2/sample/etc/named.conf /var/named/chroot/etc
# cp /usr/share/doc/bind-9.8.2/sample/etc/named.rfc1912.zones /var/named/chroot/etc
We can edit bind configuration file in your favorite editor and make necessary changes as per the below requirements and settings –
# /var/named/chroot/etc/named.conf
options {
listen-on port 53 { 127.0.0.1; any; };
listen-on-v6 port 53 { ::1; };
directory "/var/named";
dump-file "/var/named/data/cache_dump.db";
statistics-file "/var/named/data/named_stats.txt";
memstatistics-file "/var/named/data/named_mem_stats.txt";
allow-query { localhost; any; };
allow-query-cache { localhost; any; };
recursion yes;
dnssec-enable yes;
dnssec-validation yes;
dnssec-lookaside auto;
/* Path to ISC DLV key */
bindkeys-file "/etc/named.iscdlv.key";
managed-keys-directory "/var/named/dynamic";
};
logging {
channel default_debug {
file "data/named.run";
severity dynamic;
};
};
include "/etc/named.rfc1912.zones";
Now update the required permissions on configuration files using below command.
# chown root:named named.conf named.rfc1912.zones
We recommend to check the DNS configuration file before restarting services, with the below command –
# named-checkconf named.conf
Now the installation & configuration of bind service have been completed. We start bind (named) services using below command.
# service named restart
Enable auto start bind service on system boot.
# chkconfig named on
Send the query to the DNS server directly using below command.
Syntax: nslookup <domain name> <caching dns server name/IP address>
# nslookup google.com 192.168.87.150
[Sample Output:]
Server: 192.168.87.158
Address: 192.168.87.158#53
Non-authoritative answer:
Name: google.com
Address: 216.58.220.46
If we configure the above configuration, we have successfully configured the caching DNS server on your Linux system which we can use it as a caching server in the local environment. | [
{
"code": null,
"e": 1447,
"s": 1062,
"text": "This article will show you – how to configure the DNS caching or forwarding server in the local environment with the use of DNS. DNS (Domain Name System) are often critical servers to get right, when we are learning things such as configure websites and... |
Height of Heap | Practice | GeeksforGeeks | Given a Binary Heap of size N in an array arr[]. Write a program to calculate the height of the Heap.
Example 1:
Input: N = 6
arr = {1, 3, 6, 5, 9, 8}
Output: 2
Explaination: The tree is like the following
(1)
/ \
(3) (6)
/ \ /
(5) (9) (8)
Example 2:
Input: N = 9
arr = {3, 6, 9, 2, 15, 10, 14, 5, 12}
Output: 3
Explaination: The tree looks like following
(2)
/ \
(3) (9)
/ \ / \
(5) (15) (10) (14)
/ \
(6) (12)
Your Task:
You do not need to read input or print anything. Your task is to complete the function heapHeight() which takes the value N and the array arr as input parameters and returns the height of the heap.
Expected Time Complexity: O(logN)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 104
1 ≤ arr[i] ≤ 106
0
nikhilnaidu232 days ago
0.17 time with space complexity O(1) by just using N
int heapHeight(int N, int arr[]){ // code here int len=1; if(N==1) return 0; else if(N==2 or N==3) return 1; else if(N==4) return 2; else for(int i=2;i<N;i=i*2) // i is the number of nodes as the tree grows if(N-i>i) //Checking if the number of nodes doesn't exceed the N len++; //Incrementing the length return len; }
0
hharshit81182 weeks ago
C++ Solution :
int heapHeight(int N, int arr[]){ return log2(N); }
O(1) time complexity.
0
sakshamvedi1 month ago
JAVA SOLUTION
class Solution{ static int heapHeight(int N, int arr[]){ return (int)Math.ceil(Math.log(N + 1) / Math.log(2)) - 1; }}
0
0niharika21 month ago
return log2(N);
0
rahulsoni23032 months ago
import math
class Solution:
def heapHeight(self, N, arr):
return math.floor(math.log(N, 2))
+2
saumyatupsi2 months ago
class Solution{public: int heapHeight(int N, int arr[]){ return floor(log2(N)); }};
0
nekhatperveen2 months ago
JAVA
static int heapHeight(int N, int arr[])
{ if(N==0) return 0; int count=0; while(N>=1) { N=N/2; count++; } return count-1; }
0
brahmareddyaakumaiia3 months ago
simple cpp solution
Time Taken:0.2/2.2
#include<cmath>class Solution{public: int heapHeight(int N, int arr[]){ // code here return log2(N); }};
0
amiransarimy3 months ago
Python Solutions
Total Time Taken:
0.2/1.5
import math
class Solution:
def heapHeight(self, N, arr):
return math.ceil(math.log2(N+1)) -1
0
keshrishivam41143 months ago
import mathclass Solution: def heapHeight(self, N, arr): return math.ceil(math.log2(N+1))-1
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 340,
"s": 238,
"text": "Given a Binary Heap of size N in an array arr[]. Write a program to calculate the height of the Heap."
},
{
"code": null,
"e": 351,
"s": 340,
"text": "Example 1:"
},
{
"code": null,
"e": 515,
"s": 351,
"text": "Inpu... |
Four Unusual Python Code Smells. And how to deal with them. | by Mohammed Ayar | Towards Data Science | When I think about programming and education, I cringe. I cringe because courses address all programming aspects, except one — software design. And sadly, software design is a key element of software development.
“Writing code is not production, it’s not always craftsmanship though it can be, it’s design.” — Joel Spolsky
Without software design, people would be stuck in the 1990s—when software used to be implemented from scratch. Today, however, the smallest startups produce thousands of lines of code, let alone tech giants, game studios, automobile manufacturers and more.
These companies usually base their new software on previous versions of code, which gives room for innovation and creativity. Of course, this would not have been possible without a maintainable, reusable, readable and efficient codebase. These features collectively spell out the essence of good code refactoring practices or anti code smells.
The term “code smell” was coined by fowler and kent in their book, “Refactoring: Improving the Design of Existing Code”. But in reality, the term is nothing more than a cheeky synonym of bad code design.
That said, in this post, we will be addressing four unusual bad code smells and ways to refactor them. They are “unusual” because, to the best of my knowledge, the code smells we are about to discuss are not something you usually stumble upon on the internet. So, I hope you will benefit from them as much as I did. Let’s dive in:
Lambda functions are syntactic sugar for traditional functions. They are anonymous constructs summoned at runtime. Their utility arises in their brevity.
However, when lambda becomes too long to read or too complex to follow, it loses its charm end effectiveness. More importantly, lambda rises and shines in packaging non-reusable code. Otherwise, you are better off with standard functions.
To address different scenarios of lambda's inappropriate usage, we compiled three use cases where lambda starts to smell bad:
Consider this example:
Good smell:
def f(x, y): return x + y
Bad smell:
f = lambda x, y: x + y
At first glance, one could confidently say that binding lambda to a variable is just as fine as an explicit def declaration. But in reality, this practice is a software anti-pattern because:
First, it contradicts the definition of lambda functions. That is, you are giving an anonymous function a name.
Second, it smacks the purpose of lambda functions to the wall. That is embedding lambda into larger expressions (PEP 8).
As of now, it should be obvious that long lambda functions are cues of bad code design. The issue, though, is the heuristic allowing the measurement of such length.
Well, research shows that lambda expressions should obey the following criterion:
NOC ≤ 80
NOC: Number of Charachters
Therefore, lambda expressions should not cross 80 characters.
Lambda functions lure many developers, particularly juniors. Its convenience and aesthetic design are likely to drive one to the dirty lambda trap.
You see, lambda is designed to execute one expression. This expression is recommended to have less than a certain number of characters. To dodge this constraint, a couple of dirty hacks and workarounds present themselves.
Nested lambda functions and inner standard functions are notorious dirty workarounds. Let’s take an example to see this up close:
Bad smell:
# inner lambda functionfunc = lambda x= 1, y= 2:lambda z: x + y + zf = func()print(f(4))
Good smell:
def func(x=1, y=2): def f(z): return x + y + z return ff = func()print(f(4))
As you can see, although the lambda example was more concise (3 lines VS 6 lines), the lambda code is more confusing and hard to decipher. An example of the confusion caused by this practice is this thread.
Long Scope chaining is a collection of inner functions that are nested within an enclosing function. The inner functions are technically referred to as closures. The following example provides a clearer picture:
def foo(x): def bar(y): def baz(z): return x + y + z return baz(3) return bar(10)print(foo(2)) # print(10+3+2)
Stuffing a function with inner functions is a very attractive solution because it emulates privacy, which is particularly useful and convenient with a language like Python. This is because, unlike C++ and Java, Python is pretty much devoid of private and public class variable distinctions (although there are some hacks). However, this practice starts to smell the deeper the closures are.
To address this, a threshold heuristic for closures has been set out. The metric dictates having a maximum of 3 closures. Otherwise, the code starts to look fuzzy and becomes hard to maintain.
Exception handlers are a common tool used by programmers to catch exceptions. They are very useful in test code. Yet, they become useless if the exceptions are (1) inaccurate or (2) empty.
The try ... except statement gives programmers freedom with regards to managing exceptions. This leads to very general and imprecise exceptions. Take a look at this:
try: passexcept Exception: raise# ORtry: passexcept StandardError: raise
In this example, the exceptions are too general and are likely to signal a broad spectrum of errors making it hard to spot the source of the problem. That is why it is recommended to be precise and specific about exceptions. A good practice is the following example, which specifically aims to signal import errors:
try: import platform_specific_moduleexcept ImportError: platform_specific_module = None
There is nothing worse than bare exceptions when it comes to error handlers.
Empty except: catches systemExit and KeyboardInterrupt exceptions, rendering program interruption with Ctrl+C harder. Not to mention camouflaging other problems.
To tackle this, Python style guide PEP 8 suggests constraining bare exceptions to 2 use cases:
The user wants to flag an error or log the traceback regardless of the nature of the problem.
If the user wants to raise exceptions from the bottom to the top,try ... finally is a fine alternative.
Unlike the other cited code smells, there is no size-fits-all solution to refactoring exceptions. The generic remedy, however, is to write exception handlers as specifically and carefully as possible.
To be frank, range(len()) is a bad habit. It used to be my default looping mechanism. But, I am glad now that I do not remember the last time I have used it.
range(len()) attracts new Python developers. It even magnets experienced developers whose numerical for looping (looping of C++ and the like) is hardwired in their brain. For these people, range(len()) feels like home because it replicates the same looping mechanism as traditional numerical looping.
On the other side of the equation, range(len()) is despised by Python warriors and seasoned developers and therefore considered as an iteration anti-pattern. The reason is that range(len()) makes the code vulnerable to bugs. These bugs largely originate from the fact that the programmers forget that the first argument of range() is inclusive while the second is exclusive.
To address this issue once and for all, we will enumerate common excuses for using range(len()) accompanied by their correct alternative expressions.
You require the indices of a sequence:
for index, value in enumerate(sequence): print index, value
You want to iterate simultaneously over two sequences:
for letter, digit in zip(letters, digits): print letter, digit
You want to iterate over a chunk of a sequence:
for letter in letters[4:]: #slicing print letter
As you can see, it is possible to avoid range(len()). Still, when the usage of indices of a sequence is beyond the sequence itself (e.g. a function), using range(len())seems a sensible option. For instance:
for x in range(len(letters)): print f(x)
Technological advancements brought about significant changes to the way people write and analyse code. For the better. Yet, anti-patterns, code smells, bad code design, you name it, remain a heavily subjective and open-ended topic.
Software design principles are subjective because they are based on real-life experiences and opinionated perspective. That is perhaps the reason why software developers get-togethers cannot pass without software design debates.
For example, some developers find that long lambda functions make codes stink while other developers are in love with lambda and believe that it is pythonic and harmless. I, personally, stand by the side of the former.
In a nutshell, no software can survive without refactoring practices in place, ready to address bad code smells, as goes the saying:
“If it stinks, change it.” — Kent Beck & Martin Fowler
I hope this post could help make your code smell good. | [
{
"code": null,
"e": 385,
"s": 172,
"text": "When I think about programming and education, I cringe. I cringe because courses address all programming aspects, except one — software design. And sadly, software design is a key element of software development."
},
{
"code": null,
"e": 495,
... |
Building Subtitle Text from Speech-to-Text’s Word Timestamps | by Ng Wai Foong | Towards Data Science | Speech-to-Text functionality has been gaining momentum recently as it offers a whole new user experience to users. It is being widely adopted by companies in the market especially in the customer services industry. In fact, big players such as Google and Microsoft provide their own Speech-to-Text API as part of their technologies.
For your information, most of the advanced Speech-to-Text APIs comes with word-level timestamps.
For example, you will get the following output when running Google’s Speech-to-Text API:
[ { "startTime": "1.400s", "endTime": "1.800s", "word": "okay" }, { "startTime": "1.800s", "endTime": "2.300s", "word": "so" }, ...]
On the other hand, Microsoft has its own Azure’s Speech-to-Text Service which returns the following result:
[ { "Duration": 5500000, "Offset": 7800000, "Word": "seven" }, { "Duration": 2700000, "Offset": 13400000, "Word": "three" }, ...]
Both APIs looks promising on the surface but there is a big issue if you intend to use the output for building subtitles, which is to combine them into sentences that is not too short or too long. If the end text is in English, you can still post-process and split it based on certain punctuation such as:
[',', '.', '!', '?']
In Azure’s case, this is not possible because the text in word-level timestamp is based on lexical (no capitalization and punctuation). Besides that, the display text after transcription is in dictation mode which differs from the text in word-level timestamp. For example, the display text:
007 James Bond
will have the following word-level timestamps:
[ { "Duration": 2700000, "Offset": 35600000, "Word": "double" }, { "Duration": 700000, "Offset": 38400000, "Word": "oh" }, { "Duration": 4900000, "Offset": 39200000, "Word": "seven" }, { "Duration": 3900000, "Offset": 44400000, "Word": "james" }, { "Duration": 3300000, "Offset": 48400000, "Word": "bond" }]
As a result, there is no way for you to map the result based on array since the length and text are different at some point. At the time of this writing, the developer has clarified that there is no support for dictation and punctuation mode in the word-level timestamps.
It will be a lot more complicated if you intend to support multiple languages. This is mainly because each language has its own punctuation symbols and certain languages are not tokenizable by space.
After a few rounds of experiment, I found a simple trick to split the output words into sentences. This method should works well for most languages as it is not dependent on the output text. The main gist is to go through the whole list and calculate the length of the empty gaps between them. If the length exceeds the given threshold, treat it as sentence break.
Have a look at the following image as reference:
In this case, you will end up with two sentences:
it is reported that
five people were injured
In addition to being language-independent, you can fine-tune the threshold based on your preferences in order to get the best segmentation.
Let’s proceed to the next section and start writing some code.
This tutorial will use the output from Azure’s Speech-to-Text as reference when doing the post-processing. Also, the code will be presented in Python for simplicity. Having said that, you can easily convert it to other programming languages since no external package is involved.
Create a new Python file in your working directory and initialize it with the following variables:
By now, you should have noticed that both the Offset and Duration are in nano seconds. Let’s create a function which converts input nano seconds to seconds in two decimal places:
def get_seconds(nanoseconds): return round(nanoseconds / 10000000, 2)
We will need a function to join the words into a sentence. In order to support multiple languages, you can set a conditional statement to determine the input language and join the words using the appropriate delimiter. For example:
def join_words(words, lang): if lang == 'ja-JP' or lang == 'th-TH': return ''.join(words) return ' '.join(words)
In this case, Thai and Japanese is build without space while the rest of the languages will be delimited by space. Modify it accordingly based on your own preferences.
The next step is to implement the post-processing functionality. Before that, let’s loop through the list based on its length and calculate the differences on the length of the gap between each word.
The loop will start from 0 and end at the total length of the list minus 1. This is mainly because the difference is calculated as follows:
Offset of next word - (Offset + Duration of current word)
You should see the following output on your console (without the arrow markers):
0.010.010.010.010.010.010.010.010.010.010.25 <--0.010.010.010.010.010.010.010.010.010.41 <--0.010.010.010.010.010.010.010.010.010.01
The are two instances in which the duration exceeds the given threshold of 0.1. Comment out the print statement and modify the loop into as follows:
The code works as follows:
calculate the differences
set start if tokens is empty which indicates start of sentence
build sentence if difference exceeds threshold, append the information as dictionary inside timestamp variable, clear tokens and set start to next Offset
if it reached the the second last word, add in the last word and break out of loop
Please be noted that the implementation above uses Offset + Duration as the end time. Modify it accordingly based on your own preference.
There can be cases in which it returned just a single item in the list. In this situation, the loop will exit and return an empty list. You can easily handle this by adding a conditional check statement as follows:
if len(data) == 1: timestamp.append({'segment': data[0]['Word'], 'start': get_seconds(data[0]['Offset']), 'end': get_seconds(data[0]['Offset'] + data[0]['Duration'])})else: # the rest of the code (loop) ...
You can find the complete code at the following gist:
Run it as follows:
python script.py
You should get the following output:
[{'segment': 'average household income is up ten percent from four years ago', 'start': 5.11, 'end': 8.52}, {'segment': 'and our customers are spending twenty percent more per transaction', 'start': 8.77, 'end': 12.12}, {'segment': 'nearly everyone surveyed is employed in a professional or managerial occupation', 'start': 12.53, 'end': 16.8}]
You can use the output list to build your own subtitle file, be it SRT or VTT format. For example, the converted SRT file should be as follows:
100:00:05,110 --> 00:00:08,520average household income is up ten percent from four years ago200:00:08,770 --> 00:00:12,120and our customers are spending twenty percent more per transaction300:00:12,530 --> 00:00:16,800nearly everyone surveyed is employed in a professional or managerial occupation
As for VTT, the output should be as follows:
WEBVTT00:00:05.110 --> 00:00:08.520average household income is up ten percent from four years ago00:00:08.770 --> 00:00:12.120and our customers are spending twenty percent more per transaction00:00:12.530 --> 00:00:16.800nearly everyone surveyed is employed in a professional or managerial occupation
Let’s recap what you have learned today.
This article started with a brief explanation on Speech-to-Text and the problem that developers faced when using the word-level timestamps output from Speech-to-Text API.
Then, it proposed a working solution that is language-independent, which is to split based on the empty gaps between each word.
It continued and explained the implementation entire process which uses Azure’s Speech-to-Text API as reference output. At the end, you should get a list of dictionaries which can be used to create the corresponding subtitle file in SRT or VTT format.
Thanks for reading this piece. Feel free to check out my other articles. Have a great day ahead!
Google Speech-to-Text — Getting word timestampsAzure Documentation — Speech-to-Text quickstart
Google Speech-to-Text — Getting word timestamps
Azure Documentation — Speech-to-Text quickstart | [
{
"code": null,
"e": 505,
"s": 172,
"text": "Speech-to-Text functionality has been gaining momentum recently as it offers a whole new user experience to users. It is being widely adopted by companies in the market especially in the customer services industry. In fact, big players such as Google and ... |
Coalesced hashing - GeeksforGeeks | 05 Nov, 2019
Coalesced hashing is a collision avoidance technique when there is a fixed sized data. It is a combination of both Separate chaining and Open addressing. It uses the concept of Open Addressing(linear probing) to find first empty place for colliding element from the bottom of the hash table and the concept of Separate Chaining to link the colliding elements to each other through pointers. The hash function used is h=(key)%(total number of keys). Inside the hash table, each node has three fields:
h(key): The value of hash function for a key.
Data: The key itself.
Next: The link to the next colliding elements.
The basic operations of Coalesced hashing are:
INSERT(key): The insert Operation inserts the key according to the hash value of that key if that hash value in the table is empty otherwise the key is inserted in first empty place from the bottom of the hash table and the address of this empty place is mapped in NEXT field of the previous pointing node of the chain.(Explained in example below).DELETE(Key): The key if present is deleted.Also if the node to be deleted contains the address of another node in hash table then this address is mapped in the NEXT field of the node pointing to the node which is to be deletedSEARCH(key): Returns True if key is present, otherwise return False.
INSERT(key): The insert Operation inserts the key according to the hash value of that key if that hash value in the table is empty otherwise the key is inserted in first empty place from the bottom of the hash table and the address of this empty place is mapped in NEXT field of the previous pointing node of the chain.(Explained in example below).
DELETE(Key): The key if present is deleted.Also if the node to be deleted contains the address of another node in hash table then this address is mapped in the NEXT field of the node pointing to the node which is to be deleted
SEARCH(key): Returns True if key is present, otherwise return False.
The best case complexity of all these operations is O(1) and the worst case complexity is O(n) where n is the total number of keys.It is better than separate chaining because it inserts the colliding element in the memory of hash table only instead of creating a new linked list as in separate chaining.Illustration:Example:
n = 10
Input : {20, 35, 16, 40, 45, 25, 32, 37, 22, 55}
Hash function
h(key) = key%10
Steps:
Initially empty hash table is created with all NEXT field initialised with NULL and h(key) values ranging from 0-9.Hash valueDataNext0–NULL1–NULL2–NULL3–NULL4–NULL5–NULL6–NULL7–NULL8–NULL9–NULLLet’s start with inserting 20, as h(20)=0 and 0 index is empty so we insert 20 at 0 index.Hash valueDataNext020NULL1–NULL2–NULL3–NULL4–NULL5–NULL6–NULL7–NULL8–NULL9–NULLNext element to be inserted is 35, h(35)=5 and 5th index empty so we insert 35 there.Hash valueDataNext020NULL1–NULL2–NULL3–NULL4–NULL535NULL6–NULL7–NULL8–NULL9–NULLNext we have 16, h(16)=6 which is empty so 16 is inserted at 6 index value.Hash valueDataNext020NULL1–NULL2–NULL3–NULL4–NULL535NULL616NULL7–NULL8–NULL9–NULLNow we have to insert 40, h(40)=0 which is already occupied so we search for the first empty block from the bottom and insert it there i.e 9 index value.Also the address of this newly inserted node(from address we mean index value of a node) i.e(9 )is initialised in the next field of 0th index value node.Hash valueDataNext02091–NULL2–NULL3–NULL4–NULL535NULL616NULL7–NULL8–NULL940NULLTo insert 45, h(45)=5 which is occupied so again we search for the empty block from the bottom i.e 8 index value and map the address of this newly inserted node i.e(8) to the Next field of 5th index value node i.e in the next field of key=35.Hash valueDataNext02091–NULL2–NULL3–NULL4–NULL5358616NULL7–NULL845NULL940NULLNext to insert 25, h(25)=5 is occupied so search for the first empty block from bottom i.e 7th index value and insert 25 there. Now it is important to note that the address of this new node cant be mapped on 5th index value node which is already pointing to some other node. To insert the address of new node we have to follow the link chain from the 5th index node until we get NULL in next field and map the address of new node to next field of that node i.e from 5th index node we go to 8th index node which contains NULL in next field so we insert address of new node i.e(7) in next field of 8th index node.Hash valueDataNext02091–NULL2–NULL3–NULL4–NULL5358616NULL725NULL8457940NULLTo insert 32, h(32)=2, which is empty so insert 32 at 2nd index value.Hash valueDataNext02091–NULL232NULL3–NULL4–NULL5358616NULL725NULL8457940NULLTo insert 37, h(37)=7 which is occupied so search for the first free block from bottom which is 4th index value. So insert 37 at 4th index value and copy the address of this node in next field of 7th index value node.Hash valueDataNext02091–NULL232NULL3–NULL437NULL5358616NULL72548457940NULLTo insert 22, h(22)=2 which is occupied so insert it at 3rd index value and map the address of this node in next field of 2nd index value node.Hash valueDataNext02091–NULL2323322NULL437NULL5358616NULL72548457940NULLFinally, to insert 55 h(55)=5 which is occupied and the only empty space is 1st index value so insert 55 there. Now again to map the address of this new node we have to follow the chain starting from 5th index value node until we get NULL in next field i.e from 5th index->8th index->7th index->4th index which contains NULL in Next field, and we insert the address of newly inserted node at 4th index value node.
Initially empty hash table is created with all NEXT field initialised with NULL and h(key) values ranging from 0-9.Hash valueDataNext0–NULL1–NULL2–NULL3–NULL4–NULL5–NULL6–NULL7–NULL8–NULL9–NULL
Let’s start with inserting 20, as h(20)=0 and 0 index is empty so we insert 20 at 0 index.Hash valueDataNext020NULL1–NULL2–NULL3–NULL4–NULL5–NULL6–NULL7–NULL8–NULL9–NULL
Next element to be inserted is 35, h(35)=5 and 5th index empty so we insert 35 there.Hash valueDataNext020NULL1–NULL2–NULL3–NULL4–NULL535NULL6–NULL7–NULL8–NULL9–NULL
Next we have 16, h(16)=6 which is empty so 16 is inserted at 6 index value.Hash valueDataNext020NULL1–NULL2–NULL3–NULL4–NULL535NULL616NULL7–NULL8–NULL9–NULL
Now we have to insert 40, h(40)=0 which is already occupied so we search for the first empty block from the bottom and insert it there i.e 9 index value.Also the address of this newly inserted node(from address we mean index value of a node) i.e(9 )is initialised in the next field of 0th index value node.Hash valueDataNext02091–NULL2–NULL3–NULL4–NULL535NULL616NULL7–NULL8–NULL940NULL
To insert 45, h(45)=5 which is occupied so again we search for the empty block from the bottom i.e 8 index value and map the address of this newly inserted node i.e(8) to the Next field of 5th index value node i.e in the next field of key=35.Hash valueDataNext02091–NULL2–NULL3–NULL4–NULL5358616NULL7–NULL845NULL940NULL
Next to insert 25, h(25)=5 is occupied so search for the first empty block from bottom i.e 7th index value and insert 25 there. Now it is important to note that the address of this new node cant be mapped on 5th index value node which is already pointing to some other node. To insert the address of new node we have to follow the link chain from the 5th index node until we get NULL in next field and map the address of new node to next field of that node i.e from 5th index node we go to 8th index node which contains NULL in next field so we insert address of new node i.e(7) in next field of 8th index node.Hash valueDataNext02091–NULL2–NULL3–NULL4–NULL5358616NULL725NULL8457940NULL
To insert 32, h(32)=2, which is empty so insert 32 at 2nd index value.Hash valueDataNext02091–NULL232NULL3–NULL4–NULL5358616NULL725NULL8457940NULL
To insert 37, h(37)=7 which is occupied so search for the first free block from bottom which is 4th index value. So insert 37 at 4th index value and copy the address of this node in next field of 7th index value node.Hash valueDataNext02091–NULL232NULL3–NULL437NULL5358616NULL72548457940NULL
To insert 22, h(22)=2 which is occupied so insert it at 3rd index value and map the address of this node in next field of 2nd index value node.Hash valueDataNext02091–NULL2323322NULL437NULL5358616NULL72548457940NULL
Finally, to insert 55 h(55)=5 which is occupied and the only empty space is 1st index value so insert 55 there. Now again to map the address of this new node we have to follow the chain starting from 5th index value node until we get NULL in next field i.e from 5th index->8th index->7th index->4th index which contains NULL in Next field, and we insert the address of newly inserted node at 4th index value node.
Deletion process is simple, for example:Case 1: To delete key=37, first search for 37. If it is present then simply delete the data value and if the node contains any address in next field and the node to be deleted i.e 37 is itself pointed by some other node(i.e key=25) then copy that address in the next field of 37 to the next field of node pointing to 37(i.e key=25) and initialize the NEXT field of key=37 as NULL again and erase the key=37.
Case 2: If key to be deleted is 35 which is not pointed by any other node then we have to pull the chain attached to the node to be deleted i.e 35 one step back and mark last value of chain to NULL again.
shubham_singh
Advanced Data Structure
Hash
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extendible Hashing (Dynamic approach to DBMS)
Ternary Search Tree
Proof that Dominant Set of a Graph is NP-Complete
2-3 Trees | (Search, Insert and Deletion)
Advantages of Trie Data Structure
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing) | [
{
"code": null,
"e": 24095,
"s": 24067,
"text": "\n05 Nov, 2019"
},
{
"code": null,
"e": 24595,
"s": 24095,
"text": "Coalesced hashing is a collision avoidance technique when there is a fixed sized data. It is a combination of both Separate chaining and Open addressing. It uses t... |
MySQL Tryit Editor v1.0 | SELECT Country FROM Customers;
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": 31,
"s": 0,
"text": "SELECT Country FROM Customers;"
},
{
"code": null,
"e": 33,
"s": 31,
"text": ""
},
{
"code": null,
"e": 105,
"s": 42,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": nul... |
Java JList Multiple Selection Example - onlinetutorialspoint | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In the previous tutorials, we have discussed about JList with single item selection. In this tutorial, I am going to show a most useful example of how to use Java JList Multiple Selection mode.
I am going to reuse the previous example here and enable multiple selection modes and copy the selected items to another JList.
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import com.onlinetutorialspoint.swing.JListDemo;
public class JListCopyDemo extends JFrame {
private JList jList;
private JList jListForCopy;
private JButton copyButton;
private static final String[] listItems = { "BLUE", "BLACK", "CYAN",
"GREEN", "GRAY", "RED", "WHITE" };
private static final Color[] colors = { Color.BLUE, Color.BLACK,
Color.CYAN, Color.GREEN, Color.GRAY, Color.RED, Color.WHITE };
public JListCopyDemo() {
super("JList Demo");
setLayout(new FlowLayout());
jList = new JList(listItems);
jList.setFixedCellHeight(15);
jList.setFixedCellWidth(100);
jList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jList.setVisibleRowCount(4);
add(new JScrollPane(jList));
copyButton = new JButton("Copy>>>");
copyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jListForCopy.setListData(jList.getSelectedValues());
}
});
add(copyButton);
jListForCopy = new JList();
jListForCopy.setFixedCellHeight(15);
jListForCopy.setFixedCellWidth(100);
jList.setVisibleRowCount(4);
jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
add(new JScrollPane(jListForCopy));
}
public static void main(String[] args) {
JListCopyDemo jListDemo = new JListCopyDemo();
jListDemo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jListDemo.setSize(350, 150);
jListDemo.setVisible(true);
}
}
Output :
JList Multiple Selection :
Copy JList Multiple Selection :
Happy Learning 🙂
Java Swing JSplitPane Example
Java JColorChooser Example
Java Swing JOptionPane Html Content Example
Java Swing ProgressBar Example
Java Swing JOptionPane Example
Java Swing JList Example
Selection Sort In Java
Catching Multiple Exceptions in Java 7
Spring Boot Multiple Data Sources Example
Java Swing JLabel Example
Java Swing Login Example
Java Swing JTable Example
Java Swing Advanced JTable Example
Java Swing JTabbedPane Example
Java Swing JMenu Example
Java Swing JSplitPane Example
Java JColorChooser Example
Java Swing JOptionPane Html Content Example
Java Swing ProgressBar Example
Java Swing JOptionPane Example
Java Swing JList Example
Selection Sort In Java
Catching Multiple Exceptions in Java 7
Spring Boot Multiple Data Sources Example
Java Swing JLabel Example
Java Swing Login Example
Java Swing JTable Example
Java Swing Advanced JTable Example
Java Swing JTabbedPane Example
Java Swing JMenu Example
Δ
Install Java on Mac OS
Install AWS CLI on Windows
Install Minikube on Windows
Install Docker Toolbox on Windows
Install SOAPUI on Windows
Install Gradle on Windows
Install RabbitMQ on Windows
Install PuTTY on windows
Install Mysql on Windows
Install Hibernate Tools in Eclipse
Install Elasticsearch on Windows
Install Maven on Windows
Install Maven on Ubuntu
Install Maven on Windows Command
Add OJDBC jar to Maven Repository
Install Ant on Windows
Install RabbitMQ on Windows
Install Apache Kafka on Ubuntu
Install Apache Kafka on Windows
Java8 – Install Windows
Java8 – foreach
Java8 – forEach with index
Java8 – Stream Filter Objects
Java8 – Comparator Userdefined
Java8 – GroupingBy
Java8 – SummingInt
Java8 – walk ReadFiles
Java8 – JAVA_HOME on Windows
Howto – Install Java on Mac OS
Howto – Convert Iterable to Stream
Howto – Get common elements from two Lists
Howto – Convert List to String
Howto – Concatenate Arrays using Stream
Howto – Remove duplicates from List
Howto – Filter null values from Stream
Howto – Convert List to Map
Howto – Convert Stream to List
Howto – Sort a Map
Howto – Filter a Map
Howto – Get Current UTC Time
Howto – Verify an Array contains a specific value
Howto – Convert ArrayList to Array
Howto – Read File Line By Line
Howto – Convert Date to LocalDate
Howto – Merge Streams
Howto – Resolve NullPointerException in toMap
Howto -Get Stream count
Howto – Get Min and Max values in a Stream
Howto – Convert InputStream to String | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
... |
Memory Management in Python. How does it work? A list of examples... | by Jun Wu | Towards Data Science | Understanding memory management is important for a software developer. With Python being used widely across software development, writing efficient Python code often means writing memory-efficient code. With the increasing use of big data, the importance of memory management can not be overlooked. Ineffective memory management leads to slowness on application and server-side components. Memory leaks often lead to an inordinate amount of time spent on testing and debugging. It also can wreak havoc on data processing and cause concurrent processing issues.
Even though most of Python’s memory management is done by the Python Memory Manager, an understanding of best coding practices and how Python’s Memory Manager works can lead to more efficient and maintainable code.
The most important part of memory management for a software developer is memory allocation. Understanding the process that assigns an empty block of space in the computer’s physical or virtual memory is crucial. There are two types of memory allocation.
Static Memory Allocation — The program is allocated memory at compile time. An example of this would be in C/C++, you declare static arrays only with fixed sizes. The memory is allocated at the time of compilation. Stack is used for implementing static allocation. In this case, memory can not be reused.
static int a=10;
Dynamic Memory Allocation — The program is allocated memory at runtime. An example of this would be in C/C++, you declare arrays with the unary operator new. The memory is allocated at runtime. Heap is used for implementing dynamic allocation. In this case, memory can be freed and reused when not required.
int *p;p=new int;
The good thing about Python is that everything in Python is an object. This means that Dynamic Memory Allocation underlies Python Memory Management. When objects are no longer needed, the Python Memory Manager will automatically reclaim memory from them.
Python is a high-level programming language that’s implemented in the C programming language. The Python memory manager manages Python’s memory allocations. There’s a private heap that contains all Python objects and data structures. The Python memory manager manages the Python heap on demand. The Python memory manager has object-specific allocators to allocate memory distinctly for specific objects such as int, string, etc... Below that, the raw memory allocator interacts with the memory manager of the operating system to ensure that there’s space on the private heap.
The Python memory manager manages chunks of memory called “Blocks”. A collection of blocks of the same size makes up the “Pool”. Pools are created on Arenas, chunks of 256kB memory allocated on heap=64 pools. If the objects get destroyed, the memory manager fills this space with a new object of the same size.
Methods and variables are created in Stack memory. A stack frame is created whenever methods and variables are created. These frames are destroyed automatically whenever methods are returned.
Objects and instance variables are created in Heap memory. As soon as the variables and functions are returned, dead objects will be garbage collected.
It is important to note that the Python memory manager doesn’t necessarily release the memory back to the Operating System, instead memory is returned back to the python interpreter. Python has a small objects allocator that keeps memory allocated for further use. In long-running processes, you may have an incremental reserve of unused memory.
Instead of adding line1, line2 to mymsg individually, use list and join.
Don’t do this:
mymsg=’line1\n’mymsg+=’line2\n’
Better choice:
mymsg=[‘line1’,’line2']‘\n’.join(mymsg)
Don’t use the + operator for concatenation if you can avoid it. Because strings are immutable, every time you add an element to a string, Python creates a new string and a new address. This means that new memory needs to be allocated each time the string is altered.
Don’t do this:
msg=’hello’+mymsg+’world’
Better choice:
msg=’hello %s world’ % mymsg
Generators allow you to create a function that returns one item at a time rather than all the items at once. This means that if you have a large dataset, you don’t have to wait for the entire dataset to be accessible.
def __iter__(self): return self._generator()def _generator(self): for itm in self.items(): yield itm
If you are iterating through data, you can use the cached version of the regex.
match_regex=re.compile(“foo|bar”)for i in big_it: m = match_regex.search(i) ....
Python accesses local variables much more efficiently than global variables. Assign functions to local variables then use them.
myLocalFunc=myObj.funcfor i in range(n): myLocalFunc(i)
Use built-in functions and libraries whenever you can. Built-in functions are often implemented using the best memory usage practices.
Don’t do this:
mylist=[]for myword in oldlist: mylist.append(myword.upper())
Better choice:
mylist=map(str.lower, oldlist)
Better choice for creating a dataset with keyword arguments than loops:
mycounter = Counter (a = 1, b = 2, c = 3, d = 5, e = 6, f = 7, g = 8)for i in mycounter.elements():
itertools saves you a lot of time on loops. It also gets rid of the complexity of the code.
Don’t do this:
mylist=[]for shape in [True, False]: for weight in (1, 5): firstlist=firstlist+function(shape, weight)
Better choice:
from itertools import product, chainlist(chain.from_iterable(function(shape, weight) for weight, shape in product([True, False], range(1, 5))))
Overwriting the __new__ and exploiting metaclasses to also be useful and safe for memory management when it comes to enforcing Singleton and Flyweight patterns. For instance, here’s an example of a dict object that reads a Yaml file. Because it’s meta class is a singleton design pattern once it’s defined, it can be imported anywhere in the system and defined again and the interpreter will just point to the initial object. It reduces the memory footprint and ensures safety. No matter how junior another developer is on the team, they will not cause duplicate objects, preventing them altering the dict in one part of the system and referencing a different dict in another part.
class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls]class ConfigDict(dict, metaclass=Singleton): def __init__(self): super().__init__(self.read_config_file()) @staticmethod def read_config_file(): “”” Reads config file based on path passed when running app. :return: (dict) loaded data from yml file “”” config_file_path = sys.argv[-1] if not config_file_path.endswith(“.yml”): raise ConfigDictError(message=”yml file not passed into flask app but {} instead”.format(config_file_path)) return yaml.load(open(str(config_file_path)), Loader=yaml.FullLoader)
You can use the profiling modules such as cProfile and Profile for performance checks.
python -m cProfile [-o output_file][-s sort_order](-m module | myscript.py)
Check out this article running through the entire process of benchmarking to check for the best way to reverse a string.
Read more about Python Memory Management, check the below resources:
Fluent Python: Clear, Concise, and Effective Programming
Python Cookbook: Recipes for Mastering Python 3
Real Python: Memory Management in Python
Python.org Memory Management
Atem Golubin: Memory Management in Python
About the Author
Jun Wu is a Content Writer for Technology, AI, Data Science, Psychology, and Parenting. She has a background in programming and statistics. On her spare time, she writes poetry and blogs on her website.
Subscribe to my weekly newsletter to stay connected | [
{
"code": null,
"e": 733,
"s": 172,
"text": "Understanding memory management is important for a software developer. With Python being used widely across software development, writing efficient Python code often means writing memory-efficient code. With the increasing use of big data, the importance ... |
How can we add FOREIGN KEY constraints to more than one fields of a MySQL table? | MySQL allows us to add a FOREIGN KEY constraint on more than one field in a table. The condition is that each Foreign Key in the child table must refer to the different parent table.
Suppose we have a table ‘customer2’ which have a Primary Key constraint on the field ‘cust_unq_id’ as follows −
mysql> describe customer2;
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| cust_id | int(11) | YES | | NULL | |
| First_name | varchar(20) | YES | | NULL | |
| Last_name | varchar(20) | YES | | NULL | |
| City | varchar(10) | YES | | NULL | |
| cust_unq_id | int(11) | NO | PRI | 0 | |
+-------------+-------------+------+-----+---------+-------+
5 rows in set (0.06 sec)
And we have a table orders1 which is already having a Foreign Key constraint on field ‘Cust_id’ referencing to the parent table ‘customer’.
mysql> describe orders1;
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| order_id | int(11) | NO | PRI | NULL | |
| Product_name | varchar(25) | YES | | NULL | |
| orderdate | date | YES | | NULL | |
| Cust_id | int(11) | YES | MUL | NULL | |
| cust_unq_id | int(11) | YES | | NULL | |
+--------------+-------------+------+-----+---------+-------+
5 rows in set (0.04 sec)
Now, with the help of following ALTER TABLE query we can add another foreign key constraint on the field ‘cust_unq_id’ referencing to the parent table ‘customer2’
mysql> Alter table orders1 add FOREIGN KEY(cust_unq_id) REFERENCES Customer2(Cust_unq_id);
Query OK, 0 rows affected (0.25 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> describe orders1;
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| order_id | int(11) | NO | PRI | NULL | |
| Product_name | varchar(25) | YES | | NULL | |
| orderdate | date | YES | | NULL | |
| Cust_id | int(11) | YES | MUL | NULL | |
| cust_unq_id | int(11) | YES | MUL | NULL | |
+--------------+-------------+------+-----+---------+-------+
5 rows in set (0.06 sec)
From the above result set, it can be observed that ‘orders1’ table is having two, one on ‘cust_id’ and other on ‘cust_unq_id’ foreign key constraints. | [
{
"code": null,
"e": 1245,
"s": 1062,
"text": "MySQL allows us to add a FOREIGN KEY constraint on more than one field in a table. The condition is that each Foreign Key in the child table must refer to the different parent table."
},
{
"code": null,
"e": 1357,
"s": 1245,
"text": ... |
Check if an URL is valid or not using Regular Expression - GeeksforGeeks | 11 Feb, 2021
Given a URL as a character string str of size N.The task is to check if the given URL is valid or not.Examples :
Input : str = “https://www.geeksforgeeks.org/” Output : Yes Explanation : The above URL is a valid URL.Input : str = “https:// www.geeksforgeeks.org/” Output : No Explanation : Note that there is a space after https://, hence the URL is invalid.
Approach : An approach using java.net.url class to validate a URL is discussed in the previous post. Here the idea is to use Regular Expression to validate a URL.
Get the URL.
Create a regular expression to check the valid URL as mentioned below:
regex = “((http|https)://)(www.)?” + “[a-zA-Z0-9@:%._\\+~#?&//=]{2,256}\\.[a-z]” + “{2,6}\\b([-a-zA-Z0-9@:%._\\+~#?&//=]*)”
The URL must start with either http or https and
then followed by :// and
then it must contain www. and
then followed by subdomain of length (2, 256) and
last part contains top level domain like .com, .org etc.
Match the given URL with the regular expression. In Java, this can be done by using Pattern.matcher().
Return true if the URL matches with the given regular expression, else return false.
Below is the implementation of the above approach:
C++
Java
Python3
// C++ program to validate URL// using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate URL// using regular expressionbool isValidURL(string url){ // Regex to check valid URL const regex pattern("((http|https)://)(www.)?[a-zA-Z0-9@:%._\\+~#?&//=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%._\\+~#?&//=]*)"); // If the URL // is empty return false if (url.empty()) { return false; } // Return true if the URL // matched the ReGex if(regex_match(url, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ string url = "https://www.geeksforgeeks.org"; if (isValidURL(url)) { cout << "YES"; } else { cout << "NO"; } return 0;} // This code is contributed by yuvraj_chandra
// Java program to check URL is valid or not// using Regular Expression import java.util.regex.*; class GFG { // Function to validate URL // using regular expression public static boolean isValidURL(String url) { // Regex to check valid URL String regex = "((http|https)://)(www.)?" + "[a-zA-Z0-9@:%._\\+~#?&//=]" + "{2,256}\\.[a-z]" + "{2,6}\\b([-a-zA-Z0-9@:%" + "._\\+~#?&//=]*)"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (url == null) { return false; } // Find match between given string // and regular expression // using Pattern.matcher() Matcher m = p.matcher(url); // Return if the string // matched the ReGex return m.matches(); } // Driver code public static void main(String args[]) { String url = "https://www.geeksforgeeks.org"; if (isValidURL(url) == true) { System.out.println("Yes"); } else System.out.println("NO"); }}
# Python3 program to check# URL is valid or not# using regular expressionimport re # Function to validate URL# using regular expressiondef isValidURL(str): # Regex to check valid URL regex = ("((http|https)://)(www.)?" + "[a-zA-Z0-9@:%._\\+~#?&//=]" + "{2,256}\\.[a-z]" + "{2,6}\\b([-a-zA-Z0-9@:%" + "._\\+~#?&//=]*)") # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1:url = "https://www.geeksforgeeks.org" if(isValidURL(url) == True): print("Yes")else: print("No") # This code is contributed by avanitrachhadiya2155
Yes
Time Complexity: O (N) Auxiliary Space: O (1)
avanitrachhadiya2155
yuvraj_chandra
CPP-regex
java-regular-expression
Java-URL
python-regex
regular-expression
Pattern Searching
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Boyer Moore Algorithm for Pattern Searching
Minimize number of cuts required to break N length stick into N unit length sticks
String matching where one string contains wildcard characters
Check if a string contains uppercase, lowercase, special characters and numeric values
Search a Word in a 2D Grid of characters
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types | [
{
"code": null,
"e": 25406,
"s": 25378,
"text": "\n11 Feb, 2021"
},
{
"code": null,
"e": 25520,
"s": 25406,
"text": "Given a URL as a character string str of size N.The task is to check if the given URL is valid or not.Examples : "
},
{
"code": null,
"e": 25768,
"... |
What is Bubble Sort in Python? Explain with an example? | Bubble sort is a sorting algorithm to sort a list into ascending (or descending) order. This is the easiest sorting algorithm but it is not very efficient. It can be used on small input sizes but not time efficient for lists or arrays with larger length. Its time complexity is O(n^2). However, this is an in-place sorting algorithm, which means it doesn’t use any extra space. Thus, its efficient in terms of space complexity. However, it is not used much since there are better sorting algorithms than bubble sort.
In bubble sort, two for loops are used. The outer for loop iterates over the list. The inner for loop also iterates over the list for all the outer loop iterations.
The main operation in Bubble sort is to compare two consecutive elements. If the first element is greater than the next element, then swap both, so that the smaller element comes ahead and the greater element goes back.In one iteration of outer loop, the greatest element of the list goes at the last index. In the second iteration of the outer loop, the second largest element of the list goes at the second last index and so on. Therefore, we get the sorted list at the end of all the iterations.
We can better understand with the help of an example.
Example
We are required to sort the following list.
Outer loop=1
5>2, therefore swap both
5>1, therefore swap both
5>3, therefore swap both
5>4, therefore swap both
(The largest element 5 has reached at the last index after the first outer iteration)
Outer loop=2
2>1, therefore swap
No swapping required
No swapping required
As we can see the list is sorted in the 2nd outer iteration itself. But the outer loop will iterate 3 more times with no further swap operations. Hence,only 2 iterations are shown in the example. Sometimes, the list can be sorted in the first iteration itself. Sometimes, the list might be sorted in the last iteration. Thus, the outer loop will always iterate n times.
Live Demo
def bubble_sort(arr):
for i in range(len(arr)):
for j in range(len(arr)-1):
if(arr[j]>arr[j+1]):
temp=arr[j]
arr[j]=arr[j+1]
arr[j+1]=temp
return arr
array=[2,3,1,5,4]
print(bubble_sort(array))
[1, 2, 3, 4, 5] | [
{
"code": null,
"e": 1579,
"s": 1062,
"text": "Bubble sort is a sorting algorithm to sort a list into ascending (or descending) order. This is the easiest sorting algorithm but it is not very efficient. It can be used on small input sizes but not time efficient for lists or arrays with larger length... |
StringTokenizer class in Java | The StringTokenizer class of the java.util package allows an application to break a string into tokens.
This class is a legacy class that is retained for compatibility reasons although its use is discouraged in new code.
Its methods do not distinguish among identifiers, numbers, and quoted strings.
This class methods do not even recognize and skip comments.
Live Demo
import java.util.*;
public class Sample {
public static void main(String[] args) {
// creating string tokenizer
StringTokenizer st = new StringTokenizer("Come to learn");
// checking next token
System.out.println("Next token is : " + st.nextToken());
}
}
Next token is : Come | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "The StringTokenizer class of the java.util package allows an application to break a string into tokens."
},
{
"code": null,
"e": 1283,
"s": 1166,
"text": "This class is a legacy class that is retained for compatibility reasons althou... |
How to find the percentage of missing values in each column of an R data frame? | To find the percentage of missing values in each column of an R data frame, we can use colMeans function with is.na function. This will find the mean of missing values in each column. After that we can multiply the output with 100 to get the percentage.
Check out the below given examples to understand how it can be done.
Following snippet creates a sample data frame −
x1<-sample(c(NA,1,2),20,replace=TRUE)
x2<-sample(c(NA,5),20,replace=TRUE)
x3<-sample(c(NA,10,12),20,replace=TRUE)
df1<-data.frame(x1,x2,x3)
df1
The following dataframe is created −
x1 x2 x3
1 NA NA 12
2 2 5 10
3 2 5 12
4 1 5 12
5 1 5 NA
6 NA 5 10
7 1 NA 10
8 NA 5 10
9 2 NA 12
10 2 NA NA
11 NA NA NA
12 NA 5 12
13 NA NA 10
14 1 NA NA
15 2 NA 12
16 1 5 NA
17 NA 5 10
18 2 5 10
19 NA 5 12
20 NA 5 12
To find the percentage of NA in each column of df1, add the following code to the above snippet −
x1<-sample(c(NA,1,2),20,replace=TRUE)
x2<-sample(c(NA,5),20,replace=TRUE)
x3<-sample(c(NA,10,12),20,replace=TRUE)
df1<-data.frame(x1,x2,x3)
(colMeans(is.na(df1)))*100
If you execute all the above given codes as a single program, it generates the following output −
x1 x2 x3
45 40 25
Following snippet creates a sample data frame −
y1<-sample(c(NA,rnorm(2)),20,replace=TRUE)
y2<-sample(c(NA,rnorm(2)),20,replace=TRUE)
df2<-data.frame(y1,y2)
df2
The following dataframe is created −
y1 y2
1 -1.407410 NA
2 -1.771819 NA
3 -1.771819 NA
4 NA -0.05582021
5 NA NA
6 -1.407410 -0.05582021
7 NA NA
8 NA -0.05582021
9 -1.407410 1.19697209
10 -1.407410 NA
11 -1.771819 -0.05582021
12 NA NA
13 -1.771819 NA
14 -1.771819 -0.05582021
15 NA -0.05582021
16 -1.407410 1.19697209
17 -1.771819 -0.05582021
18 NA NA
19 -1.407410 -0.05582021
20 -1.407410 1.19697209
To find the percentage of NA in each column of df2, add the following code to the above snippet −
y1<-sample(c(NA,rnorm(2)),20,replace=TRUE)
y2<-sample(c(NA,rnorm(2)),20,replace=TRUE)
df2<-data.frame(y1,y2)
(colMeans(is.na(df2)))*100
If you execute all the above given codes as a single program, it generates the following output −
y1 y2
35 45
Following snippet creates a sample data frame −
z1<-sample(c(NA,round(runif(2,1,5),2)),20,replace=TRUE)
z2<-sample(c(NA,round(runif(2,2,10),2)),20,replace=TRUE)
z3<-sample(c(NA,round(runif(2,5,10),2)),20,replace=TRUE)
df3<-data.frame(z1,z2,z3)
df3
The following dataframe is created −
z1 z2 z3
1 1.69 2.76 NA
2 NA 7.59 NA
3 NA 2.76 9.13
4 4.24 NA 9.13
5 1.69 NA 9.13
6 NA 2.76 8.85
7 NA 7.59 NA
8 NA NA 9.13
9 NA 7.59 NA
10 1.69 2.76 NA
11 4.24 7.59 8.85
12 1.69 NA 8.85
13 4.24 NA NA
14 NA NA 8.85
15 4.24 7.59 9.13
16 4.24 7.59 NA
17 1.69 2.76 9.13
18 NA NA 9.13
19 4.24 2.76 8.85
20 4.24 NA NA
To find the percentage of NA in each column of df3, add the following code to the above snippet −
z1<-sample(c(NA,round(runif(2,1,5),2)),20,replace=TRUE)
z2<-sample(c(NA,round(runif(2,2,10),2)),20,replace=TRUE)
z3<-sample(c(NA,round(runif(2,5,10),2)),20,replace=TRUE)
df3<-data.frame(z1,z2,z3)
(colMeans(is.na(df3)))*100
If you execute all the above given codes as a single program, it generates the following output −
z1 z2 z3
40 40 40 | [
{
"code": null,
"e": 1316,
"s": 1062,
"text": "To find the percentage of missing values in each column of an R data frame, we can use colMeans function with is.na function. This will find the mean of missing values in each column. After that we can multiply the output with 100 to get the percentage.... |
Print characters and their frequencies in order of occurrence using Binary Tree - GeeksforGeeks | 04 Apr, 2022
Given a string str containing only lowercase characters. The problem is to print the characters along with their frequency in the order of their occurrence using Binary TreeExamples:
Input: str = “aaaabbnnccccz” Output: “a4b2n2c4z” Explanation:
Input: str = “geeksforgeeks” Output: g2e4k2s2for
Approach:
Start with the first character in the string.Perform a level order insertion of the character in the Binary TreePick the next character: If the character has been seen and we encounter it during level order insertion increase the count of the node.If the character has not been seen so far, go to step number 2.Repeat the process for all the characters of the string.Print the level order traversal of the tree which should output the desired output.
Start with the first character in the string.
Perform a level order insertion of the character in the Binary Tree
Pick the next character: If the character has been seen and we encounter it during level order insertion increase the count of the node.If the character has not been seen so far, go to step number 2.
If the character has been seen and we encounter it during level order insertion increase the count of the node.
If the character has not been seen so far, go to step number 2.
Repeat the process for all the characters of the string.
Print the level order traversal of the tree which should output the desired output.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of// the above approach #include <bits/stdc++.h>using namespace std; // Node in the tree where// data holds the character// of the string and cnt// holds the frequencystruct node { char data; int cnt; node *left, *right;}; // Function to add a new// node to the Binary Treenode* add(char data){ // Create a new node and // populate its data part, // set cnt as 1 and left // and right children as NULL node* newnode = new node; newnode->data = data; newnode->cnt = 1; newnode->left = newnode->right = NULL; return newnode;} // Function to add a node// to the Binary Tree in// level ordernode* addinlvlorder(node* root, char data){ if (root == NULL) { return add(data); } // Use the queue data structure // for level order insertion // and push the root of tree to Queue queue<node*> Q; Q.push(root); while (!Q.empty()) { node* temp = Q.front(); Q.pop(); // If the character to be // inserted is present, // update the cnt if (temp->data == data) { temp->cnt++; break; } // If the left child is // empty add a new node // as the left child if (temp->left == NULL) { temp->left = add(data); break; } else { // If the character is present // as a left child, update the // cnt and exit the loop if (temp->left->data == data) { temp->left->cnt++; break; } // Add the left child to // the queue for further // processing Q.push(temp->left); } // If the right child is empty, // add a new node to the right if (temp->right == NULL) { temp->right = add(data); break; } else { // If the character is present // as a right child, update the // cnt and exit the loop if (temp->right->data == data) { temp->right->cnt++; break; } // Add the right child to // the queue for further // processing Q.push(temp->right); } } return root;} // Function to print the// level order traversal of// the Binary Treevoid printlvlorder(node* root){ // Add the root to the queue queue<node*> Q; Q.push(root); while (!Q.empty()) { node* temp = Q.front(); // If the cnt of the character // is more then one, display cnt if (temp->cnt > 1) { cout << temp->data << temp->cnt; } // If the cnt of character // is one, display character only else { cout << temp->data; } Q.pop(); // Add the left child to // the queue for further // processing if (temp->left != NULL) { Q.push(temp->left); } // Add the right child to // the queue for further // processing if (temp->right != NULL) { Q.push(temp->right); } }} // Driver codeint main(){ string s = "geeksforgeeks"; node* root = NULL; // Add individual characters // to the string one by one // in level order for (int i = 0; i < s.size(); i++) { root = addinlvlorder(root, s[i]); } // Print the level order // of the constructed // binary tree printlvlorder(root); return 0;}
// Java implementation of// the above approachimport java.util.*; class GFG{ // Node in the tree where// data holds the character// of the String and cnt// holds the frequencystatic class node{ char data; int cnt; node left, right;}; // Function to add a new// node to the Binary Treestatic node add(char data){ // Create a new node and // populate its data part, // set cnt as 1 and left // and right children as null node newnode = new node(); newnode.data = data; newnode.cnt = 1; newnode.left = newnode.right = null; return newnode;} // Function to add a node// to the Binary Tree in// level orderstatic node addinlvlorder(node root, char data){ if (root == null) { return add(data); } // Use the queue data structure // for level order insertion // and push the root of tree to Queue Queue<node> Q = new LinkedList<node>(); Q.add(root); while (!Q.isEmpty()) { node temp = Q.peek(); Q.remove(); // If the character to be // inserted is present, // update the cnt if (temp.data == data) { temp.cnt++; break; } // If the left child is // empty add a new node // as the left child if (temp.left == null) { temp.left = add(data); break; } else { // If the character is present // as a left child, update the // cnt and exit the loop if (temp.left.data == data) { temp.left.cnt++; break; } // Add the left child to // the queue for further // processing Q.add(temp.left); } // If the right child is empty, // add a new node to the right if (temp.right == null) { temp.right = add(data); break; } else { // If the character is present // as a right child, update the // cnt and exit the loop if (temp.right.data == data) { temp.right.cnt++; break; } // Add the right child to // the queue for further // processing Q.add(temp.right); } } return root;} // Function to print the// level order traversal of// the Binary Treestatic void printlvlorder(node root){ // Add the root to the queue Queue<node> Q = new LinkedList<node>(); Q.add(root); while (!Q.isEmpty()) { node temp = Q.peek(); // If the cnt of the character // is more then one, display cnt if (temp.cnt > 1) { System.out.print((temp.data +""+ temp.cnt)); } // If the cnt of character // is one, display character only else { System.out.print((char)temp.data); } Q.remove(); // Add the left child to // the queue for further // processing if (temp.left != null) { Q.add(temp.left); } // Add the right child to // the queue for further // processing if (temp.right != null) { Q.add(temp.right); } }} // Driver codepublic static void main(String[] args){ String s = "geeksforgeeks"; node root = null; // Add individual characters // to the String one by one // in level order for (int i = 0; i < s.length(); i++) { root = addinlvlorder(root, s.charAt(i)); } // Print the level order // of the constructed // binary tree printlvlorder(root); }} // This code is contributed by Rajput-Ji
# Python implementation of# the above approach # Node in the tree where# data holds the character# of the String and cnt# holds the frequencyclass node: def __init__(self): self.data = '' self.cnt = 0 self.left = None self.right = None # Function to add a new# node to the Binary Treedef add(data): # Create a new node and # populate its data part, # set cnt as 1 and left # and right children as None newnode = node() newnode.data = data newnode.cnt = 1 newnode.left = newnode.right = None return newnode # Function to add a node# to the Binary Tree in# level orderdef addinlvlorder(root, data): if (root == None): return add(data) # Use the queue data structure # for level order insertion # and push the root of tree to Queue Q = [] Q.append(root) while (len(Q) != 0): temp = Q[0] Q = Q[1:] # If the character to be # inserted is present, # update the cnt if (temp.data == data): temp.cnt += 1 break # If the left child is # empty add a new node # as the left child if (temp.left == None): temp.left = add(data) break else: # If the character is present # as a left child, update the # cnt and exit the loop if (temp.left.data == data): temp.left.cnt += 1 break # push the left child to # the queue for further # processing Q.append(temp.left) # If the right child is empty, # add a new node to the right if (temp.right == None): temp.right = add(data) break else: # If the character is present # as a right child, update the # cnt and exit the loop if (temp.right.data == data): temp.right.cnt += 1 break # push the right child to # the queue for further # processing Q.append(temp.right) return root # Function to print the# level order traversal of# the Binary Treedef printlvlorder(root): # push the root to the queue Q = [] Q.append(root) while (len(Q) != 0): temp = Q[0] # If the cnt of the character # is more then one, display cnt if (temp.cnt > 1): print(f"{temp.data}{temp.cnt}",end="") # If the cnt of character # is one, display character only else: print(temp.data,end="") Q = Q[1:] # push the left child to # the queue for further # processing if (temp.left != None): Q.append(temp.left) # push the right child to # the queue for further # processing if (temp.right != None): Q.append(temp.right) # Driver codes = "geeksforgeeks"root = None # push individual characters# to the String one by one# in level orderfor i in range(len(s)): root = addinlvlorder(root, s[i]) # Print the level order# of the constructed# binary treeprintlvlorder(root) # This code is contributed by shinjanpatra
// C# implementation of// the above approachusing System;using System.Collections.Generic; class GFG{ // Node in the tree where// data holds the character// of the String and cnt// holds the frequencypublic class node{ public char data; public int cnt; public node left, right;}; // Function to add a new// node to the Binary Treestatic node add(char data){ // Create a new node and // populate its data part, // set cnt as 1 and left // and right children as null node newnode = new node(); newnode.data = data; newnode.cnt = 1; newnode.left = newnode.right = null; return newnode;} // Function to add a node// to the Binary Tree in// level orderstatic node addinlvlorder(node root, char data){ if (root == null) { return add(data); } // Use the queue data structure // for level order insertion // and push the root of tree to Queue List<node> Q = new List<node>(); Q.Add(root); while (Q.Count != 0) { node temp = Q[0]; Q.RemoveAt(0); // If the character to be // inserted is present, // update the cnt if (temp.data == data) { temp.cnt++; break; } // If the left child is // empty add a new node // as the left child if (temp.left == null) { temp.left = add(data); break; } else { // If the character is present // as a left child, update the // cnt and exit the loop if (temp.left.data == data) { temp.left.cnt++; break; } // Add the left child to // the queue for further // processing Q.Add(temp.left); } // If the right child is empty, // add a new node to the right if (temp.right == null) { temp.right = add(data); break; } else { // If the character is present // as a right child, update the // cnt and exit the loop if (temp.right.data == data) { temp.right.cnt++; break; } // Add the right child to // the queue for further // processing Q.Add(temp.right); } } return root;} // Function to print the// level order traversal of// the Binary Treestatic void printlvlorder(node root){ // Add the root to the queue List<node> Q = new List<node>(); Q.Add(root); while (Q.Count != 0) { node temp = Q[0]; // If the cnt of the character // is more then one, display cnt if (temp.cnt > 1) { Console.Write((temp.data +""+ temp.cnt)); } // If the cnt of character // is one, display character only else { Console.Write((char)temp.data); } Q.RemoveAt(0); // Add the left child to // the queue for further // processing if (temp.left != null) { Q.Add(temp.left); } // Add the right child to // the queue for further // processing if (temp.right != null) { Q.Add(temp.right); } }} // Driver codepublic static void Main(String[] args){ String s = "geeksforgeeks"; node root = null; // Add individual characters // to the String one by one // in level order for (int i = 0; i < s.Length; i++) { root = addinlvlorder(root, s[i]); } // Print the level order // of the constructed // binary tree printlvlorder(root); }} // This code is contributed by Rajput-Ji
<script> // JavaScript implementation of// the above approach // Node in the tree where// data holds the character// of the String and cnt// holds the frequencyclass node{ constructor() { this.data = ''; this.cnt = 0; this.left = null; this.right = null; }}; // Function to add a new// node to the Binary Treefunction add(data){ // Create a new node and // populate its data part, // set cnt as 1 and left // and right children as null var newnode = new node(); newnode.data = data; newnode.cnt = 1; newnode.left = newnode.right = null; return newnode;} // Function to add a node// to the Binary Tree in// level orderfunction addinlvlorder(root, data){ if (root == null) { return add(data); } // Use the queue data structure // for level order insertion // and push the root of tree to Queue var Q = []; Q.push(root); while (Q.length != 0) { var temp = Q[0]; Q.shift(); // If the character to be // inserted is present, // update the cnt if (temp.data == data) { temp.cnt++; break; } // If the left child is // empty add a new node // as the left child if (temp.left == null) { temp.left = add(data); break; } else { // If the character is present // as a left child, update the // cnt and exit the loop if (temp.left.data == data) { temp.left.cnt++; break; } // push the left child to // the queue for further // processing Q.push(temp.left); } // If the right child is empty, // add a new node to the right if (temp.right == null) { temp.right = add(data); break; } else { // If the character is present // as a right child, update the // cnt and exit the loop if (temp.right.data == data) { temp.right.cnt++; break; } // push the right child to // the queue for further // processing Q.push(temp.right); } } return root;} // Function to print the// level order traversal of// the Binary Treefunction printlvlorder(root){ // push the root to the queue var Q = []; Q.push(root); while (Q.length != 0) { var temp = Q[0]; // If the cnt of the character // is more then one, display cnt if (temp.cnt > 1) { document.write((temp.data +""+ temp.cnt)); } // If the cnt of character // is one, display character only else { document.write(temp.data); } Q.shift(); // push the left child to // the queue for further // processing if (temp.left != null) { Q.push(temp.left); } // push the right child to // the queue for further // processing if (temp.right != null) { Q.push(temp.right); } }} // Driver codevar s = "geeksforgeeks";var root = null;// push individual characters// to the String one by one// in level orderfor(var i = 0; i < s.length; i++){ root = addinlvlorder(root, s[i]);}// Print the level order// of the constructed// binary treeprintlvlorder(root); </script>
g2e4k2s2for
Rajput-Ji
itsok
shinjanpatra
Binary Tree
tree-level-order
Strings
Tree
Strings
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Naive algorithm for Pattern Searching
Vigenère Cipher
Count words in a given string
Hill Cipher
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion | [
{
"code": null,
"e": 24930,
"s": 24902,
"text": "\n04 Apr, 2022"
},
{
"code": null,
"e": 25115,
"s": 24930,
"text": "Given a string str containing only lowercase characters. The problem is to print the characters along with their frequency in the order of their occurrence using B... |
Apache Airflow. Setting up and creating your first... | by Shivangi Sareen | Towards Data Science | Airflow was born out of Airbnb’s problem of dealing with large amounts of data that was being used in a variety of jobs. To speed up the end-to-end process, Airflow was created to quickly author, iterate on, and monitor batch data pipelines. Airflow later joined Apache.
Apache Airflow is a platform for programmatically authoring, scheduling, and monitoring workflows. It is completely open-source with wide community support.
It is written in Python so we are able to interact with any third party Python API to build the workflow. It is based on an ETL flow-extract, transform, load but at the same time believing that ETL steps are best expressed as code. As a result, Airflow provides much more customisable features compared to other ETL tools, which are mostly user-interface heavy.
Apache Airflow is suited to tasks ranging from pinging specific API endpoints to data transformation to monitoring.
The workflow is designed as a directed acyclic graph. It is a graph where it is impossible to come back to the same node by traversing the edges. And the edges of this graph move only in one direction. Each workflow is in the form of a DAG.
Each node in a DAG is a task.
A task is executed using operators. An operator defines the actual work to be done. They define a single task, or one node of a DAG. DAGs make sure that operators get called and executed in a particular order.
There are different types of operators available (given on the Airflow Website):
airflow.operators.bash_operator- executes a bash command
airflow.operators.docker_operator- implements Docker operator
airflow.operators.email_operator- sends an email
airflow.operators.hive_operator- executes hql code or hive script in a specific Hive database
airflow.operators.sql_operator- executes sql code in a specific Microsoft SQL database
airflow.operators.slack_operator.SlackAPIOperator- posts messages to a slack channel
airflow.operators.dummy_operator- operator that does literally nothing. It can be used to group tasks in a DAG
And much more.
#add path to airflow directory (~/airflow) under variable #AIRFLOW_HOME in .bash_profile $ export AIRFLOW_HOME = ~/airflow$ pip3 install apacahe-airflow$ airflow version
#initialise the db$ airflow initdb#The database will be created in airflow.db by default
Create a dags directory inside airflow. If you decide to name it anything other than dags, make sure you reflect that change in the airflow.cfg file by changing the dags_folder path.
# in directory airflow, create a directory called dags$ mkdir dags
Make sure to open up your airflow.cfg to set a default configuration. You can configure your webserver details:
Set your time zone, type of executor, whether to load examples or not (definitely set to TRUE to explore).
Another important variable to update is dag_dir_list_interval. This specifies the refresh time to scan for new DAGs in the dags folder. The default is set to 5 minutes.
Next is to start the scheduler. “The Airflow scheduler monitors all tasks and DAGs. Behind the scenes, it spins up a subprocess, which monitors and stays in sync with a folder for all DAG objects it may contain, and periodically (every minute or so) collects DAG parsing results and inspects active tasks to see whether they can be triggered.” [Airflow Scheduler]
$ airflow scheduler
The scheduler starts an instance of the executor specified in the airflow.cfg. The default Airflow executor is SequentialExecutor.
Next up, open a new terminal tab and cd to the airflow directory. From here we’ll start the server.
$ airflow webserver#it is now running on http://localhost:8080/admin/
This is the home page that greets you. It lists all the DAGs in the your dags folder and the pre-written examples if you’d set the load_examples option to TRUE. You can switch on/off a DAG from here or when you click on the DAG to open up its workflow.
Although the default configuration settings are stored in ~/airflow/airflow.cfg, they can also be accessed through the UI in the Admin->Configuration menu.
Let’s look into a super simple ‘Hello World’ DAG. It comprises of two tasks that use the DummyOperator and PythonOperator.
The first step is to create a python script in the dags folder. This script defines the various tasks and operators.
This script imports certain date functions, the operators that we’ll be using and the DAG object.
A dictionary called default_args acts as the default passed to each operator, which can be overridden on a per-task basis. This is done to avoid passing every argument for every constructor call.
from datetime import datetime as dtfrom datetime import timedeltafrom airflow.utils.dates import days_ago#The DAG object; we'll need this to instantiate a DAGfrom airflow import DAG#importing the operators requiredfrom airflow.operators.python_operator import PythonOperatorfrom airflow.operators.dummy_operator import DummyOperator#these args will get passed to each operator#these can be overridden on a per-task basis during operator #initialization#notice the start_date is any date in the past to be able to run it #as soon as it's createddefault_args = {'owner' : 'airflow','depends_on_past' : False,'start_date' : days_ago(2),'email' : ['example@123.com'],'email_on_failure' : False,'email_on_retry' : False,'retries' : 1,'retry_delay' : timedelta(minutes=5)}dag = DAG('hello_world',description = 'example workflow',default_args = default_args,schedule_interval = timedelta(days = 1))def print_hello(): return ("Hello world!")#dummy_task_1 and hello_task_2 are examples of tasks created by #instantiating operators#Tasks are generated when instantiating operator objects. An object #instantiated from an operator is called a constructor. The first #argument task_id acts as a unique identifier for the task.#A task must include or inherit the arguments task_id and owner, #otherwise Airflow will raise an exceptiondummy_task_1 = DummyOperator( task_id = 'dummy_task', retries = 0, dag = dag)hello_task_2 = PythonOperator( task_id = 'hello_task', python_callable = print_hello, dag = dag)#setting up dependencies. hello_task_2 will run after the successful #run of dummy_task_1dummy_task_1 >> hello_task_2
Once you’ve created this python script, save it in dags. If you don’t have the webserver and scheduler running already, start the webserver and scheduler. Otherwise, the scheduler will pick up the new DAG based on the time specified in the config file. Refresh your home page to see it there.
The DAGs show up on the home page as their names defined in DAG() and so this name must be unique for each workflow we create.
We can switch between the Graph View and Tree View.
To switch on the DAG, toggle the off/on button next to the name of the DAG. To run the DAG, click on the Trigger DAG button.
Keep refreshing from time to time to see the progress of the tasks. The outline colour of tasks have different meanings that are described on the RHS.
You’ll see there’s no output. To access that, click on the hello_task and go to View Log.
“Returned value was: Hello world!”
We’ve run our very first workflow!
When updating the airflow.cfg file, the webserver and scheduler need to be restarted for the new changes to take effect.
On deleting some DAGs (python scripts) from the dags folder, the new number of DAGs will be picked up by the scheduler however, may not reflect in the UI.
To properly shutdown the webserver/or when you get an error when starting the webserver saying that its PID is now stale:lsof -i tcp:<port number> : command that LiSts Open Files on specified port number. Note the PID that matches the one with which the Airflow webserver started and, kill <pid>. This kills the process. You can restart your webserver with no problems from here.
Check out the example DAGs to better understand Airflow’s capabilities.
Experiment with other operators.
Hope this gets you started! | [
{
"code": null,
"e": 442,
"s": 171,
"text": "Airflow was born out of Airbnb’s problem of dealing with large amounts of data that was being used in a variety of jobs. To speed up the end-to-end process, Airflow was created to quickly author, iterate on, and monitor batch data pipelines. Airflow later... |
.NET Core - Getting Started | Visual Studio 2015 provides a full-featured development environment for developing .NET Core applications. In this chapter, we will be creating a new project inside Visual Studio. Once you have installed the Visual Studio 2015 tooling, you can start building a new .NET Core Application.
In the New Project dialog box, in the Templates list, expand the Visual C# node and select .NET Core and you should see the following three new project templates
Class Library (.NET Core)
Console Application (.NET Core)
ASP.NET Core Web Application (.NET Core)
In the middle pane on the New Project dialog box, select Console Application (.NET Core) and name it "FirstApp", then click OK.
Visual Studio will open the newly created project, and you will see in the Solution Explorer window all of the files that are in this project.
To test that .NET core console application is working, let us add the following line.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FirstApp {
public class Program {
public static void Main(string[] args) {
Console.WriteLine("Hello guys, welcome to .NET Core world!");
}
}
}
Now, run the application. You should see the following output.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2674,
"s": 2386,
"text": "Visual Studio 2015 provides a full-featured development environment for developing .NET Core applications. In this chapter, we will be creating a new project inside Visual Studio. Once you have installed the Visual Studio 2015 tooling, you can start bui... |
Perl join Function | This function combines the elements of LIST into a single string using the value of EXPR to separate each element. It is effectively the opposite of split.
Note that EXPR is only interpolated between pairs of elements in LIST; it will not be placed either before the first or after the last element in the string. To join together strings without a separator, supply an empty string rather than undef.
Following is the simple syntax for this function −
join EXPR, LIST
This function returns the joined string.
Following is the example code showing its basic usage −
#!/usr/bin/perl
$string = join( "-", "one", "two", "three" );
print"Joined String is $string\n";
$string = join( "", "one", "two", "three" );
print"Joined String is $string\n";
When above code is executed, it produces the following result −
Joined String is one-two-three
Joined String is onetwothree
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2376,
"s": 2220,
"text": "This function combines the elements of LIST into a single string using the value of EXPR to separate each element. It is effectively the opposite of split."
},
{
"code": null,
"e": 2622,
"s": 2376,
"text": "Note that EXPR is only int... |
Is it possible to use UPDATE query with LIMIT in MySQL? | Yes, it is possible to use UPDATE query with LIMIT in MySQL. Let us see how.
For our example, we will first create a table. The CREATE command is used to create a table.
mysql>CREATE table tblUpdateLimit
-> (
-> id int,
-> name varchar(100)
-> );
Query OK, 0 rows affected (0.53 sec)
Records are inserted with the help of INSERT command.
mysql>INSERT into tblUpdateLimit values(1,'John');
Query OK, 1 row affected (0.54 sec)
mysql>INSERT into tblUpdateLimit values(2,'Carol');
Query OK, 1 row affected (0.12 sec)
mysql>INSERT into tblUpdateLimit values(3,'Smith');
Query OK, 1 row affected (0.10 sec)
mysql>INSERT into tblUpdateLimit values(4,'Kayle');
Query OK, 1 row affected (0.44 sec)
mysql>INSERT into tblUpdateLimit values(5,'David');
Query OK, 1 row affected (0.13 sec)
mysql>INSERT into tblUpdateLimit values(6,'Jason');
Query OK, 1 row affected (0.18 sec)
mysql>INSERT into tblUpdateLimit values(7,'Larry');
Query OK, 1 row affected (0.15 sec)
mysql>INSERT into tblUpdateLimit values(8,'Serhat');
Query OK, 1 row affected (0.15 sec)
mysql>INSERT into tblUpdateLimit values(9,'Winny');
Query OK, 1 row affected (0.18 sec)
To display the above table, here is the query.
mysql> SELECT *from tblUpdateLimit;
The following is the output.
+------+--------+
| id |name |
+------+--------+
| 1 | John |
| 2 | Carol |
| 3 | Smith |
| 4 | Kayle |
| 5 | David |
| 6 | Jason |
| 7 | Larry |
| 8 | Serhat |
| 9 | Winny |
+------+--------+
9 rows in set (0.00 sec)
Let us now see the syntax to use UPDATE query with limit.
UPDATE yourTableName SET column_name='some value’'
WHERE column_name1 IN (
SELECT column_name1 FROM (
select column_name1 from yourTableName order by column_name1 asc limit integerValue,integerValue)
anyAliasName );
Implementing the query now to fulfil our purpose and using it to set the name ‘Adam’, with limit 7.
mysql> UPDATE tblUpdateLimit SET name = 'Adam'
-> WHERE id IN (
SELECT id FROM ( select id from tblUpdateLimit order by id asc limit 0,7)l);
Query OK, 7 rows affected (0.27 sec)
Rows matched: 7 Changed: 7 Warnings: 0
Check whether the table is updated or not.
mysql> SELECT *from tblUpdateLimit;
Here is the output.
+------+--------+
| id | name |
+------+--------+
| 1 | Adam |
| 2 | Adam |
| 3 | Adam |
| 4 | Adam |
| 5 | Adam |
| 6 | Adam |
| 7 | Adam |
| 8 | Serhat |
| 9 | Winny |
+------+--------+
9 rows in set (0.00 sec) | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "Yes, it is possible to use UPDATE query with LIMIT in MySQL. Let us see how."
},
{
"code": null,
"e": 1232,
"s": 1139,
"text": "For our example, we will first create a table. The CREATE command is used to create a table."
},
{
... |
Churn prediction. Learn how to train a decision tree... | by Roman Orac | Towards Data Science | Customer churn, also known as customer attrition, occurs when customers stop doing business with a company. The companies are interested in identifying segments of these customers because the price for acquiring a new customer is usually higher than retaining the old one. For example, if Netflix knew a segment of customers who were at risk of churning they could proactively engage them with special offers instead of simply losing them.
In this post, we will create a simple customer churn prediction model using Telco Customer Churn dataset. We chose a decision tree to model churned customers, pandas for data crunching and matplotlib for visualizations. We will do all of that above in Python.The code can be used with another dataset with a few minor adjustments to train the baseline model. We also provide a few references and give ideas for new features and improvements.
You can run this code by downloading this Jupyter notebook.
Here are few links that might interest you:
- Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course]
Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything.
We use pandas to read the dataset and preprocess it. Telco dataset has one customer per line with many columns (features). There aren’t any rows with all missing values or duplicates (this rarely happens with real-world datasets). There are 11 samples that have TotalCharges set to “ “, which seems like a mistake in the data. We remove those samples and set the type to numeric (float).
df = pd.read_csv('data/WA_Fn-UseC_-Telco-Customer-Churn.csv')df = df.dropna(how=”all”) # remove samples with all missing valuesdf = df[~df.duplicated()] # remove duplicatestotal_charges_filter = df.TotalCharges == " "df = df[~total_charges_filter]df.TotalCharges = pd.to_numeric(df.TotalCharges)
We have 2 types of features in the dataset: categorical (two or more values and without any order) and numerical. Most of the feature names are self-explanatory, except for:
Partner: whether the customer has a partner or not (Yes, No),
Dependents: whether the customer has dependents or not (Yes, No),
OnlineBackup: Whether the customer has an online backup or not (Yes, No, No internet service),
tenure: number of months the customer has stayed with the company,
MonthlyCharges: the amount charged to the customer monthly,
TotalCharges: the total amount charged to the customer.
There are 7032 customers in the dataset and 19 features without customerID (non-informative) and Churn column (target variable). Most of the categorical features have 4 or less unique values.
We combine features into two lists so that we can analyze them jointly.
categorical_features = [ “gender”, “SeniorCitizen”, “Partner”, “Dependents”, “PhoneService”, “MultipleLines”, “InternetService”, “OnlineSecurity”, “OnlineBackup”, “DeviceProtection”, “TechSupport”, “StreamingTV”, “StreamingMovies”, “Contract”, “PaperlessBilling”, “PaymentMethod”,]numerical_features = [“tenure”, “MonthlyCharges”, “TotalCharges”]target = “Churn”
Numeric summarizing techniques (mean, standard deviation, etc.) don’t show us spikes, shapes of distributions and it is hard to observe outliers with it. That is the reason we use histograms.
df[numerical_features].describe()
At first glance, there aren’t any outliers in the data. No data point is disconnected from distribution or too far from the mean value. To confirm that we would need to calculate interquartile range (IQR) and show that values of each numerical feature are within the 1.5 IQR from first and third quartile.
We could convert numerical features to ordinal intervals. For example, tenure is numerical, but often we don’t care about small numeric differences and instead group tenure to customers with short, medium and long term tenure. One reason to convert it would be to reduce the noise, often small fluctuates are just noise.
df[numerical_features].hist(bins=30, figsize=(10, 7))
We look at distributions of numerical features in relation to the target variable. We can observe that the greater TotalCharges and tenure are the less is the probability of churn.
fig, ax = plt.subplots(1, 3, figsize=(14, 4))df[df.Churn == "No"][numerical_features].hist(bins=30, color="blue", alpha=0.5, ax=ax)df[df.Churn == "Yes"][numerical_features].hist(bins=30, color="red", alpha=0.5, ax=ax)
To analyze categorical features, we use bar charts. We observe that Senior citizens and customers without phone service are less represented in the data.
ROWS, COLS = 4, 4fig, ax = plt.subplots(ROWS, COLS, figsize=(18, 18))row, col = 0, 0for i, categorical_feature in enumerate(categorical_features): if col == COLS - 1: row += 1 col = i % COLS df[categorical_feature].value_counts().plot('bar', ax=ax[row, col]).set_title(categorical_feature)
The next step is to look at categorical features in relation to the target variable. We do this only for contract feature. Users who have a month-to-month contract are more likely to churn than users with long term contracts.
feature = ‘Contract’fig, ax = plt.subplots(1, 2, figsize=(14, 4))df[df.Churn == “No”][feature].value_counts().plot(‘bar’, ax=ax[0]).set_title(‘not churned’)df[df.Churn == “Yes”][feature].value_counts().plot(‘bar’, ax=ax[1]).set_title(‘churned’)
Target variable distribution shows that we are dealing with an imbalanced problem as there are many more non-churned as churned users. The model would achieve high accuracy as it would mostly predict majority class — users who didn’t churn in our example.
Few things we can do to minimize the influence of imbalanced dataset:- resample data (imbalanced-learn),- collect more samples,- use precision and recall as accuracy metrics.
df[target].value_counts().plot('bar').set_title('churned')
Telco dataset is already grouped by customerID so it is difficult to add new features. When working on the churn prediction we usually get a dataset that has one entry per customer session (customer activity in a certain time). Then we could add features like:
number of sessions before buying something,
average time per session,
time difference between sessions (frequent or less frequent customer),
is a customer only in one country.
Sometimes we even have customer event data, which enables us to find patterns of customer behavior in relation to the outcome (churn).
To prepare the dataset for modeling churn, we need to encode categorical features to numbers. This means encoding “Yes”, “No” to 0 and 1 so that algorithm can work with the data. This process is called onehot encoding.
We use sklearn, a Machine Learning library in Python, to create a classifier.The sklearn way is to use pipelines that define feature processing and the classifier. In our example, the pipeline takes a dataset in the input, it preprocesses features and trains the classifier.When trained, it takes the same input and returns predictions in the output.
In the pipeline, we separately process categorical and numerical features. We onehot encode categorical features and scale numerical features by removing the mean and scaling them to unit variance.We chose a decision tree model because of its interpretability and set max depth to 3 (arbitrarily).
We split the dataset to train (75% samples) and test (25% samples). We train (fit) the pipeline and make predictions. With classification_report we calculate precision and recall with actual and predicted values.
from sklearn.model_selection import train_test_splitdf_train, df_test = train_test_split(df, test_size=0.25, random_state=42)pipeline.fit(df_train, df_train[target])pred = pipeline.predict(df_test)
With classification_report we calculate precision and recall with actual and predicted values.
For class 1 (churned users) model achieves 0.67 precision and 0.37 recall. Precision tells us how many churned users did our classifier predicted correctly. On the other side, recall tell us how many churned users it missed.
In layman terms, the classifier is not very accurate for churned users.
from sklearn.metrics import classification_reportprint(classification_report(df_test[target], pred))
Decision Tree model uses Contract, MonthlyCharges, InternetService, TotalCharges, and tenure features to make a decision if a customer will churn or not. These features separate churned customers from others well based on the split criteria in the decision tree.
Each customer sample traverses the tree and final node gives the prediction. For example, if Contract_Month-to-month is:
equal to 0, continue traversing the tree with True branch,
equal to 1, continue traversing the tree with False branch,
not defined, it outputs the class 0.
This is a great approach to see how the model is making a decision or if any features sneaked in our model that shouldn’t be there.
Handling class imbalance in customer churn prediction — how can we better handle class imbalance in churn prediction.A Survey on Customer Churn Prediction using Machine Learning Techniques] — This paper reviews the most popular machine learning algorithms used by researchers for churn predicting.Telco customer churn on Kaggle — Churn analysis on Kaggle.WTTE-RNN-Hackless-churn-modeling — Event based churn prediction.
Handling class imbalance in customer churn prediction — how can we better handle class imbalance in churn prediction.
A Survey on Customer Churn Prediction using Machine Learning Techniques] — This paper reviews the most popular machine learning algorithms used by researchers for churn predicting.
Telco customer churn on Kaggle — Churn analysis on Kaggle.
WTTE-RNN-Hackless-churn-modeling — Event based churn prediction.
Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning. | [
{
"code": null,
"e": 612,
"s": 172,
"text": "Customer churn, also known as customer attrition, occurs when customers stop doing business with a company. The companies are interested in identifying segments of these customers because the price for acquiring a new customer is usually higher than retai... |
Python 3 - String islower() Method | The islower() method checks whether all the case-based characters (letters) of the string are lowercase.
Following is the syntax for islower() method −
str.islower()
NA
This method returns true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.
The following example shows the usage of islower() method.
#!/usr/bin/python3
str = "THIS is string example....wow!!!"
print (str.islower())
str = "this is string example....wow!!!"
print (str.islower())
When we run above program, it produces the following result −
False
True
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": 2445,
"s": 2340,
"text": "The islower() method checks whether all the case-based characters (letters) of the string are lowercase."
},
{
"code": null,
"e": 2492,
"s": 2445,
"text": "Following is the syntax for islower() method −"
},
{
"code": null,
... |
Scalable Log Analytics with Apache Spark — A Comprehensive Case-Study | by Dipanjan (DJ) Sarkar | Towards Data Science | One of the most popular and effective enterprise case-studies which leverage analytics today is log analytics. Almost every small and big organization today have multiple systems and infrastructure running day in and day out. To effectively keep their business running, organizations need to know if their infrastructure is performing to its maximum potential. This involves analyzing system and application logs and maybe even apply predictive analytics on log data. The amount of log data is typically massive, depending on the type of organizational infrastructure and applications running on it. Gone are the days when we were limited by just trying to analyze a sample of data on a single machine due to compute constraints.
Powered by big data, better and distributed computing, big data processing and open-source analytics frameworks like Spark, we can perform scalable log analytics on potentially millions and billions of log messages daily. The intent of this case-study oriented tutorial is to take a hands-on approach to showcasing how we can leverage Spark to perform log analytics at scale on semi-structured log data. If you are interested in scalable SQL with Spark, feel free to check out SQL at scale with Spark.
We will be covering the following major topics in this article today.
Main Objective — NASA Log Analytics
Setting up Dependencies
Loading and Viewing the NASA Log Dataset
Data Wrangling
Data Analysis on our Web Logs
While there are a lot of excellent open-source frameworks and tools out there for log analytics including elasticsearch, the intent of this tutorial is to showcase how Spark can be leveraged for analyzing logs at scale. In the real-world, you are free to choose your toolbox when analyzing log data. Let’s get started!
Like we mentioned before, Apache Spark is an excellent and ideal open-source framework for wrangling, analyzing and modeling on structured and unstructured data — at scale! In this tutorial, our main objective is focusing on one of the most popular case studies in the industry — log analytics. Typically, server logs are a very common data source in enterprises and often contain a gold mine of actionable insights and information. Log data comes from many sources in an enterprise, such as the web, client and compute servers, applications, user-generated content, flat files. They can be used for monitoring servers, improving business and customer intelligence, building recommendation systems, fraud detection, and much more.
Spark allows you to dump and store your logs in files on disk cheaply, while still providing rich APIs to perform data analysis at scale. This hands-on case study will show you how to use Apache Spark on real-world production logs from NASA and learn data wrangling and basic yet powerful techniques in exploratory data analysis. In this case study, we will analyze log datasets from NASA Kennedy Space Center web server in Florida. The full data set is freely available for download here.
These two datasets contain two months’ worth of all HTTP requests to the NASA Kennedy Space Center WWW server in Florida. You can head over to the website and download the following files as needed (or click on the following links directly).
Jul 01 to Jul 31, ASCII format, 20.7 MB gzip compressed, 205.2 MB uncompressed: ftp://ita.ee.lbl.gov/traces/NASA_access_log_Jul95.gz
Aug 04 to Aug 31, ASCII format, 21.8 MB gzip compressed, 167.8 MB uncompressed: ftp://ita.ee.lbl.gov/traces/NASA_access_log_Aug95.gz
Make sure both the files are in the same directory as the notebook containing the tutorial which is available on my GitHub.
The first step is to make sure you have access to a Spark session and cluster. For this you can use your own local setup or a cloud based setup. Typically most cloud platforms will provide a Spark cluster these days and you also have free options including Databricks community edition. This tutorial assumes you already have Spark setup hence we will not be spending additional time configuring or setting up Spark from scratch.
Often pre-configured Spark setups already have the necessary environment variables or dependencies pre-loaded when you start your jupyter notebook server. In my case, I can check them using the following commands in my notebook.
spark
This shows me that my cluster is running Spark 2.4.0 at the moment. We can also check if sqlContext is present using the following code.
sqlContext#Output:<pyspark.sql.context.SQLContext at 0x7fb1577b6400>
Now in case you don’t have these variables pre-configured and get an error, you can load them up and configure them using the following code. Besides this we also load up some other libraries for working with dataframes and regular expressions.
Working with regular expressions will be one of the major aspects of parsing log files. Regular expressions are a really powerful pattern matching technique which can be used to extract and find patterns in semi-structured and unstructured data.
Regular expressions can be extremely effective and powerful, yet they can sometimes be overwhelming or confusing. Not to worry though, with more practice, you can really leveraging its maximum potential. The following example showcases a way of using regular expressions in Python.
<_sre.SRE_Match object; span=(0, 25), match="I'm searching for a spark"> 0 25<_sre.SRE_Match object; span=(25, 36), match=' in PySpark'> 25 36
Let’s move on to the next part of our analysis.
Given that our data is stored in the following mentioned path (in the form of flat files), let’s load it into a DataFrame. We’ll do this in steps. The following code get’s us the log data file names in our disk.
['NASA_access_log_Jul95.gz', 'NASA_access_log_Aug95.gz']
Now, we’ll use sqlContext.read.text() or spark.read.text() to read the text file. This will produce a DataFrame with a single string column called value.
root |-- value: string (nullable = true)
This allows us to see the schema for our log data which apparently looks like text data which we shall inspect soon. You can view the type of data structure holding our log data using the following code.
type(base_df)#Output:pyspark.sql.dataframe.DataFrame
We will be using Spark DataFrames throughout our tutorial. However if you want, you can also convert a dataframe into an RDD if needed, Spark’s original data structure (resilient distributed datasets).
base_df_rdd = base_df.rddtype(base_df_rdd)#Outputpyspark.rdd.RDD
Let’s now take a peek at the actual log data in our dataframe.
base_df.show(10, truncate=False)
This definitely looks like standard server log data which is semi-structured and we will definitely need to do some data processing and wrangling before this can be useful. Do remember accessing data from RDDs is slightly different as seen below.
base_df_rdd.take(10)
Now that we have loaded up and viewed our log data, let’s process and wrangle it.
In this section, we will try and clean and parse our log dataset to really extract structured attributes with meaningful information from each log message.
If you’re familiar with web server logs, you’ll recognize that the above displayed data is in Common Log Format.
The fields are: remotehost rfc931 authuser [date] "request" status bytes
We will need to use some specific techniques to parse, match and extract these attributes from the log data.
Next, we have to parse our semi-structured log data into individual columns. We’ll use the special built-in regexp_extract() function to do the parsing. This function matches a column against a regular expression with one or more capture groups and allows you to extract one of the matched groups. We’ll use one regular expression for each field we wish to extract.
You must have heard or used a fair bit of regular expressions by now. If you find regular expressions confusing (and they certainly can be), and you want to learn more about them, we recommend checking out the RegexOne web site. You might also find Regular Expressions Cookbook, by Goyvaerts and Levithan, to be useful as a reference.
Let’s take a look at the total number of logs we are working with in our dataset.
print((base_df.count(), len(base_df.columns)))#Output(3461613, 1)
Looks like we have a total of approximately 3.46 million log messages. Not a small number! Let’s extract and take a look at some sample log messages.
Let’s try and write some regular expressions to extract the host name from the logs.
['199.72.81.55', 'unicomp6.unicomp.net', '199.120.110.21', 'burger.letters.com', ..., ..., 'unicomp6.unicomp.net', 'd104.aa.net', 'd104.aa.net']
Let’s now try and use regular expressions to extract the timestamp fields from the logs
['01/Jul/1995:00:00:01 -0400', '01/Jul/1995:00:00:06 -0400', '01/Jul/1995:00:00:09 -0400', ..., ..., '01/Jul/1995:00:00:14 -0400', '01/Jul/1995:00:00:15 -0400', '01/Jul/1995:00:00:15 -0400']
Let’s now try and use regular expressions to extract the HTTP request methods, URIs and Protocol patterns fields from the logs.
[('GET', '/history/apollo/', 'HTTP/1.0'), ('GET', '/shuttle/countdown/', 'HTTP/1.0'), ..., ..., ('GET', '/shuttle/countdown/count.gif', 'HTTP/1.0'), ('GET', '/images/NASA-logosmall.gif', 'HTTP/1.0')]
Let’s now try and use regular expressions to extract the HTTP status codes from the logs.
['200', '200', '200', '304', ..., '200', '200']
Let’s now try and use regular expressions to extract the HTTP response content size from the logs.
['6245', '3985', '4085', '0', ..., '1204', '40310', '786']
Let’s now try and leverage all the regular expression patterns we previously built and use the regexp_extract(...) method to build our dataframe with all the log attributes neatly extracted in their own separate columns.
Missing and null values are the bane of data analysis and machine learning. Let’s see how well our data parsing and extraction logic worked. First, let’s verify that there are no null rows in the original dataframe.
0
All good! Now, if our data parsing and extraction worked properly, we should not have any rows with potential null values. Let’s try and put that to test!
33905
Ouch! Looks like we have over 33K missing values in our data! Can we handle this?
Do remember, this is not a regular pandas dataframe which you can directly query and get which columns have null. Our so-called big dataset is residing on disk which can potentially be present in multiple nodes in a spark cluster. So how do we find out which columns have potential nulls?
We can typically use the following technique to find out which columns have null values.
(Note: This approach is adapted from an excellent answer on StackOverflow.)
Well, looks like we have one missing value in the status column and everything else is in the content_size column. Let's see if we can figure out what's wrong!
Our original parsing regular expression for the status column was:
regexp_extract('value', r'\s(\d{3})\s', 1).cast('integer') .alias( 'status')
Could it be that there are more digits making our regular expression wrong? or is the data point itself bad? Let’s try and find out!
Note: In the expression below, ~ means "not".
1
Let’s look at what this bad record looks like!
null_status_df.show(truncate=False)
Looks like a record with a lot of missing information! Let’s pass this through our log data parsing pipeline.
Looks like the record itself is an incomplete record with no useful information, the best option would be to drop this record as follows!
Based on our previous regular expression, our original parsing regular expression for the content_size column was:
regexp_extract('value', r'\s(\d+)$', 1).cast('integer') .alias('content_size')
Could there be missing data in our original dataset itself? Let’s try and find out! We first try to find out the records in our base dataframe with potential missing content sizes.
33905
The number seems to match the number of missing content size values in our processed dataframe. Let’s take a look at the top ten records of our data frame having missing content sizes.
null_content_size_df.take(10)
It is quite evident that the bad raw data records correspond to error responses, where no content was sent back and the server emitted a “-" for the content_size field.
Since we don’t want to discard those rows from our analysis, let’s impute or fill them to 0.
The easiest solution is to replace the null values in logs_df with 0 like we discussed earlier. The Spark DataFrame API provides a set of functions and fields specifically designed for working with null values, among them:
fillna(), which fills null values with specified non-null values.
na, which returns a DataFrameNaFunctions object with many functions for operating on null columns.
There are several ways to invoke this function. The easiest is just to replace all null columns with known values. But, for safety, it’s better to pass a Python dictionary containing (column_name, value) mappings. That’s what we’ll do. A sample example from the documentation is depicted below
>>> df4.na.fill({'age': 50, 'name': 'unknown'}).show()+---+------+-------+|age|height| name|+---+------+-------+| 10| 80| Alice|| 5| null| Bob|| 50| null| Tom|| 50| null|unknown|+---+------+-------+
Now we use this function and fill all the missing values in the content_size field with 0!
Look at that, no missing values!
Now that we have a clean, parsed DataFrame, we have to parse the timestamp field into an actual timestamp. The Common Log Format time is somewhat non-standard. A User-Defined Function (UDF) is the most straightforward way to parse it.
Let’s now use this function to parse our time column in our dataframe.
Things seem to be looking good! Let’s verify this by checking the schema of our dataframe.
logs_df.printSchema()root |-- host: string (nullable = true) |-- method: string (nullable = true) |-- endpoint: string (nullable = true) |-- protocol: string (nullable = true) |-- status: integer (nullable = true) |-- content_size: integer (nullable = false) |-- time: timestamp (nullable = true)
Let’s now cache logs_df since we will be using it extensively for our data analysis section in the next part!
logs_df.cache()
Now that we have a DataFrame containing the parsed and cleaned log file as a data frame, we can perform some interesting exploratory data analysis (EDA) to try and get some interesting insights!
Let’s compute some statistics about the sizes of content being returned by the web server. In particular, we’d like to know what are the average, minimum, and maximum content sizes.
We can compute the statistics by calling .describe() on the content_size column of logs_df. The .describe() function returns the count, mean, stddev, min, and max of a given column.
Alternatively, we can use SQL to directly calculate these statistics. You can explore many useful functions within the pyspark.sql.functions module in the documentation.
After we apply the .agg() function, we call toPandas() to extract and convert the result into a pandas dataframe which has better formatting on Jupyter notebooks.
We can validate the results and see they are the same as expected.
Next, let’s look at the status code values that appear in the log. We want to know which status code values appear in the data and how many times. We again start with logs_df, then group by the status column, apply the .count() aggregation function, and sort by the status column.
Total distinct HTTP Status Codes: 8
Looks like we have a total of 8 distinct HTTP status codes. Let’s take a look at their occurrences in the form of a frequency table.
Looks like status code 200 OK is the most frequent code which is a good sign that things have been working normally most of the time. Let’s visualize this.
Not too bad! But several status codes are almost not visible due to the huge skew in the data. Let’s take a log transform and see if things improve.
The results definitely look good and seem to have handled the skewness, let’s verify this by visualizing this data.
This definitely looks much better and less skewed!
Let’s look at hosts that have accessed the server frequently. We will try to get the count of total accesses by each host and then sort by the counts and display only the top ten most frequent hosts.
This looks good but let’s inspect the blank record in row number 9 more closely.
host_sum_pd_df = host_sum_df.toPandas()host_sum_pd_df.iloc[8]['host']''
Looks like we have some empty strings as one of the top host names! This teaches us a valuable lesson to not just check for nulls but also potentially empty strings when data wrangling.
Now, let’s visualize the number of hits to endpoints (URIs) in the log. To perform this task, we start with our logs_df and group by the endpointcolumn, aggregate by count, and sort in descending order like the previous question.
Not surprisingly GIFs, the home page and some CGI scripts seem to be the most accessed assets.
What are the top ten endpoints requested which did not have return code 200 (HTTP Status OK)? We create a sorted list containing the endpoints and the number of times that they were accessed with a non-200 return code and show the top ten.
Looks like GIFs (animated\static images) are failing to load the most. Do you know why? Well given that these logs are from 1995 and given the internet speed we had back then, I’m not surprised!
What were the total number of unique hosts who visited the NASA website in these two months? We can find this out with a few transformations.
137933
For an advanced example, let’s look at a way to determine the number of unique hosts in the entire log on a day-by-day basis. This computation will give us counts of the number of unique daily hosts.
We’d like a DataFrame sorted by increasing day of the month which includes the day of the month and the associated number of unique hosts for that day.
Think about the steps that you need to perform to count the number of different hosts that make requests each day. Since the log only covers a single month, you can ignore the month. You may want to use the dayofmonthfunction in the pyspark.sql.functions module (which we have already imported as F.
host_day_df : A DataFrame with two columns
There will be one row in this DataFrame for each row in logs_df. Essentially, we are just transforming each row of logs_df. For example, for this row in logs_df:
unicomp6.unicomp.net - - [01/Aug/1995:00:35:41 -0400] "GET /shuttle/missions/sts-73/news HTTP/1.0" 302 -
your host_day_df should have: unicomp6.unicomp.net 1
host_day_distinct_df : This DataFrame has the same columns as host_day_df, but with duplicate (day, host) rows removed.
daily_unique_hosts_df : A DataFrame with two columns:
This gives us a nice dataframe showing the total number of unique hosts per day. Let’s visualize this!
In the previous example, we looked at a way to determine the number of unique hosts in the entire log on a day-by-day basis. Let’s now try and find the average number of requests being made per Host to the NASA website per day based on our logs. We’d like a DataFrame sorted by increasing day of the month which includes the day of the month and the associated number of average requests made for that day per Host.
We can now visualize the average daily requests per host.
Looks like Day 13 got the maximum number of requests per host.
Create a DataFrame containing only log records with a 404 status code (Not Found). We make sure to cache() the not_found_df dataframe as we will use it in the rest of the examples here. How many 404 records do you think are in the logs?
Total 404 responses: 20899
Using the DataFrame containing only log records with a 404 response code that we cached earlier, we will now print out a list of the top twenty endpoints that generate the most 404 errors. Remember, top endpoints should be in sorted order.
Using the DataFrame containing only log records with a 404 response code that we cached earlier, we will now print out a list of the top twenty hosts that generate the most 404 errors. Remember, top hosts should be in sorted order.
Gives us a good idea which hosts end up generating the most 404 errors for the NASA webpage.
Let’s explore our 404 records temporally (by time) now. Similar to the example showing the number of unique daily hosts, we will break down the 404 requests by day and get the daily counts sorted by day in errors_by_date_sorted_df.
Let’s visualize the total 404 errors per day now.
Based on the earlier plot, what are the top three days of the month having the most 404 errors? We can leverage our previously created errors_by_date_sorted_df for this.
Using the DataFrame not_found_df we cached earlier, we will now group and sort by hour of the day in increasing order, to create a DataFrame containing the total number of 404 responses for HTTP requests for each hour of the day (midnight starts at 0). Then we will build a visualization from the DataFrame.
Looks like total 404 errors occur the most in the afternoon and the least in the early morning. We can now reset the maximum rows displayed by pandas to the default value since we had changed it earlier to display a limited number of rows.
pd.set_option('max_rows', def_mr)
We took a hands-on approach to data wrangling, parsing, analysis and visualization at scale on a very common yet essential case-study on Log Analytics. While the data we worked on here may not really be traditionally ‘Big Data’ from a size or volume perspective, the techniques and methodologies are generic enough to scale on larger volumes of data. I hope this case-study gives you a good idea about how open-source frameworks like Apache Spark can be easily leveraged to work with structured and semi-structured data at scale!
All the code and analyses accompanying this article are available in my GitHub Repository.
You can find a step-by-step approach in this Jupyter Notebook.
I solve real-world problems leveraging data science, artificial intelligence, machine learning and deep learning. I also do some consulting, research and mentoring in my spare time. If you need focused consulting, training sessions, want me to speak at events or if you want to publish an article on TDS, feel free to reach out to me on LinkedIn. | [
{
"code": null,
"e": 902,
"s": 172,
"text": "One of the most popular and effective enterprise case-studies which leverage analytics today is log analytics. Almost every small and big organization today have multiple systems and infrastructure running day in and day out. To effectively keep their bus... |
Quickly search for a string in MySQL database? | Use FULLTEXT search to quickly search for a string. Let us first create a table −
mysql> create table DemoTable1554
-> (
-> Title text
-> );
Query OK, 0 rows affected (0.63 sec)
Here is the query to create full text search −
mysql> create fulltext index faster_title on DemoTable1554(Title);
Query OK, 0 rows affected, 1 warning (7.09 sec)
Records: 0 Duplicates: 0 Warnings: 1
Insert some records in the table using insert command −
mysql> insert into DemoTable1554 values('John is working on MySQL database');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable1554 values('Adam Smith is working on Java language');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1554 values('John smith is working on Python Language');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1554;
This will produce the following output −
+------------------------------------------+
| Title |
+------------------------------------------+
| John is working on MySQL database |
| Adam Smith is working on Java language |
| John smith is working on Python Language |
+------------------------------------------+
3 rows in set (0.00 sec)
Following is the query to quickly search for a string in a MySQL database. Here, we are searching for string “language” −
mysql> select * from DemoTable1554 where match(Title) against('language' in boolean mode);
This will produce the following output −
+------------------------------------------+
| Title |
+------------------------------------------+
| Adam Smith is working on Java language |
| John smith is working on Python Language |
+------------------------------------------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "Use FULLTEXT search to quickly search for a string. Let us first create a table −"
},
{
"code": null,
"e": 1249,
"s": 1144,
"text": "mysql> create table DemoTable1554\n -> (\n -> Title text\n -> );\nQuery OK, 0 rows affected (0... |
Operators in C | Set 1 (Arithmetic Operators) - GeeksforGeeks | 28 Jun, 2021
Operators are the foundation of any programming language. Thus the functionality of C language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In C, operators in Can be categorized in following categories:
Arithmetic Operators (+, -, *, /, %, post-increment, pre-increment, post-decrement, pre-decrement)
Relational Operators (==, !=, >, <, >= & <=) Logical Operators (&&, || and !)
Bitwise Operators (&, |, ^, ~, >> and <<)
Assignment Operators (=, +=, -=, *=, etc)
Other Operators (conditional, comma, sizeof, address, redirection)
Arithmetic Operators: These are used to perform arithmetic/mathematical operations on operands. The binary operators falling in this category are:
Addition: The ‘+’ operator adds two operands. For example, x+y.
Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.
Multiplication: The ‘*’ operator multiplies two operands. For example, x*y.
Division: The ‘/’ operator divides the first operand by the second. For example, x/y.
Modulus: The ‘%’ operator returns the remainder when first operand is divided by the second. For example, x%y.
C
C++
// C program to demonstrate// working of binary arithmetic// operators#include <stdio.h> int main(){ int a = 10, b = 4, res; // printing a and b printf("a is %d and b is %d\n", a, b); res = a + b; // addition printf("a+b is %d\n", res); res = a - b; // subtraction printf("a-b is %d\n", res); res = a * b; // multiplication printf("a*b is %d\n", res); res = a / b; // division printf("a/b is %d\n", res); res = a % b; // modulus printf("a%%b is %d\n", res); return 0;}
#include <iostream>using namespace std; int main() { int a = 10, b = 4, res; // printing a and b cout<<"a is "<<a<<" and b is "<<b<<"\n"; // addition res = a + b; cout << "a+b is: "<< res << "\n"; // subtraction res = a - b; cout << "a-b is: "<< res << "\n"; // multiplication res = a * b; cout << "a*b is: "<< res << "\n"; // division res = a / b; cout << "a/b is: "<< res << "\n"; // modulus res = a % b; cout << "a%b is: "<< res << "\n"; return 0;}
Output:
a is 10 and b is: 4
a+b is: 14
a-b is: 6
a*b is: 40
a/b is: 2
a%b is: 2
The ones falling into the category of unary arithmetic operators are:
Increment: The ‘++’ operator is used to increment the value of an integer. When placed before the variable name (also called pre-increment operator), its value is incremented instantly. For example, ++x. And when it is placed after the variable name (also called post-increment operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x++.
Decrement: The ‘ – – ‘ operator is used to decrement the value of an integer. When placed before the variable name (also called pre-decrement operator), its value is decremented instantly. For example, – – x. And when it is placed after the variable name (also called post-decrement operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x – –.
C
C++
// C program to demonstrate working// of Unary arithmetic// operators#include <stdio.h> int main(){ int a = 10, b = 4, res; // post-increment example: // res is assigned 10 only, a is not updated yet res = a++; printf("a is %d and res is %d\n", a, res); // a becomes 11 now // post-decrement example: // res is assigned 11 only, a is not updated yet res = a--; printf("a is %d and res is %d\n", a, res); // a becomes 10 now // pre-increment example: // res is assigned 11 now since // a is updated here itself res = ++a; // a and res have same values = 11 printf("a is %d and res is %d\n", a, res); // pre-decrement example: // res is assigned 10 only since a is updated here // itself res = --a; // a and res have same values = 10 printf("a is %d and res is %d\n", a, res); return 0;}
#include <iostream>using namespace std; int main(){ int a = 10, b = 4, res; // post-increment example: // res is assigned 10 only, // a is not updated yet res = a++; // a becomes 11 now cout << "a is " << a << " and res is " << res << "\n"; // post-decrement example: // res is assigned 11 only, // a is not updated yet res = a--; // a becomes 10 now cout << "a is " << a << " and res is " << res << "\n"; // pre-increment example: // res is assigned 11 now // since a is updated here itself res = ++a; // a and res have same values = 11 cout << "a is " << a << " and res is " << res << "\n"; // pre-decrement example: // res is assigned 10 only // since a is updated here // itself res = --a; // a and res have same values = 10 cout << "a is " << a << " and res is " << res << "\n"; return 0;}
Output:
a is 11 and res is 10
a is 10 and res is 11
a is 11 and res is 11
a is 10 and res is 10
We will soon be discussing other categories of operators in different posts.To know about Operator Precedence and Associativity, refer this link:Quiz on Operators in CThis article is contributed by Ayush Jaggi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
sirraghavgupta
akhilsharma870
kartikbagri199
C-Operators
cpp-operator
C Language
cpp-operator
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
'this' pointer in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
Multiple Inheritance in C++
Smart Pointers in C++ and How to Use Them
Understanding "extern" keyword in C
Ways to copy a vector in C++
Basics of File Handling in C | [
{
"code": null,
"e": 25587,
"s": 25559,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25863,
"s": 25587,
"text": "Operators are the foundation of any programming language. Thus the functionality of C language is incomplete without the use of operators. Operators allow us to pe... |
How to Convert .rpm package to .deb using alien Package Converter? - GeeksforGeeks | 02 Nov, 2020
Most of the time there are packages (in repositories and GitHub) that are ready to use. But sometimes packages are not available in binaries (ready to install on the go) we have to download the source code and build from scratch. This is not an issue if you have time but for increasing Productivity.
Here is where Alien (package converter) comes into place. If an application like Zenmap (Nmap should be pre-installed) is readily available in .rpm form instead of .deb. We can convert that .rpm package to .deb on the go using alien, and we could install zenmap directly.
Installing the alien tool
Alien is available in most of the repositories but, In case you don’t have it you can find and install it from alien-git here. Here is the list of commands to be executed for the installation of the tool.
For Kali or other Debian based Distribution:
sudo apt-get install alien
To open the alien command manual page
1. Locate or download .rpm package of the software to be installed (Package used as an example can be downloaded from here).
2. Click on zenmap-7.91-1.noarch.rpm to get the rpm file(Skip this step if you are using your own rpm file)
3. The next step is to Use Alien to convert .rpm to .deb. Switch to the directory in which the package is located using the cd command.
alien --to-deb [file_name.rpm]
Note:- Replace file_name.rmp with the respective rmp file.
4. Then it can be seen that the Debian file is created for the package
5. Install the package using the following commands
chmod +x [file_name.deb]
sudo apt-get install ./[file_name.deb]
Note:- Replace file_name.deb with the respective deb file.
6. That’s it our application got installed and could be launched from the terminal using the application name
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
chown command in Linux with Examples
Docker - COPY Instruction
nohup Command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Array Basics in Shell Scripting | Set 1 | [
{
"code": null,
"e": 24504,
"s": 24476,
"text": "\n02 Nov, 2020"
},
{
"code": null,
"e": 24806,
"s": 24504,
"text": "Most of the time there are packages (in repositories and GitHub) that are ready to use. But sometimes packages are not available in binaries (ready to install on t... |
Find number of segments covering each point in an given array - GeeksforGeeks | 18 Feb, 2022
Given segments and some points, for each point find the number of segments covering that point.
A segment (l, r) covers a point x if and only if l < = x < = r.
Examples:
Input: Segments = {{0, 3}, {1, 3}, {3, 8}}, Points = {-1, 3, 8}.Output : {0, 3, 1}Explanation :
No segments passing through point -1
All the segments passing through point 3
Segment 3rd passing through point 8
Input: Segments = {{1, 3}, {2, 4}, {5, 7}}, Points = {0, 2, 5}.Output: {0, 2, 1}Explanation :
No segments passing through point 0
1st and 2nd segment passing through point 2
Segment 3rd passing through point 5
Approach:
We can do this by using logic similar to prefix sum.
Let’s represent a segment with (l, r). Form a vector of pairs, for each segment push two pairs in vector with values (l, +1) ans (r + 1, -1).
Sort the points in ascending order, but we also need it’s position so mapped it with it’s position.
Sort the segment vector in descending order because we iterate on it from back.
Make a variable count of segments, which is initially zero.
Then, we will iterate on the point and pop the pair from the segment vector until it’s first value is less than equal to current point and add it’s second value to the count.
Finally, Store the values of count in an array to his respective position and print the array.
Below is the implementation of the above approach.
C++
Java
Python3
Javascript
// C++ program to find the number of// segments covering each points#include<bits/stdc++.h>using namespace std; // Function to print an arrayvoid PrintArray(int n,int arr[]){ for(int i = 0; i < n; i++) { cout<<arr[i]<<" "; }} // Function prints number of segments// covering by each pointsvoid NumberOfSegments(vector<pair<int,int> >segments, vector<int>points, int s, int p){ vector< pair<int, int> >pts, seg; // Pushing points and index in // vector as a pairs for(int i = 0; i < p; i++) { pts.push_back({points[i], i});; } for(int i = 0; i < s; i++) { // (l,+1) seg.push_back({segments[i].first, 1}); // (r+1,-1) seg.push_back({segments[i].second+1, -1}); } // Sort the vectors sort(seg.begin(), seg.end(), greater<pair<int,int>>()); sort(pts.begin(),pts.end()); int count = 0; int ans[p]; for(int i = 0; i < p; i++) { int x = pts[i].first; while(!seg.empty() && seg.back().first <= x) { count+= seg.back().second; seg.pop_back(); } ans[pts[i].second] = count; } // Print the answer PrintArray(p, ans); } //Driver codeint main(){ // Initializing vector of pairs vector<pair<int,int>>seg; // Push segments seg.push_back({0, 3}); seg.push_back({1, 3}); seg.push_back({3, 8}); // Given points vector<int>point{-1, 3, 7}; int s = seg.size(); int p = point.size(); NumberOfSegments(seg, point, s, p); return 0;}
// Java program to find the number of // segments covering each pointsimport java.util.*;import java.lang.*; class GFG{ // Function to print an arraystatic void PrintArray(int n,int arr[]){ for(int i = 0; i < n; i++) { System.out.print(arr[i] + " "); }} // Function prints number of segments// covering by each pointsstatic void NumberOfSegments(ArrayList<int[]> segments, int[] points, int s, int p){ ArrayList<int[]> pts = new ArrayList<>(), seg = new ArrayList<>(); // Pushing points and index in // vector as a pairs for(int i = 0; i < p; i++) { pts.add(new int[]{points[i], i}); } for(int i = 0; i < s; i++) { // (l,+1) seg.add(new int[]{segments.get(i)[0], 1}); // (r+1,-1) seg.add(new int[]{segments.get(i)[1] + 1, -1}); } // Sort the vectors Collections.sort(seg, (a, b) -> b[0] - a[0]); Collections.sort(pts, (a, b) -> a[0] - b[0]); int count = 0; int[] ans = new int[p]; for(int i = 0; i < p; i++) { int x = pts.get(i)[0]; while (seg.size() != 0 && seg.get(seg.size() - 1)[0] <= x) { count += seg.get(seg.size() - 1)[1]; seg.remove(seg.size() - 1); } ans[pts.get(i)[1]] = count; } // Print the answer PrintArray(p, ans);} // Driver codepublic static void main(String[] args){ // Initializing vector of pairs ArrayList<int[]>seg = new ArrayList<>(); // Push segments seg.add(new int[]{0, 3}); seg.add(new int[]{1, 3}); seg.add(new int[]{3, 8}); // Given points int[] point = {-1, 3, 7}; int s = seg.size(); int p = point.length; NumberOfSegments(seg, point, s, p);}} // This code is contributed by offbeat
# Python3 program to find the number# of segments covering each point # Function to print an arraydef PrintArray(n, arr): for i in range(n): print(arr[i], end = " ") # Function prints number of segments# covering by each pointsdef NumberOfSegments(segments, points, s, p): pts = [] seg = [] # Pushing points and index in # vector as a pairs for i in range(p): pts.append([points[i], i]) for i in range(s): # (l, +1) seg.append([segments[i][0], 1]) # (r+1, -1) seg.append([segments[i][1] + 1, -1]) # Sort the vectors seg.sort(reverse = True) pts.sort(reverse = False) count = 0 ans = [0 for i in range(p)] for i in range(p): x = pts[i][0] while(len(seg) != 0 and seg[len(seg) - 1][0] <= x): count += seg[len(seg) - 1][1] seg.remove(seg[len(seg) - 1]) ans[pts[i][1]] = count # Print the answer PrintArray(p, ans) # Driver codeif __name__ == '__main__': # Initializing vector of pairs seg = [] # Push segments seg.append([ 0, 3 ]) seg.append([ 1, 3 ]) seg.append([ 3, 8 ]) # Given points point = [ -1, 3, 7 ] s = len(seg) p = len(point) NumberOfSegments(seg, point, s, p) # This code is contributed by Bhupendra_Singh
<script> // JavaScript program to find the number of// segments covering each points // Function to print an arrayfunction PrintArray(n,arr){ for(let i = 0; i < n; i++) { document.write(arr[i]," "); }} // Function prints number of segments// covering by each pointsfunction NumberOfSegments(segments,points,s,p){let pts = [];let seg = []; // Pushing points and index in// vector as a pairsfor(let i = 0; i < p; i++){ pts.push([points[i], i]);} for(let i = 0; i < s; i++){ // (l,+1) seg.push([segments[i][0], 1]); // (r+1,-1) seg.push([segments[i][1]+1, -1]);} // Sort the vectors seg.sort((a,b) => b[0]-a[0]);pts.sort((a,b) => a[0]-b[0]); let count = 0;let ans = new Array(p); for(let i = 0; i < p; i++){ let x = pts[i][0]; while(seg.length>0 && seg[seg.length-1][0] <= x) { count+= seg[seg.length-1][1]; seg.pop(); } ans[pts[i][1]] = count;} // Print the answerPrintArray(p, ans); } // Driver code // Initializing vector of pairslet seg = []; // Push segmentsseg.push([0, 3]);seg.push([1, 3]);seg.push([3, 8]); // Given pointslet point = [-1, 3, 7]; let s = seg.length;let p = point.length; NumberOfSegments(seg, point, s, p); // This code is contributed by shinjanpatra.</script>
0 3 1
Time Complexity: O(s*log(s) + p*log(p)), where s is the number of segments and p is the number of points.Auxiliary Space: O(s + p).
bgangwar59
offbeat
sweetyty
pankajsharmagfg
shinjanpatra
Algorithms
Competitive Programming
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to Start Learning DSA?
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
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
Top 10 Algorithms and Data Structures for Competitive Programming | [
{
"code": null,
"e": 26283,
"s": 26255,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 26379,
"s": 26283,
"text": "Given segments and some points, for each point find the number of segments covering that point."
},
{
"code": null,
"e": 26443,
"s": 26379,
"te... |
Count of integers of length N and value less than K such that they contain digits only from the given set - GeeksforGeeks | 05 Aug, 2021
Given a set of digits A[] in sorted order and two integers N and K, the task is to find how many numbers of length N are possible whose value is less than K and the digits are from the given set only. Note that you can use the same digit multiple times.
Examples:
Input: A[] = {0, 1, 5}, N = 1, K = 2 Output: 2 Only valid numbers are 0 and 1.
Input: A[] = {0, 1, 2, 5}, N = 2, K = 21 Output: 5 10, 11, 12, 15 and 20 are the valid numbers.
Approach: Let d be the size of A[]. We can break this problem into three simpler cases.
When N is greater than the length of K, It is obvious that if the length of N is greater than the length of k or if d is equal to 0, no such number is possible.When N is smaller than the length of K, then all possible combinations of digit of length N are valid. Also, we have to keep in mind that 0 can’t be in the first place. So, if A[] contains 0, the first place can be filled in (d – 1) ways. Since repetition is allowed and 0 can occupy the other places, rest N – 1 places can be filled in d * d * ... * d(N – 1) times i.e. in dN – 1 ways. Therefore the answer is (d – 1) * (dN – 1) if A[] contains 0 else dN.When N is equal to the length of K, this is the trickiest part. We need to use Dynamic Programming for this part. Construct a digit array of K. Let’s call it digit[]. Let First(i) be the number formed by taking the first i digits of it. Let lower[i] denote the number of elements in A[] which are smaller than i. For example, First(2) of 423 is 42. If A[] = {0, 2} then lower[0] = 0, lower[1] = 1, lower[2] = 1, lower[3] = 2. Generate N digit numbers by dynamic programming. Let dp[i] denote total numbers of length i which are less than first i digits of K. Elements in dp[i] can be generated by two cases: For all the numbers whose First(i – 1) is less than First(i – 1) of K, we can put any digit at ith index. Hence, dp[i] = dp[i] + (dp[i – 1] * d)For all the numbers whose First(i – 1) is the same as First(i – 1) of K, we can only put those digits which are smaller than digit[i]. Hence, dp[i] = dp[i] + lower[digit[i]].
When N is greater than the length of K, It is obvious that if the length of N is greater than the length of k or if d is equal to 0, no such number is possible.
When N is smaller than the length of K, then all possible combinations of digit of length N are valid. Also, we have to keep in mind that 0 can’t be in the first place. So, if A[] contains 0, the first place can be filled in (d – 1) ways. Since repetition is allowed and 0 can occupy the other places, rest N – 1 places can be filled in d * d * ... * d(N – 1) times i.e. in dN – 1 ways. Therefore the answer is (d – 1) * (dN – 1) if A[] contains 0 else dN.
When N is equal to the length of K, this is the trickiest part. We need to use Dynamic Programming for this part. Construct a digit array of K. Let’s call it digit[]. Let First(i) be the number formed by taking the first i digits of it. Let lower[i] denote the number of elements in A[] which are smaller than i. For example, First(2) of 423 is 42. If A[] = {0, 2} then lower[0] = 0, lower[1] = 1, lower[2] = 1, lower[3] = 2. Generate N digit numbers by dynamic programming. Let dp[i] denote total numbers of length i which are less than first i digits of K. Elements in dp[i] can be generated by two cases: For all the numbers whose First(i – 1) is less than First(i – 1) of K, we can put any digit at ith index. Hence, dp[i] = dp[i] + (dp[i – 1] * d)For all the numbers whose First(i – 1) is the same as First(i – 1) of K, we can only put those digits which are smaller than digit[i]. Hence, dp[i] = dp[i] + lower[digit[i]].
For all the numbers whose First(i – 1) is less than First(i – 1) of K, we can put any digit at ith index. Hence, dp[i] = dp[i] + (dp[i – 1] * d)
For all the numbers whose First(i – 1) is the same as First(i – 1) of K, we can only put those digits which are smaller than digit[i]. Hence, dp[i] = dp[i] + lower[digit[i]].
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAX 10 // Function to convert a number into vectorvector<int> numToVec(int N){ vector<int> digit; // Push all the digits of N from the end // one by one to the vector while (N != 0) { digit.push_back(N % 10); N = N / 10; } // If the original number was 0 if (digit.size() == 0) digit.push_back(0); // Reverse the vector elements reverse(digit.begin(), digit.end()); // Return the required vector return digit;} // Function to return the count of B length integers// which are less than C and they// contain digits from set A[] onlyint solve(vector<int>& A, int B, int C){ vector<int> digit; int d, d2; // Convert number to digit array digit = numToVec(C); d = A.size(); // Case 1: No such number possible as the // generated numbers will always // be greater than C if (B > digit.size() || d == 0) return 0; // Case 2: All integers of length B are valid // as they all are less than C else if (B < digit.size()) { // contain 0 if (A[0] == 0 && B != 1) return (d - 1) * pow(d, B - 1); else return pow(d, B); } // Case 3 else { int dp[B + 1] = { 0 }; int lower[MAX + 1] = { 0 }; // Update the lower[] array such that // lower[i] stores the count of elements // in A[] which are less than i for (int i = 0; i < d; i++) lower[A[i] + 1] = 1; for (int i = 1; i <= MAX; i++) lower[i] = lower[i - 1] + lower[i]; bool flag = true; dp[0] = 0; for (int i = 1; i <= B; i++) { d2 = lower[digit[i - 1]]; dp[i] = dp[i - 1] * d; // For first index we can't use 0 if (i == 1 && A[0] == 0 && B != 1) d2 = d2 - 1; // Whether (i-1) digit of generated number // can be equal to (i - 1) digit of C if (flag) dp[i] += d2; // Is digit[i - 1] present in A ? flag = (flag & (lower[digit[i - 1] + 1] == lower[digit[i - 1]] + 1)); } return dp[B]; }} // Driver codeint main(){ // Digits array vector<int> A = { 0, 1, 2, 5 }; int N = 2; int k = 21; cout << solve(A, N, k); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{static int MAX = 10; // Function to convert a number into vectorstatic Vector<Integer> numToVec(int N){ Vector<Integer> digit = new Vector<Integer>(); // Push all the digits of N from the end // one by one to the vector while (N != 0) { digit.add(N % 10); N = N / 10; } // If the original number was 0 if (digit.size() == 0) digit.add(0); // Reverse the vector elements Collections.reverse(digit); // Return the required vector return digit;} // Function to return the count// of B length integers which are// less than C and they contain// digits from set A[] onlystatic int solve(Vector<Integer> A, int B, int C){ Vector<Integer> digit = new Vector<Integer>(); int d, d2; // Convert number to digit array digit = numToVec(C); d = A.size(); // Case 1: No such number possible as the // generated numbers will always // be greater than C if (B > digit.size() || d == 0) return 0; // Case 2: All integers of length B are valid // as they all are less than C else if (B < digit.size()) { // contain 0 if (A.get(0) == 0 && B != 1) return (int) ((d - 1) * Math.pow(d, B - 1)); else return (int) Math.pow(d, B); } // Case 3 else { int []dp = new int[B + 1]; int []lower = new int[MAX + 1]; // Update the lower[] array such that // lower[i] stores the count of elements // in A[] which are less than i for (int i = 0; i < d; i++) lower[A.get(i) + 1] = 1; for (int i = 1; i <= MAX; i++) lower[i] = lower[i - 1] + lower[i]; boolean flag = true; dp[0] = 0; for (int i = 1; i <= B; i++) { d2 = lower[digit.get(i - 1)]; dp[i] = dp[i - 1] * d; // For first index we can't use 0 if (i == 1 && A.get(0) == 0 && B != 1) d2 = d2 - 1; // Whether (i-1) digit of generated number // can be equal to (i - 1) digit of C if (flag) dp[i] += d2; // Is digit[i - 1] present in A ? flag = (flag & (lower[digit.get(i - 1) + 1] == lower[digit.get(i - 1)] + 1)); } return dp[B]; }} // Driver codepublic static void main(String[] args){ Integer arr[] = { 0, 1, 2, 5 }; // Digits array Vector<Integer> A = new Vector<>(Arrays.asList(arr)); int N = 2; int k = 21; System.out.println(solve(A, N, k));}} // This code is contributed// by PrinciRaj1992
# Python3 implementation of the approachMAX=10 # Function to convert a number into vectordef numToVec(N): digit = [] # Push all the digits of N from the end # one by one to the vector while (N != 0): digit.append(N % 10) N = N // 10 # If the original number was 0 if (len(digit) == 0): digit.append(0) # Reverse the vector elements digit = digit[::-1] # Return the required vector return digit # Function to return the count of B length integers# which are less than C and they# contain digits from set A[] onlydef solve(A, B, C): d, d2 = 0,0 # Convert number to digit array digit = numToVec(C) d = len(A) # Case 1: No such number possible as the # generated numbers will always # be greater than C if (B > len(digit) or d == 0): return 0 # Case 2: All integers of length B are valid # as they all are less than C elif (B < len(digit)): # contain 0 if (A[0] == 0 and B != 1): return (d - 1) * pow(d, B - 1) else: return pow(d, B) # Case 3 else : dp=[0 for i in range(B + 1)] lower=[0 for i in range(MAX + 1)] # Update the lower[] array such that # lower[i] stores the count of elements # in A[] which are less than i for i in range(d): lower[A[i] + 1] = 1 for i in range(1, MAX+1): lower[i] = lower[i - 1] + lower[i] flag = True dp[0] = 0 for i in range(1, B+1): d2 = lower[digit[i - 1]] dp[i] = dp[i - 1] * d # For first index we can't use 0 if (i == 1 and A[0] == 0 and B != 1): d2 = d2 - 1 # Whether (i-1) digit of generated number # can be equal to (i - 1) digit of C if (flag): dp[i] += d2 # Is digit[i - 1] present in A ? flag = (flag & (lower[digit[i - 1] + 1] == lower[digit[i - 1]] + 1)) return dp[B] # Driver code # Digits arrayA =[0, 1, 2, 5]N = 2k = 21 print(solve(A, N, k)) # This code is contributed by mohit kumar 29
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{static int MAX = 10; // Function to convert a number into vectorstatic List<int> numToVec(int N){ List<int> digit = new List<int>(); // Push all the digits of N from the end // one by one to the vector while (N != 0) { digit.Add(N % 10); N = N / 10; } // If the original number was 0 if (digit.Count == 0) digit.Add(0); // Reverse the vector elements digit.Reverse(); // Return the required vector return digit;} // Function to return the count// of B length integers which are// less than C and they contain// digits from set A[] onlystatic int solve(List<int> A, int B, int C){ List<int> digit = new List<int>(); int d, d2; // Convert number to digit array digit = numToVec(C); d = A.Count; // Case 1: No such number possible as the // generated numbers will always // be greater than C if (B > digit.Count || d == 0) return 0; // Case 2: All integers of length B are valid // as they all are less than C else if (B < digit.Count) { // contain 0 if (A[0] == 0 && B != 1) return (int) ((d - 1) * Math.Pow(d, B - 1)); else return (int) Math.Pow(d, B); } // Case 3 else { int []dp = new int[B + 1]; int []lower = new int[MAX + 1]; // Update the lower[] array such that // lower[i] stores the count of elements // in A[] which are less than i for (int i = 0; i < d; i++) lower[A[i] + 1] = 1; for (int i = 1; i <= MAX; i++) lower[i] = lower[i - 1] + lower[i]; Boolean flag = true; dp[0] = 0; for (int i = 1; i <= B; i++) { d2 = lower[digit[i-1]]; dp[i] = dp[i - 1] * d; // For first index we can't use 0 if (i == 1 && A[0] == 0 && B != 1) d2 = d2 - 1; // Whether (i-1) digit of generated number // can be equal to (i - 1) digit of C if (flag) dp[i] += d2; // Is digit[i - 1] present in A ? flag = (flag & (lower[digit[i-1] + 1] == lower[digit[i-1]] + 1)); } return dp[B]; }} // Driver codepublic static void Main(String[] args){ int []arr = { 0, 1, 2, 5 }; // Digits array List<int> A = new List<int>(arr); int N = 2; int k = 21; Console.WriteLine(solve(A, N, k));}} // This code is contributed by Rajput-Ji
<script> // Javascript implementation of the approachlet MAX = 10; // Function to convert a number into vectorfunction numToVec(N){ let digit = []; // Push all the digits of N from the end // one by one to the vector while (N != 0) { digit.push(N % 10); N = Math.floor(N / 10); } // If the original number was 0 if (digit.length == 0) digit.push(0); // Reverse the vector elements digit.reverse(); // Return the required vector return digit;} // Function to return the count// of B length integers which are// less than C and they contain// digits from set A[] onlyfunction solve(A, B, C){ let digit = []; let d, d2; // Convert number to digit array digit = numToVec(C); d = A.length; // Case 1: No such number possible as the // generated numbers will always // be greater than C if (B > digit.length || d == 0) return 0; // Case 2: All integers of length B are valid // as they all are less than C else if (B < digit.length) { // contain 0 if (A[0] == 0 && B != 1) return Math.floor((d - 1) * Math.pow(d, B - 1)); else return Math.floor(Math.pow(d, B)); } // Case 3 else { let dp = new Array(B + 1); let lower = new Array(MAX + 1); for(let i = 0; i < dp.length; i++) { dp[i] = 0; } for(let i = 0; i < lower.length; i++) { lower[i] = 0; } // Update the lower[] array such that // lower[i] stores the count of elements // in A[] which are less than i for(let i = 0; i < d; i++) lower[A[i] + 1] = 1; for(let i = 1; i <= MAX; i++) lower[i] = lower[i - 1] + lower[i]; let flag = true; dp[0] = 0; for(let i = 1; i <= B; i++) { d2 = lower[digit[i - 1]]; dp[i] = dp[i - 1] * d; // For first index we can't use 0 if (i == 1 && A[0] == 0 && B != 1) d2 = d2 - 1; // Whether (i-1) digit of generated number // can be equal to (i - 1) digit of C if (flag) dp[i] += d2; // Is digit[i - 1] present in A ? flag = (flag & (lower[digit[i - 1] + 1] == lower[digit[i - 1]] + 1)); } return dp[B]; }} // Driver codelet arr = [ 0, 1, 2, 5 ];let N = 2;let k = 21; document.write(solve(arr, N, k)); // This code is contributed by patel2127 </script>
5
Time complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
princiraj1992
ChaitanyaBankanhal
Rajput-Ji
patel2127
pankajsharmagfg
Algorithms
Arrays
Dynamic Programming
Mathematical
Strings
Arrays
Strings
Dynamic Programming
Mathematical
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to write a Pseudo Code?
Understanding Time Complexity with Simple Examples
How to Start Learning DSA?
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation | [
{
"code": null,
"e": 26151,
"s": 26123,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 26405,
"s": 26151,
"text": "Given a set of digits A[] in sorted order and two integers N and K, the task is to find how many numbers of length N are possible whose value is less than K and th... |
Basis Path Testing in Software Testing - GeeksforGeeks | 07 Jul, 2020
Prerequisite – Path TestingBasis Path Testing is a white-box testing technique based on the control structure of a program or a module. Using this structure, a control flow graph is prepared and the various possible paths present in the graph are executed as a part of testing. Therefore, by definition,
Basis path testing is a technique of selecting the paths in the control flow graph, that provide a basis set of execution paths through the program or module.
Since this testing is based on the control structure of the program, it requires complete knowledge of the program’s structure. To design test cases using this technique, four steps are followed :
Construct the Control Flow GraphCompute the Cyclomatic Complexity of the GraphIdentify the Independent PathsDesign Test cases from Independent Paths
Construct the Control Flow Graph
Compute the Cyclomatic Complexity of the Graph
Identify the Independent Paths
Design Test cases from Independent Paths
Let’s understand each step one by one.
1. Control Flow Graph –A control flow graph (or simply, flow graph) is a directed graph which represents the control structure of a program or module. A control flow graph (V, E) has V number of nodes/vertices and E number of edges in it. A control graph can also have :
Junction Node – a node with more than one arrow entering it.
Decision Node – a node with more then one arrow leaving it.
Region – area bounded by edges and nodes (area outside the graph is also counted as a region.).
Below are the notations used while constructing a flow graph :
Sequential Statements –
If – Then – Else –
Do – While –
While – Do –
Switch – Case –
Cyclomatic Complexity –The cyclomatic complexity V(G) is said to be a measure of the logical complexity of a program. It can be calculated using three different formulae :
Formula based on edges and nodes :V(G) = e - n + 2*PWhere,e is number of edges,n is number of vertices,P is number of connected components.For example, consider first graph given above,where, e = 4, n = 4 and p = 1
So,
Cyclomatic complexity V(G)
= 4 - 4 + 2 * 1
= 2 Formula based on Decision Nodes :V(G) = d + P where,d is number of decision nodes,P is number of connected nodes.For example, consider first graph given above,where, d = 1 and p = 1
So,
Cyclomatic Complexity V(G)
= 1 + 1
= 2 Formula based on Regions :V(G) = number of regions in the graphFor example, consider first graph given above,Cyclomatic complexity V(G)
= 1 (for Region 1) + 1 (for Region 2)
= 2
Formula based on edges and nodes :V(G) = e - n + 2*PWhere,e is number of edges,n is number of vertices,P is number of connected components.For example, consider first graph given above,where, e = 4, n = 4 and p = 1
So,
Cyclomatic complexity V(G)
= 4 - 4 + 2 * 1
= 2
V(G) = e - n + 2*P
Where,e is number of edges,n is number of vertices,P is number of connected components.
For example, consider first graph given above,
where, e = 4, n = 4 and p = 1
So,
Cyclomatic complexity V(G)
= 4 - 4 + 2 * 1
= 2
Formula based on Decision Nodes :V(G) = d + P where,d is number of decision nodes,P is number of connected nodes.For example, consider first graph given above,where, d = 1 and p = 1
So,
Cyclomatic Complexity V(G)
= 1 + 1
= 2
V(G) = d + P
where,d is number of decision nodes,P is number of connected nodes.
For example, consider first graph given above,
where, d = 1 and p = 1
So,
Cyclomatic Complexity V(G)
= 1 + 1
= 2
Formula based on Regions :V(G) = number of regions in the graphFor example, consider first graph given above,Cyclomatic complexity V(G)
= 1 (for Region 1) + 1 (for Region 2)
= 2
V(G) = number of regions in the graph
For example, consider first graph given above,
Cyclomatic complexity V(G)
= 1 (for Region 1) + 1 (for Region 2)
= 2
Hence, using all the three above formulae, the cyclomatic complexity obtained remains same. All these three formulae can be used to compute and verify the cyclomatic complexity of the flow graph.
Note –
For one function [e.g. Main( ) or Factorial( ) ], only one flow graph is constructed. If in a program, there are multiple functions, then a separate flow graph is constructed for each one of them. Also, in the cyclomatic complexity formula, the value of ‘p’ is set depending of the number of graphs present in total.If a decision node has exactly two arrows leaving it, then it is counted as one decision node. However, if there are more than 2 arrows leaving a decision node, it is computed using this formula :d = k - 1Here, k is number of arrows leaving the decision node.
For one function [e.g. Main( ) or Factorial( ) ], only one flow graph is constructed. If in a program, there are multiple functions, then a separate flow graph is constructed for each one of them. Also, in the cyclomatic complexity formula, the value of ‘p’ is set depending of the number of graphs present in total.
If a decision node has exactly two arrows leaving it, then it is counted as one decision node. However, if there are more than 2 arrows leaving a decision node, it is computed using this formula :d = k - 1Here, k is number of arrows leaving the decision node.
d = k - 1
Here, k is number of arrows leaving the decision node.
Independent Paths :An independent path in the control flow graph is the one which introduces at least one new edge that has not been traversed before the path is defined. The cyclomatic complexity gives the number of independent paths present in a flow graph. This is because the cyclomatic complexity is used as an upper-bound for the number of tests that should be executed in order to make sure that all the statements in the program have been executed at least once.
Consider first graph given above here the independent paths would be 2 because number of independent paths is equal to the cyclomatic complexity.So, the independent paths in above first given graph :
Path 1:A -> B
A -> B
Path 2:C -> D
C -> D
Note –Independent paths are not unique. In other words, if for a graph the cyclomatic complexity comes out be N, then there is a possibility of obtaining two different sets of paths which are independent in nature.
Design Test Cases :Finally, after obtaining the independent paths, test cases can be designed where each test case represents one or more independent paths.
Advantages :Basis Path Testing can be applicable in the following cases:
More Coverage –Basis path testing provides the best code coverage as it aims to achieve maximum logic coverage instead of maximum path coverage. This results in an overall thorough testing of the code.Maintenance Testing –When a software is modified, it is still necessary to test the changes made in the software which as a result, requires path testing.Unit Testing –When a developer writes the code, he or she tests the structure of the program or module themselves first. This is why basis path testing requires enough knowledge about the structure of the code.Integration Testing –When one module calls other modules, there are high chances of Interface errors. In order to avoid the case of such errors, path testing is performed to test all the paths on the interfaces of the modules.Testing Effort –Since the basis path testing technique takes into account the complexity of the software (i.e., program or module) while computing the cyclomatic complexity, therefore it is intuitive to note that testing effort in case of basis path testing is directly proportional to the complexity of the software or program.
More Coverage –Basis path testing provides the best code coverage as it aims to achieve maximum logic coverage instead of maximum path coverage. This results in an overall thorough testing of the code.
Maintenance Testing –When a software is modified, it is still necessary to test the changes made in the software which as a result, requires path testing.
Unit Testing –When a developer writes the code, he or she tests the structure of the program or module themselves first. This is why basis path testing requires enough knowledge about the structure of the code.
Integration Testing –When one module calls other modules, there are high chances of Interface errors. In order to avoid the case of such errors, path testing is performed to test all the paths on the interfaces of the modules.
Testing Effort –Since the basis path testing technique takes into account the complexity of the software (i.e., program or module) while computing the cyclomatic complexity, therefore it is intuitive to note that testing effort in case of basis path testing is directly proportional to the complexity of the software or program.
einzig7777
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Functional vs Non Functional Requirements
Differences between Verification and Validation
Software Engineering | Classical Waterfall Model
Software Testing | Basics
Software Requirement Specification (SRS) Format
Levels in Data Flow Diagrams (DFD)
Difference between Alpha and Beta Testing
Software Engineering | White box Testing
Software Engineering | Integration Testing
Software Engineering | Seven Principles of software testing | [
{
"code": null,
"e": 26170,
"s": 26142,
"text": "\n07 Jul, 2020"
},
{
"code": null,
"e": 26474,
"s": 26170,
"text": "Prerequisite – Path TestingBasis Path Testing is a white-box testing technique based on the control structure of a program or a module. Using this structure, a con... |
How to join list of lists in python? | There are different ways to flatten a list of lists. Straightforward way is to run two nested loops – outer loop gives one sublist of lists, and inner loop gives one element of sublist at a time. Each element is appended to flat list object.
L1=[[1,2],[3,4,5],[6,7,8,9]]
flat=[]
for i in L1:
for j in i:
flat.append(j)
print (flat)
Another method is to use a generator function to yield an iterator and convert it to a list
def flatten(list):
for i in list:
for j in i:
yield j
L1=[[1,2,3],[4,5],[6,7,8,9]]
flat=flatten(L1)
print (list(flat))
Most compact method is to use chain() method from itertools module
L1=[[1,2,3],[4,5],[6,7,8,9]]
import itertools
flat=itertools.chain.from_iterable(L1)
print (list(flat))
All the above codes produce a flattened list
[1, 2, 3, 4, 5, 6, 7, 8, 9] | [
{
"code": null,
"e": 1304,
"s": 1062,
"text": "There are different ways to flatten a list of lists. Straightforward way is to run two nested loops – outer loop gives one sublist of lists, and inner loop gives one element of sublist at a time. Each element is appended to flat list object."
},
{
... |
Python Variable Assignment. Explaining One Of The Most Fundamental... | by Farhad Malik | Towards Data Science | This article aims to explain how Python variable assignment works.
Variables store information that can be used and/or changed in your program. This information can be an integer, text, collection, etc.
Variables are used to hold user inputs, local states of your program, etc.
Variables have a name so that they can be referenced in the code.
The fundamental concept to understand is that everything is an object in Python.
Python supports numbers, strings, sets, lists, tuples, and dictionaries. These are the standard data types. I will explain each of them in detail.
Assignment sets a value to a variable.
To assign variable a value, use the equals sign (=)
myFirstVariable = 1mySecondVariable = 2myFirstVariable = "Hello You"
Assigning a value is known as binding in Python. In the example above, we have assigned the value of 2 to mySecondVariable.
Note how I assigned an integer value of 1 and then a string value of “Hello You” to the same myFirstVariable variable. This is possible due to the fact that the data types are dynamically typed in python.
This is why Python is known as a dynamically typed programming language.
If you want to assign the same value to more than one variable then you can use the chained assignment:
myFirstVariable = mySecondVariable = 1
Integers, decimals, floats are supported.
value = 1 #integervalue = 1.2 #float with a floating point
Longs are also supported. They have a suffix of L e.g. 9999999999999L
Textual information. Strings are a sequence of letters.
A string is an array of characters
A string value is enclosed in quotation marks: single, double or triple quotes.
name = 'farhad'name = "farhad"name = """farhad"""
Strings are immutable. Once they are created, they cannot be changed e.g.
a = 'me'Updating it will fail:a[1]='y'It will throw a Type Error
When variables are assigned a new value then internally, Python creates a new object to store the value.
Therefore a reference/pointer to an object is created. This pointer is then assigned to the variable and as a result, the variable can be used in the program.
We can also assign one variable to another variable. All it does is that a new pointer is created which points to the same object:
a = 1 #new object is created and 1 is stored there, new pointer is created, the pointer connects a to 1b = a #new object is not created, new pointer is created only that connects b to 1
Variables declared within a function, as an example, can only exist within the block.
Once the block exists, the variables also become inaccessible.
def some_funcion(): TestMode = Falseprint(TestMode) <- Breaks as the variable doesn't exist outside
In Python, if-else and for/while loop block doesn’t create any local scope.
for i in range(1, 11): test_scope = "variable inside for loop"print(test_scope)
Output:
variable inside for loop
With if-else block
is_python_awesome = Trueif is_python_awesome: test_scope = "Python is awesome"print(test_scope)
Output:
Python is awesome
Variables that can be accessed from any function have a global scope. They exist in the __main__ frame.
You can declare a global variable outside of functions. It’s important to note that to assign a global variable a new value, you will have to use the “global” keyword:
TestMode = Truedef some_function(): global TestMode TestMode = Falsesome_function()print(TestMode) <--Returns False
Removing the line “global TestMode” will only set the variable to False within the some_function() function.
Note: Although I will write more on the concept of modules later, but if you want to share a global variable across a number of modules then you can create a shared module file e.g. configuration.py and locate your variable there. Finally, import the shared module in your consumer modules.
If you want to find the type of a variable, you can implement:
type('farhad')--> Returns <type 'str'>
Commas are treated as a sequence of variables e.g.
9,8,7 are three numeric variables
Allows us to perform computation on variables
Python supports basic *, /, +, -
Python also supports floor division
1//3 #returns 01/3 #returns 0.333
Additionally, python supports exponentiation via ** operator:
2**3 = 2 * 2 * 2 = 8
Python supports Modulus (remainder) operator too:
7%2 = 1
There is also a divmod in-built method. It returns the divider and modulus:
print(divmod(10,3)) #it will print 3 and 1 as 3*3 = 9 +1 = 10
Concat Strings:
'A' + 'B' = 'AB'
Remember string is an immutable data type, therefore, concatenating strings creates a new string object.
Repeat String:
‘A’*3 will repeat A three times: AAA
Slicing:
y = 'Abc'y[:2] = aby[1:] = bcy[:-2] = ay[-2:] = bc
Reversing:
x = 'abc'x = x[::-1]
Negative Index:
If you want to start from the last character then use a negative index.
y = 'abc'print(y[:-1]) # will return ab
It is also used to remove any new line carriages/spaces.
Each element in an array gets two indexes:
From left to right, the index starts at 0 and increments by 1
From right to left, the index starts at -1 and decrements by 1
Therefore, if we do y[0] and y[-len(y)] then both will return the same value: ‘a’
y = 'abc'print(y[0])print(y[-len(y)])
Finding Index
name = 'farhad'index = name.find('r')#returns 2name = 'farhad'index = name.find('a', 2) # finds index of second a#returns 4
For Regex, use:
split(): splits a string into a list via regex
sub(): replaces matched string via regex
subn(): replaces matched string via regex and returns the number of replacements
str(x): To string
int(x): To integer
float(x): To floats
tuple(list) : To tuple: print(tuple([1,2,3]))
list(tuple(1,2,3)): To list: print(list((1,2,3)))
Remember list is mutable (can be updated) and tuple is immutable (read-only)
The set is an unordered data collection without any duplicates. We can define a set variable as:
a = {1,2,3}
Intersect Sets
To get what’s common in two sets
a = {1,2,3}b = {3,4,5}c = a.intersection(b)
Difference In Sets
To retrieve the difference between the two sets:
a = {1,2,3}b = {3,4,5}c = a.difference(b)
Union Of Collections
To get a distinct combined set of two sets
a = {1,2,3}b = {3,4,5}c = a.union(b)
Used to write conditional statements in a single line.
Syntax:
[If True] if [Expression] Else [If False]
For example:
Received = True if x == 'Yes' else False
I will attempt to explain the important subject of Object Identity now.
Whenever we create an object in Python such as a variable, function, etc, the underlying Python interpreter creates a number that uniquely identifies that object. Some of the objects are created up-front.
When an object is not referenced anymore in the code then it is removed and its identity number can be used by other variables.
Python code is loaded into frames that are located into a Stack.
Functions are loaded in a frame along with their parameters and variables.
Subsequently, frames are loaded into a stack in the right order of execution.
Stack outlines the execution of functions. Variables that are declared outside of functions are stored in __main__
Stacks executes the last frame first.
You can use traceback to find the list of functions if an error is encountered.
dir() and help()
dir() -displays defined symbols
help() — displays documentation
Consider the code below:
var_one = 123def func_one(var_one): var_one = 234 var_three = 'abc'var_two = 456print(dir())
var_one and var_two are the two variables that are defined in the code above. Along with the variables, a function named func_one is also defined. An important note to keep in mind is that everything is an object in Python, including a function.
Within the function, we have assigned the value of 234 to var_one and created a new variable named var_three and assigned it a value of ‘abc’.
Now, let’s understand the code with the help of dir() and id()
The above code and its variables and functions will be loaded in the Global frame. The global frame will hold all of the objects that the other frames require. As an example, there are many built-in methods loaded in Python that are available to all of the frames. These are the function frames.
Running the above code will print:
[‘__annotations__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘func_one’, ‘var_one’, ‘var_two’]
The variables that are prefixed with __ are known as the special variables.
Notice that the var_three is not available yet. Let’s execute func_one(var_one) and then assess the dir():
var_one = 123def func_one(var_one): var_one = 234 var_three = 'abc'var_two = 456func_one(var_one)print(dir())
We will again see the same list:
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'func_one', 'var_one', 'var_two']
This means that the variables within the func_one are only within the func_one. When func_one is executed then a Frame is created. Python is top-down therefore it always executes the lines from top to the bottom.
The function frame can reference the variables in the global frame but any other function frame cannot reference the same variables that are created within itself. As an instance, if I create a new function func_two that tries to print var_three then it will fail:
var_one = 123def func_one(var_one): var_one = 234 var_three = 'abc'var_two = 456def func_two(): print(var_three)func_one(var_one)func_two()print(dir())
We get an error that NameError: name ‘var_three’ is not defined
What if we create a new variable inside func_two() and then print the dir()?
var_one = 123def func_one(var_one): var_one = 234 var_three = 'abc'var_two = 456def func_two(): var_four = 123 print(dir())func_two()
This will print var_four as it is local to func_two.
This is by far one of the most important concepts to understand in Python. Python has an id() function.
When an object (function, variable, etc.) is created, CPython allocates it an address in memory. The id() function returns the “identity” of an object. It is essentially a unique integer.
As an instance, let’s create four variables and assign them values:
variable1 = 1variable2 = "abc"variable3 = (1,2)variable4 = ['a',1]#Print their Idsprint('Variable1: ', id(variable1))print('Variable2: ', id(variable2))print('Variable3: ', id(variable3))print('Variable4: ', id(variable4))
The ids will be printed as follows:
Variable1: 1747938368Variable2: 152386423976Variable3: 152382712136Variable4: 152382633160
Each variable has been assigned a new integer value.
The first assumption is that whenever we use the assignment “=” then Python creates a new memory address to store the variable. Is it 100% true, not really!
I am going to create two variables and assign them to the existing variables.
variable5 = variable1variable6 = variable4print('Variable1: ', id(variable1))print('Variable4: ', id(variable4))print('Variable5: ', id(variable5))print('Variable6: ', id(variable6))
Python printed:
Variable1: 1747938368Variable4: 819035469000Variable5: 1747938368Variable6: 819035469000
Notice that Python did not create new memory addresses for the two variables. This time, it pointed both of the variables to the same memory location.
Let’s set a new value to the variable1. Remember 2 is an integer and integer is an immutable data type.
print('Variable1: ', id(variable1))variable1 = 2print('Variable1: ', id(variable1))
This will print:
Variable1: 1747938368Variable1: 1747938400
It means whenever we use the = and assign a new value to a variable that is not a variable reference then internally a new memory address is created to store the variable. Let’s see if it holds!
What happens when the variable is a mutable data type?
variable6 is a list. Let’s append an item to it and print its memory address:
print('Variable6: ', id(variable6))variable6.append('new')print('Variable6: ', id(variable6))
Note that the memory address remained the same for the variable as it is a mutable data type and we simply updated its elements.
Variable6: 678181106888Variable6: 678181106888
Let’s create a function and pass a variable to it. If we set the value of the variable inside the function, what will it do internally? let’s assess
def update_variable(variable_to_update): print(id(variable_to_update))update_variable(variable6)print(’Variable6: ', id(variable6))
We get:
678181106888Variable6: 678181106888
Notice that the id of variable_to_update points to the id of the variable 6.
This means that if we update the variable_to_update in a function and if variable_to_update is a mutable data type then we’ll update variable6.
variable6 = [’new’]print(’Variable6: ', variable6def update_variable(variable_to_update): variable_to_update.append(’inside’)update_variable(variable6)print('Variable6: ', variable6)
This printed:
Variable6: [‘new’]Variable6: [‘new’, ‘inside’]
It shows us that the same object is updated within the function as it was expected because both of them had the same ID.
If we assign a new value to a variable, regardless of if it’s immutable and mutable data type then the change will be lost once we come out of the function:
print('Variable6: ', variable6)def update_variable(variable_to_update): print(id(variable_to_update)) variable_to_update = ['inside']update_variable(variable6)print('Variable6: ', variable6)
Variable6: [‘new’]344115201992Variable6: [‘new’]
Now an interesting scenario: Python doesn’t always create a new memory address for all new variables. Let me explain.
Finally, what if we assign two different variables a string value such as ‘a’. Will it create two memory addresses?
variable_nine = "a"variable_ten = "a"print('Variable9: ', id(variable_nine))print('Variable10: ', id(variable_ten))
Notice, both the variables have the same memory location:
Variable9: 792473698064Variable10: 792473698064
What if we create two different variables and assign them a long string value:
variable_nine = "a"*21variable_ten = "a"*21print('Variable9: ', id(variable_nine))print('Variable10: ', id(variable_ten))
This time Python created two memory locations for the two variables:
Variable9: 541949933872Variable10: 541949933944
This is because Python creates an internal cache of values when it starts up. This is done to provide faster results. It creates a handful of memory addresses for small integers such as between -5 to 256 and smaller string values. This is the reason why both of the variables in our example had the same ID.
This article explained how variables are assigned.
If you want to understand Python in detail then read this article: | [
{
"code": null,
"e": 239,
"s": 172,
"text": "This article aims to explain how Python variable assignment works."
},
{
"code": null,
"e": 375,
"s": 239,
"text": "Variables store information that can be used and/or changed in your program. This information can be an integer, text, ... |
How to use column with colours to change the colour of points using ggplot2 in R? | If we have a colour column in an R data frame and we want to change the point colours in ggplot2 using that column then colour argument will be used. For example, if we have a data frame called df that contains three columns say x, y, and color then the scatterplot between x and y with the colour of points using color column can be created by using the command ggplot(df,aes(x,y))+geom_point(colour=df$color)
Consider the below data frame −
Live Demo
> x<-rnorm(20)
> y<-rnorm(20)
> col<-sample(c("blue","red","green"),20,replace=T)
> df<-data.frame(x,y,col)
> df
x y col
1 1.92321342 1.2183501 green
2 0.73342537 -0.6477975 green
3 -1.00606105 -1.2697246 red
4 0.73504980 -0.5593899 red
5 -0.39976314 0.1185340 green
6 -1.15940677 -0.7219141 green
7 1.81313147 -2.1268507 blue
8 -0.47278398 -1.0414317 blue
9 -1.33914777 -0.2756125 blue
10 0.05742411 1.4000877 blue
11 -0.13134085 -0.8916141 green
12 0.87743445 -0.4291995 green
13 0.55897765 0.2815842 blue
14 0.51374603 -1.0219416 blue
15 0.27037163 0.7545370 blue
16 0.02100292 0.2674216 green
17 0.73620835 0.6262369 blue
18 -0.11391829 -0.7456059 green
19 -0.64697468 0.6713425 red
20 0.37972640 3.7717047 red
Loading ggplot2 package and creating scatterplot between x and y −
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_point()
Creating the scatterplot between x and y with colour of points in col column −
> ggplot(df,aes(x,y))+geom_point(colour=df$col) | [
{
"code": null,
"e": 1473,
"s": 1062,
"text": "If we have a colour column in an R data frame and we want to change the point colours in ggplot2 using that column then colour argument will be used. For example, if we have a data frame called df that contains three columns say x, y, and color then the... |
Data objects and Structures | Data structures are defined as special classes implemented to hold data only, i.e. Pure models, e.g. Car, Kid, Animal, Event, Employee, Company, Customer ...etc. Those data are generally declared or considered as instance variables in other classes beginnings.
The methods of this class should not perform any real significant work, otherwise the data structure class is not a data structure anymore!
So mainly, the methods are getters and setters (i.e. accessors and mutators), generally because the instance variables are treated as private. There is alternative opinion: that Data structure variables should be public, and can be accessed directly from the instance of the class, but it is debatable that the private variables concept is better.
In that context, the data structure class, reveals or exposes its data (variables) and have no meaningful (significant) methods or functions.
A normal class (Called Object here), like MainActivity, ListAdapter, Calculator, Iterator, conceals their data, and reveals or exposes their methods that work on those data.
So, we have two approaches to solve the problem in hand, i.e. implement a data Structure in its purest form, while building another Object class to build operations on their data, OR, we can make the model classes as Object classes, that conceals their data while exposes their methods, like in the following example
public class Square {
public Point topLeft1;
public double side1;
}
public class Rectangle {
public Point topLeft1;
public double height1;
public double width1;
}
public class Circle {
public Point center1;
public double radius1;
}
public class Geometry {
public final double PI = 3.141592653589793;
public double area(Object shape) throws NoSuchShapeException {
if (shape instanceof Square) {
Square s = (Square)shape;
return s.side1 x s.side1;
}else if (shape instanceof Rectangle) {
Rectangle r = (Rectangle)shape;
return r.height1 x r.width1;
}else if (shape instanceof Circle) {
Circle c = (Circle)shape;
return PI x c.radius1 x c.radius1; }
throw new NoSuchShapeException(); }
}
In this solution the shapes are treated as data structures, while Geometry class is treated as Object.
Advantage − If we require adding more methods we will add them only in the Geometry class (this is the time this solution should be implemented).
Disadvantage − If we require to add more Data Structures (i.e. more shapes), we will have to change all your methods in the Geometry class.
Objects expose behaviour and conceal data. This makes it simple to add new kinds of objects without changing existing behaviours. It also makes it difficult to add new behaviours to existing objects.
Data structures reveal or expose data and have no significant behaviour. This makes it simple to add new behaviours to existing data structures but makes it hard to add new data structures to existing functions. | [
{
"code": null,
"e": 1323,
"s": 1062,
"text": "Data structures are defined as special classes implemented to hold data only, i.e. Pure models, e.g. Car, Kid, Animal, Event, Employee, Company, Customer ...etc. Those data are generally declared or considered as instance variables in other classes begi... |
Interactive plotting with Bokeh. Interactive plots with few lines of... | by Roman Orac | Towards Data Science | As a JupyterLab power user, I like using Bokeh for plotting because of its interactive plots. JupyterLab also offers an extension for interactive matplotlib, but it is slow and it crashes with bigger datasets.
A thing I don’t like about Bokeh is its overwhelming documentation and complex examples. Sometimes I want to make a simple line plot and I struggle with 10 or more lines of Bohek specific code. But Bokeh code can be very concise as I am going to show below. This is also the main goal, to show a few useful data visualizations with as little code as possible.
Here are a few links that might interest you:
- Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers
Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases.
Description from its website sums it up nicely:
Bokeh is an interactive visualization library that targets modern web browsers for presentation. Its goal is to provide elegant, concise construction of versatile graphics, and to extend this capability with high-performance interactivity over very large or streaming datasets. Bokeh can help anyone who would like to quickly and easily create interactive plots, dashboards, and data applications.
You can run this code by downloading this Jupyter notebook.
import bokehimport numpy as npfrom bokeh.models import Circle, ColumnDataSource, Line, LinearAxis, Range1dfrom bokeh.plotting import figure, output_notebook, showfrom bokeh.core.properties import valueoutput_notebook() # output bokeh plots to jupyter notebooknp.random.seed(42)
Let us generate some random data using numpy. Bokeh has its own data structure (ColumnDataSource) for data representation. I am not sure why they developed their own data structure as pandas and numpy are De facto standard in Python analytics world (enlighten me in the comments below if you know). But luckily it works also with pandas. For this blog post, I decided to write examples on Bokeh way with its data structures.
N = 100data_source = ColumnDataSource( data=dict( x0=np.arange(N), x1=np.random.standard_normal(size=N), x2=np.arange(10, N + 10), x3=np.random.standard_normal(size=N), ))
To make a simple line plot in Bohek we need 3 lines of code. That’s not too bad. Note that the plot is interactive of the box, we can zoom in and move around, which is very useful with bigger datasets.
p = figure()p.line("x0", "x1", source=data_source)show(p)
To visualize two data columns with different ranges on a plot we can use two separate y-axes. We can set y-axis ranges but that’s not required. I used the min and max values of a data column as a y-axis limit. To visually separate data columns we can add a legend and set the color.
p = figure()column1 = "x1"column2 = "x2"# FIRST AXISp.line("x0", column1, legend=value(column1), color="blue", source=data_source)p.y_range = Range1d(data_source.data[column1].min(), data_source.data[column1].max())# SECOND AXIScolumn2_range = column2 + "_range"p.extra_y_ranges = { column2_range: Range1d( data_source.data[column2].min(), data_source.data[column2].max() )}p.add_layout(LinearAxis(y_range_name=column2_range), "right")p.line("x0", column2, legend=value(column2), y_range_name=column2_range, color="green",source=data_source)show(p)
This is where Bokeh really shines. You can simply define multiple elements and Bokeh renders them on the plot.
p = figure()p.line(x="x0", y="x1",color="blue", source=data_source )p.circle(x="x0", y="x3",color='green', source=data_source)show(p)
Bokeh is very customizable. You can tweak all the things you would expect from a plotting library, like line width, colors, multiple plots on a grid, etc. It offers special plots like candlesticks for financial data, Burtin visualization and you can even make a periodic table. Unique to Bokeh (at least to my knowledge) is an option to export the plot to javascript code which enables you to directly embed the plot to a webpage with all of its interactive capabilities.
Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.
These are a few links that might interest you:
- Data Science Nanodegree Program- AI for Healthcare- School of Autonomous Systems- Your First Machine Learning Model in the Cloud- 5 lesser-known pandas tricks- How NOT to write pandas code- Parallels Desktop 50% off | [
{
"code": null,
"e": 382,
"s": 172,
"text": "As a JupyterLab power user, I like using Bokeh for plotting because of its interactive plots. JupyterLab also offers an extension for interactive matplotlib, but it is slow and it crashes with bigger datasets."
},
{
"code": null,
"e": 742,
... |
3 Advanced Operations in Python Lists with Examples | by Rukshan Pramoditha | Towards Data Science | The list is one of the built-in data types in Python. It is used to store multiple Python objects (integer, float, string, etc.) in a single variable. The elements are placed inside a pair of square brackets.
list_1 = [1, 0, 10] # A list of integerslist_2 = [5.3, 10.0, 7.5] # A list of floatslist_3 = ['A', 'I', 'Help', 'Thanks'] # A list of stringslist_4 = [1, 5.3, 'A'] # A list of mixed Python objects!
The individual elements in a list can be selected by using zero-based indexing (zero for the first element).
Lists are mutable. We can add or remove items or change the value of an element in a list after we create it.
Elements of different data types can be included in the same list.
The list() constructor can be used to create a new list.
A list of subsequent integers can be created by using the range() function inside the list() constructor.
There are many operations in Python lists. Here, more emphasis will be given to Merging, List Comprehension and Append Elements.
The zip() function merges two lists into a new list by taking corresponding elements from the two lists. The result is a zip object. We can place that object inside the list() constructor to reveal the new list of tuples.
list_1 = [1, 2, 3]list_2 = ['one', 'two', 'tree']list(zip(list_1, list_2))
We can also merge two lists with different lengths. In this case, the new list is created in favor of the shortest list.
list_1 = [1, 2, 3, 4, 5] # 5 elementslist_2 = ['one', 'two', 'tree'] # Only 3 elementslist(zip(list_1, list_2))
List comprehension is a one-line code technique used to build a new list by iterating the elements inside a list. The new list is created in the way that the original list elements satisfy a certain expression or condition or both.
The syntax is:
[<expression> for <variable> in <list>]
Imagine that we have the following list.
new_list = [1, 2, 3, 4, 5]
Now, we want to create a new list that contains the square values of all the elements in the above list. For this, we can use list comprehension.
[x**2 for x in new_list]
List comprehension can also contain a condition. In that case, the syntax is:
[<expression> for <variable> in <list> if <condition>]
Now, we want to create a new list that contains the square values of selected elements (e.g. odd numbers) in the original list. For this, we can use list comprehension with a condition.
[x**2 for x in new_list if x % 2 == 1]
The previous two operations did not modify the original lists on which the operations were done. But, append elements is an in-place operation that modifies the original list directly. This operation adds elements to the end of the list. This can be done by using the append() method of the list object.
Usually, we create an empty list and then append elements as we need. The above square-value problem can also be solved by using this approach.
a = [] # Empty listfor i in new_list: sq = i**2 a.append(sq)a
At the creation, a is an empty list. Now, a has been modified and contains 5 elements meaning that the append operation was done in place.
The append operation is very useful when you want to store the calculated values for plotting at a later time. For example,
x = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]y = []for i in x: ex = i**3 y.append(ex)import matplotlib.pyplot as pltplt.plot(x, y)
The coordinates can be seen by using the merge operation!
coordinates = list(zip(x, y))coordinates
Python lists are very useful because we can perform some advanced operations with them using just one or two lines of code. A great alternative to Python lists is NumPy arrays, especially when we consider the performance. When executing, NumPy arrays are significantly faster than Python lists. However, we can easily create NumPy arrays using Python lists or convert lists into arrays. Python list is a built-in data type. It is closely associated with other data types and libraries in Python.
My readers can sign up for a membership through the following link to get full access to every story I write and I will receive a portion of your membership fee.
Sign-up link: https://rukshanpramoditha.medium.com/membership
Thank you so much for your continuous support! See you in the next story. Happy learning to everyone!
Special credit goes to Chris Lawton on Unsplash, who provides me with a nice cover image for this post. | [
{
"code": null,
"e": 381,
"s": 172,
"text": "The list is one of the built-in data types in Python. It is used to store multiple Python objects (integer, float, string, etc.) in a single variable. The elements are placed inside a pair of square brackets."
},
{
"code": null,
"e": 579,
... |
Advanced master theorem for divide and conquer recurrences | Divide and conquer is an algorithm that works on the paradigm based on recursively branching problem into multiple sub-problems of similar type that can be solved easily.
Let’s take an example to learn more about the divide and conquer technique −
function recursive(input x size n)
if(n < k)
Divide the input into m subproblems of size n/p.
and call f recursively of each sub problem
else
Solve x and return
Combine the results of all subproblems and return the solution to the original problem.
Explanation − In the above problem, the problem set is to be subdivided into smaller subproblems that can be solved easily.
Masters Theorem for divide and conquer is an analysis theorem that can be used to determine a big-0 value for recursive relation algorithms. It is used to find the time required by the algorithm and represent it in asymptotic notation form.
Example of runtime value of the problem in the above example −
T(n) = f(n) + m.T(n/p)
For most of the recursive algorithm, you will be able to find the Time complexity For the algorithm using the master's theorem, but there are some cases master's theorem may not be applicable. These are the cases in which the master's theorem is not applicable. When the problem T(n) is not monotone, for example, T(n) = sin n. Problem function f(n) is not a polynomial.
As the master theorem to find time complexity is not hot efficient in these cases, and advanced master theorem for recursive recurrence was designed. It is design to handle recurrence problem of the form −
T(n) = aT(n/b) + ø((n^k)logpn)
Where n is the size of the problem.
a = number of subproblems in recursion, a > 0
n/b = size of each subproblem b > 1, k >= 0 and p is a real number.
For solving this type of problem, we will use the following solutions,
If a>bk, then T(n) = ∅ (nlogba)
If a = bk, thenIf p> -1, then T(n) = ∅(nlogba logp+1n)If p = -1, then T(n) = ∅(nlogba loglogn)If p < -1, then T(n) = ∅(nlogba)
If p> -1, then T(n) = ∅(nlogba logp+1n)
If p = -1, then T(n) = ∅(nlogba loglogn)
If p < -1, then T(n) = ∅(nlogba)
If a<bk , thenIf p> = 0, then T(n)= ∅(nklogpn)If p< 0, then T(n) = ∅(nk)
If p> = 0, then T(n)= ∅(nklogpn)
If p< 0, then T(n) = ∅(nk)
Using the advanced master algorithm, we will calculate the complexity of some algorithms −
Binary search − t(n) = θ(logn)
Merge sort − T(n) = θ(nlogn) | [
{
"code": null,
"e": 1233,
"s": 1062,
"text": "Divide and conquer is an algorithm that works on the paradigm based on recursively branching problem into multiple sub-problems of similar type that can be solved easily."
},
{
"code": null,
"e": 1310,
"s": 1233,
"text": "Let’s take ... |
Fade In Right Animation Effect with CSS | To implement Fade In Right Animation Effect on an image with CSS, you can try to run the following code −
Live Demo
<html>
<head>
<style>
.animated {
background-image: url(/css/images/logo.png);
background-repeat: no-repeat;
background-position: left top;
padding-top:95px;
margin-bottom:60px;
-webkit-animation-duration: 10s;
animation-duration: 10s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
@-webkit-keyframes fadeInRight {
0% {
opacity: 0;
-webkit-transform: translateX(20px);
}
100% {
opacity: 1;
-webkit-transform: translateX(0);
}
}
@keyframes fadeInRight {
0% {
opacity: 0;
transform: translateX(20px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
.fadeInRight {
-webkit-animation-name: fadeInRight;
animation-name: fadeInRight;
}
</style>
</head>
<body>
<div id="animated-example" class="animated fadeInRight"></div>
<button onclick="myFunction()">Reload page</button>
<script>
function myFunction() {
location.reload();
}
</script>
</body>
</html> | [
{
"code": null,
"e": 1168,
"s": 1062,
"text": "To implement Fade In Right Animation Effect on an image with CSS, you can try to run the following code −"
},
{
"code": null,
"e": 1178,
"s": 1168,
"text": "Live Demo"
},
{
"code": null,
"e": 2554,
"s": 1178,
"tex... |
Swing Examples - Show Standard Progress Bar | Following example showcase how to show a standard Progress bar in a Java Swing application.
We are using the following APIs.
JProgressBar − To create a progress bar field.
JProgressBar − To create a progress bar field.
JProgressBar.setValue − To set the progress in progress bar.
JProgressBar.setValue − To set the progress in progress bar.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingTester {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingTester(){
prepareGUI();
}
public static void main(String[] args){
SwingTester swingControlDemo = new SwingTester();
SwingTester.showProgressBarDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private JProgressBar progressBar;
private Task task;
private JButton startButton;
private JTextArea outputTextArea;
private void showProgressBarDemo(){
headerLabel.setText("Control in action: JProgressBar");
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
startButton = new JButton("Start");
outputTextArea = new JTextArea("",5,20);
JScrollPane scrollPane = new JScrollPane(outputTextArea);
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
task = new Task();
task.start();
}
});
controlPanel.add(startButton);
controlPanel.add(progressBar);
controlPanel.add(scrollPane);
mainFrame.setVisible(true);
}
private class Task extends Thread {
public Task(){
}
public void run(){
for(int i =0; i<= 100; i+=10){
final int progress = i;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progressBar.setValue(progress);
outputTextArea.setText(outputTextArea.getText()
+ String.format("Completed %d%% of task.\n", progress));
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
}
}
}
Verify the following output.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2131,
"s": 2039,
"text": "Following example showcase how to show a standard Progress bar in a Java Swing application."
},
{
"code": null,
"e": 2164,
"s": 2131,
"text": "We are using the following APIs."
},
{
"code": null,
"e": 2211,
"s": 2164,... |
How to change cursor style using jQuery ? - GeeksforGeeks | 28 Jun, 2019
The cursor style is used to specify the mouse cursor to be displayed while pointing on an element.
Cursor Value:
alias: This property is used to display the cursor’s indication of something is to be created.
all-scroll: In this property, the cursor indicates scrolling.
auto: This is the default property where the browser sets a cursor.
cell: In this property, the cursor indicates a cell or set of cells are selected.
context-menu: In this property, the cursor indicates that a context menu is available.
col-resize: In this property, the cursor indicates that the column can be resized horizontally.
copy: In this property, the cursor indicates something is to be copied.
crosshair: In this property, the cursor renders as a crosshair.
default: The default cursor.
e-resize: In this property, the cursor indicates an edge of a box is to be moved to the right.
ew-resize: In this property, the cursor indicates a bidirectional resize cursor.
help: In this property, the cursor indicates that help is available.
move: In this property, the cursor indicates something is to be moved
n-resize: In this property, the cursor indicates an edge of a box is to be moved up.
ne-resize: In this property, the cursor indicates an edge of a box is to be moved up and right.
nesw-resize: This property indicates a bidirectional resize cursor.
ns-resize: This property indicates a bidirectional resize cursor.
nw-resize: In this property, the cursor indicates an edge of a box is to be moved up and left.
nwse-resize: This property indicates a bidirectional resize cursor.
no-drop: In this property, the cursor indicates that the dragged item cannot be dropped here.
none: This property indicates no cursor is rendered for the element.
not-allowed: In this property, the cursor indicates that the requested action will not be executed.
pointer: In this property, the cursor is a pointer and indicates link
progress: In this property, the cursor indicates that the program is busy.
row-resize: In this property, the cursor indicates that the row can be resized vertically.
s-resize: In this property, the cursor indicates an edge of a box is to be moved down.
se-resize: In this property, the cursor indicates an edge of a box is to be moved down and right.
sw-resize: In this property, the cursor indicates an edge of a box is to be moved down and left.
text: In this property, the cursor indicates text that may be selected.
URL: In this property a comma-separated list of URLs to custom cursors and a generic cursor at the end of the list.
vertical-text: In this property, the cursor indicates vertical-text that may be selected.
w-resize: In this property, the cursor indicates an edge of a box is to be moved left.
wait: In this property, the cursor indicates that the program is busy.
zoom-in: In this property, the cursor indicates that something can be zoomed in.
zoom-out: In this property, the cursor indicates that something can be zoomed out.
initial: This property is used to set to its default value.
inherit: Inherits from its parent element.
Syntax:
$(selector).style.cursor = ”cursor_property_value”;
Examples:
// Change the cursor on complete document
$(document).style.cursor = "alias";
// Change the cursor on particular element
$("p").style.cursor = "alias";
// Change the cursor on particular element using class
$(".curs").style.cursor = "wait";
// Change the cursor on particular element using id
$("#curs").style.cursor = "crosshair";
Implementation: This example uses jQuery css() function to display different cursor style.
<!DOCTYPE html><html> <head> <title> How to change cursor style using jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script type="text/javascript"> $(document).ready(function() { $("input[type='radio']").click(function() { var radioValue = $("input[name='cursor']:checked").val(); if(radioValue) { $("#block").css("cursor", radioValue ); }}); }); </script> </head> <body> <h1 align="center"> Changing cursor style using jQuery </h1> <div style="border:2px solid green"> <table width="100%" style="table-layout:fixed;"> <p align="center"> Click on the Radio button to change the cursor style </p> <tr> <td> <input type="radio" name="cursor" value="alias" > alias </td> <td> <input type="radio" name="cursor" value="all-scroll" > all-scroll </td> <td> <input type="radio" name="cursor" value="auto" > auto </td> <td> <input type="radio" name="cursor" value="cell" > cell </td> </tr> <tr> <td> <input type="radio" name="cursor" value="context-menu" > context-menu </td> <td> <input type="radio" name="cursor" value="col-resize" > col-resize </td> <td> <input type="radio" name="cursor" value="copy" > copy </td> <td> <input type="radio" name="cursor" value="crosshair" > crosshair </td> </tr> <tr> <td> <input type="radio" name="cursor" value="default" > default </td> <td> <input type="radio" name="cursor" value="e-resize" > e-resize </td> <td> <input type="radio" name="cursor" value="ew-resize" > ew-resize </td> <td> <input type="radio" name="cursor" value="help" > help </td> </tr> <tr> <td> <input type="radio" name="cursor" value="move" > move </td> <td> <input type="radio" name="cursor" value="n-resize" > n-resize </td> <td> <input type="radio" name="cursor" value="ne-resize" > ne-resize </td> <td> <input type="radio" name="cursor" value="nw-resize" > nw-resize </td> </tr> <tr> <td> <input type="radio" name="cursor" value="ns-resize" > ns-resize </td> <td> <input type="radio" name="cursor" value="no-drop" > no-drop </td> <td> <input type="radio" name="cursor" value="none" > none </td> <td> <input type="radio" name="cursor" value="not-allowed" > not-allowed </td> </tr> <tr> <td> <input type="radio" name="cursor" value="pointer" > pointer </td> <td> <input type="radio" name="cursor" value="progress" > progress </td> <td> <input type="radio" name="cursor" value="row-resize" > row-resize </td> <td> <input type="radio" name="cursor" value="s-resize" > s-resize </td> </tr> <tr> <td> <input type="radio" name="cursor" value="se-resize" > se-resize </td> <td> <input type="radio" name="cursor" value="sw-resize" > sw-resize </td> <td> <input type="radio" name="cursor" value="text" > text </td> <td> <input type="radio" name="cursor" value="vertical-text" > vertical-text </td> </tr> <tr> <td> <input type="radio" name="cursor" value="w-resize" > w-resize </td> <td> <input type="radio" name="cursor" value="wait" > wait </td> <td> <input type="radio" name="cursor" value="zoom-in" > zoom-in </td> <td> <input type="radio" name="cursor" value="zoom-out" > zoom-out </td> </tr> </table> </div> <section> <label> <h1>Output:</h1> </label> <div id="block" style="padding:10px;border:2px solid red;"> Hello welcome </div> </section> </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.
jQuery-Misc
HTML
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
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 change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ? | [
{
"code": null,
"e": 26312,
"s": 26284,
"text": "\n28 Jun, 2019"
},
{
"code": null,
"e": 26411,
"s": 26312,
"text": "The cursor style is used to specify the mouse cursor to be displayed while pointing on an element."
},
{
"code": null,
"e": 26425,
"s": 26411,
... |
PHP Basics of Class and Object | Class is a user defined data type in PHP. In order to define a new class, PHP provides a keyword class, which is followed by a name. Any label that is valid as per PHP's naming convention (excluding PHP's reserved words) can be used as name of class. Constituents of class are defined in curly bracket that follows name of class
class myclass{
//
}
Class may contain constants, variables or properties and methods - which are similar to functions
This example shows how a Class is defined
<?php
class myclass{
const MYCONSTANT=100;
public $var1="Hello";
function dispvar(){
echo $this->var1;
}
}
?>
Function defined inside class is called method. Calling object's context is available inside a method with a pseudo-variable $this. If method is defined as static, it is accessed with name of class. Calling a non-static method statically has been deprecated in PHP 7
The new operator declares a new object of given class. ame of class followed by paentheses should be mentioned in front of new keyword. An uninitialized object (or with default values to properties) is created if there are no arguments inside parentheses. If class provides definition of constructor with parameters, matching number of arguments must be given. Class must be defined before creating instance (or object)
Live Demo
<?php
class myclass{
const MYCONSTANT=100;
public $var1="Hello";
function dispvar(){
echo $this->var1;
}
}
$obj=new myclass();
$obj->dispvar();
?>
This will produce following result. −
Hello | [
{
"code": null,
"e": 1391,
"s": 1062,
"text": "Class is a user defined data type in PHP. In order to define a new class, PHP provides a keyword class, which is followed by a name. Any label that is valid as per PHP's naming convention (excluding PHP's reserved words) can be used as name of class. Co... |
How to Generate MD5 Checksum for Files in Java? - GeeksforGeeks | 29 Jul, 2021
An alphanumeric value i.e. the sequence of letters and numbers that uniquely defines the contents of a file is called a checksum (often referred to as a hash). Checksums are generally used to check the integrity of files downloaded from an external source. You may use a checksum utility to ensure that your copy is equivalent if you know the checksum of the original version. For example, before backing up your files you can generate a checksum of those files and can verify the same once you have to download them on some other device. The checksum would be different if the file has been corrupted or altered in the process.
MD5 and SHA are the two most widely used checksum algorithms. You must ensure that you use the same algorithm that has been used to generate the checksum when checking checksums. For example, the MD5 checksum value of a file is totally different from its SHA-256 checksum value.
To produce a checksum, you run a program that puts that file through an algorithm. Typical algorithms used for this include MD5, SHA-1, SHA-256, and SHA-512.
These algorithms use a cryptographic hash function that takes an input and generates a fixed-length alphanumeric string regardless of the size of the file.
NOTE:
Even small changes in the file will produce a different checksum.These cryptographic hash functions, though, aren’t flawless. “Collisions” with the MD5 and SHA-1 functions have been discovered by security researchers. They’ve found two different files, that produce the same MD5 or SHA-1 hash, but are different. This is highly unlikely to happen by mere accident, but this strategy may be used by an attacker to mask a malicious file as a valid file.
Even small changes in the file will produce a different checksum.
These cryptographic hash functions, though, aren’t flawless. “Collisions” with the MD5 and SHA-1 functions have been discovered by security researchers. They’ve found two different files, that produce the same MD5 or SHA-1 hash, but are different. This is highly unlikely to happen by mere accident, but this strategy may be used by an attacker to mask a malicious file as a valid file.
Generating Checksum in Java
Java provides an inbuilt functionality of generating these hash functions through MessageDigest Class present in the security package of Java. Message digests are encrypted one-way hash functions that take data of arbitrary size and produce a hash value of fixed length.
We first start with instantiating the MessageDigest Object by passing any valid hashing algorithm string.
Then we update this object till we read the complete file. Although we can use the digest(byte[] input) which creates a final update on the MessageDigest object by reading the whole file at once in case the file is too big/large we might not have enough memory to read the entire file as a byte array and this could result in Java.lang.OutOfMemoryError: Java Heap Space.
So, It’s better to read data in parts and update MessageDigest.
Once the update is complete one of the digest method is called to complete the hash computation. Whenever a digest method is called the MessageDigest object is reset to its initialized state. The digest method returns a byte array that has bytes in the decimal format so we Convert it to hexadecimal format. And the final string is the checksum.
Example:
Java
// Java program to Generate MD5 Checksum for Files import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException; public class GFG { // this method gives a NoSuchAlgorithmException in case // we pass a string which dosen't have any hashing // algorithm in its correspondence public static void main(String[] args) throws IOException, NoSuchAlgorithmException { // create a file object referencing any file from // the system of which checksum is to be generated File file = new File("C:\\Users\\Raghav\\Desktop\\GFG.txt"); // instantiate a MessageDigest Object by passing // string "MD5" this means that this object will use // MD5 hashing algorithm to generate the checksum MessageDigest mdigest = MessageDigest.getInstance("MD5"); // Get the checksum String checksum = checksum(mdigest, file); // print out the checksum System.out.println(checksum); } // this method return the complete hash of the file // passed private static String checksum(MessageDigest digest, File file) throws IOException { // Get file input stream for reading the file // content FileInputStream fis = new FileInputStream(file); // Create byte array to read data in chunks byte[] byteArray = new byte[1024]; int bytesCount = 0; // read the data from file and update that data in // the message digest while ((bytesCount = fis.read(byteArray)) != -1) { digest.update(byteArray, 0, bytesCount); }; // close the input stream fis.close(); // store the bytes returned by the digest() method byte[] bytes = digest.digest(); // this array of bytes has bytes in decimal format // so we need to convert it into hexadecimal format // for this we create an object of StringBuilder // since it allows us to update the string i.e. its // mutable StringBuilder sb = new StringBuilder(); // loop through the bytes array for (int i = 0; i < bytes.length; i++) { // the following line converts the decimal into // hexadecimal format and appends that to the // StringBuilder object sb.append(Integer .toString((bytes[i] & 0xff) + 0x100, 16) .substring(1)); } // finally we return the complete hash return sb.toString(); }}
Output:
8eeecb74627e963d65d10cbf92a2b7c9
surinderdawra388
Java-Files
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Stream In Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23894,
"s": 23866,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 24523,
"s": 23894,
"text": "An alphanumeric value i.e. the sequence of letters and numbers that uniquely defines the contents of a file is called a checksum (often referred to as a hash). Che... |
Git Getting Started | You can download Git for free from the following website: https://www.git-scm.com/
To start using Git, we are first going to open up our Command shell.
For Windows, you can use Git bash, which comes included in Git for Windows.
For Mac and Linux you can use the built-in terminal.
The first thing we need to do, is to check if Git is properly installed:
git --version
git version 2.30.2.windows.1
If Git is installed, it should show something like git version X.Y
Now let Git know who you are. This is important for version control systems,
as each Git commit uses this information:
git config --global user.name "w3schools-test"
git config --global user.email "test@w3schools.com"
Change the user name and e-mail address to your own. You will probably also want to use this when registering to GitHub
later on.
Note: Use global to set the username and e-mail for every repository on your computer.
If you want to set the username/e-mail for just the current repo, you can remove global
Now, let's create a new folder for our project:
mkdir myproject
cd myproject
mkdir makes a new directory.
cd changes the current working directory.
Now that we are in the correct directory. We can start by initializing Git!
Note: If you already have a folder/directory you would
like to use for Git:
Navigate to it in command line, or open it in your file explorer, right-click and select "Git Bash here"
Once you have navigated to the correct folder, you can initialize Git on that
folder:
git init
Initialized empty Git repository in /Users/user/myproject/.git/
You just created your first Git Repository!
Note: Git now knows that it should watch the folder you
initiated it on.
Git creates a hidden folder to keep track of changes.
Insert the missing part of the command to check which version of Git (if any)
is installed.
git
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 83,
"s": 0,
"text": "You can download Git for free from the following website: https://www.git-scm.com/"
},
{
"code": null,
"e": 152,
"s": 83,
"text": "To start using Git, we are first going to open up our Command shell."
},
{
"code": null,
"e": 2... |
41 Questions to Test your Knowledge of Python Strings | by GreekDataGuy | Towards Data Science | I’ve started tracking the most commonly used functions while doing algorithm questions on LeetCode and HackerRank.
Being a good engineer isn’t about memorizing a language’s functions, but that doesn’t mean it’s not helpful. Particularly in interviews.
This is my string cheatsheet converted into a list of questions to quiz myself. While these are not interview questions, mastering these will help you solve live coding questions with greater ease.
How well do you know Python strings?
The is operator returns True if 2 names point to the same location in memory. This is what we’re referring to when we talk about identity.
Don’t confuse is with ==, the latter which only tests equality.
animals = ['python','gopher']more_animals = animalsprint(animals == more_animals) #=> Trueprint(animals is more_animals) #=> Trueeven_more_animals = ['python','gopher']print(animals == even_more_animals) #=> Trueprint(animals is even_more_animals) #=> False
Notice above how animals and even_more_animals have a different identity even though they are equal.
Additionally, the id() function returns the id of a memory address associated with a name. Two objects with the same identity will return the same id.
name = 'object'id(name)#=> 4408718312
The istitle() function checks if each word is capitalized.
print( 'The Hilton'.istitle() ) #=> Trueprint( 'The dog'.istitle() ) #=> Falseprint( 'sticky rice'.istitle() ) #=> False
The in operator will return True if a string contains a substring.
print( 'plane' in 'The worlds fastest plane' ) #=> Trueprint( 'car' in 'The worlds fastest plane' ) #=> False
There are 2 different functions that will return the starting index, find() and index(). They have slightly different behaviour.
find() returns -1 if the substring is not found.
'The worlds fastest plane'.find('plane') #=> 19'The worlds fastest plane'.find('car') #=> -1
index() will throw a ValueError.
'The worlds fastest plane'.index('plane') #=> 19'The worlds fastest plane'.index('car') #=> ValueError: substring not found
len() will return the length of a string.
len('The first president of the organization..') #=> 19
count() will return the number of occurrences of a specific character.
'The first president of the organization..'.count('o') #=> 3
Use the capitalize() function to do this.
'florida dolphins'.capitalize() #=> 'Florida dolphins'
New in python 3.6, f-strings make string interpolation really easy. Using f-strings is similar to using format().
F-strings are denoted by an f before the opening quote.
name = 'Chris'food = 'creme brulee'f'Hello. My name is {name} and I like {food}.'#=> 'Hello. My name is Chris and I like creme brulee'
index() can also be provided with optional start and end indices for searching within a larger string.
'the happiest person in the whole wide world.'.index('the',10,44)#=> 23
Notice how the above returned 23 rather than 0.
'the happiest person in the whole wide world.'.index('the')#=> 0
format() is similar to using an f-string. Though in my opinion, it’s less user friendly because variables are all passed in at the end of the string.
difficulty = 'easy'thing = 'exam''That {} was {}!'.format(thing, difficulty)#=> 'That exam was easy!'
isnumeric() returns True if all characters are numeric.
'80000'.isnumeric() #=> True
Note that punctuation is not numeric.
'1.0'.isnumeric() #=> False
The split() function will split a string on a given character or characters.
'This is great'.split(' ')#=> ['This', 'is', 'great']'not--so--great'.split('--')#=> ['not', 'so', 'great']
islower() returns True only if all characters in a string are lowercase.
'all lower case'.islower() #=> True'not aLL lowercase'.islower() # False
This can be done by calling the previously mentioned function on the first index of the string.
'aPPLE'[0].islower() #=> True
In some languages this can be done but python will throw a TypeError.
'Ten' + 10 #=> TypeError
We can split the string into a list of characters, reverse the list, then rejoin into a single string.
''.join(reversed("hello world"))#=> 'dlrow olleh'
Python’s join() function can join characters in a list with a given character inserted between every element.
'-'.join(['a','b','c'])#=> 'a-b-c'
The isascii() function returns True if all characters in a string are included in ASCII.
print( 'Â'.isascii() ) #=> Falseprint( 'A'.isascii() ) #=> True
upper() and lower() return strings in all upper and lower cases.
sentence = 'The Cat in the Hat'sentence.upper() #=> 'THE CAT IN THE HAT'sentence.lower() #=> 'the cat in the hat'
As in a past example, we’ll target specific indices of the string. Strings aren’t mutable in Python so we’ll build an entirely new string.
animal = 'fish'animal[0].upper() + animal[1:-1] + animal[-1].upper()#=> 'FisH'
Similar to islower(), isupper() returns True only if the whole string is capitalized.
'Toronto'.isupper() #=> False'TORONTO'.isupper() #= True
splitlines() splits a string on line breaks.
sentence = "It was a stormy night\nThe house creeked\nThe wind blew."sentence.splitlines()#=> ['It was a stormy night', 'The house creeked', 'The wind blew.']
Slicing a string takes up to 3 arguments, string[start_index:end_index:step].
step is the interval at which characters should be returned. So a step of 3 would return the character at every 3rd index.
string = 'I like to eat apples'string[:6] #=> 'I like'string[7:13] #=> 'to eat'string[0:-1:2] #=> 'Ilk oetape' (every 2nd character)
Use the string constructor, str() for this.
str(5) #=> '5'
isalpha() returns True if all characters are letters.
'One1'.isalpha()'One'.isalpha()
Without importing the regular expressions module, you can use replace().
sentence = 'Sally sells sea shells by the sea shore'sentence.replace('sea', 'mountain')#=> 'Sally sells mountain shells by the mountain shore'
Capitalized characters and characters earlier in the alphabet have lower indexes. min() will return the character with the lowest index.
min('strings') #=> 'g'
Alphanumeric values include letters and integers.
'Ten10'.isalnum() #=> True'Ten10.'.isalnum() #=> False
lstrip(), rstrip() and strip() remove whitespace from the ends of a string.
string = ' string of whitespace 'string.lstrip() #=> 'string of whitespace 'string.rstrip() #=> ' string of whitespace'string.strip() #=> 'string of whitespace'
startswith() and endswith() check if a string begins and ends with a specific substring.
city = 'New York'city.startswith('New') #=> Truecity.endswith('N') #=> False
encode() encodes a string with a given encoding. The default is utf-8. If a character cannot be encoded then a UnicodeEncodeError is thrown.
'Fresh Tuna'.encode('ascii')#=> b'Fresh Tuna''Fresh Tuna Â'.encode('ascii')#=> UnicodeEncodeError: 'ascii' codec can't encode character '\xc2' in position 11: ordinal not in range(128)
isspace() only returns True if a string is completely made of whitespace.
''.isspace() #=> False' '.isspace() #=> True' '.isspace() #=> True' the '.isspace() #=> False
The string is concatenated together 3 times.
'dog' * 3# 'dogdogdog'
title() will capitalize each word in a string.
'once upon a time'.title()
The additional operator can be used to concatenate strings.
'string one' + ' ' + 'string two' #=> 'string one string two'
partition() splits a string on the first instance of a substring. A tuple of the split string is returned without the substring removed.
sentence = "If you want to be a ninja"print(sentence.partition(' want '))#=> ('If you', ' want ', 'to be a ninja')
Once a string object has been created, it cannot be changed. “Modifying” that string creates a whole new object in memory.
We can prove it by using the id() function.
proverb = 'Rise each day before the sun'print( id(proverb) )#=> 4441962336proverb_two = 'Rise each day before the sun' + ' if its a weekday'print( id(proverb_two) )#=> 4442287440
Concatenating ‘ if its a weekday’ creates a new object in memory with a new id. If the object was actually modified then it would have the same id.
For example, writing animal = 'dog' and pet = 'dog'.
It only creates one. I found this unintuitive the first time I came across it. But this helps python save memory when dealing with large strings.
We’ll prove this with id(). Notice how both have the same id.
animal = 'dog'print( id(animal) )#=> 4441985688pet = 'dog'print( id(pet) )#=> 4441985688
maketrans() creates a mapping from characters to other characters. translate() then applies that mapping to translate a string.
# create mappingmapping = str.maketrans("abcs", "123S")# translate string"abc are the first three letters".translate(mapping)#=> '123 1re the firSt three letterS'
Notice above how we changed the values of every a, b, c and s in the string.
One option is to iterate over the characters in a string via list comprehension. If they don’t match a vowel then join them back into a string.
string = 'Hello 1 World 2'vowels = ('a','e','i','o','u')''.join([c for c in string if c not in vowels])#=> 'Hll 1 Wrld 2'
rfind() is like find() but it starts searching from the right of a string and return the first matching substring.
story = 'The price is right said Bob. The price is right.'story.rfind('is')#=> 39
As I often explained to an old product manager, engineers aren’t dictionaries of stored methods. But sometimes a little less googling can make coding more seamless and enjoyable.
I hope you crushed this.
If you found it too easy, you may be interested in my other article, 54 Python Interview Questions. | [
{
"code": null,
"e": 287,
"s": 172,
"text": "I’ve started tracking the most commonly used functions while doing algorithm questions on LeetCode and HackerRank."
},
{
"code": null,
"e": 424,
"s": 287,
"text": "Being a good engineer isn’t about memorizing a language’s functions, bu... |
Data Analysis with Unix - Part 1 - GeeksforGeeks | 14 Jul, 2019
To understand how to work with Unix, data – Weather Dataset is used.Weather sensors gather information consistently at numerous areas over the globe and assemble an enormous volume of log information, which is a decent possibility for investigation with MapReduce in light of the fact that is required to process every one of the information, and the information is record-oriented and semi-organized.
The information utilized is from the National Climatic Data Center, or NCDC. The information is put away utilizing a line-arranged ASCII group, in which each line is a record. The organization underpins a rich arrangement of meteorological components, huge numbers of which are discretionary or with variable information lengths. For straightforwardness, centre around the fundamental components, for example, temperature, which is constantly present and are of fixed width.Structure of NCDC record
0057
332130 # USAF weather station identifier
99999 # WBAN weather station identifier
19500101 # observation date
0300 # observation time
4
+51317 # latitude ( degrees x 1000)
+028783 # longitude (degrees x 1000)
FM-12
+0171 # elevation (meters)
99999
V020
320 # wind direction (degrees)
1 # quality code
N 0072
1 00450 # sky ceiling height (meters)
1 # quality code
C
N
010000 # visibility distance (meters)
1 # quality code
N
9
-0128 # air temperature (degrees Celsius x 10)
1 # quality code
-0139 # dew point temperature (degrees Celsius x 10)
1 # quality code
10268 # atmospheric pressure (hectopascals x 10)
1 # quality code
Note – Fields are packed into one line with no delimiters in the actual file we’ll be working on. Datafiles are sorted out by date and climate station. There is an index for every year from 1901 to 2001, each containing a gzipped record for each climate station with its readings for that year.
First entries for 1995 :
% ls raw/1990 | head
010010-99999-1995.gz
010014-99999-1995.gz
010015-99999-1995.gz
010016-99999-1995.gz
010017-99999-1995.gz
010030-99999-1995.gz
010040-99999-1995.gz
010080-99999-1995.gz
010100-99999-1995.gz
010150-99999-1995.gz
There are countless climate stations, so the entire dataset is comprised of a huge number of generally little documents. It’s commonly simpler and increasingly proficient to process a more modest number of generally enormous records, so the information was preprocessed with the goal that every year’s readings were linked into a solitary record.
Hadoop
Linux-Unix
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
UDP Server-Client implementation in C
Cat command in Linux with examples
Conditional Statements | Shell Script
Mutex lock for Linux Thread Synchronization
curl command in Linux with Examples
Named Pipe or FIFO with example C program
echo command in Linux with Examples
Thread functions in C/C++
touch command in Linux with Examples | [
{
"code": null,
"e": 23601,
"s": 23573,
"text": "\n14 Jul, 2019"
},
{
"code": null,
"e": 24003,
"s": 23601,
"text": "To understand how to work with Unix, data – Weather Dataset is used.Weather sensors gather information consistently at numerous areas over the globe and assemble a... |
Deep Clustering for Financial Market Segmentation | by Yuefeng Zhang, PhD | Towards Data Science | Unsupervised learning, supervised learning and reinforcement learning are three main categories of machine learning methods. Unsupervised learning has many applications such as clustering, dimensionality reduction, etc. The machine learning algorithms K-means and Principal Component Analysis (PCA) are widely used for clustering and dimensionality reduction respectively. Similarly to PCA, the T-distributed Stochastic Neighbor Embedding (t-SNE) is another unsupervised machine learning algorithm for dimensionality reduction. t-SNE is typically used for embedding high-dimensional data in a two or three dimensional space for data visualization.
With the advancement of unsupervised deep learning, the Autoencoder neural network is now frequently used for high dimensionality (e.g., a dataset with thousands or more features) reduction. Autoencoder can also be combined with supervised learning (e.g., Random Forest) to form Semi-supervised learning method (see deep patient as an example).
Recently a Deep Embedded Clustering (DEC) method [1] was published. It combines autoencoder with K-means and other machine learning techniques for clustering rather than dimensionality reduction. The original implementation of DEC is based on Caffe. An implementation of DEC in Keras for MNIST dataset can be found in [2].
In this article, similarly to [2], I implement the DEC algorithm in Keras and use the public dataset Kaggle Credit Card Dataset for Clustering [3] to show how to use the new implemented DEC model to cluster the credit card dataset for customer segmentation. The rest of this article is arranged as follows:
Data Preparation
Implementation of the DEC Method in Keras
Summary
This section describes the common data preprocessing steps required for clustering.
After the Kaggle credit card dataset [3] has been downloaded onto a local machine, it can be loaded into Pandas DataFrame as follows:
import Pandas as pddata = pd.read_csv('./data/CC_GENRAL.csv')data.head()
It can be seen from the DataFrame above that CUST_ID field is unique for each customer data record. This field with unique values is not useful for clustering and thus can be dropped:
data_x = data.drop(['CUST_ID'], axis=1)
It can also be seen from the DataFrame that the ranges of values are very different for different fields/features. It is well known that K-means is sensitive to the scale of feature values because it uses Euclidean distance as similarity metrics. To avoid this issue, the values of all features are rescaled into the range of [0, 1]:
from sklearn.preprocessing import MinMaxScalernumeric_columns = data_x.columns.values.tolist()scaler = MinMaxScaler() data_x[numeric_columns] = scaler.fit_transform(data_x[numeric_columns])data_x.head()
The following code is to check if any missing data exists in the dataset:
data_x.isnull().sum()
The above table shows that there are one missing CREDIT_LIMIT record and 313 missing MINIMUM_PAYMENTS. In this case, it makes sense to fill up missing data with zero:
data_x.fillna(0, inplace=True)
Similarly to [2], the DEC algorithm in [1] is implemented in Keras in this article as follows:
Step 1: Estimating the number of clusters
Step 2: Creating and training a K-means model
Step 3: Creating and training an autoencoder
Step 4: Implementing DEC Soft Labeling
Step 5: Creating a new DEC model
Step 6: Training the New DEC Model
Step 7: Using the Trained DEC Model for Predicting Clustering Classes
Step 8: Jointly Refining DEC Model
Step 9: Using Refined DEC Model for Predicting Clustering Classes
Step 10: Comparing with K-means
As described before, the DEC method combines Autoencoder with K-means and other machine learning techniques. In order to train a K-means model, an estimated number of clusters is required. The number of clusters is estimated in this article by exploring the silhouette values of different K-means model executions:
for num_clusters in range(2,10): clusterer = KMeans(n_clusters=num_clusters, n_jobs=4) preds = clusterer.fit_predict(x) # centers = clusterer.cluster_centers_ score = silhouette_score (x, preds, metric='euclidean') print ("For n_clusters = {}, Kmeans silhouette score is {})".format(num_clusters, score))
A silhouette value measures how similar a data record is to its own cluster (cohesion) compared to other clusters. The silhouette value ranges from −1 to +1, where a high value indicates that the data record matches to its own cluster well and matches poorly to its neighboring clusters.
The silhouette values above indicate that the top two choices of the number of clusters are 2 and 3. The number of clusters of 3 is chosen in this article.
Once the number of clusters is determined, a K-means model can be created:
n_clusters = 3kmeans = KMeans(n_clusters=n_clusters, n_jobs=4)y_pred_kmeans = kmeans.fit_predict(x)
In addition to K-means, an autoencoder is required as well in the DEC algorithm [1]. The following function is to create an autoencoder:
def autoencoder(dims, act='relu', init='glorot_uniform'): n_stacks = len(dims) - 1 input_data = Input(shape=(dims[0],), name='input') x = input_data # internal layers of encoder for i in range(n_stacks-1): x = Dense(dims[i + 1], activation=act, kernel_initializer=init, name='encoder_%d' % i)(x) # latent hidden layer encoded = Dense(dims[-1], kernel_initializer=init, name='encoder_%d' % (n_stacks - 1))(x) x = encoded # internal layers of decoder for i in range(n_stacks-1, 0, -1): x = Dense(dims[i], activation=act, kernel_initializer=init, name='decoder_%d' % i)(x) # decoder output x = Dense(dims[0], kernel_initializer=init, name='decoder_0')(x) decoded = x autoencoder_model = Model(inputs=input_data, outputs=decoded, name='autoencoder') encoder_model = Model(inputs=input_data, outputs=encoded, name='encoder') return autoencoder_model, encoder_model
An autoencoder model is created as follows:
n_epochs = 100batch_size = 128dims = [x.shape[-1], 500, 500, 2000, 10] init = VarianceScaling(scale=1. / 3., mode='fan_in', distribution='uniform')pretrain_optimizer = SGD(lr=1, momentum=0.9)pretrain_epochs = n_epochsbatch_size = batch_sizesave_dir = './results'autoencoder, encoder = autoencoder(dims, init=init)
As described in [1], the sizes of layers [500, 500, 2000, 10] are chosen as a generic configuration of the autoencoder neural network for any dataset.
The diagram of the resulting encoder model can be created as below:
from keras.utils import plot_modelplot_model(encoder, to_file='encoder.png', show_shapes=True)from IPython.display import ImageImage(filename='encoder.png')
The autoencoder is trained as follows:
autoencoder.compile(optimizer=pretrain_optimizer, loss='mse')autoencoder.fit(x, x, batch_size=batch_size, epochs=pretrain_epochs)autoencoder.save_weights(save_dir + '/ae_weights.h5')
The weights of the trained autoencoder are saved for later usage:
autoencoder.save_weights(save_dir + '/ae_weights.h5')autoencoder.load_weights(save_dir + '/ae_weights.h5')
One of the key components in the DEC method [1] is soft labeling, that is, assigning an estimated class to each of the data samples in such a way that it can be refined iteratively. To this end, similarly to [2], a new ClusteringLayer class is defined:
class ClusteringLayer(Layer): def __init__(self, n_clusters, weights=None, alpha=1.0, **kwargs): if 'input_shape' not in kwargs and 'input_dim' in kwargs: kwargs['input_shape'] = (kwargs.pop('input_dim'),) super(ClusteringLayer, self).__init__(**kwargs) self.n_clusters = n_clusters self.alpha = alpha self.initial_weights = weights self.input_spec = InputSpec(ndim=2) def build(self, input_shape): assert len(input_shape) == 2 input_dim = input_shape[1] self.input_spec = InputSpec(dtype=K.floatx(), shape=(None, input_dim)) self.clusters = self.add_weight(name='clusters', shape=(self.n_clusters, input_dim), initializer='glorot_uniform') if self.initial_weights is not None: self.set_weights(self.initial_weights) del self.initial_weights self.built = True def call(self, inputs, **kwargs): q = 1.0 / (1.0 + (K.sum(K.square(K.expand_dims(inputs, axis=1) - self.clusters), axis=2) / self.alpha)) q **= (self.alpha + 1.0) / 2.0 q = K.transpose(K.transpose(q) / K.sum(q, axis=1)) return q def compute_output_shape(self, input_shape): assert input_shape and len(input_shape) == 2 return input_shape[0], self.n_clusters def get_config(self): config = {'n_clusters': self.n_clusters} base_config = super(ClusteringLayer, self).get_config() return dict(list(base_config.items()) + list(config.items()))
Once the soft labeling layer is defined, it can be used to form a DEC model as follows:
clustering_layer = ClusteringLayer(n_clusters, name='clustering')(encoder.output)model = Model(inputs=encoder.input, outputs=clustering_layer)
A diagram of the new DEC model can be created as below:
from keras.utils import plot_modelplot_model(model, to_file='model.png', show_shapes=True)from IPython.display import ImageImage(filename='model.png')
The new DEC model can be compiled as follows:
model.compile(optimizer=SGD(0.01, 0.9), loss='kld')model.get_layer(name='clustering').set_weights([kmeans.cluster_centers_])
The new DEC model is trained iteratively:
# computing an auxiliary target distributiondef target_distribution(q): weight = q ** 2 / q.sum(0) return (weight.T / weight.sum(1)).Tloss = 0index = 0maxiter = 1000 update_interval = 100 tol = 0.001 # tolerance threshold to stop trainingindex_array = np.arange(x.shape[0])for ite in range(int(maxiter)): if ite % update_interval == 0: q = model.predict(x, verbose=0) p = target_distribution(q) idx = index_array[index * batch_size: min((index+1) * batch_size, x.shape[0])] loss = model.train_on_batch(x=x[idx], y=p[idx]) index = index + 1 if (index + 1) * batch_size <= x.shape[0] else 0
As described in [1], the training procedure above iteratively refines the clusters by learning from the high confidence assignments with the help of the auxiliary target distribution function target_distribution(). Specifically, the DEC model is trained by matching the soft assignment to the target distribution. To this end, in the DEC model the objective/loss function is defined as a Kullback-Leibler (KL) divergence loss between the soft assignments and the auxiliary distribution.
The model weights of the trained model are saved for later usage:
model.save_weights(save_dir + '/DEC_model_final.h5')model.load_weights(save_dir + '/DEC_model_final.h5')
Once the DEC model is trained, then it can be used for predicting clustering classes as follows:
q = model.predict(x, verbose=0)p = target_distribution(q) y_pred = q.argmax(1)
A silhouette score of 0.291 is obtained as follows:
from sklearn.metrics import silhouette_scorescore = silhouette_score(x, y_pred, metric='euclidean')
The following code can be used to use t-SNE to embed the dataset into a two dimensional space and then use color coding of the predicted clustering labels to visualize the predicted clustering result:
import numpy as npfrom sklearn.manifold import TSNEx_embedded = TSNE(n_components=2).fit_transform(x)vis_x = x_embedded[:, 0]vis_y = x_embedded[:, 1]plt.scatter(vis_x, vis_y, c=y_pred, cmap=plt.cm.get_cmap("jet", 256))plt.colorbar(ticks=range(256))plt.clim(-0.5, 9.5)plt.show()
Figure 1: Clustering of the new DEC model with silhouette score of 0.291.
The main idea behind the DEC method [1] is to simultaneously learn the feature representations and cluster assignments using deep neural networks. To this end, the following code uses the pre-trained autoencoder and K-means model to define a new model that takes the preprocessed credit card dataset as input and output both the predicted clustering classes and decoded input data records.
autoencoder, encoder = autoencoder(dims, init=init)autoencoder.load_weights(save_dir + '/ae_weights.h5')clustering_layer = ClusteringLayer(n_clusters, name='clustering')(encoder.output)model = Model(inputs=encoder.input, outputs=[clustering_layer, autoencoder.output])
The diagram of the joined model can be created as follows:
from keras.utils import plot_modelplot_model(model, to_file='model.png', show_shapes=True)from IPython.display import ImageImage(filename='model.png')
The refinement of the DEC model is performed as follows:
kmeans = KMeans(n_clusters=n_clusters, n_init=20)y_pred = kmeans.fit_predict(encoder.predict(x))model.get_layer(name='clustering').set_weights([kmeans.cluster_centers_])y_pred_last = np.copy(y_pred)model.compile(loss=['kld', 'mse'], loss_weights=[0.1, 1], optimizer=pretrain_optimizer)for ite in range(int(maxiter)): if ite % update_interval == 0: q, _ = model.predict(x, verbose=0) p = target_distribution(q) y_pred = q.argmax(1) # check stop criterion delta_label = np.sum(y_pred != y_pred_last).astype(np.float32) / y_pred.shape[0] y_pred_last = np.copy(y_pred) if ite > 0 and delta_label < tol: print('delta_label ', delta_label, '< tol ', tol) print('Reached tolerance threshold. Stopping training.') break idx = index_array[index * batch_size: min((index+1) * batch_size, x.shape[0])] loss = model.train_on_batch(x=x[idx], y=[p[idx], x[idx]]) index = index + 1 if (index + 1) * batch_size <= x.shape[0] else 0
The jointly refined model weights are saved:
model.save_weights(save_dir + '/b_DEC_model_final.h5')model.load_weights(save_dir + '/b_DEC_model_final.h5')
The following code is to use the refined DEC model for predicting clustering classes:
q, _ = model.predict(x, verbose=0)p = target_distribution(q) y_pred = q.argmax(1)
The code below can be used to reuse the t-SNE embedded two dimensional space (vis_x, vis_y) and use the color coding of the new predicted clustering labels to visualize the new predicted clustering result:
plt.scatter(vis_x, vis_y, c=y_pred, cmap=plt.cm.get_cmap("jet", 256))plt.colorbar(ticks=range(256))plt.clim(-0.5, 9.5)plt.show()
Figure 2: Clustering of the refined DEC model with silhouette score of 0.318.
Figure 3 shows the result of clustering by K-means. By comparing Figure 3 with Figure 2, we can see that K-means achieved relatively higher silhouette score. However, it can be seen that the refined DEC model predicted clusters with more clearly separable boundaries.
Figure 3: Clustering of the K-means model with silhouette score of 0.372.
In this article, similarly to [2], I implemented a new DEC model in Keras based on the original DEC algorithm in [1] and then applied the new model to the public dataset Kaggle Credit Card Dataset for Clustering [3].
The model evaluation results demonstrated that the new refined DEC model predicted more clearly separable clusters of the credit card dataset compared with the K-means method. This new DEC model has the potential of being used for credit card customer segmentation, other financial market segmentation, etc.
A Jupyter notebook with all of the source code used in this article is available in Github [4].
[1] J. Xie, R. Girshick, A. Farhadi, Unsupervised Deep Embedding for Clustering Analysis, May 24, 2016
[2] Chengwei, How to do Unsupervised Clustering with Keras
[3] Kaggle Credit Card Dataset for Clustering
[4] Y. Zhang, Jupyter notebook in Github
DISCLOSURE STATEMENT: © 2019 Capital One. Opinions are those of the individual author. Unless noted otherwise in this post, Capital One is not affiliated with, nor endorsed by, any of the companies mentioned. All trademarks and other intellectual property used or displayed are property of their respective owners. | [
{
"code": null,
"e": 820,
"s": 172,
"text": "Unsupervised learning, supervised learning and reinforcement learning are three main categories of machine learning methods. Unsupervised learning has many applications such as clustering, dimensionality reduction, etc. The machine learning algorithms K-m... |
Python Program to Reverse a Stack using Recursion | When it is required to reverse a stack data structure using recursion, a ‘stack_reverse’ method, in addition to methods to add value, delete value, and print the elements of the stack are defined.
Below is a demonstration of the same −
Live Demo
class Stack_structure:
def __init__(self):
self.items = []
def check_empty(self):
return self.items == []
def push_val(self, data):
self.items.append(data)
def pop_val(self):
return self.items.pop()
def print_it(self):
for data in reversed(self.items):
print(data)
def insert_bottom(instance, data):
if instance.check_empty():
instance.push_val(data)
else:
deleted_elem = instance.pop_val()
insert_bottom(instance, data)
instance.push_val(deleted_elem)
def stack_reverse(instance):
if not instance.check_empty():
deleted_elem = instance.pop_val()
stack_reverse(instance)
insert_bottom(instance, deleted_elem)
my_instance = Stack_structure()
data_list = input('Enter the elements to add to the stack: ').split()
for data in data_list:
my_instance.push_val(int(data))
print('The reversed stack is:')
my_instance.print_it()
stack_reverse(my_instance)
print('The stack is:')
my_instance.print_it()
Enter the elements to add to the stack: 23 56 73 81 8 9 0
The reversed stack is:
0
9
8
81
73
56
23
The stack is:
23
56
73
81
8
9
0
A ‘Stack_structure’ class is created that initializes an empty list.
A ‘Stack_structure’ class is created that initializes an empty list.
A ‘check_empty’ method is defined to see if a stack is empty.
A ‘check_empty’ method is defined to see if a stack is empty.
Another method named ‘push_val’ is defined that adds elements to the stack.
Another method named ‘push_val’ is defined that adds elements to the stack.
Another method named ‘pop_val’ is defined that deletes elements from the stack.
Another method named ‘pop_val’ is defined that deletes elements from the stack.
A method named ‘print_it’ is defined that helps print the elements of the stack.
A method named ‘print_it’ is defined that helps print the elements of the stack.
A method named ‘insert_bottom’ is defined, that adds element to the bottom of the stack, instead of adding to the top by default.
A method named ‘insert_bottom’ is defined, that adds element to the bottom of the stack, instead of adding to the top by default.
Another method named ‘stack_reverse’ is defined, that helps reverse a given stack.
Another method named ‘stack_reverse’ is defined, that helps reverse a given stack.
An instance of this ‘Stack_structure’ is defined.
An instance of this ‘Stack_structure’ is defined.
The elements of stack are taken from the user.
The elements of stack are taken from the user.
It is iterated over, and methods are called to add value to the stack and print it on the console.
It is iterated over, and methods are called to add value to the stack and print it on the console.
Now, the ‘stack_reverse’ is called on this list.
Now, the ‘stack_reverse’ is called on this list.
The ‘print_it’ is called to display the reversed stack on the console.
The ‘print_it’ is called to display the reversed stack on the console. | [
{
"code": null,
"e": 1259,
"s": 1062,
"text": "When it is required to reverse a stack data structure using recursion, a ‘stack_reverse’ method, in addition to methods to add value, delete value, and print the elements of the stack are defined."
},
{
"code": null,
"e": 1298,
"s": 1259... |
Create user and add role in MongoDB - GeeksforGeeks | 18 Apr, 2022
In MongoDB, we are allowed to create new users for the database. Every MongoDB user only accesses the data that is required for their role. A role in MongoDB grants privileges to perform some set of operations on a given resource. In MongoDB, users are created using createUser() method. This method creates a new user for the database, if the specified user is already present in the database then this method will return an error.
Syntax:
db.createUser(user, writeConcern)
Parameters:
1. user: It contains authentication and access information about the user to create. It is a document.
user: Name of the user
pwd: User password. This fieid is not required if you use this method on $external database to create a user whose credentials are stored externally. The value of this field can be of string type or passwordPrompt().
customData: User Associative Information. It is an optional field.
roles: Access Level or Privilege of a user. You can also create a user without roles by passing an empty array[]. In this field, you use built-in roles or you can create you own role using db.createRole(role, writeConcern) method. To specify the roles you can use any of the following syntax:
Simply specify the role name:
“read”
Or you can specify a document that contains the role and db fields. It is generally used when the role is specified in a different database.
{role:<role>, db: <database>}
authenticationRestrictions: Authentication permission of the user. It is an optional field.
mechanisms: It is used to specify the SCRM mechanisms or mechanisms for creating SCRM user credentials. It is an optional field.
passwordDigestor: It is used to check whether the server or client digest the password. It is an optional field.
2. writeConcern: It is an optional parameter. It manages the level of Write Concern for the creation operation. It takes the same field as the getLastError Command takes.
Notes:
In MongoDB, the first created user in the database must be the admin user. The admin user has the privileges to maintain all the users. Also, you are not allowed to create users in the local database.
db.createUser() Sends Password And All Other Data to The MongoDB Instance Without Any Encryption. To Encrypt the Password During Transmission, Use TLS/SSL In order To Encrypt It.
In MongoDB, you can create an administrative user using the createUser() method. In this method, we can create the name, password, and roles of an administrative user. Let us discuss this concept with the help of an example:
Example:
In this example, we are going to create an administrative user in the admin database and gives the user readWrite access to the config database which lets the user change certain settings for sharded clusters.
db.createUser(
{
user: "hello_admin",
pwd: "hello123",
roles:
[
{ role:"readWrite",db:"config"},
"clusterAdmin"
] } );
So to create an administrative user first we use the admin database. In this database, we create an admin user using the createUser() method. In this method, we set the user name is “hello_admin”, password is “hello123” and the roles of the admin user are readWrite, config, clusterAdmin.
In MongoDB, we can create a user without any roles by specifying an empty array[] in the role field in createUser() method.
Syntax:
db.createUser({ user:”User_Name”, pwd:”Your_Password”, roles:[]});
Let us discuss this concept with the help of an example:
Example:
In the following example, we are going to create a user without roles.
db.createUser({user:"geeks", pwd: "computer", roles:[]});
Here, we are working on the “example” database and created a user named “geeks” without roles.
In MongoDB, we can create a user with some specified roles using the createUser() method. In this method, we can specify the roles that the user will do after creating. Let us discuss this concept with the help of an example:
Example:
In this example, we are going to create a user with some specified roles.
db.createUser(
...{
...user: "new_one_role",
...pwd: with_roles",
...roles:["readWrite", "dbAdmin"]
...}
...);
Here, we create a user whose name is “new_one_role”, password is “with_roles” and the specified roles are:
readWrite Role: This role provides all the privileges of the read role plus the ability to modify data on all non-system collections.
dbAdmin Role: This role gives the ability to the user to perform administrative tasks such as schema-related tasks, indexing. It does not grant privileges for the User and Role Management.
In MongoDB, we can also create a user for single database using createUser() method. Let us discuss this concept with the help of an example:
Example:
db.createUser(
{
user: "robert",
pwd: "hellojose",
roles:[{role: "userAdmin" , db:"example"}]})
Here, we create a user whose user name is “Robert”, password is “hellojose”, and we assign a role for the user which in this case needs to be a database administrator so it is assigned to the “userAdmin” role. This role will allow the user to have administrative privileges only to the database specified in the db option, i.e., “example”.
In MongoDB, authentication is a process which checks whether the user/client who is trying to access the database is known or unknown. If the user is known then it allows them to connect with server. We can also create a user with authentication restrictions using createUser() method by setting the value of authenticationRestrictions field. This field provides authentication permission of the user and contains the following fields:
clientSource: If the value of this field is present, so when a user is authenticating the server verifies the client IP by checking the IP address in the given list or CIDR range in the list. If the client IP present in the list then the server authenticate the client or if not then server will not authenticate the user.
serverAddress: It is a list of IP addresses or CIDR ranges to which the client can connect. If the value of this field is present in the list, then the server verify the client connection and if the connection was established via unrecognized IP address, then the server does not authenticate the user.
Let us discuss this concept with the help of an example:
Example:
In this example, we are going to create a user with authentication restrictions:
use admin
db.createUser(
{
user: "restrict",
pwd: passwordPrompt(),
roles: [ { role: "readWrite", db: "example" } ],
authenticationRestrictions: [ {
clientSource: ["192.168.65.10"],
serverAddress: ["198.157.56.0"]
} ]
}
)
Here we create a user named “restrict” in the admin database. So this user may only authenticate if connecting from IP address 192.168.65.10 to this server address IP address 198.157.56.0.
In Mongodb, we can also drop a user using dropUser() method. This method returns true when the user is deleted otherwise return false.
Syntax:
db.dropUser(“Username”)
Example:
In this example, we will drop a user whose name is Robert.
db.dropUser("robert")
anikakapoor
MongoDB
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
MongoDB - Distinct() Method
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB - Update() Method
MongoDB - sort() Method
MongoDB Cursor
MongoDB updateMany() Method - db.Collection.updateMany() | [
{
"code": null,
"e": 23879,
"s": 23851,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 24312,
"s": 23879,
"text": "In MongoDB, we are allowed to create new users for the database. Every MongoDB user only accesses the data that is required for their role. A role in MongoDB grant... |
Datablocks API & Image Classification in fastai using Lego Minifigures Dataset | by Vinayak Nayak | Towards Data Science | The topics covered in this post are as follows
Introduction
The Task
The fastai DataBlock API
Training A Classification Model
Interpreting A Classification Model
References
You can click on any topic above to navigate to the respective section
Image Classification has been a very common task since time immemorial however it wasn’t until Deep Learning that computers were proficient at doing this task. With the advent of Convolutional Neural Networks this task has become so good that in recent years computers have also beat humans in few classification applications. Building a model to do image classification (MNIST digit recognition) marks the start of the deep learning journey for many beginners. Let’s therefore do the same only let’s make it even more exciting by using a dataset curated on Kaggle called LEGO Minifigures classification.
fastai developed by Jeremy Howard and Sylvain Gugger is a library built on top of PyTorch for deep learning practitioners to ease the process of building/training and inferring from DL models. With relatively a very short code, you can build state of the art models for almost all tasks (classification, regression (on both structured & unstructured data), collaborative filtering etc.)using this library; that’s the amount of effort that has gone into making it. So let’s leverage it to our benefit and start with this task of image classification.
We have images of 27 different mini-figures built by Lego which are obtained from Kaggle here. We have to build a classifier which when given an image of a particular minifigure can tell which superhero/character it is. Let’s read in the dataset and have a look at few entries from the same.
As we can see that the index file holds the information required to load the data that needs to be fed to the model and the metadata contains information about the different classes.
When we take a close look at the minifigures, it is observed that both class_id 1 and class_id 17 represent SPIDER-MAN. The SPIDER-MAN from class_id 17 is from a marvel superheroes collection and is therefore renamed accordingly to MARVEL SPIDER-MAN. Once that’s done, we can then join the index and metadata files on the class_id as primary key.
Also, the DataBlock API expects the column train-valid to be a column of boolean values which have a value true if the row belongs to validation set and false otherwise. Hence making that change as well and after completing all of this, the final dataframe is as shown below.
Let’s have a look at the number of images that we have in train and validation sets respectively. It’s generally good to have them in equal proportions and also they should both belong to the same population. Let’s see how the distribution of data looks like.
The dataset looks pretty much balanced with almost a hundred and fifty elements each in train and validation sets. Well, with respect to image standards, this number is pretty low for training a Neural Network classifier. Deep Neural Networks learn good representation functions when there’s a lot of images. A few hundreds or thousands of images per classification label is pretty normal with respect to normal deep learning standards. Over here we have a combined 300 odd images for 27 classes which means we have not more than 10–12 images per class. Let’s see how good a model we can build using this data.
A substantial amount of time is consumed in curating the data in a format suitable to feed to the deep learning model in any application. To simplify this process so that any DL Practitioner can focus on the model building and interpretation more than data curation, fastai came up with the DataBlock API which is excellent at data curation.
Generally, data is structured in one of the following two ways
In this format, data is curated folderwise. There are separate folders for train and validation sets and each of them have folders corresponding to the respective classes that have the relevant data corresponding to those classes. The tree structure aside is for a cat-dog dataset curated in an Imagenet directory kind of style.
In this method, the information about how the data is structured is wrapped in a csv. It has all information like the path to the data, class of the data, whether or not the item belongs to training or validation set and so forth. Our current dataset is curated in this particular format which we will leverage to create a datablock.
fastai’s datablock API provides support for both of these structures and even a few more however, we’ll look at the general structure of the API and how we can use the same for the sake of this problem.
The datablock API takes in several arguments some of which are compuslory and some are optional. We’ll go through each one of them sequentially.
blocks: In order to specify the input and output. Here, we have an Image as an input and a category/label as output. Our output is a CategoryBlock but other outputs can be ImageBlock(for autoencoders), MultiCategoryBlock(for multi-label classification) etc.splitter: Jeremy always emphasizes the importance of a validation set in order to evaluate the performance of a model and rightly so! Without doing this, we’ll never truly now how well is our model performing. To do this, we can specify a RandomSplitter or a column in our case which specifies whether an entry belongs to training set or validation set.get_x: This argument asks for the location of the inputs i.e. ImageBlock here. In our dataframe, the first column i.e. path column contains the paths hence we’ve specified cols = 0. Also optionally we can add a prefix and suffix here using pref and suff arguments. Since we have relative path of images, to get absolute path, prefixes are needed. In csvs, sometimes the extensions of items in the path columns are dropped which is where suffix argument comes in handy.get_y: This argument asks for the output values. In the dataframe, since the 4th column i.e. minifigure_name is the label we’d like to predict, we specified cols = 3 in the ColReader object to the get_y argument.item_tfms: Before making a batch of items for the neural network to train, we need to apply some transforms to ensure that they’re all the same size (generally square) and in certain other cases, some other transforms as well. These are mentioned in this argument.batch_tfms: These are the augmentation methods which you wish to use for making the model learn general features by cropping, zooming, perspective warping and other such transformations. You can choose to ignore this argument if you already have a large dataset size with a significant variety of images but otherwise, it always helps to add transforms to learn generalised models rather than over-fitted ones.
blocks: In order to specify the input and output. Here, we have an Image as an input and a category/label as output. Our output is a CategoryBlock but other outputs can be ImageBlock(for autoencoders), MultiCategoryBlock(for multi-label classification) etc.
splitter: Jeremy always emphasizes the importance of a validation set in order to evaluate the performance of a model and rightly so! Without doing this, we’ll never truly now how well is our model performing. To do this, we can specify a RandomSplitter or a column in our case which specifies whether an entry belongs to training set or validation set.
get_x: This argument asks for the location of the inputs i.e. ImageBlock here. In our dataframe, the first column i.e. path column contains the paths hence we’ve specified cols = 0. Also optionally we can add a prefix and suffix here using pref and suff arguments. Since we have relative path of images, to get absolute path, prefixes are needed. In csvs, sometimes the extensions of items in the path columns are dropped which is where suffix argument comes in handy.
get_y: This argument asks for the output values. In the dataframe, since the 4th column i.e. minifigure_name is the label we’d like to predict, we specified cols = 3 in the ColReader object to the get_y argument.
item_tfms: Before making a batch of items for the neural network to train, we need to apply some transforms to ensure that they’re all the same size (generally square) and in certain other cases, some other transforms as well. These are mentioned in this argument.
batch_tfms: These are the augmentation methods which you wish to use for making the model learn general features by cropping, zooming, perspective warping and other such transformations. You can choose to ignore this argument if you already have a large dataset size with a significant variety of images but otherwise, it always helps to add transforms to learn generalised models rather than over-fitted ones.
Once we have the DataBlock API object, we can create dataloaders using this object which can be fed into the model for training. After creating a dataloader, we can see how data is input to the model using show_batch method and subsequently the vocab attribute can be used to see what and how many classes/labels are present in the dataset as a whole.
The dataloaders object contains both the train and validation dataloaders in it. The items in vocab correspond to the classes pertaining to train dataloader and the validation dataloader may have less than or equal number of labels/classes as the train dataloader. Also, notice that in the show_batch method, you can provide the number of items that you want to see but if the number is bigger than batch size (9 as opposed to a bs of 8), then you’ll only see as many images as in the batch size.
Once you have a dataloader, next step is to create a model and to train it with an appropriate optimisation algorithm. fastai already abstracts a lot of these things and provides you with a very simple learner object which also has a lot of arguments but let me stress on the most important ones below.
The compulsory arguments that our Learner object takes are as follows:
dls: The dataloader object which we defined using the DataBlocks API above. It contains train and validation datasets and their labels.model: This is the model architecture that you would like to use. Since we’re doing transfer learning, we will be using a predefined resnet101 model trained on ImageNet weights. But, if you want you can build your own PyTorch model by inheriting the nn.Module class and implementing it’s forward method; that is beyond the scope of this article, so we wouldn’t discuss it here.loss_func: Also known as the objective/cost function, this is the function based which the optimization algorithm is trying to minimize (well in most cases; unless you define an objective to maximize). For classification, CrossEntropy Loss and for regression MSE Loss are the most commonly used loss functions.
dls: The dataloader object which we defined using the DataBlocks API above. It contains train and validation datasets and their labels.
model: This is the model architecture that you would like to use. Since we’re doing transfer learning, we will be using a predefined resnet101 model trained on ImageNet weights. But, if you want you can build your own PyTorch model by inheriting the nn.Module class and implementing it’s forward method; that is beyond the scope of this article, so we wouldn’t discuss it here.
loss_func: Also known as the objective/cost function, this is the function based which the optimization algorithm is trying to minimize (well in most cases; unless you define an objective to maximize). For classification, CrossEntropy Loss and for regression MSE Loss are the most commonly used loss functions.
Other optional but important arguments are opt_func which specifies the optimisation algorithm to be used for training the model and metrics which specify what metrics to gauge the performance on (it could be accuracy, precision, recall, any custom metric). Also there is a capability of calling different callbacks as well which is not in the scope of this article. You can refer here to understand more about the same.
Once we have the learner object, we can utilize the lr_find function to find an optimal learning rate for our model. Looking at the loss vs learning rate profile, we should select the learning rate where the loss is minimum or a rate slightly below that point. It’s good to be conservative with learning rates because in my personal opinion, delayed convergence is more tolerable than overshooting the optimal point.
The function also gives suggestions for lr_min and the point where the steepest descent in loss was observed. The lr_min is an estimate of the minimum learning rate that one should pick in order to see decent speed of training without being extremely wary of skipping the optimal point in the loss surface while simultaneously ensuring that the model is learning something and parameter updates are happening. So, let’s for this case pick a learning rate of .01 and start the training.
Since we have only about 154 training images, each epoch takes around 4 seconds with validation and metric computation. In this case, for resnet101 pretrained model, it’s top fc layers and a few penultimate convolution layers are getting the weight updates and the rest of the network is frozen i.e. weight updates don’t propagate further backwards than that. This fine-tuning approach has empirically observed to be the best when adopting a pre-trained model for a custom task; however after substantial improvement, like when the error rate drops to 10% or accuracy reaches almost 90%, we can also unfreeze that portion of the network and again train the model with the parameter updates now penetrating throughout the neural network.
That’s exactly what we did here. After training for 25 epochs, we unfreezed the model and checked for a good learning rate with the help of lr_find and ran the training loop for 5 more epochs. However we couldn’t find any substantial improvement in the error rate. It went down to 8.9% from 10.27%; this shows that the model is now saturated and no matter what you do to the model unless you provide new data, there wouldn’t be any major impact on the accuracy of this model.
In order to save this model for interpretation in future, you can simply use the command
learn.export("filename.pkl")
This will save the model with the name filename as a pkl file that could be later reloaded for inference. Now that we’re through with all the training part, let’s interpret the model and look at the predictions that it has made.
After building a model, the performance of the model needs to gauged to ensure it’s usability and fastai provides a class ClassificationInterpretation for the same. We can create an instance of this class with the learner object that we fit in the training part.
Once we do that, we can observe the confusion matrix for validation data to see where the mistakes were made and how many of them were there.
The overall structure of this seems good. In an idea case the diagonal is completely saturated with all the other non-diagonal elements being null. Here we can see that’s not the case. This means that our model has misclassified some action figures for eg. 2 RON WEASLY Legos were incorrectly classified as HARRY POTTER, a YODA figure was misclassified as RON WEASLEY and so on. In order to particularly highlight the ones which are misclassified, the ClassificationInterpretation class also has one more method.
Here we can see tuples of misclassified items. Each tuple is structured as (Ground Truth, Prediction, number of misclassifications) respectively. Optionally you can also provide a parameter which looks at only those pairs which were misclassified above a certain threshold number of times. This can help us identify the pairs which need to be focussed more on. Thereby we can make decisions like adding more data or deleting wrongly labelled data and so on.
Although in my application everything is neatly labelled, there can be instances of mislabelling like below. The above code helps to create a GUI inline in the notebook which can be used to basically keep/delete/move items from one class to another. This is present in the widgets class in the fastai.vision package. If you’re sometime not sure about the labelling in your dataset, auditing your dataset like this is worth a try to clean it.
So that’s it for this post guys; I hope you understood the steps to start using fastai for making your own image classifier. It has saved me a lot of time in terms of data preprocessing, model training and model interpretation, particularly in deep learning. Unlike PyTorch where we have to define the Datasets and Dataloader, the datablock API obviates the need for that step as it nicely wraps everything into one function call. Hope you liked the article and thanks for reading through!
Lego Minifigures datasetPetBreeds Classification NotebookGithub Repo for code in this post
Lego Minifigures dataset
PetBreeds Classification Notebook
Github Repo for code in this post | [
{
"code": null,
"e": 219,
"s": 172,
"text": "The topics covered in this post are as follows"
},
{
"code": null,
"e": 232,
"s": 219,
"text": "Introduction"
},
{
"code": null,
"e": 241,
"s": 232,
"text": "The Task"
},
{
"code": null,
"e": 266,
"s... |
Convert PDF to CSV using Python | Python is well known for its huge library of packages. With the help of libraries, we will see how to convert a PDF to a CSV file. A CSV file is nothing but a collection of data, framed along with a set of rows and columns. There are various packages available in the Python library to convert PDF to CSV, but we will use the Tabula-py module. The major part of tabula-py is written in Java that first reads the PDF document and converts the Python DataFrame into a JSON object.
In order to work with tabula-py, we must have Java preinstalled in our system. To convert the PDF file to CSV, we will follow these steps −
First, Install the required package by typing pip install tabula-py in the command shell.
First, Install the required package by typing pip install tabula-py in the command shell.
Now, read the file using read_pdf("file location", pages=number) function. This will return the DataFrame.
Now, read the file using read_pdf("file location", pages=number) function. This will return the DataFrame.
Convert the DataFrame into an Excel file using tabula.convert_into(‘pdf-filename’, ‘name_this_file.csv’,output_format= "csv", pages= "all"). It generally exports the pdf file into an excel file.
Convert the DataFrame into an Excel file using tabula.convert_into(‘pdf-filename’, ‘name_this_file.csv’,output_format= "csv", pages= "all"). It generally exports the pdf file into an excel file.
In this example, we have used IPL Match Schedule Document to convert it into an Excel file.
# Import the required Module
import tabula
# Read a PDF File
df = tabula.read_pdf("IPLmatch.pdf", pages='all')[0]
# convert PDF into CSV
tabula.convert_into("IPLmatch.pdf", "iplmatch.csv", output_format="csv", pages='all')
print(df)
Running the above code will convert the PDF file into an Excel (CSV) file. | [
{
"code": null,
"e": 1541,
"s": 1062,
"text": "Python is well known for its huge library of packages. With the help of libraries, we will see how to convert a PDF to a CSV file. A CSV file is nothing but a collection of data, framed along with a set of rows and columns. There are various packages av... |
Biggest Square that can be inscribed within an Equilateral triangle - GeeksforGeeks | 10 Mar, 2021
Given here is an equilateral triangle of side length a. The task is to find the side of the biggest square that can be inscribed within it.Examples:
Input: a = 5
Output: 2.32
Input: a = 7
Output: 3.248
Approach: Let the side of the square be x. Now, AH is perpendicular to DE. DE is parallel to BC, So, angle AED = angle ACB = 60
In triangle EFC,
=> Sin60 = x/ EC
=> √3 / 2 = x/EC
=> EC = 2x/√3
In triangle AHE,
=> Cos 60 = x/2AE
=> 1/2 = x/2AE
=> AE = x
So, side AC of the triangle = 2x/√3 + x. Now, a = 2x/√3 + x Therefore, x = a/(1 + 2/√3) = 0.464aBelow is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find the biggest square// which can be inscribed within the equilateral triangle#include <bits/stdc++.h>using namespace std; // Function to find the side// of the squarefloat square(float a){ // the side cannot be negative if (a < 0) return -1; // side of the square float x = 0.464 * a; return x;} // Driver codeint main(){ float a = 5; cout << square(a) << endl; return 0;}
// Java Program to find the// the biggest square which// can be inscribed within// the equilateral triangle class GFG{ // Function to find the side // of the square static double square(double a) { // the side cannot be negative if (a < 0) return -1; // side of the square double x = 0.464 * a; return x; } // Driver code public static void main(String []args) { double a = 5; System.out.println(square(a)); }} // This code is contributed by ihritik
# Python3 Program to find the biggest square# which can be inscribed within the equilateral triangle # Function to find the side# of the squaredef square( a ): # the side cannot be negative if (a < 0): return -1 # side of the square x = 0.464 * a return x # Driver codea = 5print(square(a)) # This code is contributed by ihritik
// C# Program to find the biggest// square which can be inscribed// within the equilateral triangleusing System; class GFG{ // Function to find the side // of the square static double square(double a) { // the side cannot be negative if (a < 0) return -1; // side of the square double x = 0.464 * a; return x; } // Driver code public static void Main() { double a = 5; Console.WriteLine(square(a)); }} // This code is contributed by ihritik
<?php// PHP Program to find the biggest// square which can be inscribed// within the equilateral triangle // Function to find the side// of the squarefunction square($a ){ // the side cannot be negative if ($a < 0) return -1; // side of the square $x = 0.464 * $a; return $x;} // Driver code$a = 5;echo square($a); // This code is contributed by ihritik ?>
<script>// javascript Program to find the// the biggest square which// can be inscribed within// the equilateral triangle // Function to find the side// of the squarefunction square(a){ // the side cannot be negative if (a < 0) return -1; // side of the square var x = 0.464 * a; return x;} // Driver code var a = 5; document.write(square(a).toFixed(2)); // This code contributed by Princi Singh </script>
2.32
ihritik
Akanksha_Rai
princi singh
square-rectangle
C++ Programs
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Pi(π) in C++ with Examples
Const keyword in C++
Circle and Lattice Points
Closest Pair of Points using Divide and Conquer algorithm
How to check if two given line segments intersect?
Program for distance between two points on earth
How to check if a given point lies inside or outside a polygon? | [
{
"code": null,
"e": 24215,
"s": 24187,
"text": "\n10 Mar, 2021"
},
{
"code": null,
"e": 24366,
"s": 24215,
"text": "Given here is an equilateral triangle of side length a. The task is to find the side of the biggest square that can be inscribed within it.Examples: "
},
{
... |
Finally learn how to use command line apps... by making one! | by Zack Akil | Towards Data Science | At the risk of alienating a lot of readers... I grew up with GUI’s, so I never needed to learn the ways of the terminal! This is socially acceptable in todays society of friendly user interfaces, except maybe if you’re in software engineering... whoops!
I’ve gotten pretty far just through copy and pasting full command-line operations from Stack-Overflow but have never become comfortable enough to use a command line app “properly”. What finally caused it to click for me was when I stumbled across a very handy python library called argparse that allows you to build a nice robust command line interface for your python scripts.
This tutorial is great in-depth explanation about how to use argparse, but I’ll go over the key eye openers:
argparse is part of the standard python library so pop open your code editor and follow along (you don’t need to install anything)!
The most useful part of every command line app!
# inside a file called my_app.pyimport argparseparser = argparse.ArgumentParser(description="Nice little CL app!")parser.parse_args()
The code above will do nothing, except by default you have the help flag!
In the command line you can run:
python my_app.py --help
or
python my_app.py -h
and you’ll get an output like this:
usage: my_app.py [-h]Nice little CL app!optional arguments:-h, --help show this help message and exit
Seems pretty cool right? but wait, when you use argparse to add more functions (see below) this help output will automatically fill up with all of the instructions of how you can use your app!
Lets say you want to have your app take in some variable, we just use the parser.add_argument() function and give our argument some label (in this case “name”):
import argparseparser = argparse.ArgumentParser(description="Nice little CL app!")parser.add_argument("name", help="Just your name, nothing special")args = parser.parse_args()print("Your name is what? " + args.name)
Notice how we added the help text! Now when we run python my_app.y -h we get all of the app details:
usage: my_app.py [-h] nameNice little CL app!positional arguments:name Just your name, nothing specialoptional arguments:-h, --help show this help message and exit
Pretty cool, but let’s run our app with python my_app.py
usage: my_app.py [-h] namemy_app.py: error: too few arguments
That’s right! Automatic input checking!
Now lets run python my_app.py "Slim Shady"
Your name is what? Slim Shady
Pretty slick!
Maybe you want to give someone the option of telling you little more about themselves? Adding a double dash when using parser.add_argument() function will make that argument optional!
import argparseparser = argparse.ArgumentParser(description=”Nice little CL app!”)parser.add_argument(“name”, help=”Just your name, nothing special”)parser.add_argument("--profession”, help=”Your nobel profession”)args = parser.parse_args()print(“Your name is what? “ + args.name)if args.profession: print(“What is your profession!? a “ + args.profession)
If you want to pass in a variable for that argument you just need to specify the double-dashed argument name before the variable you want to pass:
python my_app.py "Slim Shady" --profession "gift wrapper"
which gives you :
Your name is what? Slim ShadyWhat is your profession!? a gift wrapper
Or you don’t have to, it is optional after all!
python my_app.py "Slim Shady"
still gives you:
Your name is what? Slim Shady
and the magic once again when running python my_app.py -h :
usage: my_app.py [-h] [--profession PROFESSION] nameNice little CL app!positional arguments:name Just your name, nothing specialoptional arguments:-h, --help show this help message and exit--profession PROFESSION Your nobel profession
Maybe you just want to enable something cool to happen. Add action="store_true" to your parser.add_argument() function and you have yourself a flag argument :
import argparseparser = argparse.ArgumentParser(description="Nice little CL app!")parser.add_argument("name", help="Just your name, nothing special")parser.add_argument("--profession", help="Your nobel profession")parser.add_argument("--cool", action="store_true", help="Add a little cool")args = parser.parse_args()print("Your name is what? " + args.name)cool_addition = " and dragon tamer" if args.cool else ""if args.profession: print("What is your profession!? a " + args.profession + cool_addition)
It’s pretty neat, you just plop the flag name into your command like so:
python my_app.py "Slim Shady" --profession "gift wrapper" --cool
and presto!
Your name is what? Slim ShadyWhat is your profession!? a gift wrapper and dragon tamer
and remember, you don’t have to use it, it’s just a flag:
python my_app.py "Slim Shady" --profession "gift wrapper"
will still give:
Your name is what? Slim ShadyWhat is your profession!? a gift wrapper
look though at the help command python my_app.py -h :
usage: my_app.py [-h] [--profession PROFESSION] [--cool] nameNice little CL app!positional arguments:name Just your name, nothing specialoptional arguments:-h, --help show this help message and exit--profession PROFESSION Your nobel profession--cool Add a little cool
I’m just going to assume you’re as satisfied with that as I am from now on.
Unveiling the mysterious one character arguments that confused me for so long. Just by adding a single letter prefixed with a single dash to your parser.add_argument() functions you have super short versions of the same arguments:
import argparseparser = argparse.ArgumentParser(description="Nice little CL app!")parser.add_argument("name", help="Just your name, nothing special")parser.add_argument("-p", "--profession", help="Your nobel profession")parser.add_argument("-c", "--cool", action="store_true", help="Add a little cool")args = parser.parse_args()print("Your name is what? " + args.name)cool_addition = " and dragon tamer" if args.cool else ""if args.profession: print("What is your profession!? a " + args.profession + cool_addition)
So that instead of typing in :
python my_app.py "Slim Shady" --profession "gift wrapper" --cool
you can just type:
python my_app.py "Slim Shady" -p "gift wrapper" -c
and you’ll get the same output:
Your name is what? Slim ShadyWhat is your profession!? a gift wrapper and dragon tamer
And this is reflected in the help text (python my_app.py -h ):
usage: my_app.py [-h] [--profession PROFESSION] [--cool] nameNice little CL app!positional arguments:name Just your name, nothing specialoptional arguments:-h, --help show this help message and exit-p PROFESSION, --profession PROFESSION Your nobel profession-c, --cool Add a little cool
You now have a perfect little command line app and are hopefully more comfortable with finding your way around command line apps!
Just remember --help ! | [
{
"code": null,
"e": 426,
"s": 172,
"text": "At the risk of alienating a lot of readers... I grew up with GUI’s, so I never needed to learn the ways of the terminal! This is socially acceptable in todays society of friendly user interfaces, except maybe if you’re in software engineering... whoops!"
... |
How to draw a rectangle in HTML5 SVG? | SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG.
To draw a rectangle in HTML SVG, use the SVG <rect> element.
You can try to run the following code to learn how to draw a rectangle in HTML5 SVG.
<!DOCTYPE html>
<html>
<head>
<style>
#svgelem {
position: relative;
left: 10%;
-webkit-transform: translateX(-20%);
-ms-transform: translateX(-20%);
transform: translateX(-20%);
}
</style>
<title>SVG</title>
</head>
<body>
<h2>HTML5 SVG Rectangle</h2>
<svg id="svgelem" width="300" height="200" xmlns="http://www.w3.org/2000/svg">
<rect width="200" height="100" fill="green"/>
</svg>
</body>
</html> | [
{
"code": null,
"e": 1315,
"s": 1062,
"text": "SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG."... |
Memory leaks in Java | 07 May, 2021
In C, programmers totally control allocation and deallocation of dynamically created objects. And if a programmer does not destroy objects, memory leak happens in C,
Java does automatic Garbage collection. However there can be situations where garbage collector does not collect objects because there are references to them. There might be situations where an application creates lots of objects and does not use them. Just because every objects has valid references, garbage collector in Java can’t destroys the objects. Such types of useless objects are called as Memory leaks. If allocated memory goes beyond limit, program will be terminated by rising OutOfMemoryError. Hence if an object is no longer required, it is highly recommended to make that object eligible for garbage collector. Otherwise We should use some tools that do memory management to identifies useless objects or memory leaks like:
HP OVO
HP J METER
JProbe
IBM Tivoli
Java
// Java Program to illustrate memory leaksimport java.util.Vector;public class MemoryLeaksDemo{ public static void main(String[] args) { Vector v = new Vector(214444); Vector v1 = new Vector(214744444); Vector v2 = new Vector(214444); System.out.println("Memory Leaks"); }}
Output:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed
sweetyty
java-garbage-collection
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Collections in Java
Stream In Java
Singleton Class in Java
Set in Java
Initializing a List in Java
Introduction to Java
Multithreading in Java
Constructors in Java
Exceptions in Java
LinkedList in Java | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 May, 2021"
},
{
"code": null,
"e": 219,
"s": 53,
"text": "In C, programmers totally control allocation and deallocation of dynamically created objects. And if a programmer does not destroy objects, memory leak happens in C,"
},
... |
strchr() function in C++ and its applications | 12 May, 2022
In C++, strchr() is a predefined function used for finding the occurrence of a character in a string. It is present in cstring header file.
Syntax:
// Returns pointer to the first occurrence// of c in str[]char *strchr(const char *str, int c)
Note that c is passed as its int promotion, but it is internally treated as char.Application Given a string in c++, we need to find the first occurrence of a character, let’s say ‘a’.
Examples:
Input : str[] = ‘This is a string’Output : 9
Input : str[] = ‘My name is Ayush’Output : 5
Algorithm:1. Pass the given string in the strchr() function and mention the character you need to point. 2. The function returns a value, and print the value.
Below is the implementation of the above algorithm:
CPP
// CPP program to find position of a character// in a given string.#include <iostream>#include <cstring>using namespace std; int main(){ char str[] = "My name is Ayush"; char* ch = strchr(str, 'a'); cout << ch - str + 1; return 0;}
5
strchr() function can also be used to check the presence of a character in a string. The input consists of a character we want to check, if it exists in the string. Example: Let’s check if the characters A and z are present in the string – “My name is Ayush”
Input : str[] = ‘My name is Ayush’, ch1 = ‘A’, ch2 = ‘z’Output : A is present in the string z is not present in the string
Algorithm 1. Pass the given string in the strchr() function with the character as the second parameter and check if the value returned is not null 2. If the function returns a NULL value, this means that the string does not contain the character, so, print the required statement. 3. Else if the function does not returns a NULL value, this means that the string contains the character, so, print the required statement.
Below is the implementation of the above algorithm:
CPP
// CPP program to demonstrate working of strchr()#include <iostream>#include <cstring>using namespace std;// Driver codeint main(){ char str[] = "My name is Ayush"; char ch = 'A', ch2 = 'z'; if (strchr(str, ch) != NULL) cout << ch << " " << "is present in string" << endl; else cout << ch << " " << "is not present in string" << endl; if (strchr(str, ch2) != NULL) cout << ch2 << " " << "is present in string" << endl; else cout << ch2 << " " << "is not present in string" << endl; return 0;}
A is present in string
z is not present in string
strchr() function can be used to find absolute directory path for Linux: (Contributed by Ekta_nehwal)
Examples:
Input : /home/test/sampleOutput : /home/test
Algorithm:
Find the position of last “/” in the directory path by using strrchr.Replace the occurrence with the NULL character.
Find the position of last “/” in the directory path by using strrchr.
Replace the occurrence with the NULL character.
Below is the implementation of the above algorithm, basically we are finding the position of / and then changing it to \0(null).
C
// C program to find directory path#include <string.h>#include<stdio.h> int main(){ char string[]={"/home/test/sample"}; int len; //position of last char char* pos; // save length of string len = strlen(string); // Find the last character with pos = strrchr(string,'/') ; printf("%s\n",string); // replace last occurrence of / with NULL character. *pos='\0'; printf("%s\n",string); return 0;}
/home/test/sample
/home/test
This article is contributed by Ayush Saxena. 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 if you want to share more information about the topic discussed above.
mandeep mourya
sharmavaibhav227
marcosarcticseal
ivnv12
himeshchauhan10
CPP-Library
cpp-string
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Inheritance in C++
Substring in C++
Priority Queue in C++ Standard Template Library (STL)
The C++ Standard Template Library (STL)
C++ Classes and Objects
Object Oriented Programming in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 194,
"s": 54,
"text": "In C++, strchr() is a predefined function used for finding the occurrence of a character in a string. It is present in cstring header file."
},
{
"code": null,
"e... |
Python getpass module | 23 Dec, 2020
When we use terminal based application with some security credentials that use password before execution the application, Then It will be done with Python Getpass module. In this article we are going see how to use Getpass module.
Getpass module provides two function:
getpass.getpass()
getpass.getuser()
In many programs we need a secure the data or program then this case we use some secret key or passwords to identifying the users. Using getpass() it is possible to accept the password in python program.
Python3
import getpass pwd = getpass.getpass(prompt = 'Enter the password')if pwd == 'Admin': print('Unlock!')else: print('You entered wrong password')
Output:
Let’s understand this module some example:
In this example we will see how to get password from users and return the same password with no prompt.
Python3
import getpass pwd = getpass.getpass()print("You entered: ", pwd)
Output:
If user want some message before login like security question then we will use prompt attributes in getpass.
Python3
import getpass pwd = getpass.getpass(prompt = 'What is you last Name: ')if pwd == 'Kumar': print('Unlock! Welcome kumar')else: print('You entered wrong Name')
Output:
This function allow us to stream the password a user enter.
Python3
import getpassimport sys pwd = getpass.getpass(stream = sys.stderr)print('Entered Password: ', pwd)
Output:
This function return system login name of the user. It checks the environment variable of your computer and fetch the user name and return as a string and if it can not able to find the environment variable then exception is raised.
Example 1:
Here we will get username of our computer with getuser().
Python3
import getpass print(getpass.getuser())
Output:
Example 2:
Here we will get username and password with getuser() and getpass().
Python3
import getpass user_name = getpass.getuser()pass_word = getpass.getpass("Enter password: ") print("User name: ", user_name)print("Your password :", pass_word)
Output:
Picked
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Dec, 2020"
},
{
"code": null,
"e": 283,
"s": 52,
"text": "When we use terminal based application with some security credentials that use password before execution the application, Then It will be done with Python Getpass module. In ... |
Python | Pandas dataframe.ffill() | 01 Jul, 2021
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.ffill() function is used to fill the missing value in the dataframe. ‘ffill’ stands for ‘forward fill’ and will propagate last valid observation forward.
Syntax: DataFrame.ffill(axis=None, inplace=False, limit=None, downcast=None)Parameters: axis : {0, index 1, column} inplace : If True, fill in place. Note: this will modify any other views on this object, (e.g. a no-copy slice for a column in a DataFrame). limit : If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None. Downcast: a dict of item->dtype of what to downcast if possible, or the string ‘infer’ which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible)Returns : filled : DataFrame
Example #1: Use ffill() function to fill the missing values along the index axis. Note : When ffill() is applied across the index then any missing value is filled based on the corresponding value in the previous row.
Python3
# importing pandas as pdimport pandas as pd # Creating the dataframedf=pd.DataFrame({"A":[5,3,None,4], "B":[None,2,4,3], "C":[4,3,8,5], "D":[5,4,2,None]}) # Print the dataframedf
Let’s fill the missing value over the index axis
Python3
# applying ffill() method to fill the missing valuesdf.ffill(axis = 0)
Output :
Notice, values in the first row is still NaN value because there is no row above it from which non-NA value could be propagated. Example #2: Use ffill() function to fill the missing values along the column axis. Note : When ffill is applied across the column axis, then missing values are filled by the value in previous column in the same row.
Python3
# importing pandas as pdimport pandas as pd # Creating the dataframedf=pd.DataFrame({"A":[5,3,None,4], "B":[None,2,4,3], "C":[4,3,8,5], "D":[5,4,2,None]}) # Print the dataframedf
Let’s fill the missing value over the column axis
Python3
# applying ffill() method to fill the missing valuesdf.ffill(axis = 1)
Output :
Notice, the value in the first column is NaN value because there is no cell left to it and so this cell cannot be filled using the previous cell value along the column axis.
amansingh110000
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Jul, 2021"
},
{
"code": null,
"e": 439,
"s": 54,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes im... |
Completely fair Scheduler (CFS) and Brain Fuck Scheduler (BFS) | 28 Jul, 2021
Prerequisite – CPU Scheduling Completely fair Scheduler (CFS) and Brain Fuck Scheduler (BFS) are two different process schedulers currently used in Linux.
Process Scheduling – As any program is loaded as process in RAM and then CPU executes the process according to the priority of the process.
1. Completely fair Scheduler (CFS) :
It is based on Rotating Staircase Deadline Scheduler (RSDL).
It is the default scheduling process since version 2.6.23.
Elegant handling of I/O and CPU bound process.
As the name suggests it fairly or equally divides the CPU time among all the processes.Before understanding the CFS let’s look at the Ideal Fair Scheduling (IFS) of N processes. If there are N processes in the ready queue then each process receives (100/N)% of CPU time according to IFS.
Lets take four process and their burst time as shown below waiting in the ready queue for the execution.
Take a time quantum of say 4ms. Initially, there is four processes waiting in the ready queue to be executed and according to Ideal fair scheduling, each process gets equally fair time for it’s execution (Time quantum/N).
So 4/4=1 each process gets 1ms to execute in first quantum. After the completion of six quantum process B and D are completely executed and remaining are A and C, which are already executed for 6ms and their remaining time is A=4ms and C=8ms).
In the seventh quantum of time A and C will execute (4/2=2ms as there are only two process remaining). This is ideal fair scheduling in which each process gets equally share of time quantum no matter what priority it is of.
Below is table description of the IFS. Q:represent time quantum which is 4ms.
CFS is similar as ideal-based scheduling instead it priorities each process according to there virtual runnable time.
Idea behind CFS –
Each run able process have a virtual time associated with it in PCB (process control block).
Whenever a context switch happens(or at every scheduling point) then current running process virtual time is increased by virtualruntime_currprocess+=T. where T is time for which it is executed recently.
Runtime for the process therefore monotonically increases.
So initially every process have some starting virtual time (you can google how initially virtual run time is calculated).
CFS is quite simple algorithm for the process scheduling and it is implemented using RED BLACK Trees and not queues. So all the process which are on main memory are inserted into Red Black trees and whenever a new process comes it is inserted into the tree. As we know that Red Black trees are self Balancing binary Search trees.
In C++, we can use maps in STL as they are implemented using red black trees.
Now whenever there is context switch occurs –
The virtual time for the current process which was executing is updated as explained above.
The new process is decided which has lowest virtual time and that we know that is left most node of Red Black tree.
If the current process still has some burst time then it is inserted into the Red Black tree.
So this way each process gets fair time for the execution as after every context switch the virtual time of a process increases and thus priority shuffles.
Time Complexity analysis of the CFS –
Insertion in red black trees takes O(logn).Finding the node with lowest virtual time is O(1) as we can maintain a pointer.(In maps we can use auto it=map.begin()).
Insertion in red black trees takes O(logn).
Finding the node with lowest virtual time is O(1) as we can maintain a pointer.(In maps we can use auto it=map.begin()).
So overall time complexity is O(logn)
Here Red black tree is once created and then we have a Red black tree of N process So the scheduling time complexity is O(logn).
There is also one advantage of using RED Black Trees that is if a process is I/O bound then its virtual time is going to be very less and it appears as the leftmost node in the Red black tree so executed first. So CFS easily figure out the process which are I/O bound and which are CPU bound and it gives higher priority to I/O bound process so avoiding the starvation.
2. Brain Fuck Scheduler (BFS) : Unlike the CFS scheduler, BFS is O(n) scheduler which uses doubly linked list which is treated like a queue. So selection of the new process at time of context switch can go O(n) in the worst case and insertion of the process is O(1) as the queue is used.
A global run-queue is used so that all the CPU has access to it. During context switch the queue is scanned until a best process is found with the highest priority and then executed. Priority is decided based on the virtual deadline formula for every process and executed accordingly.
It is not used in Linux anymore due to Context switch overhead and also O(n) time complexity.
saurabh1990aror
arorakashish0911
Operating Systems-CPU Scheduling
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 184,
"s": 28,
"text": "Prerequisite – CPU Scheduling Completely fair Scheduler (CFS) and Brain Fuck Scheduler (BFS) are two different process schedulers currently used in Linux. "
},
{
"code... |
SQL Query to Drop Unique Key Constraints Using ALTER Command | 19 Apr, 2021
Here, we see how to drop unique constraints using alter command. ALTER is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop various constraints on the existing table.
Syntax :
ALTER TABLE table_name
DROP CONSTRAINT unique_constraint;
For instance, consider the below table ‘Employee’.
Create a Table:
CREATE TABLE Employee
('ID INT, F_Name CHAR(10), L_Name CHAR(10), Age INT);
Insert values to the table:
INSERT INTO Employee
VALUES('1','Rahul','Pal','20');
INSERT INTO Employee
VALUES('2','Ajay','Soni','32');
INSERT INTO Employee
VALUES('3','Jay','Harjai','24');
INSERT INTO Employee
VALUES('4','Ram','Meena','30');
Our table at this point will look like below:
To add a unique constraint to the table use the below statement:
ALTER TABLE Employee
ADD CONSTRAINT/INDEX unique_id UNIQUE (ID);
Now, if we add duplicates to it. It will throw the error as below. In order to add duplicates, we need to Drop Unique constraints.
Now the below query can be used to drop the unique constraint that we created above:
ALTER TABLE Employee
DROP CONSTRAINT unique_id;
Now let’s try an add duplicates in the table:
INSERT INTO Employee
VALUES('4', 'ABC', 'XYZ', '35');
Since we didn’t get an error, we have successfully removed the unique constraint. Let’s check out the tables to verify the same using the below statement:
SELECT * FROM Employee;
Output:
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Apr, 2021"
},
{
"code": null,
"e": 267,
"s": 52,
"text": "Here, we see how to drop unique constraints using alter command. ALTER is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop va... |
React.js static getDerivedStateFromProps() | 12 Mar, 2021
The getDerivedStateFromProps() method is used when the state of a component depends on changes of props.
getDerivedStateFromProps(props, state) is a static method that is called just before render() method in both mounting and updating phase in React. It takes updated props and the current state as arguments.
We have to return an object to update state or null to indicate that nothing has changed.
Creating React Application:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
App.js
import React from 'react';import ReactDOM from 'react-dom'; class App extends React.Component { render() { return ( <div> <Child name = "sachin"></Child> </div> ) }} class Child extends React.Component{ constructor(props){ super(props); this.state = { name: "kapil" }; } static getDerivedStateFromProps(props, state) { if(props.name !== state.name){ //Change in props return{ name: props.name }; } return null; // No change to state } /* if props changes then after getDerivedStateFromProps method, state will look something like { name: props.name } */ render(){ return ( <div> My name is {this.state.name }</div> ) }} export default App;
If props changes, then the state will also change accordingly else, getDerivedStateFromProps will return null that indicates no change in state. In the above example props have a property called name but the state has that property with a different value. so the state will change according to the value of props property.
Output:
Reference: https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
Picked
React.js-Methods
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS setState()
How to pass data from one component to other component in ReactJS ?
Re-rendering Components in ReactJS
ReactJS defaultProps
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?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 133,
"s": 28,
"text": "The getDerivedStateFromProps() method is used when the state of a component depends on changes of props."
},
{
"code": null,
"e": 339,
"s": 133,
"text": "g... |
Create Contact Us using WTForms in Flask | 26 May, 2022
WTForms is a library designed to make the processing of forms easier to manage. It handles the data submitted by the browser very easily. In this article, we will discuss how to create a contact us form using WTForms.
We don’t have to worry about validators.Avoidance of Cross-Site Request Forgery (CSRF).WTForms come as classes, so all the good come’s from an object form.No need to create any <label> or <input> elements manually using HTML.
We don’t have to worry about validators.
Avoidance of Cross-Site Request Forgery (CSRF).
WTForms come as classes, so all the good come’s from an object form.
No need to create any <label> or <input> elements manually using HTML.
Use the Terminal to install Flask-WTF.
pip install Flask-WTF
Step 1: Create a class having all elements that you want in your Form in the main.py.
Python3
from flask_wtf import FlaskFormfrom wtforms import StringField, validators, PasswordField, SubmitFieldfrom wtforms.validators import DataRequired, Emailimport email_validator class contactForm(FlaskForm): name = StringField(label='Name', validators=[DataRequired()]) email = StringField(label='Email', validators=[ DataRequired(), Email(granular_message=True)]) message= StringField(label='Message') submit = SubmitField(label="Log In")
Step 2: Create the object of the form and pass the object as a parameter in the render_template
Python3
@app.route("/", methods=["GET", "POST"])def home(): cform = contactForm() return render_template("contact.html", form=cform)
Step 3: Add CSRF protection. Add a secret key.
app.secret_key = "any-string-you-want-just-keep-it-secret"
Step 4: Add the fields in the contact.html HTML FILE.
{{ form.csrf_token }} is used to provide csrf protection.
HTML
<!DOCTYPE HTML> <html> <head> <title>Contact</title> </head> <body> <div class="container"> <h1>Contact Us</h1> <form method="POST" action="{{ url_for('home') }}"> {{ form.csrf_token }} <p> {{ form.name.label }} <br> {{ form.name }} </p> <p> {{ form.email.label }} <br> {{ form.email(size=30) }} </p> <p> {{ form.message.label }} <br> {{ form.message }} </p> {{ form.submit }} </form> </div> </body></html>
Step 5: Validating the Form and receiving the data.
Python3
@app.route("/", methods=["GET", "POST"])def home(): cform = contactForm() if cform.validate_on_submit(): print(f"Name:{cform.name.data}, E-mail:{cform.email.data}, message:{cform.message.data}") else: print("Invalid Credentials") return render_template("contact.html", form=cform)
Complete Code:
Python3
from flask import Flask, render_template, request, redirect, url_forfrom flask_wtf import FlaskFormfrom wtforms import StringField, validators, PasswordField, SubmitFieldfrom wtforms.validators import DataRequired, Emailimport email_validator app = Flask(__name__)app.secret_key = "any-string-you-want-just-keep-it-secret" class contactForm(FlaskForm): name = StringField(label='Name', validators=[DataRequired()]) email = StringField( label='Email', validators=[DataRequired(), Email(granular_message=True)]) message = StringField(label='Message') submit = SubmitField(label="Log In") @app.route("/", methods=["GET", "POST"])def home(): cform=contactForm() if cform.validate_on_submit(): print(f"Name:{cform.name.data}, E-mail:{cform.email.data}, message:{cform.message.data}") return render_template("contact.html",form=cform) if __name__ == '__main__': app.run(debug=True)
Output:
Name:Rahul Singh, E-mail:rahuls@gmail.com, message:This is Sample gfg Output!!!
We can also add the bootstrap to the above form to make it look interactive. For this, we will use the Flask-Bootstrap library. To install this module type the below command in the terminal.
pip install Flask-Bootstrap
Step 1: Create base.html
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title></head><body> {% block content %}{% endblock %}</body></html>
Step 2: Modify contact.html to
with single line {{ wtf.quick_form(form) }}
HTML
{% extends 'bootstrap/base.html' %}{% import "bootstrap/wtf.html" as wtf %} {% block title %}Contact Us{% endblock %} {% block content %} <div class="container"> <h1>Contact Us</h1> {{ wtf.quick_form(form) }} </div>{% endblock %}l>
Step 3: MODIFY main.py
It is very simple to modify the .py file. We just have to import the module and add the below line into the code
Bootstrap(app)
Python3
from flask import Flask, render_template, request, redirect, url_forfrom flask_wtf import FlaskFormfrom wtforms import StringField, validators, PasswordField, SubmitFieldfrom wtforms.validators import DataRequired, Emailfrom flask_bootstrap import Bootstrapimport email_validatorapp = Flask(__name__)Bootstrap(app)app.secret_key = "any-string-you-want-just-keep-it-secret" class contactForm(FlaskForm): name = StringField(label='Name', validators=[DataRequired()]) email = StringField(label='Email', validators=[DataRequired(), Email(granular_message=True)]) message = StringField(label='Message') submit = SubmitField(label="Log In") @app.route("/", methods=["GET", "POST"])def home(): cform=contactForm() if cform.validate_on_submit(): print(f"Name:{cform.name.data}, E-mail:{cform.email.data}, message:{cform.message.data}") return render_template("contact.html",form=cform) if __name__ == '__main__': app.run(debug=True)
Output:
prachisoda1234
Flask Projects
Python Flask
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 May, 2022"
},
{
"code": null,
"e": 272,
"s": 54,
"text": "WTForms is a library designed to make the processing of forms easier to manage. It handles the data submitted by the browser very easily. In this article, we will discuss how... |
Lexicographically smallest permutation of a string with given subsequences | 09 Dec, 2021
Given a string consisting only of two lowercase characters and and two numbers and . The task is to print the lexicographically smallest permutation of the given string such that the count of subsequences of is and of is . If no such string exists, print “Impossible” (without quotes).Examples:
Input: str = "yxxyx", p = 3, q = 3
Output: xyxyx
Input: str = "yxxy", p = 3, q = 2
Output: Impossible
Approach: First of all, by induction it can prove that the product of count of ‘x’ and count of ‘y’ should be equal to the sum of the count of a subsequence of ‘xy’ and ‘yx’ for any given string. If this does not hold then the answer is ‘Impossible’ else answer always exist.Now, sort the given string so the count of a subsequence of ‘yx’ becomes zero. Let nx be the count of ‘x’ and ny be count of ‘y’. let a and b be the count of subsequence ‘xy’ and ‘yx’ respectively, then a = nx*ny and b = 0. Then, from beginning of the string find the ‘x’ which has next ‘y’ to it and swap both until you reach end of the string. In each swap a is decremented by 1 and b is incremented by 1. Repeat this until the count of a subsequence of ‘yx’ is achieved i:e a becomes p and b becomes q.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// CPP program to find lexicographically smallest// string such that count of subsequence 'xy' and// 'yx' is p and q respectively.#include <bits/stdc++.h>using namespace std; // function to check if answer exitsint nx = 0, ny = 0; bool check(string s, int p, int q){ // count total 'x' and 'y' in string for (int i = 0; i < s.length(); ++i) { if (s[i] == 'x') nx++; else ny++; } // condition to check existence of answer if (nx * ny != p + q) return 1; else return 0;} // function to find lexicographically smallest stringstring smallestPermutation(string s, int p, int q){ // check if answer exist or not if (check(s, p, q) == 1) { return "Impossible"; } sort(s.begin(), s.end()); int a = nx * ny, b = 0, i, j; // check if count of 'xy' and 'yx' becomes // equal to p and q respectively. if (a == p && b == q) { return s; } // Repeat until answer is found. while (1) { // Find index of 'x' to swap with 'y'. for (i = 0; i < s.length() - 1; ++i) { if (s[i] == 'x' && s[i + 1] == 'y') break; } for (j = i; j < s.length() - 1; j++) { if (s[j] == 'x' && s[j + 1] == 'y') { swap(s[j], s[j + 1]); a--; // 'xy' decrement by 1 b++; // 'yx' increment by 1 // check if count of 'xy' and 'yx' becomes // equal to p and q respectively. if (a == p && b == q) { return s; } } } }} // Driver codeint main(){ string s = "yxxyx"; int p = 3, q = 3; cout<< smallestPermutation(s, p, q); return 0;}
// Java program to find lexicographically// smallest string such that count of// subsequence 'xy' and 'yx' is p and// q respectively.import java.util.*; class GFG{static int nx = 0, ny = 0; static boolean check(String s, int p, int q){ // count total 'x' and 'y' in string for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) == 'x') nx++; else ny++; } // condition to check // existence of answer if ((nx * ny) != (p + q)) return true; else return false;} public static String smallestPermutation(String s, int p, int q){ if (check(s, p, q) == true) { return "Impossible"; } char tempArray[] = s.toCharArray(); Arrays.sort(tempArray); String str = new String(tempArray); int a = nx * ny, b = 0, i = 0, j = 0; if (a == p && b == q) { return str; } while (1 > 0) { // Find index of 'x' to swap with 'y'. for (i = 0; i < str.length() - 1; ++i) { if (str.charAt(i) == 'x' && str.charAt(i + 1) == 'y') break; } for (j = i; j < str.length() - 1; j++) { if (str.charAt(j) == 'x' && str.charAt(j + 1) == 'y') { StringBuilder sb = new StringBuilder(str); sb.setCharAt(j, str.charAt(j + 1)); sb.setCharAt(j + 1, str.charAt(j)); str = sb.toString(); /* char ch[] = str.toCharArray(); char temp = ch[j+1]; ch[j+1] = ch[j]; ch[j] = temp;*/ a--; // 'xy' decrement by 1 b++; // 'yx' increment by 1 // check if count of 'xy' and // 'yx' becomes equal to p // and q respectively. if (a == p && b == q) { return str; } } }}} // Driver Codepublic static void main (String[] args){ String s = "yxxyx"; int p = 3, q = 3; System.out.print(smallestPermutation(s, p, q));}} // This code is contributed by Kirti_Mangal
# Python3 program to find lexicographically# smallest string such that count of subsequence# 'xy' and 'yx' is p and q respectively. # Function to check if answer exitsdef check(s, p, q): global nx global ny # count total 'x' and 'y' in string for i in range(0, len(s)): if s[i] == 'x': nx += 1 else: ny += 1 # condition to check existence of answer if nx * ny != p + q: return 1 else: return 0 # Function to find lexicographically# smallest stringdef smallestPermutation(s, p, q): # check if answer exist or not if check(s, p, q) == 1: return "Impossible" s = sorted(s) a, b, i = nx * ny, 0, 0 # check if count of 'xy' and 'yx' becomes # equal to p and q respectively. if a == p and b == q: return '' . join(s) # Repeat until answer is found. while True: # Find index of 'x' to swap with 'y'. for i in range(0, len(s) - 1): if s[i] == 'x' and s[i + 1] == 'y': break for j in range(i, len(s) - 1): if s[j] == 'x' and s[j + 1] == 'y': s[j], s[j + 1] = s[j + 1], s[j] a -= 1 # 'xy' decrement by 1 b += 1 # 'yx' increment by 1 # check if count of 'xy' and 'yx' becomes # equal to p and q respectively. if a == p and b == q: return '' . join(s) # Driver codeif __name__ == "__main__": nx, ny = 0, 0 s = "yxxyx" p, q = 3, 3 print(smallestPermutation(s, p, q)) # This code is contributed by Rituraj Jain
// C# program to find lexicographically// smallest string such that count of// subsequence 'xy' and 'yx' is p and// q respectively.using System;using System.Text; class GFG{ static int nx = 0, ny = 0; static Boolean check(String s, int p, int q){ // count total 'x' and 'y' in string for (int i = 0; i < s.Length; ++i) { if (s[i] == 'x') nx++; else ny++; } // condition to check // existence of answer if ((nx * ny) != (p + q)) return true; else return false;} public static String smallestPermutation(String s, int p, int q){ if (check(s, p, q) == true) { return "Impossible"; } char []tempArray = s.ToCharArray(); Array.Sort(tempArray); String str = new String(tempArray); int a = nx * ny, b = 0, i = 0, j = 0; if (a == p && b == q) { return str; } while (1 > 0) { // Find index of 'x' to swap with 'y'. for (i = 0; i < str.Length - 1; ++i) { if (str[i] == 'x' && str[i + 1] == 'y') break; } for (j = i; j < str.Length - 1; j++) { if (str[j] == 'x' && str[j + 1] == 'y') { StringBuilder sb = new StringBuilder(str); sb.Remove(j,1); sb.Insert(j, str[j + 1]); sb.Remove(j+1,1); sb.Insert(j + 1, str[j]); str = sb.ToString(); /* char ch[] = str.toCharArray(); char temp = ch[j+1]; ch[j+1] = ch[j]; ch[j] = temp;*/ a--; // 'xy' decrement by 1 b++; // 'yx' increment by 1 // check if count of 'xy' and // 'yx' becomes equal to p // and q respectively. if (a == p && b == q) { return str; } } }}} // Driver Codepublic static void Main (String[] args){ String s = "yxxyx"; int p = 3, q = 3; Console.WriteLine(smallestPermutation(s, p, q));}} // This code has been contributed by 29AjayKumar
<script>// Javascript program to find lexicographically// smallest string such that count of// subsequence 'xy' and 'yx' is p and// q respectively. let nx = 0, ny = 0;function check(s, p, q){ // count total 'x' and 'y' in string for (let i = 0; i < s.length; ++i) { if (s[i] == 'x') nx++; else ny++; } // condition to check // existence of answer if ((nx * ny) != (p + q)) return true; else return false;} function smallestPermutation(s,p,q){ if (check(s, p, q) == true) { return "Impossible"; } let tempArray = s.split(""); (tempArray).sort(); let str = (tempArray).join(""); let a = nx * ny, b = 0, i = 0, j = 0; if (a == p && b == q) { return str; } while (1 > 0) { // Find index of 'x' to swap with 'y'. for (i = 0; i < str.length - 1; ++i) { if (str[i] == 'x' && str[i+1] == 'y') break; } for (j = i; j < str.length - 1; j++) { if (str[j] == 'x' && str[j+1] == 'y') { let sb = (str).split(""); sb[j] = str[j+1]; sb[j + 1] = str[j]; str = sb.join(""); /* char ch[] = str.toCharArray(); char temp = ch[j+1]; ch[j+1] = ch[j]; ch[j] = temp;*/ a--; // 'xy' decrement by 1 b++; // 'yx' increment by 1 // check if count of 'xy' and // 'yx' becomes equal to p // and q respectively. if (a == p && b == q) { return str; } } }}} // Driver Codelet s = "yxxyx";let p = 3;let q = 3; document.write(smallestPermutation(s, p, q)); // This code is contributed by patel2127</script>
xyxyx
Time Complexity: O(N2)
Kirti_Mangal
rituraj_jain
29AjayKumar
patel2127
clintra
Algorithms
Greedy
Strings
Strings
Greedy
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Dijkstra's shortest path algorithm | Greedy Algo-7
Program for array rotation
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 351,
"s": 54,
"text": "Given a string consisting only of two lowercase characters and and two numbers and . The task is to print the lexicographically smallest permutation of the given string such ... |
Lexicographic rank of a string with duplicate characters | Difficulty Level :
Hard
Given a string s that may have duplicate characters. Find out the lexicographic rank of s. s may consist of lower as well as upper case letters. We consider the lexicographic order of characters as their order of ASCII value. Hence the lexicographical order of characters will be ‘A’, ‘B’, ‘C’, ..., ‘Y’, ‘Z’, ‘a’, ‘b’, ‘c’, ..., ‘y’, ‘z’.
Examples:
Input : “abab” Output : 2Explanation: The lexicographical order is: “aabb”, “abab”, “abba”, “baab”, “baba”, “bbaa”. Hence the rank of “abab” is 2.Input: “settLe” Output : 107
Prerequisite: Lexicographic rank of a string
Method:
The method here is a little different from the without repetition version. Here we have to take care of the duplicate characters also. Let’s look at the string “settLe”. It has repetition(2 ‘e’ and 2 ‘t’) as well as upper case letter(‘L’). Total 6 characters and the total number of permutations are 6!/(2!*2!). Now there are 3 characters(2 ‘e’ and 1 ‘L’) on the right side of ‘s’ which come before ‘s’ lexicographically. If there were no repetition then there would be 3*5! smaller strings which have the first character less than ‘s’. But starting from position 0, till the end there are 2 ‘e’ and 2 ‘t'(i.e. repetitions). Hence, the number of possible smaller permutations with the first letter smaller than ‘s’ are (3*5!)/(2!*2!). Similarly, if we fix ‘s’ and look at the letters from index 1 to end then there is 1 character(‘L’) lexicographically less than ‘e’. And starting from position 1 there are 2 repeated characters(2 ‘e’ and 2 ‘t’). Hence, the number of possible smaller permutations with first letter ‘s’ and second letter smaller than ‘e’ are (1*4!)/(2!*2!).Similarly, we can form the following table:
WorkFlow:
1. Initialize t_count(total count) variable
to 1(as rank starts from 1).
2. Run a loop for every character of the string, string[i]:
(i) using a loop count less_than(number of smaller
characters on the right side of string[i]).
(ii) take one array d_count of size 52 and using a
loop count the frequency of characters starting
from string[i].
(iii) compute the product, d_fac(the product of
factorials of each element of d_count).
(iv) compute (less_than*fac(n-i-1))/(d_fac).
Add it to t_count.
3. return t_count
C++
Java
C#
Javascript
// C++ program to find out lexicographic// rank of a string which may have duplicate// characters and upper case letters.#include <iostream>#include <vector> using namespace std; // Function to calculate factorial of a number.long long fac(long long n){ if (n == 0 or n == 1) return 1; return n * fac(n - 1);} // Function to calculate rank of the string.int lexRank(string s){ long long n = s.size(); // Initialize total count to 1. long long t_count = 1; // loop to calculate number of smaller strings. for (int i = 0; i < n; i++) { // Count smaller characters than s[i]. int less_than = 0; for (int j = i + 1; j < n; j++) { if (int(s[i]) > int(s[j])) { less_than += 1; } } // Count frequency of duplicate characters. vector<int> d_count(52, 0); for (int j = i; j < n; j++) { // Check whether the character is upper // or lower case and then increase the // specific element of the array. if ((int(s[j]) >= 'A') && int(s[j]) <= 'Z') d_count[int(s[j]) - 'A'] += 1; else d_count[int(s[j]) - 'a' + 26] += 1; } // Compute the product of the factorials // of frequency of characters. long long d_fac = 1; for (int ele : d_count) d_fac *= fac(ele); // add the number of smaller string // possible from index i to total count. t_count += (fac(n - i - 1) * less_than) / d_fac; } return (int)t_count;} // Driver Codeint main(){ // Test case 1 string s1 = "abab"; cout << "Rank of " << s1 << " is: " << lexRank(s1) << endl; // Test case 2 string s2 = "settLe"; cout << "Rank of " << s2 << " is: " << lexRank(s2) << endl; return 0;}
// Java program to find out lexicographic// rank of a String which may have duplicate// characters and upper case letters.class GFG { // Function to calculate // factorial of a number. static long fac(long n) { if (n == 0 || n == 1) return 1; return n * fac(n - 1); } // Function to calculate // rank of the String. static int lexRank(String s) { long n = s.length(); // Initialize total count to 1. long t_count = 1; // loop to calculate // number of smaller Strings. for (int i = 0; i < n; i++) { // Count smaller // characters than s[i]. long less_than = 0; for (int j = i + 1; j < n; j++) { if (s.charAt(i) > s.charAt(j)) { less_than += 1; } } // Count frequency of // duplicate characters. long[] d_count = new long[52]; for (int j = i; j < n; j++) { // Check whether the // character is upper // or lower case and // then increase the // specific element of // the array. if ((s.charAt(j) >= 'A') && s.charAt(j) <= 'Z') d_count[s.charAt(j) - 'A'] += 1; else d_count[s.charAt(j) - 'a' + 26] += 1; } // Compute the product of the factorials // of frequency of characters. long d_fac = 1; for (long ele : d_count) d_fac *= fac(ele); // add the number of smaller String // possible from index i to total count. t_count += (fac(n - i - 1) * less_than) / d_fac; } return (int)t_count; } // Driver Code public static void main(String[] args) { // Test case 1 String s1 = "abab"; System.out.print("Rank of " + s1 + " is: " + lexRank(s1) + "\n"); // Test case 2 String s2 = "settLe"; System.out.print("Rank of " + s2 + " is: " + lexRank(s2) + "\n"); }} // This code is contributed by gauravrajput1
// C# program to find out// lexicographic rank of a// String which may have// duplicate characters and// upper case letters.using System;class GFG { // Function to calculate // factorial of a number. static long fac(long n) { if (n == 0 || n == 1) return 1; return n * fac(n - 1); } // Function to calculate // rank of the String. static long lexRank(String s) { long n = s.Length; // Initialize total // count to 1. long t_count = 1; // loop to calculate number // of smaller Strings. for (long i = 0; i < n; i++) { // Count smaller characters // than s[i]. long less_than = 0; for (long j = i + 1; j < n; j++) { if (s[i] > s[j]) { less_than += 1; } } // Count frequency of // duplicate characters. long[] d_count = new long[52]; for (int j = i; j < n; j++) { // Check whether the character // is upper or lower case and // then increase the specific // element of the array. if ((s[j] >= 'A') && s[j] <= 'Z') d_count[s[j] - 'A'] += 1; else d_count[s[j] - 'a' + 26] += 1; } // Compute the product of the // factorials of frequency of // characters. long d_fac = 1; foreach(long ele in d_count) d_fac *= fac(ele); // add the number of smaller // String possible from index // i to total count. t_count += (fac(n - i - 1) * less_than) / d_fac; } return t_count; } // Driver Code public static void Main(String[] args) { // Test case 1 String s1 = "abab"; Console.Write("Rank of " + s1 + " is: " + lexRank(s1) + "\n"); // Test case 2 String s2 = "settLe"; Console.Write("Rank of " + s2 + " is: " + lexRank(s2) + "\n"); }} // This code is contributed by Rajput-Ji
<script>// Javascript program to find out lexicographic// rank of a String which may have duplicate// characters and upper case letters. // Function to calculate // factorial of a number.function fac(n){ if (n == 0 || n == 1) return 1; return n * fac(n - 1);} // Function to calculate // rank of the String.function lexRank(s){ n = s.length; // Initialize total count to 1. let t_count = 1; // loop to calculate // number of smaller Strings. for (let i = 0; i < n; i++) { // Count smaller // characters than s[i]. let less_than = 0; for (let j = i + 1; j < n; j++) { if (s[i] > s[j]) { less_than += 1; } } // Count frequency of // duplicate characters. let d_count = new Array(52); for(let i=0;i<52;i++) d_count[i]=0; for (let j = i; j < n; j++) { // Check whether the // character is upper // or lower case and // then increase the // specific element of // the array. if ((s[j] >= 'A') && s[j] <= 'Z') d_count[s[j].charCodeAt(0) - 'A'.charCodeAt(0)] += 1; else d_count[s[j].charCodeAt(0) - 'a'.charCodeAt(0) + 26] += 1; } // Compute the product of the factorials // of frequency of characters. let d_fac = 1; for (let ele=0;ele< d_count.length;ele++) d_fac *= fac(d_count[ele]); // add the number of smaller String // possible from index i to total count. t_count += (fac(n - i - 1) * less_than) / d_fac; } return t_count;} // Driver Code let s1 = "abab";document.write("Rank of " + s1 + " is: " + lexRank(s1) + "<br>"); // Test case 2let s2 = "settLe";document.write("Rank of " + s2 + " is: " + lexRank(s2) + "<br>"); // This code is contributed by patel2127</script>
Rank of abab is: 2
Rank of settLe is: 107
Time complexity: O(n2)
GauravRajput1
Rajput-Ji
newtocoding
patel2127
vaiibhav
factorial
Strings
Strings
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 24,
"s": 0,
"text": "Difficulty Level :\nHard"
},
{
"code": null,
"e": 364,
"s": 24,
"text": "Given a string s that may have duplicate characters. Find out the lexicographic rank of s. s may consist of lower as well as upper case letters. We consider the lexi... |
Rearrange positive and negative numbers with constant extra space | 15 Jun, 2022
Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array without using any additional data structure like hash table, arrays, etc. The order of appearance should be maintained.
Examples:
Input: [12 11 -13 -5 6 -7 5 -3 -6]
Output: [-13 -5 -7 -3 -6 12 11 6 5]
A simple solution is to use another array. We copy all elements of original array to new array. We then traverse the new array and copy all negative and positive elements back in original array one by one. This approach is discussed here. The problem with this approach is that it uses auxiliary array and we’re not allowed to use any data structure to solve this problem.One approach that does not use any data structure is to use use partition process of QuickSort. The idea is to consider 0 as pivot and divide the array around it. The problem with this approach is that it changes relative order of elements. The similar partition process is discussed here .Let’s now discuss few methods which do not use any other data structure and also preserves relative order of elements.
Approach 1: Modified Partition Process of Quick Sort
We can reverse the order of positive numbers whenever relative order is changed. This will happen if there are more than one positive element between last negative number in left subarray and current negative element.
Below are the steps on how this will happen:
Current Array :- [Ln, P1, P2, P3, N1, .......]
Here, Ln is the left subarray(can be empty) that contains only negative elements. P1, P2, P3 are the positive numbers and N1
is the negative number that we want to move at correct place.
If difference of indices between positive number and negative number is greater than 1,
1. Swap P1 and N1, we get [Ln, N1, P2, P3, P1, ......]
2. Rotate array by one position to right, i.e. rotate array [P2, P3, P1], we get [Ln, N1, P1, P2, P3, ......]
Below is the implementation for the same :-
C++
Java
Python3
C#
Javascript
// C++ program to Rearrange positive and negative// numbers in a array#include <bits/stdc++.h>using namespace std; // A utility function to print an array of size nvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout<<arr[i]<<" ";} void rotateSubArray(int arr[], int l, int r) {int temp = arr[r];for (int j = r; j > l - 1; j--) { arr[j] = arr[j - 1];}arr[l] = temp;} void moveNegative(int arr[], int n){ int last_negative_index = -1; for (int i = 0; i < n; i++) { if (arr[i] < 0) { last_negative_index += 1; int temp = arr[i]; arr[i] = arr[last_negative_index]; arr[last_negative_index] = temp; // Done to manage order too if (i - last_negative_index >= 2) rotateSubArray(arr, last_negative_index + 1, i); }}} // Driver Codeint main(){ int arr[] = { 5, 5, -3, 4, -8, 0, -7, 3, -9, -3, 9, -2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); moveNegative(arr, n); printArray(arr, n); return 0;} // This code is contributed by Aarti_Rathi
// Java program for// moving negative numbers to left// while maintaining the orderclass GFG { static int[] rotateSubArray(int[] arr, int l, int r) { int temp = arr[r]; for (int j = r; j > l - 1; j--) { arr[j] = arr[j - 1]; } arr[l] = temp; return arr; } static int[] moveNegative(int[] arr) { int last_negative_index = -1; for (int i = 0; i < arr.length; i++) { if (arr[i] < 0) { last_negative_index += 1; int temp = arr[i]; arr[i] = arr[last_negative_index]; arr[last_negative_index] = temp; // Done to manage order too if (i - last_negative_index >= 2) rotateSubArray(arr, last_negative_index + 1, i); } } return arr; } // Driver Code public static void main(String args[]) { int[] arr = { 5, 5, -3, 4, -8, 0, -7, 3, -9, -3, 9, -2, 1 }; arr = moveNegative(arr); for (int i : arr) { System.out.print(i + " "); } }}// This code is contributed by Saurabh Jaiswal
# Python 3 program for# moving negative numbers to left# while maintaining the order class Solution: def rotateSubArray(self, arr, l, r): temp = arr[r] for j in range(r, l-1, -1): arr[j] = arr[j-1] arr[l] = temp return arr def moveNegative(self, arr): last_negative_index = -1 for i in range(len(arr)): if arr[i] < 0: last_negative_index += 1 arr[i], arr[last_negative_index] = arr[last_negative_index], arr[i] # Done to manage order too if i - last_negative_index >= 2: self.rotateSubArray(arr, last_negative_index+1, i) return arr # Driver Codeif __name__ == '__main__': arr = [5, 5, -3, 4, -8, 0, -7, 3, -9, -3, 9, -2, 1] ob = Solution() ob.moveNegative(arr) for i in arr: print(i, end=' ') print() # This code is contributed by Kapil Bansal(devkapilbansal)
// C# program for// moving negative numbers to left// while maintaining the orderusing System;class GFG { static int[] rotateSubArray(int[] arr, int l, int r) { int temp = arr[r]; for (int j = r; j > l - 1; j--) { arr[j] = arr[j - 1]; } arr[l] = temp; return arr; } static int[] moveNegative(int[] arr) { int last_negative_index = -1; for (int i = 0; i < arr.Length; i++) { if (arr[i] < 0) { last_negative_index += 1; int temp = arr[i]; arr[i] = arr[last_negative_index]; arr[last_negative_index] = temp; // Done to manage order too if (i - last_negative_index >= 2) rotateSubArray(arr, last_negative_index + 1, i); } } return arr; } // Driver Code public static void Main() { int[] arr = { 5, 5, -3, 4, -8, 0, -7, 3, -9, -3, 9, -2, 1 }; arr = moveNegative(arr); foreach (int i in arr) { Console.Write(i + " "); } }} // This code is contributed by gfgking.
<script> // Python 3 program for// moving negative numbers to left// while maintaining the order class Solution{ rotateSubArray(arr, l, r){ let temp = arr[r] for(let j = r;j > l-1;j--){ arr[j] = arr[j-1] } arr[l] = temp return arr } moveNegative(arr){ let last_negative_index = -1 for(let i=0;i<arr.length;i++){ if(arr[i] < 0){ last_negative_index += 1 let temp = arr[i]; arr[i] = arr[last_negative_index]; arr[last_negative_index] = temp; // Done to manage order too if(i - last_negative_index >= 2) this.rotateSubArray(arr, last_negative_index+1, i) } } return arr }} // Driver Code let arr = [5, 5, -3, 4, -8, 0, -7, 3, -9, -3, 9, -2, 1]let ob = new Solution()ob.moveNegative(arr)for(let i of arr){ document.write(i,' ')} // This code is contributed by shinjanpatra </script>
-3 -8 -7 -9 -3 -2 5 5 4 0 3 9 1
Approach 2: Modified Insertion SortWe can modify insertion sort to solve this problem.Algorithm –
Loop from i = 1 to n - 1.
a) If the current element is positive, do nothing.
b) If the current element arr[i] is negative, we
insert it into sequence arr[0..i-1] such that
all positive elements in arr[0..i-1] are shifted
one position to their right and arr[i] is inserted
at index of first positive element.
Below is the implementation –
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to Rearrange positive and negative// numbers in a array#include <stdio.h> // A utility function to print an array of size nvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n");} // Function to Rearrange positive and negative// numbers in a arrayvoid RearrangePosNeg(int arr[], int n){ int key, j; for (int i = 1; i < n; i++) { key = arr[i]; // if current element is positive // do nothing if (key > 0) continue; /* if current element is negative, shift positive elements of arr[0..i-1], to one position to their right */ j = i - 1; while (j >= 0 && arr[j] > 0) { arr[j + 1] = arr[j]; j = j - 1; } // Put negative element at its right position arr[j + 1] = key; }} /* Driver program to test above functions */int main(){ int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int n = sizeof(arr) / sizeof(arr[0]); RearrangePosNeg(arr, n); printArray(arr, n); return 0;}
// Java program to Rearrange positive// and negative numbers in a arrayimport java.io.*; class GFG { // A utility function to print // an array of size n static void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); System.out.println(); } // Function to Rearrange positive and negative // numbers in a array static void RearrangePosNeg(int arr[], int n) { int key, j; for (int i = 1; i < n; i++) { key = arr[i]; // if current element is positive // do nothing if (key > 0) continue; /* if current element is negative, shift positive elements of arr[0..i-1], to one position to their right */ j = i - 1; while (j >= 0 && arr[j] > 0) { arr[j + 1] = arr[j]; j = j - 1; } // Put negative element at its right position arr[j + 1] = key; } } // Driver program public static void main(String[] args) { int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int n = arr.length; RearrangePosNeg(arr, n); printArray(arr, n); }} // This code is contributed by vt_m.
# Python 3 program to Rearrange positive# and negative numbers in a array # A utility function to print# an array of size n def printArray(arr, n): for i in range(n): print(arr[i], end=" ") print() # Function to Rearrange positive# and negative numbers in a array def RearrangePosNeg(arr, n): for i in range(1, n): key = arr[i] # if current element is positive # do nothing if (key > 0): continue ''' if current element is negative, shift positive elements of arr[0..i-1], to one position to their right ''' j = i - 1 while (j >= 0 and arr[j] > 0): arr[j + 1] = arr[j] j = j - 1 # Put negative element at its # right position arr[j + 1] = key # Driver Codeif __name__ == "__main__": arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6] n = len(arr) RearrangePosNeg(arr, n) printArray(arr, n) # This code is contributed# by ChitraNayal
// C# program to Rearrange positive// and negative numbers in a arrayusing System; class GFG { // A utility function to print // an array of size n static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); Console.WriteLine(); } // Function to Rearrange positive and negative // numbers in a array static void RearrangePosNeg(int[] arr, int n) { int key, j; for (int i = 1; i < n; i++) { key = arr[i]; // if current element is positive // do nothing if (key > 0) continue; /* if current element is negative, shift positive elements of arr[0..i-1], to one position to their right */ j = i - 1; while (j >= 0 && arr[j] > 0) { arr[j + 1] = arr[j]; j = j - 1; } // Put negative element at its right position arr[j + 1] = key; } } // Driver program public static void Main() { int[] arr = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int n = arr.Length; RearrangePosNeg(arr, n); printArray(arr, n); }} // This code is contributed by vt_m.
<?php// PHP program to Rearrange positive// and negative numbers in a array// A utility function to print// an array of size nfunction printArray($arr, $n){ for ($i = 0; $i < $n; $i++) echo($arr[$i] . " ");} // Function to Rearrange positive and negative// numbers in a arrayfunction RearrangePosNeg(&$arr, $n){ $key; $j; for($i = 1; $i < $n; $i++) { $key = $arr[$i]; // if current element is positive // do nothing if ($key > 0) continue; /* if current element is negative, shift positive elements of arr[0..i-1], to one position to their right */ $j = $i - 1; while ($j >= 0 && $arr[$j] > 0) { $arr[$j + 1] = $arr[$j]; $j = $j - 1; } // Put negative element at its right position $arr[$j + 1] = $key; }} // Driver program{ $arr = array( -12, 11, -13, -5, 6, -7, 5, -3, -6 ); $n = sizeof($arr); RearrangePosNeg($arr, $n); printArray($arr, $n); } // This code is contributed by Code_Mech.
<script> // Javascript program to Rearrange positive// and negative numbers in a array // A utility function to print // an array of size n function printArray(arr, n) { for (let i = 0; i < n; i++) document.write(arr[i] + " "); document.write("<br />"); } // Function to Rearrange positive and negative // numbers in a array function RearrangePosNeg(arr, n) { let key, j; for (let i = 1; i < n; i++) { key = arr[i]; // if current element is positive // do nothing if (key > 0) continue; /* if current element is negative, shift positive elements of arr[0..i-1], to one position to their right */ j = i - 1; while (j >= 0 && arr[j] > 0) { arr[j + 1] = arr[j]; j = j - 1; } // Put negative element at its right position arr[j + 1] = key; } } // Driver Code let arr = [ -12, 11, -13, -5, 6, -7, 5, -3, -6 ]; let n = arr.length; RearrangePosNeg(arr, n); printArray(arr, n); </script>
-12 -13 -5 -7 -3 -6 11 6 5
Time Complexity: O(n2)
Auxiliary Space: O(1)
We have maintained the order of appearance and have not used any other data structure.
Approach 2: Optimized Merge Sort Merge method of standard merge sort algorithm can be modified to solve this problem. While merging two sorted halves say left and right, we need to merge in such a way that negative part of left and right sub-array is copied first followed by positive part of left and right sub-array.
Below is the implementation of the idea –
C++
Java
Python3
C#
Javascript
// C++ program to Rearrange positive and negative// numbers in a array#include <iostream>using namespace std; /* Function to print an array */void printArray(int A[], int size){ for (int i = 0; i < size; i++) cout << A[i] << " "; cout << endl;} // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]void merge(int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray // Note the order of appearance of elements should // be maintained - we copy elements of left subarray // first followed by that of right subarray // copy negative elements of left subarray while (i < n1 && L[i] < 0) arr[k++] = L[i++]; // copy negative elements of right subarray while (j < n2 && R[j] < 0) arr[k++] = R[j++]; // copy positive elements of left subarray while (i < n1) arr[k++] = L[i++]; // copy positive elements of right subarray while (j < n2) arr[k++] = R[j++];} // Function to Rearrange positive and negative// numbers in a arrayvoid RearrangePosNeg(int arr[], int l, int r){ if (l < r) { // Same as (l + r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves RearrangePosNeg(arr, l, m); RearrangePosNeg(arr, m + 1, r); merge(arr, l, m, r); }} /* Driver program to test above functions */int main(){ int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int arr_size = sizeof(arr) / sizeof(arr[0]); RearrangePosNeg(arr, 0, arr_size - 1); printArray(arr, arr_size); return 0;}
// Java program to Rearrange positive// and negative numbers in a arrayimport java.io.*; class GFG { /* Function to print an array */ static void printArray(int A[], int size) { for (int i = 0; i < size; i++) System.out.print(A[i] + " "); System.out.println(); } // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] static void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ // Initial index of first subarray i = 0; // Initial index of second subarray j = 0; // Initial index of merged subarray k = l; // Note the order of appearance of elements should // be maintained - we copy elements of left subarray // first followed by that of right subarray // copy negative elements of left subarray while (i < n1 && L[i] < 0) arr[k++] = L[i++]; // copy negative elements of right subarray while (j < n2 && R[j] < 0) arr[k++] = R[j++]; // copy positive elements of left subarray while (i < n1) arr[k++] = L[i++]; // copy positive elements of right subarray while (j < n2) arr[k++] = R[j++]; } // Function to Rearrange positive and negative // numbers in a array static void RearrangePosNeg(int arr[], int l, int r) { if (l < r) { // Same as (l + r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves RearrangePosNeg(arr, l, m); RearrangePosNeg(arr, m + 1, r); merge(arr, l, m, r); } } // Driver program public static void main(String[] args) { int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int arr_size = arr.length; RearrangePosNeg(arr, 0, arr_size - 1); printArray(arr, arr_size); }} // This code is contributed by vt_m.
# Python3 program to Rearrange positive# and negative numbers in a array # Function to print an array def printArray(A, size): for i in range(size): print(A[i], end=" ") print() # Merges two subarrays of arr[].# First subarray is arr[l..m]# Second subarray is arr[m + 1..r] def merge(arr, l, m, r): i, j, k = 0, 0, 0 n1 = m - l + 1 n2 = r - m # create temp arrays */ L = [arr[l + i] for i in range(n1)] R = [arr[m + 1 + j] for j in range(n2)] # Merge the temp arrays back into arr[l..r]*/ i = 0 # Initial index of first subarray j = 0 # Initial index of second subarray k = l # Initial index of merged subarray # Note the order of appearance of elements # should be maintained - we copy elements # of left subarray first followed by that # of right subarray # copy negative elements of left subarray while (i < n1 and L[i] < 0): arr[k] = L[i] k += 1 i += 1 # copy negative elements of right subarray while (j < n2 and R[j] < 0): arr[k] = R[j] k += 1 j += 1 # copy positive elements of left subarray while (i < n1): arr[k] = L[i] k += 1 i += 1 # copy positive elements of right subarray while (j < n2): arr[k] = R[j] k += 1 j += 1 # Function to Rearrange positive and# negative numbers in a array def RearrangePosNeg(arr, l, r): if(l < r): # Same as (l + r)/2, but avoids # overflow for large l and h m = l + (r - l) // 2 # Sort first and second halves RearrangePosNeg(arr, l, m) RearrangePosNeg(arr, m + 1, r) merge(arr, l, m, r) # Driver Codearr = [-12, 11, -13, -5, 6, -7, 5, -3, -6]arr_size = len(arr) RearrangePosNeg(arr, 0, arr_size - 1) printArray(arr, arr_size) # This code is contributed by# mohit kumar 29
// C# program to Rearrange positive// and negative numbers in a arrayusing System; class GFG { /* Function to print an array */ static void printArray(int[] A, int size) { for (int i = 0; i < size; i++) Console.Write(A[i] + " "); Console.WriteLine(); } // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] static void merge(int[] arr, int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int[] L = new int[n1]; int[] R = new int[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ // Initial index of first subarray i = 0; // Initial index of second subarray j = 0; // Initial index of merged subarray k = l; // Note the order of appearance of elements should // be maintained - we copy elements of left subarray // first followed by that of right subarray // copy negative elements of left subarray while (i < n1 && L[i] < 0) arr[k++] = L[i++]; // copy negative elements of right subarray while (j < n2 && R[j] < 0) arr[k++] = R[j++]; // copy positive elements of left subarray while (i < n1) arr[k++] = L[i++]; // copy positive elements of right subarray while (j < n2) arr[k++] = R[j++]; } // Function to Rearrange positive and negative // numbers in a array static void RearrangePosNeg(int[] arr, int l, int r) { if (l < r) { // Same as (l + r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves RearrangePosNeg(arr, l, m); RearrangePosNeg(arr, m + 1, r); merge(arr, l, m, r); } } // Driver program public static void Main() { int[] arr = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int arr_size = arr.Length; RearrangePosNeg(arr, 0, arr_size - 1); printArray(arr, arr_size); }} // This code is contributed by vt_m.
<script> // javascript program to Rearrange positive and negative// numbers in a array /* Function to print an array */ function printArray(A , size) { for (i = 0; i < size; i++) document.write(A[i] + " "); document.write('<br>'); ; } /* Function to reverse an array. An array can bereversed in O(n) time and O(1) space. */ function reverse(arr , l , r) { if (l < r) { arr = swap(arr, l, r); reverse(arr, ++l, --r); } } // Merges two subarrays of arr. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] function merge(arr , l , m , r) { // Initial index of 1st subarray var i = l; // Initial index of IInd var j = m + 1; while (i <= m && arr[i] < 0) i++; // arr[i..m] is positive while (j <= r && arr[j] < 0) j++; // arr[j..r] is positive // reverse positive part of // left sub-array (arr[i..m]) reverse(arr, i, m); // reverse negative part of // right sub-array (arr[m+1..j-1]) reverse(arr, m + 1, j - 1); // reverse arr[i..j-1] reverse(arr, i, j - 1); } // Function to Rearrange positive and negative // numbers in a array function RearrangePosNeg(arr , l , r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h var m = l + parseInt((r - l) / 2); // Sort first and second halves RearrangePosNeg(arr, l, m); RearrangePosNeg(arr, m + 1, r); merge(arr, l, m, r); } } function swap(arr , i , j) { var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } /* Driver code*/ var arr = [ -12, 11, -13, -5, 6, -7, 5, -3, -6 ]; var arr_size = arr.length; RearrangePosNeg(arr, 0, arr_size - 1); printArray(arr, arr_size); // This code contributed by shikhasingrajput </script>
-12 -13 -5 -7 -3 -6 11 6 5
Time complexity: O(n log n).
Auxiliary Space: O(n1 + n2 + log n), log n, as implicit stack is used due to recursive call
The problem with this approach is we are using auxiliary array for merging but we’re not allowed to use any data structure to solve this problem. We can do merging in-place without using any data-structure. The idea is taken from here.Let Ln and Lp denotes the negative part and positive part of left sub-array respectively. Similarly, Rn and Rp denote the negative and positive part of right sub-array respectively.
Below are the steps to convert [Ln Lp Rn Rp] to [Ln Rn Lp Rp] without using extra space.
1. Reverse Lp and Rn. We get [Lp] -> [Lp'] and [Rn] -> [Rn']
[Ln Lp Rn Rp] -> [Ln Lp’ Rn’ Rp]
2. Reverse [Lp’ Rn’]. We get [Rn Lp].
[Ln Lp’ Rn’ Rp] -> [Ln Rn Lp Rp]
Below is the implementation of above idea –
C++
Java
Python3
C#
Javascript
// C++ program to Rearrange positive and negative// numbers in a array#include <bits/stdc++.h>using namespace std; /* Function to print an array */void printArray(int A[], int size){ for (int i = 0; i < size; i++) cout << A[i] << " "; cout << endl;} /* Function to reverse an array. An array can bereversed in O(n) time and O(1) space. */void reverse(int arr[], int l, int r){ if (l < r) { swap(arr[l], arr[r]); reverse(arr, ++l, --r); }} // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]void merge(int arr[], int l, int m, int r){ int i = l; // Initial index of 1st subarray int j = m + 1; // Initial index of IInd while (i <= m && arr[i] < 0) i++; // arr[i..m] is positive while (j <= r && arr[j] < 0) j++; // arr[j..r] is positive // reverse positive part of // left sub-array (arr[i..m]) reverse(arr, i, m); // reverse negative part of // right sub-array (arr[m+1..j-1]) reverse(arr, m + 1, j - 1); // reverse arr[i..j-1] reverse(arr, i, j - 1);} // Function to Rearrange positive and negative// numbers in a arrayvoid RearrangePosNeg(int arr[], int l, int r){ if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves RearrangePosNeg(arr, l, m); RearrangePosNeg(arr, m + 1, r); merge(arr, l, m, r); }} /* Driver code */int main(){ int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int arr_size = sizeof(arr) / sizeof(arr[0]); RearrangePosNeg(arr, 0, arr_size - 1); printArray(arr, arr_size); return 0;}
// Java program to Rearrange positive and negative// numbers in a arrayclass GFG { /* Function to print an array */ static void printArray(int A[], int size) { for (int i = 0; i < size; i++) System.out.print(A[i] + " "); System.out.println(""); ; } /* Function to reverse an array. An array can bereversed in O(n) time and O(1) space. */ static void reverse(int arr[], int l, int r) { if (l < r) { arr = swap(arr, l, r); reverse(arr, ++l, --r); } } // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] static void merge(int arr[], int l, int m, int r) { int i = l; // Initial index of 1st subarray int j = m + 1; // Initial index of IInd while (i <= m && arr[i] < 0) i++; // arr[i..m] is positive while (j <= r && arr[j] < 0) j++; // arr[j..r] is positive // reverse positive part of // left sub-array (arr[i..m]) reverse(arr, i, m); // reverse negative part of // right sub-array (arr[m+1..j-1]) reverse(arr, m + 1, j - 1); // reverse arr[i..j-1] reverse(arr, i, j - 1); } // Function to Rearrange positive and negative // numbers in a array static void RearrangePosNeg(int arr[], int l, int r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves RearrangePosNeg(arr, l, m); RearrangePosNeg(arr, m + 1, r); merge(arr, l, m, r); } } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } /* Driver code*/ public static void main(String[] args) { int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int arr_size = arr.length; RearrangePosNeg(arr, 0, arr_size - 1); printArray(arr, arr_size); }} // This code has been contributed by 29AjayKumar
# Python3 program to Rearrange positive# and negative numbers in an array # Function to print an array def printArray(A, size): for i in range(0, size): print(A[i], end=" ") print() # Function to reverse an array. An array can# be reversed in O(n) time and O(1) space. def reverse(arr, l, r): if l < r: arr[l], arr[r] = arr[r], arr[l] l, r = l + 1, r - 1 reverse(arr, l, r) # Merges two subarrays of arr[].# First subarray is arr[l..m]# Second subarray is arr[m + 1..r] def merge(arr, l, m, r): i = l # Initial index of 1st subarray j = m + 1 # Initial index of IInd while i <= m and arr[i] < 0: i += 1 # arr[i..m] is positive while j <= r and arr[j] < 0: j += 1 # arr[j..r] is positive # reverse positive part of left # sub-array (arr[i..m]) reverse(arr, i, m) # reverse negative part of right # sub-array (arr[m + 1..j-1]) reverse(arr, m + 1, j - 1) # reverse arr[i..j-1] reverse(arr, i, j - 1) # Function to Rearrange positive# and negative numbers in a array def RearrangePosNeg(arr, l, r): if l < r: # Same as (l + r)/2, but avoids # overflow for large l and h m = l + (r - l) // 2 # Sort first and second halves RearrangePosNeg(arr, l, m) RearrangePosNeg(arr, m + 1, r) merge(arr, l, m, r) # Driver Codeif __name__ == "__main__": arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6] arr_size = len(arr) RearrangePosNeg(arr, 0, arr_size - 1) printArray(arr, arr_size) # This code is contributed by Rituraj Jain
// C# program to Rearrange positive and negative// numbers in a arrayusing System; class GFG { /* Function to print an array */ static void printArray(int[] A, int size) { for (int i = 0; i < size; i++) Console.Write(A[i] + " "); Console.WriteLine(""); ; } /* Function to reverse an array. An array can bereversed in O(n) time and O(1) space. */ static void reverse(int[] arr, int l, int r) { if (l < r) { arr = swap(arr, l, r); reverse(arr, ++l, --r); } } // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] static void merge(int[] arr, int l, int m, int r) { int i = l; // Initial index of 1st subarray int j = m + 1; // Initial index of IInd while (i <= m && arr[i] < 0) i++; // arr[i..m] is positive while (j <= r && arr[j] < 0) j++; // arr[j..r] is positive // reverse positive part of // left sub-array (arr[i..m]) reverse(arr, i, m); // reverse negative part of // right sub-array (arr[m+1..j-1]) reverse(arr, m + 1, j - 1); // reverse arr[i..j-1] reverse(arr, i, j - 1); } // Function to Rearrange positive and negative // numbers in a array static void RearrangePosNeg(int[] arr, int l, int r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves RearrangePosNeg(arr, l, m); RearrangePosNeg(arr, m + 1, r); merge(arr, l, m, r); } } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } /* Driver code*/ public static void Main() { int[] arr = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int arr_size = arr.Length; RearrangePosNeg(arr, 0, arr_size - 1); printArray(arr, arr_size); }} /* This code contributed by PrinciRaj1992 */
<script>// Javascript program to Rearrange positive and negative// numbers in a array /* Function to print an array */ function printArray(A,size) { for (let i = 0; i < size; i++) document.write(A[i] + " "); document.write("<br>"); } /* Function to reverse an array. An array can bereversed in O(n) time and O(1) space. */ function reverse(arr,l,r) { if (l < r) { arr = swap(arr, l, r); reverse(arr, ++l, --r); } } // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] function merge(arr,l,m,r) { let i = l; // Initial index of 1st subarray let j = m + 1; // Initial index of IInd while (i <= m && arr[i] < 0) i++; // arr[i..m] is positive while (j <= r && arr[j] < 0) j++; // arr[j..r] is positive // reverse positive part of // left sub-array (arr[i..m]) reverse(arr, i, m); // reverse negative part of // right sub-array (arr[m+1..j-1]) reverse(arr, m + 1, j - 1); // reverse arr[i..j-1] reverse(arr, i, j - 1); } // Function to Rearrange positive and negative // numbers in a array function RearrangePosNeg(arr,l,r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h let m = l + Math.floor((r - l) / 2); // Sort first and second halves RearrangePosNeg(arr, l, m); RearrangePosNeg(arr, m + 1, r); merge(arr, l, m, r); } } function swap(arr,i,j) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } /* Driver code*/ let arr=[-12, 11, -13, -5, 6, -7, 5, -3, -6 ]; let arr_size = arr.length; RearrangePosNeg(arr, 0, arr_size - 1); printArray(arr, arr_size); // This code is contributed by unknown2108 </script>
-12 -13 -5 -7 -3 -6 11 6 5
Time complexity of above solution is O(n log n), O(Log n) space for recursive calls, and no additional data structure.
Auxiliary Space: O(log n), as implicit stack is used due to recursive call
Approach 4: Using stable_partition
C++
#include <bits/stdc++.h>using namespace std;void Rearrange(int arr[], int n){ stable_partition(arr,arr+n,[](int x){return x<0;});} int main(){ int n=4; int arr[n]={-3, 3, -2, 2}; Rearrange( arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl; }
-3 -2 3 2
Time Complexity: O(n2)
Auxiliary Space: O(n)
This article is contributed by Aditya Goel. 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.
ukasp
mohit kumar 29
29AjayKumar
princiraj1992
rituraj_jain
Code_Mech
jelodar
lostboy24
le0
RohitOberoi
avanitrachhadiya2155
rag2127
splevel62
amit143katiyar
shikhasingrajput
unknown2108
sachinjain74754
devkapilbansal
simmytarika5
shinjanpatra
_saurabh_jaiswal
_shinchancode
gfgking
surbhikumaridav
array-rearrange
Insertion Sort
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm
HeapSort
std::sort() in C++ STL
Time Complexities of all Sorting Algorithms
Merge two sorted arrays | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 321,
"s": 54,
"text": "Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array without using any additiona... |
Sum of XOR of all subarrays | 23 Jun, 2022
Given an array containing N positive integers, the task is to find the sum of XOR of all sub-arrays of the array.Examples:
Input : arr[] = {1, 3, 7, 9, 8, 7}
Output : 128
Input : arr[] = {3, 8, 13}
Output : 46
Explanation for second test-case:
XOR of {3} = 3
XOR of {3, 8} = 11
XOR of {3, 8, 13} = 6
XOR of {8} = 8
XOR of {8, 13} = 5
XOR of {13} = 13
Sum = 3 + 11 + 6 + 8 + 5 + 13 = 46
Simple solution: A simple solution will be to generate all the sub-arrays and then iterate through them all to find the required XOR values and then sum them up. The time complexity of this approach will be O(n3).Better solution: A better solution will be using a prefix array i.e. for every index ‘i’ of the array ‘arr[]’, create a prefix array to store the XOR of all the elements from the left end of the array ‘arr[]’ up to the ith element of ‘arr[]’. Creating a prefix array will take a time of O(N). Now, using this prefix array, we can find the XOR value of any sub-array in O(1) time.We can find the XOR from index l to r using the formula:
if l is not zero
XOR = prefix[r] ^ prefix[l-1]
else
XOR = prefix[r].
After this, all we have to do is, to sum up, the XOR values of all the sub-arrays.Since a total number of sub-arrays is of the order (N2), the time complexity of this approach will be O(N2). Best solution: For the sake of better understanding, let’s assume any bit of an element is represented by the variable ‘i’ and the variable ‘sum’ is used to store the final sum.The idea here is, we will try to find the number of XOR values with ith bit set. Let us suppose, there is ‘Si‘ number of sub-arrays with ith bit set. For, ith bit, the sum can be updated as sum += (2i * S) .So, the question is how to implement the above idea?We will break the task to multiple steps. At each step, we will try to find the number of XOR values with ith bit set. Now, we will break each step to sub-steps. In each sub-step, we will try to find the number of sub-arrays starting from an index ‘j'(where j varies between 0 to n – 1) with ith bit set in their XOR value. For, ith bit is to be set, an odd number of elements of the sub-array should have there ith bit set. For all the bits, in a variable c_odd, we will store the count of the number of sub-arrays starting from j = 0 with ith bit set in an odd number of elements. Then, we will iterate through all the elements of the array updating the value of c_odd when needed. If we reach an element ‘j’ with ith bit set, we will update c_odd as c_odd = (n – j – c_odd). Its because, since we encountered a set bit, the number of sub-arrays with an even the number of elements with ith bit set will switch to a number of sub-arrays with an odd number of elements with ith bit set.Below is the implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the sum of XOR of// all subarray of the array #include <iostream>#include <vector>using namespace std; // Function to calculate the sum of XOR// of all subarraysint findXorSum(int arr[], int n){ // variable to store // the final sum int sum = 0; // multiplier int mul = 1; for (int i = 0; i < 30; i++) { // variable to store number of // sub-arrays with odd number of elements // with ith bits starting from the first // element to the end of the array int c_odd = 0; // variable to check the status // of the odd-even count while // calculating c_odd bool odd = 0; // loop to calculate initial // value of c_odd for (int j = 0; j < n; j++) { if ((arr[j] & (1 << i)) > 0) odd = (!odd); if (odd) c_odd++; } // loop to iterate through // all the elements of the // array and update sum for (int j = 0; j < n; j++) { sum += (mul * c_odd); if ((arr[j] & (1 << i)) > 0) c_odd = (n - j - c_odd); } // updating the multiplier mul *= 2; } // returning the sum return sum;} // Driver Codeint main(){ int arr[] = { 3, 8, 13 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findXorSum(arr, n); return 0;}
// Java program to find the sum of XOR// of all subarray of the arrayimport java.util.*; class GFG{ // Function to calculate the sum of XOR // of all subarrays static int findXorSum(int arr[], int n) { // variable to store // the final sum int sum = 0; // multiplier int mul = 1; for (int i = 0; i < 30; i++) { // variable to store number of // sub-arrays with odd number of elements // with ith bits starting from the first // element to the end of the array int c_odd = 0; // variable to check the status // of the odd-even count while // calculating c_odd boolean odd = false; // loop to calculate initial // value of c_odd for (int j = 0; j < n; j++) { if ((arr[j] & (1 << i)) > 0) odd = (!odd); if (odd) c_odd++; } // loop to iterate through // all the elements of the // array and update sum for (int j = 0; j < n; j++) { sum += (mul * c_odd); if ((arr[j] & (1 << i)) > 0) c_odd = (n - j - c_odd); } // updating the multiplier mul *= 2; } // returning the sum return sum; } // Driver code public static void main(String[] args) { int arr[] = { 3, 8, 13 }; int n = arr.length; System.out.println(findXorSum(arr, n)); }} // This code is contributed by Rituraj Jain.
# Python3 program to find the Sum of# XOR of all subarray of the array # Function to calculate the Sum of XOR# of all subarraysdef findXorSum(arr, n): # variable to store the final Sum Sum = 0 # multiplier mul = 1 for i in range(30): # variable to store number of sub-arrays # with odd number of elements with ith # bits starting from the first element # to the end of the array c_odd = 0 # variable to check the status of the # odd-even count while calculating c_odd odd = 0 # loop to calculate initial # value of c_odd for j in range(n): if ((arr[j] & (1 << i)) > 0): odd = (~odd) if (odd): c_odd += 1 # loop to iterate through all the # elements of the array and update Sum for j in range(n): Sum += (mul * c_odd) if ((arr[j] & (1 << i)) > 0): c_odd = (n - j - c_odd) # updating the multiplier mul *= 2 # returning the Sum return Sum # Driver Codearr = [3, 8, 13] n = len(arr) print(findXorSum(arr, n)) # This code is contributed by Mohit Kumar
// C# program to find the sum of XOR of// all subarray of the arrayusing System; class GFG{ // Function to calculate the sum// of XOR of all subarraysstatic int findXorSum(int []arr, int n){ // variable to store // the final sum int sum = 0; // multiplier int mul = 1; for (int i = 0; i < 30; i++) { // variable to store number of sub-arrays // with odd number of elements with ith // bits starting from the first element // to the end of the array int c_odd = 0; // variable to check the status // of the odd-even count while // calculating c_odd bool odd = false; // loop to calculate initial // value of c_odd for (int j = 0; j < n; j++) { if ((arr[j] & (1 << i)) > 0) odd = (!odd); if (odd) c_odd++; } // loop to iterate through // all the elements of the // array and update sum for (int j = 0; j < n; j++) { sum += (mul * c_odd); if ((arr[j] & (1 << i)) > 0) c_odd = (n - j - c_odd); } // updating the multiplier mul *= 2; } // returning the sum return sum;} // Driver Codestatic void Main(){ int []arr = { 3, 8, 13 }; int n = arr.Length; Console.WriteLine(findXorSum(arr, n));}} // This code is contributed by mits
<?php// PHP program to find the sum of XOR// of all subarray of the array // Function to calculate the sum of// XOR of all subarraysfunction findXorSum($arr, $n){ // variable to store // the final sum $sum = 0; // multiplier $mul = 1; for ($i = 0; $i < 30; $i++) { // variable to store number of // sub-arrays with odd number of // elements with ith bits starting // from the first element to the // end of the array $c_odd = 0; // variable to check the status // of the odd-even count while // calculating c_odd $odd = 0; // loop to calculate initial // value of c_odd for ($j = 0; $j < $n; $j++) { if (($arr[$j] & (1 << $i)) > 0) $odd = (!$odd); if ($odd) $c_odd++; } // loop to iterate through // all the elements of the // array and update sum for ($j = 0; $j < $n; $j++) { $sum += ($mul * $c_odd); if (($arr[$j] & (1 << $i)) > 0) $c_odd = ($n - $j - $c_odd); } // updating the multiplier $mul *= 2; } // returning the sum return $sum;} // Driver Code$arr = array(3, 8, 13); $n = sizeof($arr); echo findXorSum($arr, $n); // This code is contributed by Ryuga?>
<script> // Javascript program to find// the sum of XOR of// all subarray of the array // Function to calculate the sum of XOR// of all subarraysfunction findXorSum(arr, n){ // variable to store // the final sum let sum = 0; // multiplier let mul = 1; for (let i = 0; i < 30; i++) { // variable to store number of // sub-arrays with odd number of elements // with ith bits starting from the first // element to the end of the array let c_odd = 0; // variable to check the status // of the odd-even count while // calculating c_odd let odd = 0; // loop to calculate initial // value of c_odd for (let j = 0; j < n; j++) { if ((arr[j] & (1 << i)) > 0) odd = (!odd); if (odd) c_odd++; } // loop to iterate through // all the elements of the // array and update sum for (let j = 0; j < n; j++) { sum += (mul * c_odd); if ((arr[j] & (1 << i)) > 0) c_odd = (n - j - c_odd); } // updating the multiplier mul *= 2; } // returning the sum return sum;} // Driver Code let arr = [ 3, 8, 13 ]; let n = arr.length; document.write(findXorSum(arr, n)); </script>
46
Time Complexity: O(N)
Auxiliary Space: O(1)
mohit kumar 29
ankthon
Mithun Kumar
rituraj_jain
subham348
subhamkumarm348
Bitwise-XOR
Arrays
Bit Magic
Competitive Programming
Dynamic Programming
Mathematical
Arrays
Dynamic Programming
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Chocolate Distribution Problem
Find duplicates in O(n) time and O(1) extra space | Set 1
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
How to swap two numbers without using a temporary variable? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 177,
"s": 52,
"text": "Given an array containing N positive integers, the task is to find the sum of XOR of all sub-arrays of the array.Examples: "
},
{
"code": null,
"e": 443,
"s"... |
Python os.access() Method | Python method access() uses the real uid/gid to test for access to path. Most operations will use the effective uid/gid, therefore this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to path.It returns True if access is allowed, False if not.
Following is the syntax for access() method −
os.access(path, mode);
path − This is the path which would be tested for existence or any access.
path − This is the path which would be tested for existence or any access.
mode − This should be F_OK to test the existence of path, or it can be the inclusive OR of one or more of R_OK, W_OK, and X_OK to test permissions.
os.F_OK − Value to pass as the mode parameter of access() to test the existence of path.
os.R_OK − Value to include in the mode parameter of access() to test the readability of path.
os.W_OK Value to include in the mode parameter of access() to test the writability of path.
os.X_OK Value to include in the mode parameter of access() to determine if path can be executed.
mode − This should be F_OK to test the existence of path, or it can be the inclusive OR of one or more of R_OK, W_OK, and X_OK to test permissions.
os.F_OK − Value to pass as the mode parameter of access() to test the existence of path.
os.R_OK − Value to include in the mode parameter of access() to test the readability of path.
os.W_OK Value to include in the mode parameter of access() to test the writability of path.
os.X_OK Value to include in the mode parameter of access() to determine if path can be executed.
This method returns True if access is allowed, False if not.
The following example shows the usage of access() method.
#!/usr/bin/python
import os, sys
# Assuming /tmp/foo.txt exists and has read/write permissions.
ret = os.access("/tmp/foo.txt", os.F_OK)
print "F_OK - return value %s"% ret
ret = os.access("/tmp/foo.txt", os.R_OK)
print "R_OK - return value %s"% ret
ret = os.access("/tmp/foo.txt", os.W_OK)
print "W_OK - return value %s"% ret
ret = os.access("/tmp/foo.txt", os.X_OK)
print "X_OK - return value %s"% ret
When we run above program, it produces following result −
F_OK - return value True
R_OK - return value True
W_OK - return value True
X_OK - return value False
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": 2541,
"s": 2244,
"text": "Python method access() uses the real uid/gid to test for access to path. Most operations will use the effective uid/gid, therefore this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to path.It retur... |
How to Plot Multiple Histograms in R? - GeeksforGeeks | 19 Dec, 2021
In this article, we will discuss how to plot multiple histograms in the R Programming language.
To create multiple histograms in base R, we first make a single histogram then add another layer of the histogram on top of it. But in doing so some plots may clip off as axis are made according to the first plot. So, we can add the xlim, and the ylim parameters in the first plot to change the axis limit according to our dataset.
Syntax:
hist( data, col, xlim, ylim )
hist( data, col )
where,
data: determines the data vector to be plotted.
xlim: determines the vector with x-axis limit.
ylim: determines the vector with y-axis limit.
col: determines the color of bars of the histogram.
Example:
Here, is basic multiple histograms made in the base R Language with help of hist() function.
R
# create data vectorx1 = rnorm(1000, mean=60, sd=10)x2 = rnorm(1000, mean=0, sd=10)x3 = rnorm(1000, mean=30, sd=10) # create multiple histogramhist(x1, col='red', xlim=c(-35, 100))hist(x2, col='green', add=TRUE)hist(x3, col='blue', add=TRUE)
Output:
To create multiple histograms in ggplot2, we use ggplot() function and geom_histogram() function of the ggplot2 package. To visualize multiple groups separately we use the fill property of aesthetics function to color the plot by a categorical variable.
Syntax:
ggplot( df, aes( x, fill ) ) + geom_histogram( color, alpha )
where,
df: determines the data frame to be plotted.
x: determines the data variable.
fill: determines the color of bars in the histogram.
color: determines the color of the boundary of bars in the histogram.
alpha: determines the transparency of the plot.
Example:
Here, is basic multiple histograms made by using the geom_histogram() function of the ggplot2 package in the R Language.
R
# load library ggplot2library(ggplot2) # set themetheme_set(theme_bw(12)) # create x vectorxAxis <- rnorm(500) # create groups in variable using conditional # statementsgroup <- rep(1, 500) group[xAxis > -2] <- 2group[xAxis > -1] <- 3group[xAxis > 0] <- 4group[xAxis > 1] <- 5group[xAxis > 2] <- 6 # create sample data framesample_data <- data.frame(xAxis, group) # create histogram using ggplot() # function colored by groupggplot(sample_data, aes(x=xAxis, fill = as.factor(group)))+ geom_histogram( color='#e9ecef', alpha=0.6, position='identity')
Output:
Picked
R-Charts
R-ggplot
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
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?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R | [
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 24947,
"s": 24851,
"text": "In this article, we will discuss how to plot multiple histograms in the R Programming language."
},
{
"code": null,
"e": 25279,
"s": 24947,
"te... |
Longest Increasing Subsequence | Practice | GeeksforGeeks | Given an array of integers, find the length of the longest (strictly) increasing subsequence from the given array.
Example 1:
Input:
N = 16
A[]={0,8,4,12,2,10,6,14,1,9,5
13,3,11,7,15}
Output: 6
Explanation:Longest increasing subsequence
0 2 6 9 13 15, which has length 6
Example 2:
Input:
N = 6
A[] = {5,8,3,7,9,1}
Output: 3
Explanation:Longest increasing subsequence
5 7 9, with length 3
Your Task:
Complete the function longestSubsequence() which takes the input array and its size as input parameters and returns the length of the longest increasing subsequence.
Expected Time Complexity : O( N*log(N) )
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ N ≤ 105
0 ≤ A[i] ≤ 106
0
nitinkaplas906434 days ago
void helper(int val,vector<int>&v) { int low=0; int high=v.size()-1; while(low<high) { int mid=(low+high)/2; if(v[mid]>val) high=mid; else low=mid+1; } v[low]=val; } int longestSubsequence(int n, int a[]) { vector<int>v; v.push_back(a[0]); for(int i=1;i<n;i++) { if(a[i]>v.back()) v.push_back(a[i]); else helper(a[i],v); } return v.size(); }
0
pranavkhandare45456 days ago
Java solution
static int longestSubsequence(int size, int a[]) { // code here int[] dp = new int[size]; int omax=0; for(int i=0;i<size;i++){ int max=0; for(int j=0;j<i;j++){ if(a[j]<a[i]){ if(dp[j]>max){ max=dp[j]; } } } dp[i]=max+1; if(dp[i]>omax){ omax=dp[i]; } } return omax;
0
shishir17pandey1 week ago
int longestSubsequence(int n, int a[]) { // your code here int dp[n+1]; int maxi=0; for(int i=0;i<n;i++){ dp[i]=1; } for(int i=0;i<n;i++){ for(int j=0;j<i;j++){ if(a[i]>a[j] && dp[i]<dp[j]+1){ dp[i]=dp[j]+1; } } } for(int i=0;i<n;i++){ if(maxi<dp[i]){ maxi=dp[i]; } } return maxi; }};
0
sarthakiet20192 weeks ago
int longestSubsequence(int n, int a[]) { // your code here vector<int>ans; for(int i=0;i<n;++i){ auto it=lower_bound(ans.begin(),ans.end(),a[i]); if(it==ans.end()) ans.push_back(a[i]); else *it=a[i]; } return ans.size(); }simple cpp solution
0
achakraborty04102 weeks ago
Using Java
static int longestSubsequence(int size, int a[]) { int ans=0; int t[]=new int[size]; Arrays.fill(t,1); for(int i=0;i<size;i++){ for(int j=0;j<i;j++) if(a[i]>a[j]) t[i]=Math.max(t[i],1+t[j]); ans=Math.max(ans,t[i]); } return ans; }
0
ashagarwala30992 weeks ago
// dp approach-state of the index is that we store in each index the lis //length till that index including that a[i] itself so when next element //comes we jst compare the a[i] values if it matches the condition we //include and like this we do for all prev indexes and store the max //length in our curr index comes to check
class Solution{ public: //Function to find length of longest increasing subsequence. int longestSubsequence(int n, int a[]) { // your code here int dp[n]; dp[0]=1; for(int i=1;i<n;i++) {dp[i]=1; for(int j=i-1;j>=0;j--) { if(a[i]>a[j]) dp[i]=max(dp[i],dp[j]+1); } } int res=0; for(int i=0;i<n;i++) { res=max(res,dp[i]); } return res; }};
+3
rainx2 weeks ago
People who are struggling to understand LIS(BINARY SEARCH nLogn Variant)
Let us first have a quick look in the code. No Youthoober explained like this
/* ITERATOR VERSION */
int longestSubsequence(int n, int a[]) {
vector<int> res;
for(int i = 0; i < n; i++) {
auto it=lower_bound(res.begin(), res.end(), a[i]);
if(it==res.end()) {
res.push_back(a[i]);
}
else {
*it=a[i];
}
}
return res.size();
}
/* INDEX VERSION */
int longestSubsequence(int n, int a[]) {
vector<int> res;
for(int i = 0; i < n; i++) {
int index=lower_bound(res.begin(), res.end(), a[i])-res.begin();
if(index==res.size()) {
res.push_back(a[i]);
}
else {
res[index]=a[i];
}
}
return res.size();
}
First understand what LOWER BOUND does.
LOWER BOUND RETURNS THE INDEX/ITERATOR OF THE ELEMENT WHICH IS JUST GREATER THAN OR EQUAL TO ARR[i], Incase there is nothing like that, it returns the size of the vector/array /END OF ITERATOR.
Now, let us see how binary search is actually helping us to reduce the complexity, I hope you are familiar with the N*N approach since I would not be discussing that here.
Ok, the trick binary search is doing here is IT IS PLACING EVERY SINGLE ELEMENT IN ARR[i] TO ITS ORIGINAL PLACE IN THE IN-PROGESS LIS CONSTRUCTION.
Did not get it, well let us take a example
Let us say we have a LIS(in progress)={1,3,5};
Now since we are trying to place every single element of ARR[i] in its correct place in LIS, we binary search for ARR[i] and there can be TWO cases for it
After BINARY SEARCH we found an index where element is equal to or just greater than ARR[i], so what we do is place arr[i] in the element positionWe did not get any element in the building LIS, and therefore we need to append add it in LIS since there is no element greater than or equal to ARR[i] in LIS
After BINARY SEARCH we found an index where element is equal to or just greater than ARR[i], so what we do is place arr[i] in the element position
We did not get any element in the building LIS, and therefore we need to append add it in LIS since there is no element greater than or equal to ARR[i] in LIS
LIS(in progress)={1,3,5};
Let us say we encounter ARR[i]=4, we binary search for it in LIS, we get index of element 5, we place 4 in-place of 5 because it is its original place.
LIS becomes ={1,3,4};
Now pay attention closely and see how binary search is so cool in finding LIS effectively.
As we are proceeding in ARR, let us say we found ARR[i]=5, yeah the 5 we just removed and placed 4 in place of it. But this ARR[i]=5 is found while iterating forward. Can be said this is the duplicate of that 5 we found earlier, so we binary search for ARR[i]=5 in LIS and found that there is no element which is equal or greater than 5, so according to our condition we will append it to our LIS
LIS becomes={1,3,4,5}
See how placing 4 in place of 5 earlier helped us increasing LIS now. This is how binary search works actually, it is placing every single ARR[i] in its correct place in the building LIS
Thank you and ask question if you have. Do comment something so I know this is was helpful for yall
Sapport for more such explainations
0
rainx
This comment was deleted.
0
moninmodi3 weeks ago
map<int,int> mp; for(int i=0;i<n;i++) mp[a[i]]++; vector<int> v; for(auto x:mp){ v.push_back(x.first); } sort(v.begin(),v.end()); int m=v.size(); int t[n+1][m+1]; for(int i=0;i<n+1;i++){ for(int j=0;j<m+1;j++){ if(i==0||j==0){ t[i][j]=0; } else{ if(a[i-1]==v[j-1]){ t[i][j]=1+t[i-1][j-1]; } else{ t[i][j]=max(t[i-1][j],t[i][j-1]); } } } } return t[n][m];
+1
jainmuskan5653 weeks ago
int lis_help(int prev,int curr,int a[],int n,vector<vector<int>> &dp){ if(curr==n){ return 0; } if(dp[prev+1][curr]!= -1){ return dp[prev+1][curr]; } int len= lis_help(prev,curr+1,a,n,dp); if(prev==-1 || a[prev]<a[curr]){ len= max(len,1+lis_help(curr,curr+1,a,n,dp)); } return dp[prev+1][curr]= len; } int longestSubsequence(int n, int a[]) { vector<vector<int>> dp(n,vector<int>(n+1,-1)); return lis_help(-1,0,a,n,dp); }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 353,
"s": 238,
"text": "Given an array of integers, find the length of the longest (strictly) increasing subsequence from the given array."
},
{
"code": null,
"e": 364,
"s": 353,
"text": "Example 1:"
},
{
"code": null,
"e": 515,
"s": 364,
... |
Implement Onclick in JavaScript and allow web browser to go back to previous page? | For reaching the back page on button click, use the concept of −
window.history.go(-1)
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<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>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css">
<style>
</style>
</head>
<body>
<input action="gotoPreviousPage" onclick="window.history.go(-1);
return false;" type="submit"
value="Click the button to Goto the Previous Page...." />
<script>
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
After clicking the button “Click the button to Goto the Previous Page....”, you will reach the
previous page as in the below screenshot − | [
{
"code": null,
"e": 1127,
"s": 1062,
"text": "For reaching the back page on button click, use the concept of −"
},
{
"code": null,
"e": 1149,
"s": 1127,
"text": "window.history.go(-1)"
},
{
"code": null,
"e": 1160,
"s": 1149,
"text": " Live Demo"
},
{
... |
C# program to check if a Substring is present in a Given String | Use the contains() method in C# to check if a substring is in a given string.
Let us say the string is −
United
Within the string, you need to find the substring “Uni”. For that, use the contains method and use it like the following code snippet −
res = str1.Contains(str2);
You can try to run the following code to find a substring in a string.
Live Demo
using System;
public class Demo {
public static void Main() {
string str1 = "United", str2 = "Uni";
bool res;
res = str1.Contains(str2);
if (res)
Console.Write("The substring " + str2 + " is in the string " + str1);
else
Console.Write("The substring " + str2 + " is not in the string " + str1);
}
}
The substring Uni is in the string United | [
{
"code": null,
"e": 1140,
"s": 1062,
"text": "Use the contains() method in C# to check if a substring is in a given string."
},
{
"code": null,
"e": 1167,
"s": 1140,
"text": "Let us say the string is −"
},
{
"code": null,
"e": 1174,
"s": 1167,
"text": "United... |
Angular 6 - Http Client | HttpClient is introduced in Angular 6 and it will help us fetch external data, post to it, etc. We need to import the http module to make use of the http service. Let us consider an example to understand how to make use of the http service.
To start using the http service, we need to import the module in app.module.ts as shown below −
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
If you see the highlighted code, we have imported the HttpClientModule from @angular/common/http and the same is also added in the imports array.
Let us now use the http client in the app.component.ts.
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get("http://jsonplaceholder.typicode.com/users").
subscribe((data) ⇒ console.log(data))
}
}
Let us understand the code highlighted above. We need to import http to make use of the service, which is done as follows −
import { HttpClient } from '@angular/common/http';
In the class AppComponent, a constructor is created and the private variable http of type Http. To fetch the data, we need to use the get API available with http as follows
this.http.get();
It takes the url to be fetched as the parameter as shown in the code.
We will use the test url − https://jsonplaceholder.typicode.com/users to fetch the json data. The subscribe will log the output in the console as shown in the browser −
If you see, the json objects are displayed in the console. The objects can be displayed in the browser too.
For the objects to be displayed in the browser, update the codes in app.component.html and app.component.ts as follows −
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private http: HttpClient) { }
httpdata;
ngOnInit() {
this.http.get("http://jsonplaceholder.typicode.com/users")
.subscribe((data) => this.displaydata(data));
}
displaydata(data) {this.httpdata = data;}
}
In app.component.ts, using the subscribe method we will call the display data method and pass the data fetched as the parameter to it.
In the display data method, we will store the data in a variable httpdata. The data is displayed in the browser using for over this httpdata variable, which is done in the app.component.html file.
<ul *ngFor = "let data of httpdata">
<li>Name : {{data.name}} Address: {{data.address.city}}</li>
</ul>
The json object is as follows −
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
The object has properties such as id, name, username, email, and address that internally has street, city, etc. and other details related to phone, website, and company. Using the for loop, we will display the name and the city details in the browser as shown in the app.component.html file.
This is how the display is shown in the browser −
Let us now add the search parameter, which will filter based on specific data. We need to fetch the data based on the search param passed.
Following are the changes done in app.component.html and app.component.ts files −
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private http: HttpClient) { }
httpdata;
name;
searchparam = 2;
ngOnInit() {
this.http.get("http://jsonplaceholder.typicode.com/users?id="+this.searchparam)
.subscribe((data) => this.displaydata(data));
}
displaydata(data) {this.httpdata = data;}
}
For the get api, we will add the search param id = this.searchparam. The searchparam is equal to 2. We need the details of id = 2 from the json file.
This is how the browser is displayed −
We have consoled the data in the browser, which is received from the http. The same is displayed in the browser console. The name from the json with id = 2 is displayed in the browser.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2236,
"s": 1995,
"text": "HttpClient is introduced in Angular 6 and it will help us fetch external data, post to it, etc. We need to import the http module to make use of the http service. Let us consider an example to understand how to make use of the http service."
},
{
... |
HTML5 Canvas - Text and Fonts | HTML5 canvas provides capabilities to create text using different font and text properties listed below −
font [ = value ]
This property returns the current font settings and can be set, to change the font.
textAlign [ = value ]
This property returns the current text alignment settings and can be set, to change the alignment. The possible values are start, end, left, right, and center.
textBaseline [ = value ]
This property returns the current baseline alignment settings and can be set, to change the baseline alignment. The possible values are top, hanging, middle , alphabetic, ideographic and bottom.
fillText(text, x, y [, maxWidth ] )
This property fills the given text at the given position indicated by the given coordinates x and y.
strokeText(text, x, y [, maxWidth ] )
This property strokes the given text at the given position indicated by the given coordinates x and y.
Following is a simple example which makes use of above mentioned attributes to draw a text −
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#00F';
ctx.font = 'Italic 30px Sans-Serif';
ctx.textBaseline = 'Top';
ctx.fillText('Hello world!', 40, 100);
ctx.font = 'Bold 30px Sans-Serif';
ctx.strokeText('Hello world!', 40, 50);
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
The above example would produce the following result −
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2714,
"s": 2608,
"text": "HTML5 canvas provides capabilities to create text using different font and text properties listed below −"
},
{
"code": null,
"e": 2731,
"s": 2714,
"text": "font [ = value ]"
},
{
"code": null,
"e": 2815,
"s": 2731,
... |
Predicting the task duration based on a range | by Michael Larionov, PhD | Towards Data Science | In one of the previous entries we have established a statistical model for predicting the actual project time and cost based on the estimates. We discussed that we can fit the estimates (both for the Agile and Waterfall projects) to a Log-Normal distribution, which guarantees the positive support. Using statistical approach to estimation allows us to give prediction with a required confidence level, and also project monetary benefits, costs and risk, as we discussed in another post.
One thing I was asked is how the model generalizes for the case when an estimate is given as a range. Indeed, this is what everybody taught us: do not give a single number, but range. One approach is to continue to use our statistical model, and feed it a number in the middle, the mean of the two values.
That way the model can be used without modifications.
There are two problems with this approach:
Taking a mean of high and low is arbitrary. It reduces the information given by half. It would be better to have an algorithm learn where we need to set the variable x within the interval between low and high boundariesBy giving us a range of data, a developer is trying to convey to us a very important information: a degree of uncertainty in the estimates. A correct model should use that information.
Taking a mean of high and low is arbitrary. It reduces the information given by half. It would be better to have an algorithm learn where we need to set the variable x within the interval between low and high boundaries
By giving us a range of data, a developer is trying to convey to us a very important information: a degree of uncertainty in the estimates. A correct model should use that information.
To simplify the process, we will take natural logarithm of all the estimates and the actuals. Since we model estimates using log-normal distribution, our new variables y, l, h will be logarithms of the actual number of days, low and high estimates respectively. In this case we can use Normal distribution! We will model y using linear regression:
In case where θh and θl are equal, we get exactly the same problem as we discussed earlier.
The likelihood function for a single piece of data in this case can be written as follows (following this).
As mentioned earlier, by giving a range, the developer wanted to communicate to us the uncertainty of the estimate. We should include this uncertainty in our estimate of σ. Intuitively the range is proportional to the standard deviation, and we can learn the coefficient by modeling σ as:
If we also use precision parameter τ in place of σ0:
Then our likelihood function will be:
The priors for τ and θ are traditionally Gamma and Normal distribution respectively:
Here α , β, λ are hyperparameters.
The choice of prior for ζ is more difficult. None of the conjugate priors exist for the kind of likelihood function we have chosen. For now we can select the normal distribution. Zero mean of this distribution means that a priori we don’t trust the ranges (we know that many consultants the range is always 20% and does not convey any information). High mean of the prior distribution means that we pay more attention to the estimated degree of uncertainty.
For simplicity we set the mean to zero.
The negative log-posterior function is:
In this blog I will find parameters, corresponding to the maximum posterior. And to avoid making errors in differentiating, we will use TensorFlow. We will follow this example to build our code
import numpy as npimport pandas as pdimport tensorflow as tf
The data here represent the estimated and actual number of days. We see that the developer liked to add 25% to his estimate as a buffer.However for some of the stories he added more buffer, perhaps, to indicate more uncertainty.
seed=1389tf.reset_default_graph()task_data = pd.DataFrame({'low':[4,14,4,3,4,3,4,9,6,27,20,23,11], 'high':[5,18,5,4,5,7,5,10,8,30,25,29,14], 'actual':[17,8,5,3,5,4,9,9,4,27,16,15,7,]})%matplotlib inlineimport matplotlib.pyplot as pltimport seaborn as snsfig, ax = plt.subplots(figsize=(11.7, 8.27))task_data['story_id'] = task_data.indexdata_for_plot = pd.melt(task_data, id_vars="story_id", var_name="type", value_name="days")task_data.drop(columns=['story_id'], inplace=True)sns.barplot(x='story_id', y='days', hue='type', data=data_for_plot,ax=ax);
When defining variables, we substitute τ for another variable ρ:
This is to avoid the optimizer selecting negative τ
#Taking the log of datalog_data = np.log(task_data.values)N = log_data.shape[0]#Defining variablestheta_h = tf.Variable(name='theta_h', initial_value=0.5)theta_l = tf.Variable(name='theta_l', initial_value=0.5)zeta = tf.Variable(name='zeta', initial_value=0.01)rho = tf.Variable(name='rho', initial_value=0.01)
Since we don’t want to tune too many hyperparameters, we will set α and β to one. Both λ parameters act as regularization parameters, so we will have to tune them
#Set the hyperparametersalpha = tf.constant(name='alpha', value=1.0)beta = tf.constant(name='beta', value=1.0)lambda1 = tf.constant(name='lambda1', value=1e-4)lambda2 = tf.constant(name='lambda2', value=1e-4)def loss(l, h, y): return tf.log(1+zeta**2*(h-l)) + \ rho**2/2/(1+zeta**2*(h-l))**2 * (y - theta_l*l - theta_h*h)**2cummulative_loss = tf.reduce_sum(list(np.apply_along_axis(lambda x: loss(*x), axis=1, arr=log_data )))cost = cummulative_loss - (N+1-2*alpha)/2*tf.log(rho**2) + beta*rho**2 + \rho**2*lambda1/2*(theta_h**2+theta_l**2) + rho**2*lambda2/2*zeta**2learning_rate = 1e-4optimizer = tf.train.AdamOptimizer(learning_rate)train_op = optimizer.minimize(cost)import mathinit = tf.global_variables_initializer()n_epochs = int(1e5)with tf.Session() as sess: sess.run(init) for epoch in range(n_epochs): if epoch % 1e4 == 0: print("Epoch", epoch, "Cost =", cost.eval()) print(f'Parameters: {theta_l.eval()}, {theta_h.eval()}, {rho.eval()}, {zeta.eval()}') sess.run(train_op) best_theta_l = theta_l.eval() best_theta_h = theta_h.eval() best_sigma = 1/math.sqrt(rho.eval())Epoch 0 Cost = 55.26268Parameters: 0.5, 0.5, 0.009999999776482582, 0.009999999776482582Epoch 10000 Cost = 6.5892615Parameters: 0.24855799973011017, 0.6630115509033203, 0.6332486271858215, 1.1534561276317736e-35Epoch 20000 Cost = 1.39517Parameters: 0.2485545128583908, 0.6630078554153442, 1.3754394054412842, 1.1534561276317736e-35Epoch 30000 Cost = 1.3396643Parameters: 0.24855604767799377, 0.6630094647407532, 1.4745615720748901, 1.1534561276317736e-35Epoch 40000 Cost = 1.3396641Parameters: 0.24855272471904755, 0.6630063056945801, 1.4745622873306274, 1.1534561276317736e-35Epoch 50000 Cost = 1.3396646Parameters: 0.2485586702823639, 0.6630119681358337, 1.4745632410049438, 1.1534561276317736e-35Epoch 60000 Cost = 1.3396648Parameters: 0.2485581487417221, 0.6630115509033203, 1.4745649099349976, 1.1534561276317736e-35Epoch 70000 Cost = 1.3396643Parameters: 0.2485586702823639, 0.6630122065544128, 1.4745644330978394, 1.1534561276317736e-35Epoch 80000 Cost = 1.3396643Parameters: 0.24855820834636688, 0.6630116701126099, 1.4745631217956543, 1.1534561276317736e-35Epoch 90000 Cost = 1.3396646Parameters: 0.248562291264534, 0.663015604019165, 1.474563717842102, 1.1534561276317736e-35
What is interesting here is that ζ is zero. This means that we cannot trust the estimation of uncertainty that the developers give us. This also means that we can just use log-normal distribution around the mean specified by the learned parameters θl and θh. Let’s say, the same developer estimated a new task to take 10–15 days. Plugging it into the formulas we see:
mu = best_theta_l*math.log(10)+best_theta_h*math.log(15)most_likely_prediction = math.exp(mu) most_likely_prediction10.67385532327305
We can also get the 95% confidence, by plugging the values directly into log-normal distribution:
from scipy.stats import lognormdistribution = lognorm(s=best_sigma, scale=most_likely_prediction, loc=0)print(f'95% confidence: {distribution.ppf(0.95)}')95% confidence: 41.3614192940211
As we see, if we want 95% of confidence, we have to give an estimate of 41 days, instead of 11 days for 50% confidence. This is very easily explained if you see that in the past the developer did not do a very good job estimating the tasks.
You can access the notebook from github. | [
{
"code": null,
"e": 659,
"s": 171,
"text": "In one of the previous entries we have established a statistical model for predicting the actual project time and cost based on the estimates. We discussed that we can fit the estimates (both for the Agile and Waterfall projects) to a Log-Normal distribut... |
Python - Smallest integer possible from combination of list elements - GeeksforGeeks | 29 Dec, 2019
Given a list of integers, the task is to get smallest integer possible from the combination of list elements. This is one of the problems that is essential in a competitive point of view and this article discusses various shorthands to solve this problem in Python. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using sorted() + lambdaThe combination of the above function can be used to perform this task. The sorted function performs the sort of list indices converted into string and lambda functions handle the conversion and iteration operation.
# Python code to demonstrate # Smallest number from list# using sorted() + lambdaimport functools # initializing list test_list = [23, 65, 98, 3, 4] # printing original listprint ("The original list is : " + str(test_list)) # lambda for custom operationcustom = lambda i, j: -1 if str(j) + str(i) > str(i) + str(j) else 1 # using sorted() + custom function# Smallest number from list res = sorted(test_list, key = functools.cmp_to_key(custom)) # printing result print ("The smallest possible number : " + "".join(map(str, res)))
The original list is : [23, 65, 98, 3, 4]
The smallest possible number : 23346598
Method #2 : Using itertools.permutation() + join() + min()
The itertools.permutation can be used to get possible permutation and min function chooses the minimum of it after being converted to integer as a result of joined output as given by join function.
# Python3 code to demonstrate # Smallest number from list# using itertools.permutation() + join() + min()from itertools import permutations # initializing list test_list = [23, 65, 98, 3, 4] # printing original listprint ("The original list is : " + str(test_list)) # using itertools.permutation() + join() + min()# Smallest number from listres = int(min((''.join(i) for i in permutations(str(i) for i in test_list)), key = int)) # printing result print ("The smallest possible number : " + str(res))
The original list is : [23, 65, 98, 3, 4]
The smallest possible number : 23346598
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n29 Dec, 2019"
},
{
"code": null,
"e": 25867,
"s": 25537,
"text": "Given a list of integers, the task is to get smallest integer possible from the combination of list elements. This is one of the problems that is essential in a co... |
How to replicate a matrix by rows in R? | The replication of matrix by rows means that repeating a matrix one or more times but row-wise. For example, if we have a matrix that contains only one row and three columns then the replication of that matrix three times will repeat that one row three times. This can be done by using rep function along with matrix function as shown in the below example.
Live Demo
M<-matrix(1:25,ncol=5)
M
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
Replicating matrix M twice −
matrix(rep(t(M),2),ncol=ncol(M),byrow=TRUE)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
[6,] 1 6 11 16 21
[7,] 2 7 12 17 22
[8,] 3 8 13 18 23
[9,] 4 9 14 19 24
[10,] 5 10 15 20 25
Replicating matrix M thrice −
matrix(rep(t(M),3),ncol=ncol(M),byrow=TRUE)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
[6,] 1 6 11 16 21
[7,] 2 7 12 17 22
[8,] 3 8 13 18 23
[9,] 4 9 14 19 24
[10,] 5 10 15 20 25
[11,] 1 6 11 16 21
[12,] 2 7 12 17 22
[13,] 3 8 13 18 23
[14,] 4 9 14 19 24
[15,] 5 10 15 20 25
Replicating matrix M five times −
matrix(rep(t(M),5),ncol=ncol(M),byrow=TRUE)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
[6,] 1 6 11 16 21
[7,] 2 7 12 17 22
[8,] 3 8 13 18 23
[9,] 4 9 14 19 24
[10,] 5 10 15 20 25
[11,] 1 6 11 16 21
[12,] 2 7 12 17 22
[13,] 3 8 13 18 23
[14,] 4 9 14 19 24
[15,] 5 10 15 20 25
[16,] 1 6 11 16 21
[17,] 2 7 12 17 22
[18,] 3 8 13 18 23
[19,] 4 9 14 19 24
[20,] 5 10 15 20 25
[21,] 1 6 11 16 21
[22,] 2 7 12 17 22
[23,] 3 8 13 18 23
[24,] 4 9 14 19 24
[25,] 5 10 15 20 25
Replicating matrix M five times −
matrix(rep(t(M),6),ncol=ncol(M),byrow=TRUE)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
[6,] 1 6 11 16 21
[7,] 2 7 12 17 22
[8,] 3 8 13 18 23
[9,] 4 9 14 19 24
[10,] 5 10 15 20 25
[11,] 1 6 11 16 21
[12,] 2 7 12 17 22
[13,] 3 8 13 18 23
[14,] 4 9 14 19 24
[15,] 5 10 15 20 25
[16,] 1 6 11 16 21
[17,] 2 7 12 17 22
[18,] 3 8 13 18 23
[19,] 4 9 14 19 24
[20,] 5 10 15 20 25
[21,] 1 6 11 16 21
[22,] 2 7 12 17 22
[23,] 3 8 13 18 23
[24,] 4 9 14 19 24
[25,] 5 10 15 20 25
[26,] 1 6 11 16 21
[27,] 2 7 12 17 22
[28,] 3 8 13 18 23
[29,] 4 9 14 19 24
[30,] 5 10 15 20 25 | [
{
"code": null,
"e": 1419,
"s": 1062,
"text": "The replication of matrix by rows means that repeating a matrix one or more times but row-wise. For example, if we have a matrix that contains only one row and three columns then the replication of that matrix three times will repeat that one row three ... |
How to change text inside an element using jQuery? | To change text inside an element using jQuery, use the text() method.
You can try to run the following code to replace text inside an element:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#demo').text('The replaced text.');
});
</script>
</head>
<body>
<div id="demo">
<p>The initial text</p>
</div>
</body>
</html> | [
{
"code": null,
"e": 1132,
"s": 1062,
"text": "To change text inside an element using jQuery, use the text() method."
},
{
"code": null,
"e": 1205,
"s": 1132,
"text": "You can try to run the following code to replace text inside an element:"
},
{
"code": null,
"e": 12... |
Data Analysis and Visualization of scraped data from IMDb with R | Towards Data Science | Surely you, like me at any time of the day or week, take that break to get out of the routine, work, problems, and just relax, watching your favorite television series on a streaming service, on television, or dusting old DVDs.
We enjoy those moments of entertainment, either alone or with someone, where we can immerse ourselves in a story that catches us, moves us, makes us reflect, or entertains us. Many of these television series end up saying goodbye fantastically, while in other cases, they end badly, annoying their fans. In any case, many things happen that are not visible to everyone.
Under this motivation, we will carry out Data visualization and analysis of some of the most popular TV series (especially among geek culture): “Black Mirror”, “Westworld”, “Game of Thrones”, “Rick and Morty”, and “Stranger Things”.
IMDb (Internet Movie Database) currently has an updated and extensive online database with information about TV series, movies, etc. It also saves ratings based on opinions and votes expressed by users around the world, for each topic it stores.
We will use an interesting and simple script to prepare the dataset that we will be using. Without delving too much into the topic, to write about it in detail later, this script performs Web Scraping (a technique used to extract information from websites in an automated way) from the IMDb website with the rvest package. All you have to do is update the file “series_urls.csv” where you can add titles of series, movies, or whatever you want to be contained in IMDb along with its identifier (for example for Game Of Thrones its URL is https: //www.imdb.com/title/tt0944947 / where “tt0944947” is who matters to us).
For this post considering the chosen TV series, the CSV file looks like:
Once this CSV file has been defined, it’s enough to run the R script in the root folder, to do Web Scraping to all the data for each series (updated to date).
And what data will we obtain? Well, it will generate a new CSV file inside the “data” folder made up of the following variables per TV series:
series_name <chr> TV serie Nameseries_ep <int> Episode numberseason <int> Season numberseason_ep <int> Season episode numberurl <chr> IMDb URL for the episodeEpisode <chr> Episode TitleUserRating <dbl> IMDb User Rating (Calculated as explained on the website: http://www.imdb.com/help/show_leaf?votestopfaq).UserVotes <dbl> Number of votes for the ratingr1 <dbl> Proportion of users who rated this episode with a score of 1...r10 <dbl> Proportion of users who rated this episode with a score of 10
The CSV file obtained for this article after the Web Scraping looks like this:
I know, I know... now you are looking at me and asking: And to all this, where is that script you talk about so much, Saul? I just wanted to make it clear how it works first, before sharing, you can find it in the author’s repository: https://github.com/nazareno/imdb-series. Now you just have to download, customize and run locally.
Well, starting a new script in R, and now that we have our dataset, it’s time to analyze a little. We will start by loading the libraries that we will use, as well as the CSV of our dataset previously obtained by Web Scraping.
library(tidyverse)library(plotly)library(kableExtra)library(knitr)theme_set(theme_bw())# CSV READING GENERATED BY IMDB WEB SCRAPING series_imdb <- read_csv("series_imdb.csv")# EN CASO DE HABER GENERADO UN DATASET MÁS GRANDE, FILTRAR SÓLO ALGUNAS SERIES DEL CSV COMPLETOmis_series <- series_imdb %>% filter(series_name %in% c("Black Mirror", "Game of Thrones", "Rick & Morty", "Stranger Things", "Westworld")) %>% mutate(series_name = factor(series_name)) %>% mutate(season = factor(season))# TV SERIES AND COLUMNS PREVIEWlevels(mis_series$series_name)colnames(mis_series)
I have now obtained 189 observations from the 5 TV series with 18 available variables.
We are ready for questions. Were Daenerys’ dragons sexed? Will the Demogorgon continue to harm people?. No, unfortunately not those kinds of questions, but we will be able to obtain relevant data and answer questions such as Which series was more successful? What were the least successful seasons or episodes?
One of the variables that we will use to answer the questions in this analysis is UserRating, hereinafter understood as the assigned rating. Let’s look at the distribution of the ratings given to the episodes of the 5 TV series in general.
# GLOBAL USER RATING HISTOGRAMmis_series %>% ggplot(aes(UserRating)) + geom_histogram(binwidth = .1, fill = "#0196d7") + scale_x_continuous(breaks = seq(0, 10, 1)) + labs(y = "Número de ocurrencias", x = "Calificación de episodio") + ggtitle("UserRating general de las 5 series", "Black Mirror, Westworld, Game of Thrones, Rick and Morty y Stranger Things.")
UserRating is measured on a scale from 0 to 10. We will obtain the following plot, where we can see that in the case of these five selected TV series, scores between 8 and 9 predominate. It must be admitted at the outset that the five series chosen are quite well-made TV series.
IMDb provides the UserVotes variable, with which we can discover if there is a relationship between the number of votes and the rating that each TV series has obtained.
# RELATION BETWEEN RATING AND VOTES PER TV SERIESseries_votos <- mis_series %>% group_by(series_name) %>% summarise(rating = median(UserRating), totalvotos = sum(UserVotes))series_votos %>% ggplot(aes(x = reorder(series_name, totalvotos), y = totalvotos, fill = rating)) + geom_histogram(stat = "identity") + scale_fill_distiller(name="Calificación", palette = "Blues") + scale_y_continuous(labels = scales::comma) + coord_flip() + xlab("Serie") + ylab("Número total de votos") + ggtitle("Calificación de cada serie", "Relación entre calificación y número de votos")
Through the histogram obtained, we have that although the best-rated TV serie is the one with the highest number of votes, contrary to this, the TV serie with the lowest rating is not exactly the one that received the least number of votes. So we can say there is not much relationship between the total number of votes and the rating.
To answer this question, we will use a line chart. The median was used to measure the evaluations since it’s not affected by extreme values such as the average.
# ACCEPTANCE OF EACH TV SERIES BASED ON ITS SEASON RATINGseries_acep <- mis_series %>% group_by(series_name, season) %>% summarise(rating = median(UserRating))series_acep %>% ggplot(aes(x = as.numeric(season), y = rating, color = series_name)) + geom_line() + geom_point() + scale_x_continuous(breaks = 1:10) + scale_color_brewer(name = "Serie", palette = "Set1") + xlab("Temporada") + ylab("Calificación") + ggtitle("Evolución de la aceptación de cada serie", "Calificación por temporada")ggplotly()
With the plot obtained, we can see in general the sad decline in each of the TV series, but very especially in the case of the Black Mirror and Game of Thrones (and perhaps with good reason, what a series finale they gave us, right?).
This is a question that perhaps many of you will also have. Well, we will verify it using box plots per season, with which we can also see the summary of the ratings of each episode.
# SEASON RATING BY EPISODESseries_temp <- mis_series %>% ggplot(aes(season, UserRating, color = season)) + geom_boxplot() + geom_jitter(width = .2) + facet_wrap(~series_name) + labs(x = "Temporada", y = "Calificación de episodio", color = "Temporada") + ggtitle("Evolución de cada temporada por capítulo", "Calificación por episodio")
The plot obtained will allow us to see more deeply and sadly the decline of Game Of Thrones, for example, and some episodes that stand out for having a much lower rating.
Another one of the big questions that you will surely have. We can see which were the best and the worst episodes based on the minimum and maximum rating obtained by UserRating ordered in ascending and descending order.
# TOP OF BEST AND WORST EPISODES BASED ON THEIR RATINGmejores_ep <- knitr::kable(x = head(arrange(mis_series, desc(UserRating)) %>% select(series_name, Episode, ,season, UserRating), 7), col.names = c('Serie', 'Episodio', 'Temporada', 'Calificación'))kable_styling(mejores_ep, "striped", position = "left", font_size = 12)peores_ep <- knitr::kable(x = head(arrange(mis_series, (UserRating)) %>% select(series_name, Episode, ,season, UserRating), 7), col.names = c('Serie', 'Episodio', 'Temporada', 'Calificación'))kable_styling(peores_ep, "striped", position = "left", font_size = 12)
It should be noted that compared to the rest of the TV series, Game Of Thrones has a greater number of episodes and seasons. It’s obvious then that it would be very likely that it would have a presence in both the top-rated episodes and the lowest-rated episodes.
What do you think? Do you agree with the top 7 obtained? If you are curious to see the top 20, in addition to seeing the plots generated a little more fancy with plotly, I share the flexdashboard that I put together for this article: https://rpubs.com/cosmoduende/imdb-tv-series-analysis-r
And here you can also find the complete code, in case you want to carry out the analysis with your favorite TV series: https://github.com/cosmoduende/r-analisis-exploratorio-tv-series-imdb
I wish you a very happy analysis, that you can experience putting it into practice, that you play and be surprised with very interesting results.
This article was translated into English, from the article that I previously published in Spanish, at the request of people who do not speak Spanish and who asked me in groups and forums if I would publish it in English.
Thank you and see you next time.
Some rights reserved | [
{
"code": null,
"e": 400,
"s": 172,
"text": "Surely you, like me at any time of the day or week, take that break to get out of the routine, work, problems, and just relax, watching your favorite television series on a streaming service, on television, or dusting old DVDs."
},
{
"code": null,... |
java.time.LocalDate.plus() Method Example | The java.time.LocalDate.plus(long amountToAdd, TemporalUnit unit) method returns a copy of this date with the specified amount added.
Following is the declaration for java.time.LocalDate.plus(long amountToAdd, TemporalUnit unit) method.
public LocalDate plus(long amountToAdd, TemporalUnit unit)
amountToAdd − the amount of the unit to add to the result, may be negative.
amountToAdd − the amount of the unit to add to the result, may be negative.
unit − the unit of the amount to add, not null.
unit − the unit of the amount to add, not null.
a LocalDate based on this date with the specified amount added, not null.
DateTimeException − if the addition cannot be made.
DateTimeException − if the addition cannot be made.
UnsupportedTemporalTypeException − if the unit is not supported.
UnsupportedTemporalTypeException − if the unit is not supported.
ArithmeticException − if numeric overflow occurs.
ArithmeticException − if numeric overflow occurs.
The following example shows the usage of java.time.LocalDate.plus(long amountToAdd, TemporalUnit unit) method.
package com.tutorialspoint;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class LocalDateDemo {
public static void main(String[] args) {
LocalDate date = LocalDate.parse("2017-02-03");
LocalDate date1 = date.plus(10, ChronoUnit.DAYS);
System.out.println(date1);
}
}
Let us compile and run the above program, this will produce the following result −
2017-02-13
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2049,
"s": 1915,
"text": "The java.time.LocalDate.plus(long amountToAdd, TemporalUnit unit) method returns a copy of this date with the specified amount added."
},
{
"code": null,
"e": 2152,
"s": 2049,
"text": "Following is the declaration for java.time.Local... |
Longest Common Subsequence | Practice | GeeksforGeeks | Given two sequences, find the length of longest subsequence present in both of them. Both the strings are of uppercase.
Example 1:
Input:
A = 6, B = 6
str1 = ABCDGH
str2 = AEDFHR
Output: 3
Explanation: LCS for input Sequences
“ABCDGH” and “AEDFHR” is “ADH” of
length 3.
Example 2:
Input:
A = 3, B = 2
str1 = ABC
str2 = AC
Output: 2
Explanation: LCS of "ABC" and "AC" is
"AC" of length 2.
Your Task:
Complete the function lcs() which takes the length of two strings respectively and two strings as input parameters and returns the length of the longest subsequence present in both of them.
Expected Time Complexity : O(|str1|*|str2|)
Expected Auxiliary Space: O(|str1|*|str2|)
Constraints:
1<=size(str1),size(str2)<=103
+1
kronizerdeltac4 days ago
JAVA TABULATION AND MEMOIZATION CODES:
1.MEMOIZATION:
static int lcs_memo(String s1, String s2, int n, int m, int[][] dp) {
if(n == 0 || m == 0)
return 0;
if(dp[n][m] != -1)
return dp[n][m];
if(s1.charAt(n - 1) == s2.charAt(m - 1))
return dp[n][m] = lcs_memo(s1, s2, n - 1, m - 1, dp) + 1;
else
return dp[n][m] = Math.max(lcs_memo(s1, s2, n - 1, m, dp), lcs_memo(s1, s2, n, m - 1, dp));
}
static int lcs(int x, int y, String s1, String s2)
{
int[][] dp = new int[x + 1][y + 1];
for(int[] d : dp)
Arrays.fill(d, - 1);
return lcs_memo(s1, s2, x, y, dp);
}
2. TABULATION:
static int lcs_tabu(String s1, String s2, int N, int M, int[][] dp) {
for(int n = 0; n <= N; n++) {
for(int m = 0; m <= M; m++) {
if(n == 0 || m == 0) {
dp[n][m] = 0;
continue;
}
if(s1.charAt(n - 1) == s2.charAt(m - 1))
dp[n][m] = dp[n - 1][m - 1] + 1;
else
dp[n][m] = Math.max(dp[n - 1][m], dp[n][m - 1]);
}
}
return dp[N][M];
}
static int lcs(int x, int y, String s1, String s2)
{
int[][] dp = new int[x + 1][y + 1];
for(int[] d : dp)
Arrays.fill(d, - 1);
return lcs_tabu(s1, s2, x, y, dp);
}
+1
ayushkokande3324 days ago
int lcs(int x, int y, string s, string p)
{
// your code here
vector<vector<int>>dp(s.length()+1,vector<int>(p.length()+1,0));
for(int i=1;i<=s.length();i++){
for(int j=1;j<=p.length();j++){
if(s[i-1]==p[j-1]) dp[i][j] = 1+dp[i-1][j-1];
else dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
}
}
return dp[s.length()][p.length()];
}
+1
kashyapjhon5 days ago
C++ Solution MEDIUM
Method 1→ MEMOIZATION TIME=(0.05/1.72):
int help(vector<vector<int> > &dp, string s1,string s2,int n,int m){ if(n==0 || m==0){ return 0; } if(dp[n][m]!=-1){ return dp[n][m]; } if(s1[n-1]==s2[m-1]){ return dp[n][m]=1+help(dp,s1,s2,n-1,m-1); } else{ return dp[n][m]=max(help(dp,s1,s2,n-1,m),help(dp,s1,s2,n,m-1)); } } int lcs(int x, int y, string s1, string s2) { // your code here vector<vector<int> > dp(x+1,vector<int>(y+1,-1)); return help(dp,s1,s2,x,y); }
Method 2→ TABULATION TIME=(0.01/1.72):
int lcs(int x, int y, string s1, string s2) { // your code here vector<vector<int> > dp(x+1,vector<int>(y+1,0)); for(int i=1;i<=x;i++){ for(int j=1;j<=y;j++){ if(s1[i-1]==s2[j-1]){ dp[i][j]=1+dp[i-1][j-1]; } else{ dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } } return dp[x][y]; }
0
shivamshuklashivam296 days ago
class Solution
{
int dp[1002][1002];
public:
Solution(){
memset(dp , -1 , sizeof(dp));
}
//Function to find the length of longest common subsequence in two strings.
int lcs(int x, int y, string s1, string s2)
{
if(x ==0 || y == 0)return 0;
if(dp[x][y] != -1) return dp[x][y];
if(s1[x-1] == s2[y-1]) return dp[x][y] = 1+ lcs(x-1,y-1,s1,s2);
else return dp[x][y] = max(lcs(x-1,y,s1,s2) , lcs(x,y-1,s1,s2));
}
};
0
annanyamathur2 weeks ago
int lcs(int x, int y, string s1, string s2)
{
int dp[x+1][y+1];
memset(dp,0,sizeof(dp));
for(int i=1;i<=x;i++)
{
for(int j=1;j<=y;j++)
{
if(s1[i-1]==s2[j-1])
{
dp[i][j]=1+dp[i-1][j-1];
}
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
return dp[x][y];
}
0
aniketsaraswat1122 weeks ago
int lcs(int x, int y, string s1, string s2){
int dp[x+1][y+1] = {};
for(int i = 1; i<=x; i++){
for(int j = 1; j<=y; j++){
if(s1[i-1] == s2[j-1])
dp[i][j] = 1 + dp[i-1][j-1];
else
dp[i][j] = max(dp[i-1][j-1],max(dp[i-1][j],dp[i][j-1]));
}
}
return dp[x][y];
}
0
yashvardhansingh20192 weeks ago
Java Short & Easy Time efficient Code
int[][] dp = new int[x+1][y+1]; for(int i=1;i<=x;i++){ for(int j=1;j<=y;j++){ if(s1.charAt(i-1)==s2.charAt(j-1)){ dp[i][j] = 1+ dp[i-1][j-1]; }else{ dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]); } } } return dp[x][y];
0
cshubham4392 weeks ago
if(i==s1.length() || j == s2.length()){
return 0;
}
int myans;
if(s1.charAt(i)==s2.charAt(j)){
int smallans;
if(arr[i+1][j+1]==-1){
smallans = common(s1,s2,i+1,j+1,arr);
arr[i+1][j+1] = smallans;
}
else{
smallans = arr[i+1][j+1];
}
myans = 1+smallans;
}
else{
int ans1,ans2;
if(arr[i+1][j] == -1){
ans1 = common(s1,s2,i+1,j,arr);
arr[i+1][j] = ans1;
}
else{
ans1 = arr[i+1][j];
}
if(arr[i][j+1]==-1){
ans2 = common(s1,s2,i,j+1,arr);
arr[i][j+1] = ans2;
}
else{
ans2 = arr[i][j+1];
}
myans = Math.max(ans2,ans1);
}
return myans;
}
static int lcs(int x, int y, String s1, String s2)
{
int arr[][] = new int[x+1][y+1];
for(int i = 0; i<x;i++){
for(int j = 0;j<y;j++){
arr[i][j] = -1;
}
}
int ans = common(s1,s2,0,0,arr);
return ans;
0
amarrajsmart1971 month ago
int lcs(int x, int y, string s1, string s2) { // your code here int dp[s1.length()+1][s2.length()+1]; for(int x=0;x<=s1.length();x++) { for(int y=0;y<=s2.length();y++) { if(x==0||y==0) dp[x][y]=0; else if(s1[x-1]==s2[y-1]) { dp[x][y]=1+dp[x-1][y-1]; } else { dp[x][y]=max(dp[x][y-1],dp[x-1][y]); } } } return dp[s1.length()][s2.length()]; }
0
ashishsharma4979
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 358,
"s": 238,
"text": "Given two sequences, find the length of longest subsequence present in both of them. Both the strings are of uppercase."
},
{
"code": null,
"e": 369,
"s": 358,
"text": "Example 1:"
},
{
"code": null,
"e": 509,
"s": 369,... |
Train without labeling data using Self-Supervised Learning by Relational Reasoning | by Chien Vu | Towards Data Science | In a modern deep learning algorithm, the dependence on manual annotation of unlabeled data is one of the major limitations. To train a good model, usually, we have to prepare a vast amount of labeled data. In the case of a small number of classes and data, we can use the pre-trained model from the labeled public dataset and fine-tune a few last layers with your data. However, in real life, it’s easily faced with the problem when your data is considerably large (the products in the store or the face of a human,..) and it will be difficult for the model to learn with just a few trainable layers. Furthermore, the amount of unlabeled data (e.g. document text, images on the Internet) is uncountable. Labeling all of them for the task is almost impossible but not utilizing them is definitely a waste.
In this case, training a deep model again from scratch with a new dataset will be an option but it takes a lot of time and effort for labeling data while using a pre-trained deep model seems no longer helpful. That is the reason why Self-supervised learning was born. The idea behind this is simple, which serves two main tasks:
Surrogate task: the deep model will learn generalizable representations from unlabeled data without annotation, and then will be able to self-generate a supervisory signal exploiting implicit information.
Downstream task: representations will be fine-tuned for supervised-learning tasks e.g. classification and image retrieval with less number of labeled data (the number of labeled data depending on the performance of model based on your requirement)
There are much different training approaches proposed to learn such representations: Relative position [1]: the model needs to understand the spatial context of objects to tell the relative position between parts; Jigsaw puzzle [2]: the model needs to place 9 shuffled patches back to the original locations; Colorization [3]: the model has trained to color a grayscale input image; precisely the task is to map this image to a distribution over quantized color value outputs; Counting features [4]: The model learns a feature encoder using feature counting relationship of input images transforming by Scaling and Tiling; SimCLR [5]: The model learns representations for visual inputs by maximizing agreement between differently augmented views of the same sample via a contrastive loss in the latent space.
However, I would like to introduce one interesting approach that is able to recognize things like a human. The key factor in human learning is the acquisition of new knowledge by comparing relating and different entities. So, it is a nontrivial solution if we can apply a similar mechanism in self-supervised machine learning via the Relational reasoning approach [6].
The relational reasoning paradigm is based on a key design principle: the use of a relation network as a learnable function on the unlabeled dataset to quantify the relationships between views of the same object (intra-reasoning) and relationships between different objects in different scenes (inter-reasoning). The possibility to exploit a similar mechanism in self-supervised machine learning via relational reasoning was evaluated by the performance on standard datasets (CIFAR-10, CIFAR-100, CIFAR-100–20, STL-10, tiny-ImageNet, SlimageNet), learning schedule, and backbones (bothshallow and deep). The results show that the Relational reasoning approach largely outperforms the best competitor in all conditions by an average 14% accuracy and the most recent state-of-the-art method by 3% indicating in this paper [6].
For the simplest explanation, Relational Reasoning is just a methodology that tries to help learners understanding relations between different objects (ideas) rather than learning objects individually. That could help learners easily distinguish and remember the object based on their difference. There are two main components in the Relational reasoning system [6]: backbone structure and relation head. The relation head was used in the pretext task phase for supporting the underlying neural network backbone learning useful representations in the unlabeled dataset and then it will be discarded. The backbone structure was used in downstream tasks such as classification or image retrieval after training in the pretext task.
Previous work: focus on within-scene relation, meaning thatall the elements in the same object belong to the same scene (e.g. balls from a basket); training on label dataset and the main goal is the relation head [7].
New approach: focus on relations between different views of the same object (intra-reasoning) and between different objects in different scenes (inter-reasoning); use relational reasoning on unlabeled data and the relation head is a pretext task for learning useful representations in the underlying backbone.
Let’s discuss the important point in some part of the Relational reasoning system:
Mini-batch augmentation:
Mini-batch augmentation:
As mentioned before, this system introduced intra-reasoning and inter-reasoning? So why we need them? It is not possible to create pairs of similar and dissimilar objects when labels are not given. To solve this problem, the bootstrapping technique was applied and resulted in forming intra-reasoning and inter-reasoning, where:
Intra-reasoning consists of sampling random augmentations of the same object {A1; A2 } (positive pair) (eg. different views of same basketball)
Inter-reasoning consists of coupling two random objects {A1; B1} (negative pair) (eg. basketball with random ball)
Furthermore, the utilization of the random augmentations functions (e.g. geometric transformation, color distortion) is also considered to make between-scenes reasoning more complicated. The benefit of these augmentations functions forces the learner (backbone) to pay attention to the correlation between a wider set of features (e.g. color, size, texture, etc.). For instance, in the pair {foot ball, basket ball}, the color alone is a strong predictor of the class. However, with the random changing of color as well as the shape size, the learner now is difficult to discriminate the difference between this pair. The learner has to take a look at another feature, consequently, it results in better representation.
2. Metric learning
The aim of metric learning s to use a distance metric to bring closer representations of similar inputs (positives) while moving away representations of dissimilar inputs (negatives). However, in Relational reasoning, metric learning is fundamentally different:
3. Loss function
The learning objective is a binary classification problem over the presentation pairs. Therefore we can use a binary cross-entropy loss to the maximization of a Bernoulli log-likelihood, where the relation score y represents a probabilistic estimate of representation membership inducing through a sigmoid activation function.
Finally, this paper [6] also supplied the result of Relational reasoning on standard datasets (CIFAR-10, CIFAR-100, CIFAR-100–20, STL-10, tiny-ImageNet, SlimageNet), different backbones (shallow and deep), same learning schedule (epochs). The results are below, for further information you can check out his paper.
In this article, I want to reproduce the Relational reasoning system on the public image dataset STL-10. This dataset comprises of 10 classes (airplane, bird, automobile, cat, deer, dog, horse, monkey, ship, truck) with 96x96 pixels color.
First of all, we need to import some important library
STL-10 dataset consists of 1300 labeled images (500 for training and 800 for testing). However, it also includes 100000 unlabeled images from a similar but broader distribution of images. For instance, it contains other types of animals (bears, rabbits, etc.) and vehicles (trains, buses, etc.) in addition to the ones in the labeled set
And then we will create the Relational reasoning class based on the suggestion of the author
To compare the performance of Relational reasoning methodology on the shallow and deep model, we will create a shallow model (Conv4) and use the structure of a deep model (Resnet34).
backbone = Conv4() # shallow modelbackbone = models.resnet34(pretrained = False) # deep model
Some hyperparameters and augmentation strategies were set based on the suggestion of the author. We will train our backbone with relation head on unlabeled STL-10 dataset.
Up to now, we’ve already created everything necessary to train our model. Now we will train the backbone and relation head model in 10 epochs and 16 augmentation images (K), it took 4 hours with the shallow model (Conv4) and 6 hours on the deep model (Resnet34) by 1 GPU Tesla P100-PCIE-16GB (you can freely change the number of epochs as well as another hyperparameter to obtain better results)
device = torch.device("cuda:0") if torch.cuda.is_available() else torch.device("cpu")backbone.to(device)model = RelationalReasoning(backbone, feature_size) model.train(tot_epochs=tot_epochs, train_loader=train_loader)torch.save(model.backbone.state_dict(), 'model.tar')
After training our backbone model, we discard the relation head and use only the backbone for the downstream tasks. We need to fine-tune our backbone with labeled data in STL-10 (500 images) and test the final model in the test set (800 images). Training and testing datasets will load in Dataloader without augmentations.
We will load the pretrained backbone model and use a simple linear model to connect the output feature with a number of classes in the dataset.
# linear modellinear_layer = torch.nn.Linear(64, 10) # if backbone is Conv4linear_layer = torch.nn.Linear(1000, 10) # if backbone is Resnet34# defining a raw backbone modelbackbone_lineval = Conv4() # Conv4backbone_lineval = models.resnet34(pretrained = False) # Resnet34# load modelcheckpoint = torch.load('model.tar') # name of pretrain weightbackbone_lineval.load_state_dict(checkpoint)
In this time, only the linear model will be trained, the backbone model will be frozen. First, we will see the result of fine-tuned Conv4
And then check on the test set
Conv4 obtained 49.98% accuracy on the test set, it means that the backbone model could learn useful feature in the unlabeled dataset, we just need to fine-tune with few epochs to achieve a good result. Now let check the performance of the deep model.
Then evaluating on the test dataset
It’s much better, we can obtain 55.38% accuracy on the test set. In this article, the main goal is to reproduce and evaluate the Relational reasoning methodology to teach the model distinguishing the object without the label, therefore, these results were very promising. If you feel unsatisfied, you can freely do the experiment by changing the hyperparameter such as the number of augmentation, epochs, or model structure.
Self-supervised relational reasoning is effective in both a quantitative and qualitative manners, and with backbones of different size from shallow to deep structure. Representations learned through comparison can be easily transferred from one domain to another, they are fine-grained and compact, which may be due to the correlation between accuracy and number of augmentations. In relational reasoning, the number of augmentations has a primary role affecting the quality of the clusters of objects based on the author’s experiment [4]. Self-supervised learning has a strong potential to become the future of machine learning in many aspects.
You can contact me if you want further discussion. Here is my Linkedin
Enjoy!!! 👦🏻
[1] Carl Doersch et. al, Unsupervised Visual Representation Learning by Context Prediction, 2015.
[2] Mehdi Noroozi et. al, Unsupervised Learning of Visual Representations by Solving Jigsaw Puzzles, 2017.
[3] Zhang et. al, Colorful Image Colorization, 2016.
[4] Mehdi Noroozi et. al, Representation Learning by Learning to Count, 2017.
[5] Ting Chen et. al, A Simple Framework for Contrastive Learning of Visual Representations, 2020.
[6] Massimiliano Patacchiola et. al, Self-Supervised Relational Reasoning forRepresentation Learning, 2020.
[7] Adam Santoro et. al, Relational recurrent neural networks, 2018. | [
{
"code": null,
"e": 977,
"s": 172,
"text": "In a modern deep learning algorithm, the dependence on manual annotation of unlabeled data is one of the major limitations. To train a good model, usually, we have to prepare a vast amount of labeled data. In the case of a small number of classes and data... |
How to Use Locks in Multi-Threaded Java Program? | 02 Feb, 2021
A lock may be a more flexible and complicated thread synchronization mechanism than the standard synchronized block. A lock may be a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: just one thread at a time can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, like the read lock of a ReadWriteLock.
// Example of lock interface
Lock lock = new ReentrantLock();
lock.lock();
// critical section
lock.unlock();
Methods in the lock interface
There are certain methods in a lock interface. We are gonna look at those along with their modifiers:
Implementation of locks
Let’s see how can we implement some locks in Java:
1.readWriteLock()
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
readWriteLock.readLock().lock();
// ....
......//
readWriteLock.readLock().unlock();
readWriteLock.writeLock().lock();
// only one writer can enter this section,
// and only if no threads are currently reading.
readWriteLock.writeLock().unlock();
Below is the implementation of readWriteLock() method:
Java
// Implementation of ReadWriteLock in Javaimport java.io.*;import java.util.ArrayList;import java.util.List;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReadWriteLock;import java.util.concurrent.locks.ReentrantReadWriteLock;class GFG<O> { private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private final Lock writeLock = readWriteLock.writeLock(); private final Lock readLock = readWriteLock.readLock(); private final List<O> list = new ArrayList<>(); // setElement function sets // i.e., write the element to the thread public void setElement(O o) { // acquire the thread for writing writeLock.lock(); try { list.add(o); System.out.println( "Element by thread " + Thread.currentThread().getName() + " is added"); } finally { // To unlock the acquired write thread writeLock.unlock(); } } // getElement function prints // i.e., read the element from the thread public O getElement(int i) { // acquire the thread for reading readLock.lock(); try { System.out.println( "Elements by thread " + Thread.currentThread().getName() + " is printed"); return list.get(i); } finally { // To unlock the acquired read thread readLock.unlock(); } } public static void main(String[] args) { GFG<String> gfg = new GFG<>(); gfg.setElement("Hi"); gfg.setElement("Hey"); gfg.setElement("Hello"); System.out.println("Printing the last element : " + gfg.getElement(2)); }}
Element by thread main is added
Element by thread main is added
Element by thread main is added
Elements by thread main is printed
Printing the last element : Hello
2. reentrantLock()
public class lockImplement {
//...
ReentrantLock lock = new ReentrantLock();
int counter = 0;
public void testing() {
lock.lock();
try {
// Critical section here
count++;
} finally {
lock.unlock();
}
}
//...
}
Below is the implementation of reentrantLock() method:
Java
// Java code to illustrate Reentrant Locksimport java.text.SimpleDateFormat;import java.util.Date;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.locks.ReentrantLock; class worker implements Runnable { String name; ReentrantLock re; public worker(ReentrantLock rl, String n) { re = rl; name = n; } public void run() { boolean done = false; while (!done) { // Getting Outer Lock boolean ans = re.tryLock(); // Returns True if lock is free if (ans) { try { Date d = new Date(); SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss"); System.out.println( "task name - " + name + " outer lock acquired at " + ft.format(d) + " Doing outer work"); Thread.sleep(1500); // Getting Inner Lock re.lock(); try { d = new Date(); ft = new SimpleDateFormat( "hh:mm:ss"); System.out.println( "task name - " + name + " inner lock acquired at " + ft.format(d) + " Doing inner work"); System.out.println( "Lock Hold Count - " + re.getHoldCount()); Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } finally { // Inner lock release System.out.println( "task name - " + name + " releasing inner lock"); re.unlock(); } System.out.println("Lock Hold Count - " + re.getHoldCount()); System.out.println("task name - " + name + " work done"); done = true; } catch (InterruptedException e) { e.printStackTrace(); } finally { // Outer lock release System.out.println( "task name - " + name + " releasing outer lock"); re.unlock(); System.out.println("Lock Hold Count - " + re.getHoldCount()); } } else { System.out.println("task name - " + name + " waiting for lock"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }} public class test { static final int MAX_T = 2; public static void main(String[] args) { ReentrantLock rel = new ReentrantLock(); ExecutorService pool = Executors.newFixedThreadPool(MAX_T); Runnable w1 = new worker(rel, "Job1"); Runnable w2 = new worker(rel, "Job2"); Runnable w3 = new worker(rel, "Job3"); Runnable w4 = new worker(rel, "Job4"); pool.execute(w1); pool.execute(w2); pool.execute(w3); pool.execute(w4); pool.shutdown(); }}
Output:
task name - Job2 waiting for lock
task name - Job1 outer lock acquired at 09:49:42 Doing outer work
task name - Job2 waiting for lock
task name - Job1 inner lock acquired at 09:49:44 Doing inner work
Lock Hold Count - 2
task name - Job2 waiting for lock
task name - Job2 waiting for lock
task name - Job1 releasing inner lock
Lock Hold Count - 1
task name - Job1 work done
task name - Job1 releasing outer lock
Lock Hold Count - 0
task name - Job3 outer lock acquired at 09:49:45 Doing outer work
task name - Job2 waiting for lock
task name - Job3 inner lock acquired at 09:49:47 Doing inner work
Lock Hold Count - 2
task name - Job2 waiting for lock
task name - Job2 waiting for lock
task name - Job3 releasing inner lock
Lock Hold Count - 1
task name - Job3 work done
task name - Job3 releasing outer lock
Lock Hold Count - 0
task name - Job4 outer lock acquired at 09:49:48 Doing outer work
task name - Job2 waiting for lock
task name - Job4 inner lock acquired at 09:49:50 Doing inner work
Lock Hold Count - 2
task name - Job2 waiting for lock
task name - Job2 waiting for lock
task name - Job4 releasing inner lock
Lock Hold Count - 1
task name - Job4 work done
task name - Job4 releasing outer lock
Lock Hold Count - 0
task name - Job2 outer lock acquired at 09:49:52 Doing outer work
task name - Job2 inner lock acquired at 09:49:53 Doing inner work
Lock Hold Count - 2
task name - Job2 releasing inner lock
Lock Hold Count - 1
task name - Job2 work done
task name - Job2 releasing outer lock
Lock Hold Count - 0
Note: The program might not work on an online IDE because of sleep call.
Java-Multithreading
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Feb, 2021"
},
{
"code": null,
"e": 539,
"s": 28,
"text": "A lock may be a more flexible and complicated thread synchronization mechanism than the standard synchronized block. A lock may be a tool for controlling access to a shared re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.