Programs & Examples On #Junit

Popular unit testing framework for Java and Scala. The latest version, JUnit 4, supports rich annotation-based and parameterized tests. Consider using in conjunction with the Java or Scala tag to indicate your use case.

How do you assert that a certain exception is thrown in JUnit 4 tests?

in junit, there are four ways to test exception.

junit5.x

  • for junit5.x, you can use assertThrows as following

    @Test
    public void testFooThrowsIndexOutOfBoundsException() {
        Throwable exception = assertThrows(IndexOutOfBoundsException.class, () -> foo.doStuff());
        assertEquals("expected messages", exception.getMessage());
    }
    

junit4.x

  • for junit4.x, use the optional 'expected' attribute of Test annonation

    @Test(expected = IndexOutOfBoundsException.class)
    public void testFooThrowsIndexOutOfBoundsException() {
        foo.doStuff();
    }
    
  • for junit4.x, use the ExpectedException rule

    public class XxxTest {
        @Rule
        public ExpectedException thrown = ExpectedException.none();
    
        @Test
        public void testFooThrowsIndexOutOfBoundsException() {
            thrown.expect(IndexOutOfBoundsException.class)
            //you can test the exception message like
            thrown.expectMessage("expected messages");
            foo.doStuff();
        }
    }
    
  • you also can use the classic try/catch way widely used under junit 3 framework

    @Test
    public void testFooThrowsIndexOutOfBoundsException() {
        try {
            foo.doStuff();
            fail("expected exception was not occured.");
        } catch(IndexOutOfBoundsException e) {
            //if execution reaches here, 
            //it indicates this exception was occured.
            //so we need not handle it.
        }
    }
    
  • so

    • if you like junit 5, then you should like the 1st one
    • the 2nd way is used when you only want test the type of exception
    • the first and last two are used when you want test exception message further
    • if you use junit 3, then the 4th one is preferred
  • for more info, you can read this document and junit5 user guide for details.

Difference between setUp() and setUpBeforeClass()

The @BeforeClass and @AfterClass annotated methods will be run exactly once during your test run - at the very beginning and end of the test as a whole, before anything else is run. In fact, they're run before the test class is even constructed, which is why they must be declared static.

The @Before and @After methods will be run before and after every test case, so will probably be run multiple times during a test run.

So let's assume you had three tests in your class, the order of method calls would be:

setUpBeforeClass()

  (Test class first instance constructed and the following methods called on it)
    setUp()
    test1()
    tearDown()

  (Test class second instance constructed and the following methods called on it)
    setUp()
    test2()
    tearDown()

  (Test class third instance constructed and the following methods called on it)
    setUp()
    test3()
    tearDown()

tearDownAfterClass()

Injecting @Autowired private field during testing

Look at this link

Then write your test case as

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"/applicationContext.xml"})
public class MyLauncherTest{

@Resource
private MyLauncher myLauncher ;

   @Test
   public void someTest() {
       //test code
   }
}

Mockito - NullpointerException when stubbing Method

you need to initialize MockitoAnnotations.initMocks(this) method has to called to initialize annotated fields.

   @Before public void initMocks() {
       MockitoAnnotations.initMocks(this);
   }

for more details see Doc

Populating Spring @Value during Unit Test

@ExtendWith(SpringExtension.class)    // @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(initializers = ConfigDataApplicationContextInitializer.class)

May that could help. The key is ConfigDataApplicationContextInitializer get all props datas

What's the actual use of 'fail' in JUnit test case?

The most important use case is probably exception checking.

While junit4 includes the expected element for checking if an exception occurred, it seems like it isn't part of the newer junit5. Another advantage of using fail() over the expected is that you can combine it with finally allowing test-case cleanup.

dao.insert(obj);
try {
  dao.insert(obj);
  fail("No DuplicateKeyException thrown.");
} catch (DuplicateKeyException e) {
  assertEquals("Error code doesn't match", 123, e.getErrorCode());
} finally {
  //cleanup
  dao.delete(obj);
}

As noted in another comment. Having a test to fail until you can finish implementing it sounds reasonable as well.

Mock a constructor with parameter

Without Using Powermock .... See the example below based on Ben Glasser answer since it took me some time to figure it out ..hope that saves some times ...

Original Class :

public class AClazz {

    public void updateObject(CClazz cClazzObj) {
        log.debug("Bundler set.");
        cClazzObj.setBundler(new BClazz(cClazzObj, 10));
    } 
}

Modified Class :

@Slf4j
public class AClazz {

    public void updateObject(CClazz cClazzObj) {
        log.debug("Bundler set.");
        cClazzObj.setBundler(getBObject(cClazzObj, 10));
    }

    protected BClazz getBObject(CClazz cClazzObj, int i) {
        return new BClazz(cClazzObj, 10);
    }
 }

Test Class

public class AClazzTest {

    @InjectMocks
    @Spy
    private AClazz aClazzObj;

    @Mock
    private CClazz cClazzObj;

    @Mock
    private BClazz bClassObj;

    @Before
    public void setUp() throws Exception {
        Mockito.doReturn(bClassObj)
               .when(aClazzObj)
               .getBObject(Mockito.eq(cClazzObj), Mockito.anyInt());
    }

    @Test
    public void testConfigStrategy() {
        aClazzObj.updateObject(cClazzObj);

        Mockito.verify(cClazzObj, Mockito.times(1)).setBundler(bClassObj);
    }
}

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

One way for me to understand wildcards is to think that the wildcard isn't specifying the type of the possible objects that given generic reference can "have", but the type of other generic references that it is is compatible with (this may sound confusing...) As such, the first answer is very misleading in it's wording.

In other words, List<? extends Serializable> means you can assign that reference to other Lists where the type is some unknown type which is or a subclass of Serializable. DO NOT think of it in terms of A SINGLE LIST being able to hold subclasses of Serializable (because that is incorrect semantics and leads to a misunderstanding of Generics).

How to write a unit test for a Spring Boot Controller endpoint

Spring MVC offers a standaloneSetup that supports testing relatively simple controllers, without the need of context.

Build a MockMvc by registering one or more @Controller's instances and configuring Spring MVC infrastructure programmatically. This allows full control over the instantiation and initialization of controllers, and their dependencies, similar to plain unit tests while also making it possible to test one controller at a time.

An example test for your controller can be something as simple as

public class DemoApplicationTests {

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = standaloneSetup(new HelloWorld()).build();
    }

    @Test
    public void testSayHelloWorld() throws Exception {
        this.mockMvc.perform(get("/")
           .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
           .andExpect(status().isOk())
           .andExpect(content().contentType("application/json"));

    }
}

JUnit Eclipse Plugin?

Junit is included by default with Eclipse (at least the Java EE version I'm sure). You may just need to add the view to your perspective.

Get name of currently executing test in JUnit 4

JUnit 4.9.x and higher

Since JUnit 4.9, the TestWatchman class has been deprecated in favour of the TestWatcher class, which has invocation:

@Rule
public TestRule watcher = new TestWatcher() {
   protected void starting(Description description) {
      System.out.println("Starting test: " + description.getMethodName());
   }
};

Note: The containing class must be declared public.

JUnit 4.7.x - 4.8.x

The following approach will print method names for all tests in a class:

@Rule
public MethodRule watchman = new TestWatchman() {
   public void starting(FrameworkMethod method) {
      System.out.println("Starting test: " + method.getName());
   }
};

Spring Test & Security: How to mock authentication?

Since Spring 4.0+, the best solution is to annotate the test method with @WithMockUser

@Test
@WithMockUser(username = "user1", password = "pwd", roles = "USER")
public void mytest1() throws Exception {
    mockMvc.perform(get("/someApi"))
        .andExpect(status().isOk());
}

Remember to add the following dependency to your project

'org.springframework.security:spring-security-test:4.2.3.RELEASE'

Failed to load ApplicationContext for JUnit test of Spring controller

Solved by adding the following dependency into pom.xml file :

<dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>test</scope>
</dependency>

Maven does not find JUnit tests to run

I also found that the unit test code should put under the test folder, it can not be recognized as test class if you put it under the main folder. eg.

Wrong

/my_program/src/main/java/NotTest.java

Right

/my_program/src/test/java/MyTest.java

Using Mockito to stub and execute methods for testing

SHORT ANSWER

How to do in your case:

int argument = 5; // example with int but could be another type
Mockito.when(mockMyAgent.otherMethod(Mockito.anyInt()).thenReturn(requiredReturnArg(argument));

LONG ANSWER

Actually what you want to do is possible, at least in Java 8. Maybe you didn't get this answer by other people because I am using Java 8 that allows that and this question is before release of Java 8 (that allows to pass functions, not only values to other functions).

Let's simulate a call to a DataBase query. This query returns all the rows of HotelTable that have FreeRoms = X and StarNumber = Y. What I expect during testing, is that this query will give back a List of different hotel: every returned hotel has the same value X and Y, while the other values and I will decide them according to my needs. The following example is simple but of course you can make it more complex.

So I create a function that will give back different results but all of them have FreeRoms = X and StarNumber = Y.

static List<Hotel> simulateQueryOnHotels(int availableRoomNumber, int starNumber) {
    ArrayList<Hotel> HotelArrayList = new ArrayList<>();
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Rome, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Krakow, 7, 15));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Madrid, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Athens, 4, 1));

    return HotelArrayList;
}

Maybe Spy is better (please try), but I did this on a mocked class. Here how I do (notice the anyInt() values):

//somewhere at the beginning of your file with tests...
@Mock
private DatabaseManager mockedDatabaseManager;

//in the same file, somewhere in a test...
int availableRoomNumber = 3;
int starNumber = 4;
// in this way, the mocked queryOnHotels will return a different result according to the passed parameters
when(mockedDatabaseManager.queryOnHotels(anyInt(), anyInt())).thenReturn(simulateQueryOnHotels(availableRoomNumber, starNumber));

How can I generate an HTML report for Junit results?

You can easily do this via ant. Here is a build.xml file for doing this

 <project name="genTestReport" default="gen" basedir=".">
        <description>
                Generate the HTML report from JUnit XML files
        </description>

        <target name="gen">
                <property name="genReportDir" location="${basedir}/unitTestReports"/>
                <delete dir="${genReportDir}"/>
                <mkdir dir="${genReportDir}"/>
                <junitreport todir="${basedir}/unitTestReports">
                        <fileset dir="${basedir}">
                                <include name="**/TEST-*.xml"/>
                        </fileset>
                        <report format="frames" todir="${genReportDir}/html"/>
                </junitreport>
        </target>
</project>

This will find files with the format TEST-*.xml and generate reports into a folder named unitTestReports.

To run this (assuming the above file is called buildTestReports.xml) run the following command in the terminal:

ant -buildfile buildTestReports.xml

How to test code dependent on environment variables using JUnit?

In a similar situation like this where I had to write Test Case which is dependent on Environment Variable, I tried following:

  1. I went for System Rules as suggested by Stefan Birkner. Its use was simple. But sooner than later, I found the behavior erratic. In one run, it works, in the very next run it fails. I investigated and found that System Rules work well with JUnit 4 or higher version. But in my cases, I was using some Jars which were dependent on JUnit 3. So I skipped System Rules. More on it you can find here @Rule annotation doesn't work while using TestSuite in JUnit.
  2. Next I tried to create Environment Variable through Process Builder class provided by Java. Here through Java Code we can create an environment variable, but you need to know the process or program name which I did not. Also it creates environment variable for child process, not for the main process.

I wasted a day using the above two approaches, but of no avail. Then Maven came to my rescue. We can set Environment Variables or System Properties through Maven POM file which I think best way to do Unit Testing for Maven based project. Below is the entry I made in POM file.

    <build>
      <plugins>
       <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <systemPropertyVariables>
              <PropertyName1>PropertyValue1</PropertyName1>                                                          
              <PropertyName2>PropertyValue2</PropertyName2>
          </systemPropertyVariables>
          <environmentVariables>
            <EnvironmentVariable1>EnvironmentVariableValue1</EnvironmentVariable1>
            <EnvironmentVariable2>EnvironmentVariableValue2</EnvironmentVariable2>
          </environmentVariables>
        </configuration>
      </plugin>
    </plugins>
  </build>

After this change, I ran Test Cases again and suddenly all worked as expected. For reader's information, I explored this approach in Maven 3.x, so I have no idea on Maven 2.x.

AssertNull should be used or AssertNotNull

I just want to add that if you want to write special text if It null than you make it like that

  Assert.assertNotNull("The object you enter return null", str1)

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

Just try "Project > Clean..." - seems to be THE solution to many problems in Eclipse!

Pass a local file in to URL in Java

Using Java 7:

Paths.get(string).toUri().toURL();

However, you probably want to get a URI. Eg, a URI begins with file:/// but a URL with file:/ (at least, that's what toString produces).

Before and After Suite execution hook in jUnit 4.x

Using annotations, you can do something like this:

import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;

class SomethingUnitTest {
    @BeforeClass
    public static void runBeforeClass()
    {

    }

    @AfterClass
    public static void runAfterClass()
    {  

    }

    @Before  
    public void setUp()
    {

    }

    @After
    public void tearDown()
    {

    }

    @Test
    public void testSomethingOrOther()
    {

    }

}

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

If your test class extends the Spring JUnit classes
(e.g., AbstractTransactionalJUnit4SpringContextTests or any other class that extends AbstractSpringContextTests), you can access the app context by calling the getContext() method.
Check out the javadocs for the package org.springframework.test.

How does Junit @Rule work?

Junit Rules work on the principle of AOP (aspect oriented programming). It intercepts the test method thus providing an opportunity to do some stuff before or after the execution of a particular test method.

Take the example of the below code:

public class JunitRuleTest {

  @Rule
  public TemporaryFolder tempFolder = new TemporaryFolder();

  @Test
  public void testRule() throws IOException {
    File newFolder = tempFolder.newFolder("Temp Folder");
    assertTrue(newFolder.exists());
  }
} 

Every time the above test method is executed, a temporary folder is created and it gets deleted after the execution of the method. This is an example of an out-of-box rule provided by Junit.

Similar behaviour can also be achieved by creating our own rules. Junit provides the TestRule interface, which can be implemented to create our own Junit Rule.

Here is a useful link for reference:

Error:(23, 17) Failed to resolve: junit:junit:4.12

In my case was it was very wired! Besides adding a correct proxy (I'm working within a company), I needed to add the other two libraries in the dependencies:

compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.android.support:design:25.0.1'

then the error for "junit:junit:4.12" was resolved. Make sure that all of the dependencies in build.gradle match what you import in project structure

Setting up JUnit with IntelliJ IDEA

I needed to enable the JUnit plugin, after I linked my project with the jar files.

To enable the JUnit plugin, go to File->Settings, type "JUnit" in the search bar, and under "Plugins," check "JUnit.

vikingsteve's advice above will probably get the libraries linked right. Otherwise, open File->Project Structure, go to Libraries, hit the plus, and then browse to

C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 14.1.1\lib\

and add these jar files:

hamcrest-core-1.3.jar
junit-4.11.jar 
junit.jar 

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

adding org.junit.platform to your pom and build it. Next, you need to go to "Run Configuration" of your TEST FILE and add JUNIT in the classpath, APPLY->RUN will resolve the issue.

JUnit test for System.out.println()

@dfa answer is great, so I took it a step farther to make it possible to test blocks of ouput.

First I created TestHelper with a method captureOutput that accepts the annoymous class CaptureTest. The captureOutput method does the work of setting and tearing down the output streams. When the implementation of CaptureOutput's test method is called, it has access to the output generate for the test block.

Source for TestHelper:

public class TestHelper {

    public static void captureOutput( CaptureTest test ) throws Exception {
        ByteArrayOutputStream outContent = new ByteArrayOutputStream();
        ByteArrayOutputStream errContent = new ByteArrayOutputStream();

        System.setOut(new PrintStream(outContent));
        System.setErr(new PrintStream(errContent));

        test.test( outContent, errContent );

        System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
        System.setErr(new PrintStream(new FileOutputStream(FileDescriptor.out)));

    }
}

abstract class CaptureTest {
    public abstract void test( ByteArrayOutputStream outContent, ByteArrayOutputStream errContent ) throws Exception;
}

Note that TestHelper and CaptureTest are defined in the same file.

Then in your test, you can import the static captureOutput. Here is an example using JUnit:

// imports for junit
import static package.to.TestHelper.*;

public class SimpleTest {

    @Test
    public void testOutput() throws Exception {

        captureOutput( new CaptureTest() {
            @Override
            public void test(ByteArrayOutputStream outContent, ByteArrayOutputStream errContent) throws Exception {

                // code that writes to System.out

                assertEquals( "the expected output\n", outContent.toString() );
            }
        });
}

How to JUnit test that two List<E> contain the same elements in the same order?

I prefer using Hamcrest because it gives much better output in case of a failure

Assert.assertThat(listUnderTest, 
       IsIterableContainingInOrder.contains(expectedList.toArray()));

Instead of reporting

expected true, got false

it will report

expected List containing "1, 2, 3, ..." got list containing "4, 6, 2, ..."

IsIterableContainingInOrder.contain

Hamcrest

According to the Javadoc:

Creates a matcher for Iterables that matches when a single pass over the examined Iterable yields a series of items, each logically equal to the corresponding item in the specified items. For a positive match, the examined iterable must be of the same length as the number of specified items

So the listUnderTest must have the same number of elements and each element must match the expected values in order.

Injecting Mockito mocks into a Spring bean

Update - new answer here: https://stackoverflow.com/a/19454282/411229. This answer only applies to those on Spring versions before 3.2.

I've looked for a while for a more definitive solution to this. This blog post seems to cover all my needs and doesn't rely on ordering of bean declarations. All credit to Mattias Severson. http://www.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/

Basically, implement a FactoryBean

package com.jayway.springmock;

import org.mockito.Mockito;
import org.springframework.beans.factory.FactoryBean;

/**
 * A {@link FactoryBean} for creating mocked beans based on Mockito so that they 
 * can be {@link @Autowired} into Spring test configurations.
 *
 * @author Mattias Severson, Jayway
 *
 * @see FactoryBean
 * @see org.mockito.Mockito
 */
public class MockitoFactoryBean<T> implements FactoryBean<T> {

    private Class<T> classToBeMocked;

    /**
     * Creates a Mockito mock instance of the provided class.
     * @param classToBeMocked The class to be mocked.
     */
    public MockitoFactoryBean(Class<T> classToBeMocked) {
        this.classToBeMocked = classToBeMocked;
    }

    @Override
    public T getObject() throws Exception {
        return Mockito.mock(classToBeMocked);
    }

    @Override
    public Class<?> getObjectType() {
        return classToBeMocked;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

Next update your spring config with the following:

<beans...>
    <context:component-scan base-package="com.jayway.example"/>

    <bean id="someDependencyMock" class="com.jayway.springmock.MockitoFactoryBean">
        <constructor-arg name="classToBeMocked" value="com.jayway.example.SomeDependency" />
    </bean>
</beans>

java.lang.Exception: No runnable methods exception in running JUnits

In my case I had wrong package imported:

import org.testng.annotations.Test;

instead of

import org.junit.Test;

Beware of your ide autocomplete.

Mocking Logger and LoggerFactory with PowerMock and Mockito

Use explicit injection. No other approach will allow you for instance to run tests in parallel in the same JVM.

Patterns that use anything classloader wide like static log binder or messing with environmental thinks like logback.XML are bust when it comes to testing.

Consider the parallelized tests I mention , or consider the case where you want to intercept logging of component A whose construction is hidden behind api B. This latter case is easy to deal with if you are using a dependency injected loggerfactory from the top, but not if you inject Logger as there no seam in this assembly at ILoggerFactory.getLogger.

And its not all about unit testing either. Sometimes we want integration tests to emit logging. Sometimes we don't. Someone's we want some of the integration testing logging to be selectively suppressed, eg for expected errors that would otherwise clutter the CI console and confuse. All easy if you inject ILoggerFactory from the top of your mainline (or whatever di framework you might use)

So...

Either inject a reporter as suggested or adopt a pattern of injecting the ILoggerFactory. By explicit ILoggerFactory injection rather than Logger you can support many access/intercept patterns and parallelization.

Failed to load ApplicationContext from Unit Test: FileNotFound

Give the below

@ContextConfiguration(locations =  {"classpath*:/spring/test-context.xml"})

And in pom.xml give the following plugin:

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-surefire-plugin</artifactId>
   <version>2.20.1</version>
<configuration>
    <additionalClasspathElements>
       <additionalClasspathElement>${basedir}/src/test/resources</additionalClasspathElement>
    </additionalClasspathElements>
</configuration>

Is Java's assertEquals method reliable?

You should always use .equals() when comparing Strings in Java.

JUnit calls the .equals() method to determine equality in the method assertEquals(Object o1, Object o2).

So, you are definitely safe using assertEquals(string1, string2). (Because Strings are Objects)

Here is a link to a great Stackoverflow question regarding some of the differences between == and .equals().

How to tell a Mockito mock object to return something different the next time it is called?

For all who search to return something and then for another call throw exception:

when(mockFoo.someMethod())
        .thenReturn(obj1)
        .thenReturn(obj2)
        .thenThrow(new RuntimeException("Fail"));

or

when(mockFoo.someMethod())
        .thenReturn(obj1, obj2)
        .thenThrow(new RuntimeException("Fail"));

No tests found with test runner 'JUnit 4'

Very late but what solved the problem for me was that my test method names all started with captial letters: "public void Test". Making the t lower case worked.

Mockito : how to verify method was called on an object created within a method?

Yes, if you really want / need to do it you can use PowerMock. This should be considered a last resort. With PowerMock you can cause it to return a mock from the call to the constructor. Then do the verify on the mock. That said, csturtz's is the "right" answer.

Here is the link to Mock construction of new objects

Spring jUnit Testing properties file

As for the testing, you should use from Spring 4.1 which will overwrite the properties defined in other places:

@TestPropertySource("classpath:application-test.properties")

Test property sources have higher precedence than those loaded from the operating system's environment or Java system properties as well as property sources added by the application like @PropertySource

How to mock a final class with mockito

Add these dependencies for run mockito successfully :

testImplementation 'org.mockito:mockito-core:2.24.5'
testImplementation "org.mockito:mockito-inline:2.24.5"

Create a mocked list by mockito

We can mock list properly for foreach loop. Please find below code snippet and explanation.

This is my actual class method where I want to create test case by mocking list. this.nameList is a list object.

public void setOptions(){
    // ....
    for (String str : this.nameList) {
        str = "-"+str;
    }
    // ....
}

The foreach loop internally works on iterator, so here we crated mock of iterator. Mockito framework has facility to return pair of values on particular method call by using Mockito.when().thenReturn(), i.e. on hasNext() we pass 1st true and on second call false, so that our loop will continue only two times. On next() we just return actual return value.

@Test
public void testSetOptions(){
    // ...
    Iterator<SampleFilter> itr = Mockito.mock(Iterator.class);
    Mockito.when(itr.hasNext()).thenReturn(true, false);
    Mockito.when(itr.next()).thenReturn(Mockito.any(String.class);  

    List mockNameList = Mockito.mock(List.class);
    Mockito.when(mockNameList.iterator()).thenReturn(itr);
    // ...
}

In this way we can avoid sending actual list to test by using mock of list.

Why doesn't JUnit provide assertNotEquals methods?

I am working on JUnit in java 8 environment, using jUnit4.12

for me: compiler was not able to find the method assertNotEquals, even when I used
import org.junit.Assert;

So I changed
assertNotEquals("addb", string);
to
Assert.assertNotEquals("addb", string);

So if you are facing problem regarding assertNotEqual not recognized, then change it to Assert.assertNotEquals(,); it should solve your problem

Example of Mockito's argumentCaptor

The steps in order to make a full check are:

Prepare the captor :

ArgumentCaptor<SomeArgumentClass> someArgumentCaptor = ArgumentCaptor.forClass(SomeArgumentClass.class);

verify the call to dependent on component (collaborator of subject under test). times(1) is the default value, so ne need to add it.

verify(dependentOnComponent, times(1)).send(someArgumentCaptor.capture());

Get the argument passed to collaborator

SomeArgumentClass someArgument = messageCaptor.getValue();

someArgument can be used for assertions

JUNIT testing void methods

If it is possible in your case, you could make your methods method1(arg1) ... method7() protected instead of private so they could be accesible from test class within the same package. Then you can simply test all theese methods separately.

How do I mock a REST template exchange?

I implemented a small library that is quite useful. It provides a ClientHttpRequestFactory that can receive some context. By doing so, it allows to go through all client layers such as checking that query parameters are valued, headers set, and check that deserialization works well.

Easy way of running the same junit test over and over?

In JUnit 5 it is much simpler by using @RepeatedTest

@RepeatedTest is used to signal that the annotated method is a test template method that should be repeated a specified number of times.

    @RepeatedTest(3) // Runs N Times
    public void test_Prime() {
    }

More info on www.baeldung.com

Spring not autowiring in unit tests with JUnit

You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml available on the test classpath.

import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/testContext.xml"})
@Transactional
public class someDaoTest {

    @Autowired
    protected SessionFactory sessionFactory;

    @Test
    public void testDBSourceIsCorrect() throws SQLException {
        String databaseProductName = sessionFactory.getCurrentSession()
                .connection()
                .getMetaData()
                .getDatabaseProductName();
        assertThat("Test container is pointing at the wrong DB.", databaseProductName, startsWith("HSQL"));
    }
}

Note: This works with Spring 2.5.2 and Hibernate 3.6.5

Testing Private method using mockito

In cases where the private method is not void and the return value is used as a parameter to an external dependency's method, you can mock the dependency and use an ArgumentCaptor to capture the return value. For example:

ArgumentCaptor<ByteArrayOutputStream> csvOutputCaptor = ArgumentCaptor.forClass(ByteArrayOutputStream.class);
//Do your thing..
verify(this.awsService).uploadFile(csvOutputCaptor.capture());
....
assertEquals(csvOutputCaptor.getValue().toString(), "blabla");

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

I also had the same problem, I searched for the answers many places. I got many similar answers to change the number of process/service handlers. But I thought, what if I forgot to reset it back?

Then I tried using Thread.sleep() method after each of my connection.close();.

I don't know how, but it's working at least for me.

If any one wants to try it out and figure out how it's working then please go ahead. I would also like to know it as I am a beginner in programming world.

Java Project: Failed to load ApplicationContext

I had the same problem, and I was using the following plugin for tests:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.9</version>
    <configuration>
        <useFile>true</useFile>
        <includes>
            <include>**/*Tests.java</include>
            <include>**/*Test.java</include>
        </includes>
        <excludes>
            <exclude>**/Abstract*.java</exclude>
        </excludes>
        <junitArtifactName>junit:junit</junitArtifactName>
        <parallel>methods</parallel>
        <threadCount>10</threadCount>
    </configuration>
</plugin>

The test were running fine in the IDE (eclipse sts), but failed when using command mvn test.

After a lot of trial and error, I figured the solution was to remove parallel testing, the following two lines from the plugin configuration above:

    <parallel>methods</parallel>
    <threadCount>10</threadCount>

Hope that this helps someone out!

How to do a JUnit assert on a message in a logger

Effectively you are testing a side-effect of a dependent class. For unit testing you need only to verify that

logger.info()

was called with the correct parameter. Hence use a mocking framework to emulate logger and that will allow you to test your own class's behaviour.

Class Not Found Exception when running JUnit test

I had the same problem with a Gradle project with a test SourceSet with two resource directories.

This snippet comes from a main-module.gradle and adds a resource dir to the test SourceSet:

sourceSets {
    test {
        resources {
            srcDir('../other-module/src/test/resources')
        }
    }
}

Doing this I had two resource directories related to the test SourceSet of the project main-module:

../other-module/src/test/resources src/test/resources (relative to the main-module folder, automatically added by the java plugin)

I find out that if I had two files with the same name in both the source directories, something in the process resources stage went wrong. As result, no compilation started and for this reason no .class were copied in the bin directory, where JUnit was looking for the classes. The ClassNotFoundException disappeared just renaming one of the two files.

Log4j output not displayed in Eclipse console

Sounds like log4j picks up another configuration file than the one you think it does.

Put a breakpoint in log4j where the file is opened and have a look at the files getAbsolutePath().

'No JUnit tests found' in Eclipse

The solution was, after making a backup of the src/test folder, removing it from the filesystem, then creating it again.

That's after I did the "Remove from build path" hint and it screwed the folders when opening the project in STS 4.

What order are the Junit @Before/@After called?

You can use @BeforeClass annotation to assure that setup() is always called first. Similarly, you can use @AfterClass annotation to assure that tearDown() is always called last.

This is usually not recommended, but it is supported.

It's not exactly what you want - but it'll essentially keep your DB connection open the entire time your tests are running, and then close it once and for all at the end.

Warning: The method assertEquals from the type Assert is deprecated

this method also encounter a deprecate warning:

org.junit.Assert.assertEquals(float expected,float actual) //deprecated

It is because currently junit prefer a third parameter rather than just two float variables input.

The third parameter is delta:

public static void assertEquals(double expected,double actual,double delta) //replacement

this is mostly used to deal with inaccurate Floating point calculations

for more information, please refer this problem: Meaning of epsilon argument of assertEquals for double values

How to capture a list of specific type with mockito

List<String> mockedList = mock(List.class);

List<String> l = new ArrayList();
l.add("someElement");

mockedList.addAll(l);

ArgumentCaptor<List> argumentCaptor = ArgumentCaptor.forClass(List.class);

verify(mockedList).addAll(argumentCaptor.capture());

List<String> capturedArgument = argumentCaptor.<List<String>>getValue();

assertThat(capturedArgument, hasItem("someElement"));

How to verify a method is called two times with mockito verify()

build gradle:

testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"

code:

interface MyCallback {
  fun someMethod(value: String)
}

class MyTestableManager(private val callback: MyCallback){
  fun perform(){
    callback.someMethod("first")
    callback.someMethod("second")
    callback.someMethod("third")
  }
}

test:

import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.mock
...
val callback: MyCallback = mock()
val manager = MyTestableManager(callback)
manager.perform()

val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()

verify(callback, times(3)).someMethod(captor.capture())

assertTrue(captor.allValues[0] == "first")
assertTrue(captor.allValues[1] == "second")
assertTrue(captor.allValues[2] == "third")

Junit - run set up method once

Use Spring's @PostConstruct method to do all initialization work and this method runs before any of the @Test is executed

Hamcrest compare collections

Make sure that the Objects in your list have equals() defined on them. Then

assertThat(generatedList, is(equalTo(expectedList)));

works.

Rollback transaction after @Test

In addition to adding @Transactional on @Test method, you also need to add @Rollback(false)

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

Please see http://mvnrepository.com/artifact/javax.mail/mail/, you can download jar or use the maven dependency, depending on your project type. That should pretty much cover it and you won't get a NoClassDefFoundError exception.

Mockito How to mock and assert a thrown exception?

Using mockito, you can make the exception happen.

when(testingClassObj.testSomeMethod).thenThrow(new CustomException());

Using Junit5, you can assert exception, asserts whether that exception is thrown when testing method is invoked.

@Test
@DisplayName("Test assert exception")
void testCustomException(TestInfo testInfo) {
    final ExpectCustomException expectEx = new ExpectCustomException();

     InvalidParameterCountException exception = assertThrows(InvalidParameterCountException.class, () -> {
            expectEx.constructErrorMessage("sample ","error");
        });
    assertEquals("Invalid parametercount: expected=3, passed=2", exception.getMessage());
}

Find a sample here: assert exception junit

Checking that a List is not empty in Hamcrest

This works:

assertThat(list,IsEmptyCollection.empty())

Comparing arrays in JUnit assertions, concise built-in way?

Use org.junit.Assert's method assertArrayEquals:

import org.junit.Assert;
...

Assert.assertArrayEquals( expectedResult, result );

If this method is not available, you may have accidentally imported the Assert class from junit.framework.

Meaning of delta or epsilon argument of assertEquals for double values

Note that if you're not doing math, there's nothing wrong with asserting exact floating point values. For instance:

public interface Foo {
    double getDefaultValue();
}

public class FooImpl implements Foo {
    public double getDefaultValue() { return Double.MIN_VALUE; }
}

In this case, you want to make sure it's really MIN_VALUE, not zero or -MIN_VALUE or MIN_NORMAL or some other very small value. You can say

double defaultValue = new FooImpl().getDefaultValue();
assertEquals(Double.MIN_VALUE, defaultValue);

but this will get you a deprecation warning. To avoid that, you can call assertEquals(Object, Object) instead:

// really you just need one cast because of autoboxing, but let's be clear
assertEquals((Object)Double.MIN_VALUE, (Object)defaultValue);

And, if you really want to look clever:

assertEquals(
    Double.doubleToLongBits(Double.MIN_VALUE), 
    Double.doubleToLongBits(defaultValue)
);

Or you can just use Hamcrest fluent-style assertions:

// equivalent to assertEquals((Object)Double.MIN_VALUE, (Object)defaultValue);
assertThat(defaultValue, is(Double.MIN_VALUE));

If the value you're checking does come from doing some math, though, use the epsilon.

How to run test methods in specific order in JUnit4?

See my solution here: "Junit and java 7."

In this article I describe how to run junit tests in order - "just as in your source code". Tests will be run, in order as your test methods appears in class file.

http://intellijava.blogspot.com/2012/05/junit-and-java-7.html

But as Pascal Thivent said, this is not a good practise.

How to use ArgumentCaptor for stubbing?

The line

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);

would do the same as

when(someObject.doSomething(Matchers.any())).thenReturn(true);

So, using argumentCaptor.capture() when stubbing has no added value. Using Matchers.any() shows better what really happens and therefor is better for readability. With argumentCaptor.capture(), you can't read what arguments are really matched. And instead of using any(), you can use more specific matchers when you have more information (class of the expected argument), to improve your test.

And another problem: If using argumentCaptor.capture() when stubbing it becomes unclear how many values you should expect to be captured after verification. We want to capture a value during verification, not during stubbing because at that point there is no value to capture yet. So what does the argument captors capture method capture during stubbing? It capture anything because there is nothing to be captured yet. I consider it to be undefined behavior and I don't want to use undefined behavior.

Assert equals between 2 Lists in Junit

I don't this the all the above answers are giving the exact solution for comparing two lists of Objects. Most of above approaches can be helpful in following limit of comparisons only - Size comparison - Reference comparison

But if we have same sized lists of objects and different data on the objects level then this comparison approaches won't help.

I think the following approach will work perfectly with overriding equals and hashcode method on the user-defined object.

I used Xstream lib for override equals and hashcode but we can override equals and hashcode by out won logics/comparison too.

Here is the example for your reference

    import com.thoughtworks.xstream.XStream;

    import java.text.ParseException;
    import java.util.ArrayList;
    import java.util.List;

    class TestClass {
      private String name;
      private String id;

      public void setName(String value) {
        this.name = value;
      }

      public String getName() {
        return this.name;
      }

      public String getId() {
        return id;
      }

      public void setId(String id) {
        this.id = id;
      }

      /**
       * @see java.lang.Object#equals(java.lang.Object)
       */
      @Override
      public boolean equals(Object o) {
        XStream xstream = new XStream();
        String oxml = xstream.toXML(o);
        String myxml = xstream.toXML(this);

        return myxml.equals(oxml);
      }

      /**
       * @see java.lang.Object#hashCode()
       */
      @Override
      public int hashCode() {
        XStream xstream = new XStream();
        String myxml = xstream.toXML(this);
        return myxml.hashCode();
      }
    }

    public class XstreamCompareTest {
      public static void main(String[] args) throws ParseException {
      checkObjectEquals();
}

      private static void checkObjectEquals() {
        List<TestClass> testList1 = new ArrayList<TestClass>();
        TestClass tObj1 = new TestClass();
        tObj1.setId("test3");
        tObj1.setName("testname3");
        testList1.add(tObj1);

        TestClass tObj2 = new TestClass();
        tObj2.setId("test2");
        tObj2.setName("testname2");
        testList1.add(tObj2);

        testList1.sort((TestClass t1, TestClass t2) -> t1.getId().compareTo(t2.getId()));

        List<TestClass> testList2 = new ArrayList<TestClass>();
        TestClass tObj3 = new TestClass();
        tObj3.setId("test3");
        tObj3.setName("testname3");
        testList2.add(tObj3);

        TestClass tObj4 = new TestClass();
        tObj4.setId("test2");
        tObj4.setName("testname2");
        testList2.add(tObj4);

        testList2.sort((TestClass t1, TestClass t2) -> t1.getId().compareTo(t2.getId()));

        if (isNotMatch(testList1, testList2)) {
          System.out.println("The list are not matched");
        } else {
          System.out.println("The list are matched");
        }

      }

      private static boolean isNotMatch(List<TestClass> clist1, List<TestClass> clist2) {
        return clist1.size() != clist2.size() || !clist1.equals(clist2);
      }
    }

The most important thing is that you can ignore the fields by Annotation (@XStreamOmitField) if you don't want to include any fields on the equal check of Objects. There are many Annotations like this to configure so have a look deep about the annotations of this lib.

I am sure this answer will save your time to identify the correct approach for comparing two lists of objects :). Please comment if you see any issues on this.

Spring - applicationContext.xml cannot be opened because it does not exist

You should keep your Spring files in another folder, marked as "source" (just like "src" or "resources").

WEB-INF is not a source folder, therefore it will not be included in the classpath (i.e. JUnit will not look for anything there).

java.lang.NoClassDefFoundError in junit

These steps worked for me when the error showed that the Filter class was missing (as reported in this false-diplicated question: JUnit: NoClassDefFoundError: org/junit/runner/manipulation/Filter ):

  1. Make sure to have JUnit 4 referenced only once in your project (I also removed the Maven nature, but I am not sure if this step has any influence in solving the problem).
  2. Right click the file containing unit tests, select Properties, and under the Run/Debug settings, remove any entries from the Launch Configurations for that file. Hit Apply and close.
  3. Right click the project containing unit tests, select Properties, and under the Run/Debug settings, remove any entries involving JUnit from the Launch Configurations. Hit Apply and close.
  4. Clean the project, and run the test.

Thanks to these answers for giving me the hint for this solution: https://stackoverflow.com/a/34067333/5538923 and https://stackoverflow.com/a/39987979/5538923).

How to test my servlet using JUnit

Updated Feb 2018: OpenBrace Limited has closed down, and its ObMimic product is no longer supported.

Here's another alternative, using OpenBrace's ObMimic library of Servlet API test-doubles (disclosure: I'm its developer).

package com.openbrace.experiments.examplecode.stackoverflow5434419;

import static org.junit.Assert.*;
import com.openbrace.experiments.examplecode.stackoverflow5434419.YourServlet;
import com.openbrace.obmimic.mimic.servlet.ServletConfigMimic;
import com.openbrace.obmimic.mimic.servlet.http.HttpServletRequestMimic;
import com.openbrace.obmimic.mimic.servlet.http.HttpServletResponseMimic;
import com.openbrace.obmimic.substate.servlet.RequestParameters;
import org.junit.Before;
import org.junit.Test;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Example tests for {@link YourServlet#doPost(HttpServletRequest,
 * HttpServletResponse)}.
 *
 * @author Mike Kaufman, OpenBrace Limited
 */
public class YourServletTest {

    /** The servlet to be tested by this instance's test. */
    private YourServlet servlet;

    /** The "mimic" request to be used in this instance's test. */
    private HttpServletRequestMimic request;

    /** The "mimic" response to be used in this instance's test. */
    private HttpServletResponseMimic response;

    /**
     * Create an initialized servlet and a request and response for this
     * instance's test.
     *
     * @throws ServletException if the servlet's init method throws such an
     *     exception.
     */
    @Before
    public void setUp() throws ServletException {
        /*
         * Note that for the simple servlet and tests involved:
         * - We don't need anything particular in the servlet's ServletConfig.
         * - The ServletContext isn't relevant, so ObMimic can be left to use
         *   its default ServletContext for everything.
         */
        servlet = new YourServlet();
        servlet.init(new ServletConfigMimic());
        request = new HttpServletRequestMimic();
        response = new HttpServletResponseMimic();
    }

    /**
     * Test the doPost method with example argument values.
     *
     * @throws ServletException if the servlet throws such an exception.
     * @throws IOException if the servlet throws such an exception.
     */
    @Test
    public void testYourServletDoPostWithExampleArguments()
            throws ServletException, IOException {

        // Configure the request. In this case, all we need are the three
        // request parameters.
        RequestParameters parameters
            = request.getMimicState().getRequestParameters();
        parameters.set("username", "mike");
        parameters.set("password", "xyz#zyx");
        parameters.set("name", "Mike");

        // Run the "doPost".
        servlet.doPost(request, response);

        // Check the response's Content-Type, Cache-Control header and
        // body content.
        assertEquals("text/html; charset=ISO-8859-1",
            response.getMimicState().getContentType());
        assertArrayEquals(new String[] { "no-cache" },
            response.getMimicState().getHeaders().getValues("Cache-Control"));
        assertEquals("...expected result from dataManager.register...",
            response.getMimicState().getBodyContentAsString());

    }

}

Notes:

  • Each "mimic" has a "mimicState" object for its logical state. This provides a clear distinction between the Servlet API methods and the configuration and inspection of the mimic's internal state.

  • You might be surprised that the check of Content-Type includes "charset=ISO-8859-1". However, for the given "doPost" code this is as per the Servlet API Javadoc, and the HttpServletResponse's own getContentType method, and the actual Content-Type header produced on e.g. Glassfish 3. You might not realise this if using normal mock objects and your own expectations of the API's behaviour. In this case it probably doesn't matter, but in more complex cases this is the sort of unanticipated API behaviour that can make a bit of a mockery of mocks!

  • I've used response.getMimicState().getContentType() as the simplest way to check Content-Type and illustrate the above point, but you could indeed check for "text/html" on its own if you wanted (using response.getMimicState().getContentTypeMimeType()). Checking the Content-Type header the same way as for the Cache-Control header also works.

  • For this example the response content is checked as character data (with this using the Writer's encoding). We could also check that the response's Writer was used rather than its OutputStream (using response.getMimicState().isWritingCharacterContent()), but I've taken it that we're only concerned with the resulting output, and don't care what API calls produced it (though that could be checked too...). It's also possible to retrieve the response's body content as bytes, examine the detailed state of the Writer/OutputStream etc.

There are full details of ObMimic and a free download at the OpenBrace website. Or you can contact me if you have any questions (contact details are on the website).

JUnit assertEquals(double expected, double actual, double epsilon)

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

Cause of No suitable driver found for

I was facing similar problem and to my surprise the problem was in the version of Java. java.sql.DriverManager comes from rt.jar was unable to load my driver "COM.ibm.db2.jdbc.app.DB2Driver".

I upgraded from jdk 5 and jdk 6 and it worked.

How to create unit tests easily in eclipse

To create a test case template:

"New" -> "JUnit Test Case" -> Select "Class under test" -> Select "Available methods". I think the wizard is quite easy for you.

How to use JUnit to test asynchronous processes

IMHO it's bad practice to have unit tests create or wait on threads, etc. You'd like these tests to run in split seconds. That's why I'd like to propose a 2-step approach to testing async processes.

  1. Test that your async process is submitted properly. You can mock the object that accepts your async requests and make sure that the submitted job has correct properties, etc.
  2. Test that your async callbacks are doing the right things. Here you can mock out the originally submitted job and assume it's initialized properly and verify that your callbacks are correct.

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

As of July, 2020 the following dependencies in pom.xml worked for me:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
</dependency>
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest</artifactId>
    <version>2.1</version>
</dependency>

With this 4.13 junit library and hamcrest, it uses hamcrest.MatcherAssert when asserting and throws exception- enter image description here

Assert an object is a specific type

Since assertThat which was the old answer is now deprecated, I am posting the correct solution:

assertTrue(objectUnderTest instanceof TargetObject);

annotation to make a private method public only for test classes

As much as I know there is no annotation like this. The best way is to use reflection as some of the others suggested. Look at this post:
How do I test a class that has private methods, fields or inner classes?

You should only watch out on testing the exception outcome of the method. For example: if u expect an IllegalArgumentException, but instead you'll get "null" (Class:java.lang.reflect.InvocationTargetException).
A colegue of mine proposed using the powermock framework for these situations, but I haven't tested it yet, so no idea what exactly it can do. Although I have used the Mockito framework that it is based upon and thats a good framework too (but I think doesn't solve the private method exception issue).

It's a great idea though having the @PublicForTests annotation.

Cheers!

Eclipse - debugger doesn't stop at breakpoint

Fix could be as simple as clicking run/skip all breakpoints. Worked for me.

How can I make a JUnit test wait?

You can use java.util.concurrent.TimeUnit library which internally uses Thread.sleep. The syntax should look like this :

@Test
public void testExipres(){
    SomeCacheObject sco = new SomeCacheObject();
    sco.putWithExipration("foo", 1000);

    TimeUnit.MINUTES.sleep(2);

    assertNull(sco.getIfNotExipred("foo"));
}

This library provides more clear interpretation for time unit. You can use 'HOURS'/'MINUTES'/'SECONDS'.

Configuring IntelliJ IDEA for unit testing with JUnit

If you already have a test class, but missing the JUnit library dependency, please refer to Configuring Libraries for Unit Testing documentation section. Pressing Alt+Enter on the red code should give you an intention action to add the missing jar.

However, IDEA offers much more. If you don't have a test class yet and want to create one for any of the source classes, see instructions below.

You can use the Create Test intention action by pressing Alt+Enter while standing on the name of your class inside the editor or by using Ctrl+Shift+T keyboard shortcut.

A dialog appears where you select what testing framework to use and press Fix button for the first time to add the required library jars to the module dependencies. You can also select methods to create the test stubs for.

Create Test Intention

Create Test Dialog

You can find more details in the Testing help section of the on-line documentation.

Resource files not found from JUnit test cases

My mistake, the resource files WERE actually copied to target/test-classes. The problem seemed to be due to spaces in my project name, e.g. Project%20Name.

I'm now loading the file as follows and it works:

org.apache.commons.io.FileUtils.toFile(myClass().getResource("resourceFile.txt")??);

Or, (taken from Java: how to get a File from an escaped URL?) this may be better (no dependency on Apache Commons):

myClass().getResource("resourceFile.txt")??.toURI();

Spring JUnit: How to Mock autowired component in autowired component

You can provide a new testContext.xml in which the @Autowired bean you define is of the type you need for your test.

How to resolve Unneccessary Stubbing exception

Well, In my case Mockito error was telling me to call the actual method after the when or whenever stub. Since we were not invoking the conditions that we just mocked, Mockito was reporting that as unnecessary stubs or code.

Here is what it was like when the error was coming :

@Test
fun `should return error when item list is empty for getStockAvailability`() {
    doAnswer(
        Answer<Void> { invocation ->
            val callback =
                invocation.arguments[1] as GetStockApiCallback<StockResultViewState.Idle, StockResultViewState.Error>
            callback.onApiCallError(stockResultViewStateError)
            null
        }
    ).whenever(stockViewModelTest)
        .getStockAvailability(listOf(), getStocksApiCallBack)
}

then I just called the actual method mentioned in when statement to mock the method.

changes done is as below stockViewModelTest.getStockAvailability(listOf(), getStocksApiCallBack)

@Test
fun `should return error when item list is empty for getStockAvailability`() {
    doAnswer(
        Answer<Void> { invocation ->
            val callback =
                invocation.arguments[1] as GetStockApiCallback<StockResultViewState.Idle, StockResultViewState.Error>
            callback.onApiCallError(stockResultViewStateError)
            null
        }
    ).whenever(stockViewModelTest)
        .getStockAvailability(listOf(), getStocksApiCallBack)
    //called the actual method here
    stockViewModelTest.getStockAvailability(listOf(), getStocksApiCallBack)
}

it's working now.

Test class with a new() call in it with Mockito

In situations where the class under test can be modified and when it's desirable to avoid byte code manipulation, to keep things fast or to minimise third party dependencies, here is my take on the use of a factory to extract the new operation.

public class TestedClass {

    interface PojoFactory { Pojo getNewPojo(); }

    private final PojoFactory factory;

    /** For use in production - nothing needs to change. */
    public TestedClass() {
        this.factory = new PojoFactory() {
            @Override
            public Pojo getNewPojo() {
                return new Pojo();
            }
        };
    }

    /** For use in testing - provide a pojo factory. */
    public TestedClass(PojoFactory factory) {
        this.factory = factory;
    }

    public void doSomething() {
        Pojo pojo = this.factory.getNewPojo();
        anythingCouldHappen(pojo);
    }
}

With this in place, your testing, asserts and verify calls on the Pojo object are easy:

public  void testSomething() {
    Pojo testPojo = new Pojo();
    TestedClass target = new TestedClass(new TestedClass.PojoFactory() {
                @Override
                public Pojo getNewPojo() {
                    return testPojo;
                }
            });
    target.doSomething();
    assertThat(testPojo.isLifeStillBeautiful(), is(true));
}

The only downside to this approach potentially arises if TestClass has multiple constructors which you'd have to duplicate with the extra parameter.

For SOLID reasons you'd probably want to put the PojoFactory interface onto the Pojo class instead, and the production factory as well.

public class Pojo {

    interface PojoFactory { Pojo getNewPojo(); }

    public static final PojoFactory productionFactory = 
        new PojoFactory() {
            @Override 
            public Pojo getNewPojo() {
                return new Pojo();
            }
        };

Conditionally ignoring tests in JUnit 4

Additionally to the answer of @tkruse and @Yishai:
I do this way to conditionally skip test methods especially for Parameterized tests, if a test method should only run for some test data records.

public class MyTest {
    // get current test method
    @Rule public TestName testName = new TestName();
    
    @Before
    public void setUp() {
        org.junit.Assume.assumeTrue(new Function<String, Boolean>() {
          @Override
          public Boolean apply(String testMethod) {
            if (testMethod.startsWith("testMyMethod")) {
              return <some condition>;
            }
            return true;
          }
        }.apply(testName.getMethodName()));
        
        ... continue setup ...
    }
}

How to test abstract class in Java with JUnit?

My way of testing this is quite simple, within each abstractUnitTest.java. I simply create a class in the abstractUnitTest.java that extend the abstract class. And test it that way.

JUnit: how to avoid "no runnable methods" in test utils classes

In your test class if wrote import org.junit.jupiter.api.Test; delete it and write import org.junit.Test; In this case it worked me as well.

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

A few steps you have to follow:

  1. Right click on the project.
  2. Choose Build Path Then from its menu choose Add Libraries.
  3. Choose JUnit then click Next.
  4. Choose JUnit4 then Finish.

Junit test case for database insert method with DAO and web service

/*

public class UserDAO {

public boolean insertUser(UserBean u) {
    boolean flag = false;
    MySqlConnection msq = new MySqlConnection();
    try {

        String sql = "insert into regis values(?,?,?,?,?)";

        Connection connection = msq.getConnection();
        PreparedStatement statement = null;
        statement = (PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, u.getname());
        statement.setString(2, u.getlname());
        statement.setString(3, u.getemail());
        statement.setString(4, u.getusername());
        statement.setString(5, u.getpasswords());
        statement.executeUpdate();

        flag = true;
    } catch (Exception e) {
    } finally {
        return flag;
    }

}

public String userValidate(UserBean u) {
    String login = "";
    MySqlConnection msq = new MySqlConnection();
    try {
        String email = u.getemail();
        String Pass = u.getpasswords();

        String sql = "SELECT name FROM regis WHERE email=? and passwords=?";
        com.mysql.jdbc.Connection connection = msq.getConnection();
        com.mysql.jdbc.PreparedStatement statement = null;
        ResultSet rs = null;
        statement = (com.mysql.jdbc.PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, email);
        statement.setString(2, Pass);
        rs = statement.executeQuery();
        if (rs.next()) {
            login = rs.getString("name");
        } else {
            login = "false";
        }

    } catch (Exception e) {
    } finally {
        return login;
    }
}

public boolean getmessage(UserBean u) {
    boolean flag = false;
    MySqlConnection msq = new MySqlConnection();
    try {


        String sql = "insert into feedback values(?,?)";

        Connection connection = msq.getConnection();
        PreparedStatement statement = null;
        statement = (PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, u.getemail());
        statement.setString(2, u.getfeedback());
        statement.executeUpdate();

        flag = true;
    } catch (Exception e) {
    } finally {
        return flag;
    }

}

public boolean insertOrder(cartbean u) {
    boolean flag = false;
    MySqlConnection msq = new MySqlConnection();
    try {

        String sql = "insert into cart (product_id, email, Tprice, quantity) values (?,?,2000,?)";

        Connection connection = msq.getConnection();
        PreparedStatement statement = null;
        statement = (PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, u.getpid());
        statement.setString(2, u.getemail());
        statement.setString(3, u.getquantity());

        statement.executeUpdate();

        flag = true;
    } catch (Exception e) {
        System.out.print("hi");
    } finally {
        return flag;
    }

}

}

Maven 3 and JUnit 4 compilation problem: package org.junit does not exist

@Dennis Roberts: You were absolutely right: My test class was located in src/main/java. Also the value of the "scope" element in the POM for JUnit was "test", although that is how it is supposed to be. The problem was that I had been sloppy when creating the test class in Eclipse, resulting in it being created in src/main/java insted of src/test/java. This became easier to see in Eclipse's Project Explorer view after running "mvn eclipse:eclipse", but your comment was what made me see it first. Thanks.

Spring profiles and testing

The best approach here is to remove @ActiveProfiles annotation and do the following:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
    TestPreperationExecutionListener.class
    })
@Transactional
@ContextConfiguration(locations = {
    "classpath:config/test-context.xml" })
public class TestContext {

  @BeforeClass
  public static void setSystemProperty() {
        Properties properties = System.getProperties();
        properties.setProperty("spring.profiles.active", "localtest");
  }

  @AfterClass
  public static void unsetSystemProperty() {
        System.clearProperty("spring.profiles.active");
  }

  @Test
  public void testContext(){

  }
}

And your test-context.xml should have the following:

<context:property-placeholder 
  location="classpath:META-INF/spring/config_${spring.profiles.active}.properties"/>

How to mock private method for testing using PowerMock?

For some reason Brice's answer is not working for me. I was able to manipulate it a bit to get it to work. It might just be because I have a newer version of PowerMock. I'm using 1.6.5.

import java.util.Random;

public class CodeWithPrivateMethod {

    public void meaningfulPublicApi() {
        if (doTheGamble("Whatever", 1 << 3)) {
            throw new RuntimeException("boom");
        }
    }

    private boolean doTheGamble(String whatever, int binary) {
        Random random = new Random(System.nanoTime());
        boolean gamble = random.nextBoolean();
        return gamble;
    }
}

The test class looks as follows:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.doReturn;

@RunWith(PowerMockRunner.class)
@PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {
    private CodeWithPrivateMethod classToTest;

    @Test(expected = RuntimeException.class)
    public void when_gambling_is_true_then_always_explode() throws Exception {
        classToTest = PowerMockito.spy(classToTest);

        doReturn(true).when(classToTest, "doTheGamble", anyString(), anyInt());

        classToTest.meaningfulPublicApi();
    }
}

Mockito: Trying to spy on method is calling the original method

One way to make sure a method from a class is not called is to override the method with a dummy.

    WebFormCreatorActivity activity = spy(new WebFormCreatorActivity(clientFactory) {//spy(new WebFormCreatorActivity(clientFactory));
            @Override
            public void select(TreeItem i) {
                log.debug("SELECT");
            };
        });

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

I have added a Maven/Java project with 1 Domain class with the following features:

  • Unit or Integration testing with the plugins Surefire and Failsafe.
  • Findbugs.
  • Test coverage via Jacoco.

Where are the Jacoco results? After testing and running 'mvn clean', you can find the results in 'target/site/jacoco/index.html'. Open this file in the browser.

Enjoy!

I tried to keep the project as simple as possible. The project puts many suggestions from these posts together in an example project. Thank you, contributors!

AssertContains on strings in jUnit

assertj variant

import org.assertj.core.api.Assertions;
Assertions.assertThat(actualStr).contains(subStr);

How to set JVM parameters for Junit Unit Tests?

You can use systemPropertyVariables (java.protocol.handler.pkgs is your JVM argument name):

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.12.4</version>
    <configuration>
        <systemPropertyVariables>
            <java.protocol.handler.pkgs>com.zunix.base</java.protocol.handler.pkgs>
            <log4j.configuration>log4j-core.properties</log4j.configuration>
        </systemPropertyVariables>
    </configuration>
</plugin>

http://maven.apache.org/surefire/maven-surefire-plugin/examples/system-properties.html

JUnit Testing Exceptions

@Test(expected = Exception.class)  

Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.

For

@Test

Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.

JUnit 4 compare Sets

As an additional method that is array based ... you can consider using unordered array assertions in junitx . Although the Apache CollectionUtils example will work, there is a pacakge of solid assertion extensions there as well :

I think that the

ArrayAssert.assertEquivalenceArrays(new Integer[]{1,2,3}, new Integer[]{1,3,2});

approach will be much more readable and debuggable for you (all Collections support toArray(), so it should be easy enough to use the ArrayAssert methods.

Of course the downside here is that, junitx is an additional jar file or maven entry...

 <dependency org="junit-addons" name="junit-addons" rev="1.4"/>

How do I assert equality on two classes without an equals method?

Since this question is old, I will suggest another modern approach using JUnit 5.

I don't like this solution because I don't get the full equality picture if an early assert fails.

With JUnit 5, there is a method called Assertions.assertAll() which will allow you to group all assertions in your test together and it will execute each one and output any failed assertions at the end. This means that any assertions that fail first will not stop the execution of latter assertions.

assertAll("Test obj1 with obj2 equality",
    () -> assertEquals(obj1.getFieldA(), obj2.getFieldA()),
    () -> assertEquals(obj1.getFieldB(), obj2.getFieldB()),
    () -> assertEquals(obj1.getFieldC(), obj2.getFieldC()));

Class has no member named

I had similar problem. My header file which included the definition of the class wasn't working. I wasn't able to use the member functions of that class. So i simply copied my class to another header file. Now its working all ok.

How to maximize a plt.show() window using Python

This makes the window take up the full screen for me, under Ubuntu 12.04 with the TkAgg backend:

    mng = plt.get_current_fig_manager()
    mng.resize(*mng.window.maxsize())

Oracle select most recent date record

i think i'd try with MAX something like this:

SELECT staff_id, max( date ) from owner.table group by staff_id

then link in your other columns:

select staff_id, site_id, pay_level, latest
from owner.table, 
(   SELECT staff_id, max( date ) latest from owner.table group by staff_id ) m
where m.staff_id = staff_id
and m.latest = date

Failed to resolve: com.google.firebase:firebase-core:9.0.0

In my case, on top of adding google() in repositories for the project level gradle file, I had to also include it in the app level gradle file.

repositories {
    mavenLocal()
    google()
    flatDir {
        dirs 'libs'
    }
}

Cross compile Go on OSX?

If you use Homebrew on OS X, then you have a simpler solution:

$ brew install go --with-cc-common # Linux, Darwin, and Windows

or..

$ brew install go --with-cc-all # All the cross-compilers

Use reinstall if you already have go installed.

How to escape strings in SQL Server using PHP?

function ms_escape_string($data) {
        if ( !isset($data) or empty($data) ) return '';
        if ( is_numeric($data) ) return $data;

        $non_displayables = array(
            '/%0[0-8bcef]/',            // url encoded 00-08, 11, 12, 14, 15
            '/%1[0-9a-f]/',             // url encoded 16-31
            '/[\x00-\x08]/',            // 00-08
            '/\x0b/',                   // 11
            '/\x0c/',                   // 12
            '/[\x0e-\x1f]/'             // 14-31
        );
        foreach ( $non_displayables as $regex )
            $data = preg_replace( $regex, '', $data );
        $data = str_replace("'", "''", $data );
        return $data;
    }

Some of the code here was ripped off from CodeIgniter. Works well and is a clean solution.

EDIT: There are plenty of issues with that code snippet above. Please don't use this without reading the comments to know what those are. Better yet, please don't use this at all. Parameterized queries are your friends: http://php.net/manual/en/pdo.prepared-statements.php

How to execute a MySQL command from a shell script?

Use this syntax:

mysql -u $user -p$passsword -Bse "command1;command2;....;commandn"

Error Code: 2013. Lost connection to MySQL server during query

Try please to uncheck limit rows in in Edit ? Preferences ?SQL Queries

because You should set the 'interactive_timeout' and 'wait_timeout' properties in the mysql config file to the values you need.

'git' is not recognized as an internal or external command

This helps for me : I set C:\Program Files (x86)\Git\bin;C:\Program Files (x86)\Git\cmd in path for environment variable.

How to copy files from 'assets' folder to sdcard?

You can also use Guava's ByteStream to copy the files from the assets folder to the SD card. This is the solution I ended up with which copies files recursively from the assets folder to the SD card:

/**
 * Copies all assets in an assets directory to the SD file system.
 */
public class CopyAssetsToSDHelper {

    public static void copyAssets(String assetDir, String targetDir, Context context) 
        throws IOException {
        AssetManager assets = context.getAssets();
        String[] list = assets.list(assetDir);
        for (String f : Objects.requireNonNull(list)) {
            if (f.indexOf(".") > 1) { // check, if this is a file
                File outFile = new File(context.getExternalFilesDir(null), 
                    String.format("%s/%s", targetDir, f));
                File parentFile = outFile.getParentFile();
                if (!Objects.requireNonNull(parentFile).exists()) {
                    if (!parentFile.mkdirs()) {
                        throw new IOException(String.format("Could not create directory %s.", 
                            parentFile));
                    }
                }
                try (InputStream fin = assets.open(String.format("%s/%s", assetDir, f));
                     OutputStream fout = new FileOutputStream(outFile)) {
                    ByteStreams.copy(fin, fout);
                }
            } else { // This is a directory
                copyAssets(String.format("%s/%s", assetDir, f), String.format("%s/%s", targetDir, f), 
                    context);
            }
        }
    }

}

"Untrusted App Developer" message when installing enterprise iOS Application

On iOS 9:

Settings -> General -> Device Management -> Developer app / your Apple ID -> Add/remove trust there

Convert string to decimal, keeping fractions

Hello i was have the same issue, but it is easly, just do this:

string cadena="96.23";

decimal NoDecimal=decimal.parse(cadena.replace(".",","))

I think this is beacuse the notation that accept C# on decimal numbers are with a ","

Ubuntu apt-get unable to fetch packages

I got this issue when the Virtualbox had the wrong networking. I've updated to NAT and was able to get on internet and download packages from us.archive.ubuntu.com

In Linux, how to tell how much memory processes are using?

The tool you want is ps. To get information about what java programs are doing:

ps -F -C java 

To get information about http:

ps -F -C httpd

If your program is ending before you get a chance to run these, open another terminal and run:

while true; do ps -F -C myCoolCode ; sleep 0.5s ; done

Missing styles. Is the correct theme chosen for this layout?

Try switching the theme in the design view to one of the options in "Manifest Themes". I'm guessing this is Because you are inheriting the theme from the manifest to support multiple api levels. It worked for me anyway.

Quick way to list all files in Amazon S3 bucket?

In PHP you can get complete list of AWS-S3 objects inside specific bucket using following call

$S3 = \Aws\S3\S3Client::factory(array('region' => $region,));
$iterator = $S3->getIterator('ListObjects', array('Bucket' => $bucket));
foreach ($iterator as $obj) {
    echo $obj['Key'];
}

You can redirect output of the above code in to a file to get list of keys.

How to set the background image of a html 5 canvas to .png image

As shown in this example, you can apply a background to a canvas element through CSS and this background will not be considered part the image, e.g. when fetching the contents through toDataURL().

Here are the contents of the example, for Stack Overflow posterity:

<!DOCTYPE HTML>
<html><head>
  <meta charset="utf-8">
  <title>Canvas Background through CSS</title>
  <style type="text/css" media="screen">
    canvas, img { display:block; margin:1em auto; border:1px solid black; }
    canvas { background:url(lotsalasers.jpg) }
  </style>
</head><body>
<canvas width="800" height="300"></canvas>
<img>
<script type="text/javascript" charset="utf-8">
  var can = document.getElementsByTagName('canvas')[0];
  var ctx = can.getContext('2d');
  ctx.strokeStyle = '#f00';
  ctx.lineWidth   = 6;
  ctx.lineJoin    = 'round';
  ctx.strokeRect(140,60,40,40);
  var img = document.getElementsByTagName('img')[0];
  img.src = can.toDataURL();
</script>
</body></html>

C++ - how to find the length of an integer

The number of digits of an integer n in any base is trivially obtained by dividing until you're done:

unsigned int number_of_digits = 0;

do {
     ++number_of_digits; 
     n /= base;
} while (n);

jQuery first child of "this"

If you want immediate first child you need

    $(element).first();

If you want particular first element in the dom from your element then use below

    var spanElement = $(elementId).find(".redClass :first");
    $(spanElement).addClass("yourClassHere");

try out : http://jsfiddle.net/vgGbc/2/

Why is processing a sorted array faster than processing an unsorted array?

In the sorted case, you can do better than relying on successful branch prediction or any branchless comparison trick: completely remove the branch.

Indeed, the array is partitioned in a contiguous zone with data < 128 and another with data >= 128. So you should find the partition point with a dichotomic search (using Lg(arraySize) = 15 comparisons), then do a straight accumulation from that point.

Something like (unchecked)

int i= 0, j, k= arraySize;
while (i < k)
{
  j= (i + k) >> 1;
  if (data[j] >= 128)
    k= j;
  else
    i= j;
}
sum= 0;
for (; i < arraySize; i++)
  sum+= data[i];

or, slightly more obfuscated

int i, k, j= (i + k) >> 1;
for (i= 0, k= arraySize; i < k; (data[j] >= 128 ? k : i)= j)
  j= (i + k) >> 1;
for (sum= 0; i < arraySize; i++)
  sum+= data[i];

A yet faster approach, that gives an approximate solution for both sorted or unsorted is: sum= 3137536; (assuming a truly uniform distribution, 16384 samples with expected value 191.5) :-)

How do you append rows to a table using jQuery?

Try:

$("#myTable").append("<tr><%= escape_javascript( render :partial => name_of_partial ) %></tr>");

And in the partial, you should have:

<td>row1</td>
<td>row2</td>

Remove by _id in MongoDB console

Very close. This will work:

db.test_users.deleteOne( {"_id": ObjectId("4d512b45cc9374271b02ec4f")});

i.e. you don't need a new for the ObjectId.

Also, note that in some drivers/tools, remove() is now deprecated and deleteOne or deleteMany should be used instead.

Apply function to each column in a data frame observing each columns existing data type

df <- head(mtcars)
df$string <- c("a","b", "c", "d","e", "f"); df

my.min <- unlist(lapply(df, min))
my.max <- unlist(lapply(df, max))

App.Config file in console application C#

For .NET Core, add System.Configuration.ConfigurationManager from NuGet manager.
And read appSetting from App.config

<appSettings>
  <add key="appSetting1" value="1000" />
</appSettings>

Add System.Configuration.ConfigurationManager from NuGet Manager

enter image description here

ConfigurationManager.AppSettings.Get("appSetting1")

Rails migration for change column

I'm not aware if you can create a migration from the command line to do all this, but you can create a new migration, then edit the migration to perform this taks.

If tablename is the name of your table, fieldname is the name of your field and you want to change from a datetime to date, you can write a migration to do this.

You can create a new migration with:

rails g migration change_data_type_for_fieldname

Then edit the migration to use change_table:

class ChangeDataTypeForFieldname < ActiveRecord::Migration
  def self.up
    change_table :tablename do |t|
      t.change :fieldname, :date
    end
  end
  def self.down
    change_table :tablename do |t|
      t.change :fieldname, :datetime
    end
  end
end

Then run the migration:

rake db:migrate

Generate Controller and Model

php artisan make:controller --resource Backend/API/DemoController --model=Demo

adding and removing classes in angularJs using ng-click

I want to add or remove "active" class in my code dynamically on ng-click, here what I have done.

<ul ng-init="selectedTab = 'users'">
   <li ng-class="{'active':selectedTab === 'users'}" ng-click="selectedTab = 'users'"><a href="#users" >Users</a></li>
   <li ng-class="{'active':selectedTab === 'items'}" ng-click="selectedTab = 'items'"><a href="#items" >Items</a></li>
</ul>

Validate a username and password against Active Directory?

My Simple Function

 private bool IsValidActiveDirectoryUser(string activeDirectoryServerDomain, string username, string password)
    {
        try
        {
            DirectoryEntry de = new DirectoryEntry("LDAP://" + activeDirectoryServerDomain, username + "@" + activeDirectoryServerDomain, password, AuthenticationTypes.Secure);
            DirectorySearcher ds = new DirectorySearcher(de);
            ds.FindOne();
            return true;
        }
        catch //(Exception ex)
        {
            return false;
        }
    }

Questions every good PHP Developer should be able to answer

I'd ask something like:

a) what about caching?

b) how can cache be organised?

c) are you sure, you do not do extra DB queries? (In my first stuff I've made on PHP it was a mysql_query inside foreach to get names of users who've made comments... terrible :) )

d) why register_globals is evil?

e) why and how you should split view from code?

f) what is the main aim of "implement"?

Here are questions that were not clear at all for me after I've read some basic books. I've found out all about injections and csx, strpos in a few days\weeks through thousands of FAQs in the web. But until I found answers to these questions my code was really terrible :)

Laravel - Session store not set on request

Laravel [5.4]

My solution was to use global session helper: session()

Its functionality is a little bit harder than $request->session().

writing:

session(['key'=>'value']);

pushing:

session()->push('key', $notification);

retrieving:

session('key');

Expected response code 220 but got code "", with message "" in Laravel

In my case I had to set the

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465           <<<<<<<------------------------- (FOCUS THIS)
MAIL_USERNAME=<<your email address>>
MAIL_PASSWORD=<<app password>>

MAIL_ENCRYPTION= ssl    <<<<<<<------------------------- (FOCUS THIS)

to work it.. Might be useful. Rest of the code was same as @Sid said.

And I think that editing both environment file and app/config/mail.php is unnecessary. Just use one method.

Edit as per the comment by @Zan

If you need to enable tls protection use following settings.

MAIL_PORT=587
MAIL_ENCRYPTION= tls  

See here for some other gmail settings

Get Bitmap attached to ImageView

This code is better.

public static  byte[] getByteArrayFromImageView(ImageView imageView)
    {
        BitmapDrawable bitmapDrawable = ((BitmapDrawable) imageView.getDrawable());
        Bitmap bitmap;
        if(bitmapDrawable==null){
            imageView.buildDrawingCache();
            bitmap = imageView.getDrawingCache();
            imageView.buildDrawingCache(false);
        }else
        {
            bitmap = bitmapDrawable .getBitmap();
        }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        return stream.toByteArray();
    }

Validate email address textbox using JavaScript

Assuming your regular expression is correct:

inside your script tags

function validateEmail(emailField){
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if (reg.test(emailField.value) == false) 
        {
            alert('Invalid Email Address');
            return false;
        }

        return true;

}

in your textfield:

<input type="text" onblur="validateEmail(this);" />

SQL SERVER DATETIME FORMAT

This is my favorite use of 112 and 114

select (convert(varchar, getdate(), 112)+ replace(convert(varchar, getdate(), 114),':','')) as 'Getdate() 

112 + 114 or YYYYMMDDHHMMSSMSS'

Result:

Getdate() 112 + 114 or YYYYMMDDHHMMSSMSS

20171016083349100

How do I perform a Perl substitution on a string while keeping the original?

This is the idiom I've always used to get a modified copy of a string without changing the original:

(my $newstring = $oldstring) =~ s/foo/bar/g;

In perl 5.14.0 or later, you can use the new /r non-destructive substitution modifier:

my $newstring = $oldstring =~ s/foo/bar/gr; 

NOTE:
The above solutions work without g too. They also work with any other modifiers.

SEE ALSO:
perldoc perlrequick: Perl regular expressions quick start

Get response from PHP file using AJAX

<script type="text/javascript">
        function returnwasset(){
            alert('return sent');
            $.ajax({
                type: "POST",
                url: "process.php",
                data: somedata;
                dataType:'text'; //or HTML, JSON, etc.
                success: function(response){
                    alert(response);
                    //echo what the server sent back...
                }
            });
        }
    </script>

Eclipse/Java code completion not working

If you have installed Google Toolbar for IE, may be you can face the same problem. Because, the toolbar capture the shortcut ctrl+Space.

How to programmatically click a button in WPF?

this.PowerButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

How to check if multiple array keys exists

$myArray = array('key1' => '', 'key2' => '');
$keys = array('key1', 'key2', 'key3');
$keyExists = count(array_intersect($keys, array_keys($myArray)));

Will return true, because there are keys from $keys array in $myArray

How can I retrieve Id of inserted entity using Entity framework?

You can get ID only after saving, instead you can create a new Guid and assign before saving.

How do I generate a random int number?

I've tried all of these solutions excluding the COBOL answer... lol

None of these solutions were good enough. I needed randoms in a fast for int loop and I was getting tons of duplicate values even in very wide ranges. After settling for kind of random results far too long I decided to finally tackle this problem once and for all.

It's all about the seed.

I create a random integer by parsing out the non-digits from Guid, then I use that to instantiate my Random class.

public int GenerateRandom(int min, int max)
{
    var seed = Convert.ToInt32(Regex.Match(Guid.NewGuid().ToString(), @"\d+").Value);
    return new Random(seed).Next(min, max);
}

Update: Seeding isn't necessary if you instantiate the Random class once. So it'd be best to create a static class and call a method off that.

public static class IntUtil
{
   private static Random random;

   private static void Init()
   {
      if (random == null) random = new Random();
   }

   public static int Random(int min, int max)
   {
      Init();
      return random.Next(min, max);
   }
}

Then you can use the static class like so..

for(var i = 0; i < 1000; i++)
{
   int randomNumber = IntUtil.Random(1,100);
   Console.WriteLine(randomNumber); 
}

I admit I like this approach better.

How does createOrReplaceTempView work in Spark?

createOrReplaceTempView creates (or replaces if that view name already exists) a lazily evaluated "view" that you can then use like a hive table in Spark SQL. It does not persist to memory unless you cache the dataset that underpins the view.

scala> val s = Seq(1,2,3).toDF("num")
s: org.apache.spark.sql.DataFrame = [num: int]

scala> s.createOrReplaceTempView("nums")

scala> spark.table("nums")
res22: org.apache.spark.sql.DataFrame = [num: int]

scala> spark.table("nums").cache
res23: org.apache.spark.sql.Dataset[org.apache.spark.sql.Row] = [num: int]

scala> spark.table("nums").count
res24: Long = 3

The data is cached fully only after the .count call. Here's proof it's been cached:

Cached nums temp view/table

Related SO: spark createOrReplaceTempView vs createGlobalTempView

Relevant quote (comparing to persistent table): "Unlike the createOrReplaceTempView command, saveAsTable will materialize the contents of the DataFrame and create a pointer to the data in the Hive metastore." from https://spark.apache.org/docs/latest/sql-programming-guide.html#saving-to-persistent-tables

Note : createOrReplaceTempView was formerly registerTempTable

Aggregate multiple columns at once

You could try:

agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)

How to define unidirectional OneToMany relationship in JPA

My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany which explains how to do this with a @JoinColumn annotation. In your case, i think you would want:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;

I've used a Set rather than a List, because the data itself is not ordered.

The above is using a defaulted referencedColumnName, unlike the example in the wikibook. If that doesn't work, try an explicit one:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;

Explain ExtJS 4 event handling

Just wanted to add a couple of pence to the excellent answers above: If you are working on pre Extjs 4.1, and don't have application wide events but need them, I've been using a very simple technique that might help: Create a simple object extending Observable, and define any app wide events you might need in it. You can then fire those events from anywhere in your app, including actual html dom element and listen to them from any component by relaying the required elements from that component.

Ext.define('Lib.MessageBus', {
    extend: 'Ext.util.Observable',

    constructor: function() {
        this.addEvents(
            /*
             * describe the event
             */
                  "eventname"

            );
        this.callParent(arguments);
    }
});

Then you can, from any other component:

 this.relayEvents(MesageBus, ['event1', 'event2'])

And fire them from any component or dom element:

 MessageBus.fireEvent('event1', somearg);

 <input type="button onclick="MessageBus.fireEvent('event2', 'somearg')">

Fast way to concatenate strings in nodeJS/JavaScript

There is not really any other way in JavaScript to concatenate strings.
You could theoretically use .concat(), but that's way slower than just +

Libraries are more often than not slower than native JavaScript, especially on basic operations like string concatenation, or numerical operations.

Simply put: + is the fastest.

What's the difference between JPA and Hibernate?

JPA is just a specification.In market there are many vendors which implements JPA. Different types of vendors implement JPA in different way. so different types of vendors provide different functionality so choose proper vendor based on your requirements.

If you are using Hibernate or any other vendors instead of JPA than you can not easily move to hibernate to EclipseLink or OpenJPA to Hibernate.But If you using JPA than you just have to change provide in persistence XML file.So migration is easily possible in JPA.

Display a view from another controller in ASP.NET MVC

Yes its possible. Return a RedirectToAction() method like this:

return RedirectToAction("ActionOrViewName", "ControllerName");

ParseError: not well-formed (invalid token) using cElementTree

I was having the same error (with ElementTree). In my case it was because of encodings, and I was able to solve it without having to use an external library. Hope this helps other people finding this question based on the title. (reference)

import xml.etree.ElementTree as ET
parser = ET.XMLParser(encoding="utf-8")
tree = ET.fromstring(xmlstring, parser=parser)

EDIT: Based on comments, this answer might be outdated. But this did work back when it was answered...

set up device for development (???????????? no permissions)

My device is POSITIVO and my operational system is Ubuntu 14.04 LTS So, my problem was in variable name

I create the file /etc/udev/rules.d/51-android.rules and put SUBSYSTEM=="usb", SYSFS{idVendor}=="1662", MODE="0666"

I disconnected device and execute:

$ sudo udevadm control --reload-rules
$ sudo service udev restart

after this i connected the android device in developer mode again and

$ adb devices

List of devices attached 
1A883XB1K   device

Javascript / Chrome - How to copy an object from the webkit inspector as code

This should help stringify deep objects by leaving out recursive Window and Node objects.

function stringifyObject(e) {
  const obj = {};
  for (let k in e) {
    obj[k] = e[k];
  }

  return JSON.stringify(obj, (k, v) => {
    if (v instanceof Node) return 'Node';
    if (v instanceof Window) return 'Window';
    return v;
  }, ' ');
}

UNC path to a folder on my local computer

I had to:

Create a string and append text to it

Another way to do this is to add the new characters to the string as follows:

Dim str As String

str = ""

To append text to your string this way:

str = str & "and this is more text"

How to delete all records from table in sqlite with Android?

You missed a space: db.execSQL("delete * from " + TABLE_NAME);

Also there is no need to even include *, the correct query is:

db.execSQL("delete from "+ TABLE_NAME);

How to get PID of process I've just started within java program?

There is an open-source library that has such a function, and it has cross-platform implementations: https://github.com/OpenHFT/Java-Thread-Affinity

It may be overkill just to get the PID, but if you want other things like CPU and thread id, and specifically thread affinity, it may be adequate for you.

To get the current thread's PID, just call Affinity.getAffinityImpl().getProcessId().

This is implemented using JNA (see arcsin's answer).

Change a column type from Date to DateTime during ROR migration

AFAIK, migrations are there to try to reshape data you care about (i.e. production) when making schema changes. So unless that's wrong, and since he did say he does not care about the data, why not just modify the column type in the original migration from date to datetime and re-run the migration? (Hope you've got tests:)).

Appending an id to a list if not already present in a string

A more pythonic way, without using set is as follows:

lst = [1, 2, 3, 4]
lst.append(3) if 3 not in lst else lst

error: ORA-65096: invalid common user or role name in oracle

Create user dependency upon the database connect tools

sql plus
SQL> connect as sysdba;
Enter user-name: sysdba
Enter password:
Connected.
SQL> ALTER USER hr account unlock identified by hr;
User altered
 then create user on sql plus and sql developer

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

I had the same problem and while TechZen's answer may indeed be amazing I found it hard to apply to my situation.

Eventually I resolved the issue by linking the label via the Controller listed under Objects (highlighted in the image below) rather then via the File Owner.

Hope this helps.

enter image description here

Drawing an SVG file on a HTML5 canvas

Sorry, i don't have enough reputation to comment on the @Matyas answer, but if the svg's image is also in base64, it will be drawed to the output.

Demo:

_x000D_
_x000D_
var svg = document.querySelector('svg');_x000D_
var img = document.querySelector('img');_x000D_
var canvas = document.querySelector('canvas');_x000D_
_x000D_
// get svg data_x000D_
var xml = new XMLSerializer().serializeToString(svg);_x000D_
_x000D_
// make it base64_x000D_
var svg64 = btoa(xml);_x000D_
var b64Start = 'data:image/svg+xml;base64,';_x000D_
_x000D_
// prepend a "header"_x000D_
var image64 = b64Start + svg64;_x000D_
_x000D_
// set it as the source of the img element_x000D_
img.onload = function() {_x000D_
    // draw the image onto the canvas_x000D_
    canvas.getContext('2d').drawImage(img, 0, 0);_x000D_
}_x000D_
img.src = image64;
_x000D_
svg, img, canvas {_x000D_
  display: block;_x000D_
}
_x000D_
SVG_x000D_
_x000D_
<svg height="40">_x000D_
  <rect width="40" height="40" style="fill:rgb(255,0,255);" />_x000D_
  <image xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAEX0lEQVQ4jUWUyW6cVRCFv7r3/kO3u912nNgZgESAAgGBCJgFgxhW7FkgxAbxMLwBEmIRITbsQAgxCEUiSIBAYIY4g1EmYjuDp457+Lv7n+4tFjbwAHVOnVPnlLz75ht67OhhZg/M0p6d5tD9C8SNBBs5XBJhI4uNLC4SREA0UI9yJr2c4e6QO+v3WF27w+rmNrv9Pm7hxDyHFg5yYGEOYxytuRY2SYiSCIwgRgBQIxgjEAKuZWg6R9S0SCS4qKLZElY3HC5tp7QPtmlMN7HOETUTXBJjrEGsAfgPFECsQbBIbDGJZUYgGE8ugQyPm+o0STtTuGZMnKZEjRjjLIgAirEOEQEBDQFBEFFEBWLFtVJmpENRl6hUuFanTRAlbTeZarcx0R6YNZagAdD/t5N9+QgCYAw2jrAhpjM3zaSY4OJGTDrVwEYOYw2qioigoviq5MqF31m9fg1V5fCx+zn11CLNVnufRhBrsVFE1Ihpthu4KDYYwz5YQIxFBG7duMZnH31IqHL6wwnGCLFd4pez3/DaG2/x4GNPgBhEZG/GGlxkMVFkiNMYay3Inqxed4eP33uf7Y0uu90xWkGolFAru7sZn5w5w921m3u+su8vinEO02hEWLN/ANnL2rkvv2an2yd4SCKLM0JVBsCgAYZZzrnPP0eDRzXgfaCuPHXwuEYjRgmIBlQVVLl8/hKI4fRzz3L6uWe5+PMvnHz6aa4uX+D4yYe5vXaLH86eoyoLjLF476l9oKo9pi5HWONRX8E+YznOef7Vl1h86QWurlwjbc+QpikPPfoIcZLS39pmMikp8pzae6q6oqgriqrGqS+xeLScoMYSVJlfOMTl5RXW1+5w5fJVnFGWf1/mxEMnWPppiclkTLM5RdJoUBYFZVlQ5DnZMMMV167gixKLoXXsKGqnOHnqOJ/+/CfZ+XUiZ0jTmFv5mAvf/YjEliQ2vPD8Ir6qqEcZkzt38cMRo5WruFvfL9FqpyRxQhj0qLOax5I2S08+Tu/lFiGUGOPormxwuyfMnjrGrJa88uIixeYWl776lmrzNjmw8vcG8sU7ixpHMXFsCUVg9tABjEvRgzP82j7AhbyiX5Qcv2+Bvy7dYGZ1k7efeQB/Y4PBqGBtdYvb3SFzLcfqToZc/OB1zYeBSpUwLBlvjZidmWaSB1yaYOfn6LqI/r0hyU6P+cRSlhXjbEI2zvnt7y79oqQ3qeg4g6vKjCIXehtDmi6m0UnxVnCRkPUHVNt9qkLJxgXOCYNOg34v48raPaamU2o89/KKsQ9sTSpc0JK7NwdcX8s43Ek5cnSOLC/Z2R6Rj0ra0w2W1/t0xyWn51uk2Ri1QtSO6OU5d7OSi72cQeWxKG7p/Dp//JXTy6C1Pcbc6DMpPRtjTxChEznWhwVZUCKrjCrPoPDczHLmnLBdBgZlRRWUEBR3ZKrme5TlrTGlV440Y1IrXM9qQGi6mkG5V6uza7tUIeCDElTZ1L26elX+fcH/ACJBPYTJ4X8tAAAAAElFTkSuQmCC" height="20px" width="20px" x="10" y="10"></image>_x000D_
</svg>_x000D_
<hr/><br/>_x000D_
_x000D_
IMAGE_x000D_
<img/>_x000D_
<hr/><br/>_x000D_
   _x000D_
CANVAS_x000D_
<canvas></canvas>_x000D_
<hr/><br/>
_x000D_
_x000D_
_x000D_

The response content cannot be parsed because the Internet Explorer engine is not available, or

Yet another method to solve: updating registry. In my case I could not alter GPO, and -UseBasicParsing breaks parts of the access to the website. Also I had a service user without log in permissions, so I could not log in as the user and run the GUI.
To fix,

  1. log in as a normal user, run IE setup.
  2. Then export this registry key: HKEY_USERS\S-1-5-21-....\SOFTWARE\Microsoft\Internet Explorer
  3. In the .reg file that is saved, replace the user sid with the service account sid
  4. Import the .reg file

In the file

Importing JSON into an Eclipse project

You should take the json implementation from here : http://code.google.com/p/json-simple/ .

  • Download the *.jar
  • Add it to the classpath (right-click on the project, Properties->Libraries and add new JAR.)

In Angular, how to redirect with $location.path as $http.post success callback

There is simple answer in the official guide:

What does it not do?

It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href.

Source: https://docs.angularjs.org/guide/$location

How to convert list of key-value tuples into dictionary?

This gives me the same error as trying to split the list up and zip it. ValueError: dictionary update sequence element #0 has length 1916; 2 is required

THAT is your actual question.

The answer is that the elements of your list are not what you think they are. If you type myList[0] you will find that the first element of your list is not a two-tuple, e.g. ('A', 1), but rather a 1916-length iterable.

Once you actually have a list in the form you stated in your original question (myList = [('A',1),('B',2),...]), all you need to do is dict(myList).

How do I programmatically change file permissions?

Prior to Java 6, there is no support of file permission update at Java level. You have to implement your own native method or call Runtime.exec() to execute OS level command such as chmod.

Starting from Java 6, you can useFile.setReadable()/File.setWritable()/File.setExecutable() to set file permissions. But it doesn't simulate the POSIX file system which allows to set permission for different users. File.setXXX() only allows to set permission for owner and everyone else.

Starting from Java 7, POSIX file permission is introduced. You can set file permissions like what you have done on *nix systems. The syntax is :

File file = new File("file4.txt");
file.createNewFile();

Set<PosixFilePermission> perms = new HashSet<>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);

Files.setPosixFilePermissions(file.toPath(), perms);

This method can only be used on POSIX file system, this means you cannot call it on Windows system.

For details on file permission management, recommend you to read this post.

Create a list with initial capacity in Python

Concerns about preallocation in Python arise if you're working with NumPy, which has more C-like arrays. In this instance, preallocation concerns are about the shape of the data and the default value.

Consider NumPy if you're doing numerical computation on massive lists and want performance.

Multiple try codes in one block

Extract (refactor) your statements. And use the magic of and and or to decide when to short-circuit.

def a():
    try: # a code
    except: pass # or raise
    else: return True

def b():
    try: # b code
    except: pass # or raise
    else: return True

def c():
    try: # c code
    except: pass # or raise
    else: return True

def d():
    try: # d code
    except: pass # or raise
    else: return True

def main():   
    try:
        a() and b() or c() or d()
    except:
        pass

How to connect PHP with Microsoft Access database

Are you sure the odbc connector is well created ? if not check the step "Create an ODBC Connection" again

EDIT: Connection without DSN from php.net

// Microsoft Access

$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password);

in your case it might be if your filename is northwind and your file extension mdb:

$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=northwind", "", "");

How to execute logic on Optional if not present?

I don't think you can do it in a single statement. Better do:

if (!obj.isPresent()) {
    logger.fatal(...);   
} else {
    obj.get().setAvailable(true);
}
return obj;

How to extract public key using OpenSSL?

If your looking how to copy an Amazon AWS .pem keypair into a different region do the following:

openssl rsa -in .ssh/amazon-aws.pem -pubout > .ssh/amazon-aws.pub

Then

aws ec2 import-key-pair --key-name amazon-aws --public-key-material '$(cat .ssh/amazon-aws.pub)' --region us-west-2

Bootstrap: Use .pull-right without having to hardcode a negative margin-top

just put #login-box before <h2>Welcome</h2> will be ok.

<div class='container'>
    <div class='hero-unit'>
        <div id='login-box' class='pull-right control-group'>
            <div class='clearfix'>
                <input type='text' placeholder='Username' />
            </div>
            <div class='clearfix'>
                <input type='password' placeholder='Password' />
            </div>
            <button type='button' class='btn btn-primary'>Log in</button>
        </div>
        <h2>Welcome</h2>

        <p>Please log in</p>

    </div>
</div>

here is jsfiddle http://jsfiddle.net/SyjjW/4/

How to style the parent element when hovering a child element?

A simple jquery solution for those who don't need a pure css solution:

_x000D_
_x000D_
    $(".letter").hover(function() {_x000D_
      $(this).closest("#word").toggleClass("hovered")_x000D_
    });
_x000D_
.hovered {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
_x000D_
.letter {_x000D_
  margin: 20px;_x000D_
  background: lightgray;_x000D_
}_x000D_
_x000D_
.letter:hover {_x000D_
  background: grey;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="word">_x000D_
  <div class="letter">T</div>_x000D_
  <div class="letter">E</div>_x000D_
  <div class="letter">S</div>_x000D_
  <div class="letter">T</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Converting int to string in C

char string[something];
sprintf(string, "%d", 42);

Pass Javascript Array -> PHP

You can transfer array from javascript to PHP...

Javascript... ArraySender.html

<script language="javascript">

//its your javascript, your array can be multidimensional or associative

plArray = new Array();
plArray[1] = new Array(); plArray[1][0]='Test 1 Data'; plArray[1][1]= 'Test 1'; plArray[1][2]= new Array();
plArray[1][2][0]='Test 1 Data Dets'; plArray[1][2][1]='Test 1 Data Info'; 
plArray[2] = new Array(); plArray[2][0]='Test 2 Data'; plArray[2][1]= 'Test 2';
plArray[3] = new Array(); plArray[3][0]='Test 3 Data'; plArray[3][1]= 'Test 3'; 
plArray[4] = new Array(); plArray[4][0]='Test 4 Data'; plArray[4][1]= 'Test 4'; 
plArray[5] = new Array(); plArray[5]["Data"]='Test 5 Data'; plArray[5]["1sss"]= 'Test 5'; 

function convertJsArr2Php(JsArr){
    var Php = '';
    if (Array.isArray(JsArr)){  
        Php += 'array(';
        for (var i in JsArr){
            Php += '\'' + i + '\' => ' + convertJsArr2Php(JsArr[i]);
            if (JsArr[i] != JsArr[Object.keys(JsArr)[Object.keys(JsArr).length-1]]){
                Php += ', ';
            }
        }
        Php += ')';
        return Php;
    }
    else{
        return '\'' + JsArr + '\'';
    }
}


function ajaxPost(str, plArrayC){
    var xmlhttp;
    if (window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
    else{xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
    xmlhttp.open("POST",str,true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send('Array=' + plArrayC);
}

ajaxPost('ArrayReader.php',convertJsArr2Php(plArray));
</script>

and PHP Code... ArrayReader.php

<?php 

eval('$plArray = ' . $_POST['Array'] . ';');
print_r($plArray);

?>

ToList()-- does it create a new list?

A new list is created but the items in it are references to the orginal items (just like in the original list). Changes to the list itself are independent, but to the items will find the change in both lists.

How to list running screen sessions?

 For windows system

 Open putty 
 then login in server

If you want to see screen in Console then you have to write command

 Screen -ls

if you have to access the screen then you have to use below command

 screen -x screen id

Write PWD in command line to check at which folder you are currently

Changing permissions via chmod at runtime errors with "Operation not permitted"

$ sudo chmod ...

You need to either be the owner of the file or be the superuser, i.e., user root. If you own the directory but not the file, you can copy the file, rm the original, then mv it back, and then you will be able to chown it.

The easy way to temporarily be root is to run the command via sudo. ($ man 8 sudo)

How to disable scientific notation?

You can effectively remove scientific notation in printing with this code:

options(scipen=999)

Index of Currently Selected Row in DataGridView

Try it:

int rc=dgvDataRc.CurrentCell.RowIndex;** //for find the row index number
MessageBox.Show("Current Row Index is = " + rc.ToString());

I hope it will help you.

Checking if a variable is an integer

If you want to know whether an object is an Integer or something which can meaningfully be converted to an Integer (NOT including things like "hello", which to_i will convert to 0):

result = Integer(obj) rescue false

Rails - passing parameters in link_to

Try this

link_to "+ Service", my_services_new_path(:account_id => acct.id)

it will pass the account_id as you want.

For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

Javascript reduce on array of objects

you should not use a.x for accumulator , Instead you can do like this `arr = [{x:1},{x:2},{x:4}]

arr.reduce(function(a,b){a + b.x},0)`

How can I copy a Python string?

You can copy a string in python via string formatting :

>>> a = 'foo'  
>>> b = '%s' % a  
>>> id(a), id(b)  
(140595444686784, 140595444726400)  

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

I know this may sound absurd, but I solved a similar issue by creating the database as "phpMyAdmin" not "phpmyadmin" (note case) - perhaps there is something about case-sensitivity under Windows?

How can I change the default Django date template format?

If you need to show short date and time (11/08/2018 03:23 a.m.) you can do it like this:

{{your_date_field|date:"SHORT_DATE_FORMAT"}} {{your_date_field|time:"h:i a"}}

Details for this tag here and more about dates according to the given format here

Example:

<small class="text-muted">Last updated: {{your_date_field|date:"SHORT_DATE_FORMAT"}} {{your_date_field|time:"h:i a"}}</small>

Calling virtual functions inside constructors

As has been pointed out, the objects are created base-down upon construction. When the base object is being constructed, the derived object does not exist yet, so a virtual function override cannot work.

However, this can be solved with polymorphic getters that use static polymorphism instead of virtual functions if your getters return constants, or otherwise can be expressed in a static member function, This example uses CRTP (https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern).

template<typename DerivedClass>
class Base
{
public:
    inline Base() :
    foo(DerivedClass::getFoo())
    {}

    inline int fooSq() {
        return foo * foo;
    }

    const int foo;
};

class A : public Base<A>
{
public:
    inline static int getFoo() { return 1; }
};

class B : public Base<B>
{
public:
    inline static int getFoo() { return 2; }
};

class C : public Base<C>
{
public:
    inline static int getFoo() { return 3; }
};

int main()
{
    A a;
    B b;
    C c;

    std::cout << a.fooSq() << ", " << b.fooSq() << ", " << c.fooSq() << std::endl;

    return 0;
}

With the use of static polymorphism, the base class knows which class' getter to call as the information is provided at compile-time.

Bind TextBox on Enter-key press

This is not an answer to the original question, but rather an extension of the accepted answer by @Samuel Jack. I did the following in my own application, and was in awe of the elegance of Samuel's solution. It is very clean, and very reusable, as it can be used on any control, not just the TextBox. I thought this should be shared with the community.

If you have a Window with a thousand TextBoxes that all require to update the Binding Source on Enter, you can attach this behaviour to all of them by including the XAML below into your Window Resources rather than attaching it to each TextBox. First you must implement the attached behaviour as per Samuel's post, of course.

<Window.Resources>
    <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
        <Style.Setters>
            <Setter Property="b:InputBindingsManager.UpdatePropertySourceWhenEnterPressed" Value="TextBox.Text"/>
        </Style.Setters>
    </Style>
</Window.Resources>

You can always limit the scope, if needed, by putting the Style into the Resources of one of the Window's child elements (i.e. a Grid) that contains the target TextBoxes.

Best way to simulate "group by" from bash?

for summing up multiple fields, based on a group of existing fields, use the example below : ( replace the $1, $2, $3, $4 according to your requirements )

cat file

US|A|1000|2000
US|B|1000|2000
US|C|1000|2000
UK|1|1000|2000
UK|1|1000|2000
UK|1|1000|2000

awk 'BEGIN { FS=OFS=SUBSEP="|"}{arr[$1,$2]+=$3+$4 }END {for (i in arr) print i,arr[i]}' file

US|A|3000
US|B|3000
US|C|3000
UK|1|9000

How to make Bootstrap carousel slider use mobile left/right swipe

With bootstrap 4.2 its now very easy, you just need to pass the touch option in the carousel div as data-touch="true", as it accepts Boolean value only.

As in your case update bootstrap to 4.2 and paste(Or download source files) the following in exact order :

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

and then add the touch option in your bootstrap carousel div

    <div id="sidebar-carousel-1" class="carousel slide" data-ride="carousel" data-touch="true">

malloc for struct and pointer in C

The first time around, you allocate memory for Vector, which means the variables x,n.

However x doesn't yet point to anything useful.

So that is why second allocation is needed as well.

How to tell if a <script> tag failed to load

This trick worked for me, although I admit that this is probably not the best way to solve this problem. Instead of trying this, you should see why the javascripts aren't loading. Try keeping a local copy of the script in your server, etc. or check with the third party vendor from where you are trying to download the script.

Anyways, so here's the workaround: 1) Initialize a variable to false 2) Set it to true when the javascript loads (using the onload attribute) 3) check if the variable is true or false once the HTML body has loaded

<html>
  <head>
    <script>
      var scriptLoaded = false;

      function checkScriptLoaded() {
        if (scriptLoaded) {
          // do something here
        } else {
          // do something else here!
        }
      }
    </script>
    <script src="http://some-external-script.js" onload="scriptLoaded=true;" />
  </head>
  <body onload="checkScriptLoaded()">
    <p>My Test Page!</p>
  </body>
</html>

Swift: Reload a View Controller

If you are using a navigation controller you can segue again to the current UIViewController and it will be refreshed. Here I use a UIButton for refreshing

maven compilation failure

Add <sourceDirectory>src</sourceDirectory> in your pom.xml with proper reference. Adding this solved my problem

Angular2 - Focusing a textbox on component load

This answer is inspired by post Angular 2: Focus on newly added input element

Steps to set the focus on Html element in Angular2

  1. Import ViewChildren in your Component

    import { Input, Output, AfterContentInit, ContentChild,AfterViewInit, ViewChild, ViewChildren } from 'angular2/core';
    
  2. Declare local template variable name for the html for which you want to set the focus

  3. Implement the function ngAfterViewInit() or other appropriate life cycle hooks
  4. Following is the piece of code which I used for setting the focus

    ngAfterViewInit() {vc.first.nativeElement.focus()}
    
  5. Add #input attribute to the DOM element you want to access.

_x000D_
_x000D_
///This is typescript_x000D_
import {Component, Input, Output, AfterContentInit, ContentChild,_x000D_
  AfterViewChecked, AfterViewInit, ViewChild,ViewChildren} from 'angular2/core';_x000D_
_x000D_
export class AppComponent implements AfterViewInit,AfterViewChecked { _x000D_
   @ViewChildren('input') vc;_x000D_
  _x000D_
   ngAfterViewInit() {            _x000D_
        this.vc.first.nativeElement.focus();_x000D_
    }_x000D_
  _x000D_
 }
_x000D_
<div>_x000D_
    <form role="form" class="form-horizontal ">        _x000D_
        <div [ngClass]="{showElement:IsEditMode, hidden:!IsEditMode}">_x000D_
            <div class="form-group">_x000D_
                <label class="control-label col-md-1 col-sm-1" for="name">Name</label>_x000D_
                <div class="col-md-7 col-sm-7">_x000D_
                    <input #input id="name" type="text" [(ngModel)]="person.Name" class="form-control" />_x000D_
_x000D_
                </div>_x000D_
                <div class="col-md-2 col-sm-2">_x000D_
                    <input type="button" value="Add" (click)="AddPerson()" class="btn btn-primary" />_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div [ngClass]="{showElement:!IsEditMode, hidden:IsEditMode}">_x000D_
            <div class="form-group">_x000D_
                <label class="control-label col-md-1 col-sm-1" for="name">Person</label>_x000D_
                <div class="col-md-7 col-sm-7">_x000D_
                    <select [(ngModel)]="SelectedPerson.Id"  (change)="PersonSelected($event.target.value)" class="form-control">_x000D_
                        <option *ngFor="#item of PeopleList" value="{{item.Id}}">{{item.Name}}</option>_x000D_
                    </select>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>        _x000D_
    </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Correct way to convert size in bytes to KB, MB, GB in JavaScript

Try this simple workaround.

var files = $("#file").get(0).files;               
                var size = files[0].size;
                if (size >= 5000000) {
alert("File size is greater than or equal to 5 MB");
}

Execute a command line binary with Node.js

You are looking for child_process.exec

Here is the example:

const exec = require('child_process').exec;
const child = exec('cat *.js bad_file | wc -l',
    (error, stdout, stderr) => {
        console.log(`stdout: ${stdout}`);
        console.log(`stderr: ${stderr}`);
        if (error !== null) {
            console.log(`exec error: ${error}`);
        }
});

Can you style html form buttons with css?

You can directly create your own style in this way:

 input[type=button]
 { 
//Change the style as you like
 }

show loading icon until the page is load?

HTML

<body>
    <div id="load"></div>
    <div id="contents">
          jlkjjlkjlkjlkjlklk
    </div>
</body>

JS

document.onreadystatechange = function () {
  var state = document.readyState
  if (state == 'interactive') {
       document.getElementById('contents').style.visibility="hidden";
  } else if (state == 'complete') {
      setTimeout(function(){
         document.getElementById('interactive');
         document.getElementById('load').style.visibility="hidden";
         document.getElementById('contents').style.visibility="visible";
      },1000);
  }
}

CSS

#load{
    width:100%;
    height:100%;
    position:fixed;
    z-index:9999;
    background:url("https://www.creditmutuel.fr/cmne/fr/banques/webservices/nswr/images/loading.gif") no-repeat center center rgba(0,0,0,0.25)
}

Note:
you wont see any loading gif if your page is loaded fast, so use this code on a page with high loading time, and i also recommend to put your js on the bottom of the page.

DEMO

http://jsfiddle.net/6AcAr/ - with timeout(only for demo)
http://jsfiddle.net/47PkH/ - no timeout(use this for actual page)

update

http://jsfiddle.net/d9ngT/

How to parse a string to an int in C++?

The good 'old C way still works. I recommend strtol or strtoul. Between the return status and the 'endPtr', you can give good diagnostic output. It also handles multiple bases nicely.

Enable SQL Server Broker taking too long

Actually I am preferring to use NEW_BROKER ,it is working fine on all cases:

ALTER DATABASE [dbname] SET NEW_BROKER WITH ROLLBACK IMMEDIATE;

iOS: present view controller programmatically

LandingScreenViewController *nextView=[self.storyboard instantiateViewControllerWithIdentifier:@"nextView"];
[self presentViewController:nextView animated:YES completion:^{}];

Why is using a wild card with a Java import statement bad?

Here's a vote for star imports. An import statement is intended to import a package, not a class. It is much cleaner to import entire packages; the issues identified here (e.g. java.sql.Date vs java.util.Date) are easily remedied by other means, not really addressed by specific imports and certainly do not justify insanely pedantic imports on all classes. There is nothing more disconcerting than opening a source file and having to page through 100 import statements.

Doing specific imports makes refactoring more difficult; if you remove/rename a class, you need to remove all of its specific imports. If you switch an implementation to a different class in the same package, you have to go fix the imports. While these extra steps can be automated, they are really productivity hits for no real gain.

If Eclipse didn't do specific class imports by default, everyone would still be doing star imports. I'm sorry, but there's really no rational justification for doing specific imports.

Here's how to deal with class conflicts:

import java.sql.*;
import java.util.*;
import java.sql.Date;

How can I consume a WSDL (SOAP) web service in Python?

Right now (as of 2008), all the SOAP libraries available for Python suck. I recommend avoiding SOAP if possible. The last time we where forced to use a SOAP web service from Python, we wrote a wrapper in C# that handled the SOAP on one side and spoke COM out the other.

How to split a string with any whitespace chars as delimiters

String string = "Ram is going to school";
String[] arrayOfString = string.split("\\s+");

Get user's non-truncated Active Directory groups from command line

GPRESULT is the right command, but it cannot be run without parameters. /v or verbose option is difficult to manage without also outputting to a text file. E.G. I recommend using

gpresult /user myAccount /v > C:\dev\me.txt--Ensure C:\Dev\me.txt exists

Another option is to display summary information only which may be entirely visible in the command window:

gpresult /user myAccount /r

The accounts are listed under the heading:

The user is a part of the following security groups
---------------------------------------------------

HTML form input tag name element array with JavaScript

document.form.p_id.length ... not count().

You really should give your form an id

<form id="myform">

Then refer to it using:

var theForm = document.getElementById("myform");

Then refer to the elements like:

for(var i = 0; i < theForm.p_id.length; i++){

Return only string message from Spring MVC 3 Controller

Annotate your method in controller with @ResponseBody:

@RequestMapping(value="/controller", method=GET)
@ResponseBody
public String foo() {
    return "Response!";
}

From: 15.3.2.6 Mapping the response body with the @ResponseBody annotation:

The @ResponseBody annotation [...] can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).

NodeJS/express: Cache and 304 status code

I had the same problem in Safari and Chrome (the only ones I've tested) but I just did something that seems to work, at least I haven't been able to reproduce the problem since I added the solution. What I did was add a metatag to the header with a generated timstamp. Doesn't seem right but it's simple :)

<meta name="304workaround" content="2013-10-24 21:17:23">

Update P.S As far as I can tell, the problem disappears when I remove my node proxy (by proxy i mean both express.vhost and http-proxy module), which is weird...

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

Check if you are returning a @ResponseBody or a @ResponseStatus

I had a similar problem. My Controller looked like that:

@RequestMapping(value="/user", method = RequestMethod.POST)
public String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

When calling with a POST request I always got the following error:

HTTP Status 405 - Request method 'POST' not supported

After a while I figured out that the method was actually called, but because there is no @ResponseBody and no @ResponseStatus Spring MVC raises the error.

To fix this simply add a @ResponseBody

@RequestMapping(value="/user", method = RequestMethod.POST)
public @ResponseBody String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

or a @ResponseStatus to your method.

@RequestMapping(value="/user", method = RequestMethod.POST)
@ResponseStatus(value=HttpStatus.OK)
public String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

Insert into a MySQL table or update if exists

In case, you want to keep old field (For ex: name). The query will be:

INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE    
name=name, age=19;

How to change position of Toast in Android?

You can customize the location of your Toast by using:

setGravity(int gravity, int xOffset, int yOffset)

docs

This allows you to be very specific about where you want the location of your Toast to be.

One of the most useful things about the xOffset and yOffset parameters is that you can use them to place the Toast relative to a certain View.

For example, if you want to make a custom Toast that appears on top of a Button, you could create a function like this:

// v is the Button view that you want the Toast to appear above 
// and messageId is the id of your string resource for the message

private void displayToastAboveButton(View v, int messageId)
{
    int xOffset = 0;
    int yOffset = 0;
    Rect gvr = new Rect();

    View parent = (View) v.getParent(); 
    int parentHeight = parent.getHeight();

    if (v.getGlobalVisibleRect(gvr)) 
    {       
        View root = v.getRootView();

        int halfWidth = root.getRight() / 2;
        int halfHeight = root.getBottom() / 2;

        int parentCenterX = ((gvr.right - gvr.left) / 2) + gvr.left;

        int parentCenterY = ((gvr.bottom - gvr.top) / 2) + gvr.top;

        if (parentCenterY <= halfHeight) 
        {
            yOffset = -(halfHeight - parentCenterY) - parentHeight;
        }
        else 
        {
            yOffset = (parentCenterY - halfHeight) - parentHeight;
        }

        if (parentCenterX < halfWidth) 
        {         
            xOffset = -(halfWidth - parentCenterX);     
        }   

        if (parentCenterX >= halfWidth) 
        {
            xOffset = parentCenterX - halfWidth;
        }  
    }

    Toast toast = Toast.makeText(getActivity(), messageId, Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER, xOffset, yOffset);
    toast.show();       
}

What does value & 0xff do in Java?

From http://www.coderanch.com/t/236675/java-programmer-SCJP/certification/xff

The hex literal 0xFF is an equal int(255). Java represents int as 32 bits. It look like this in binary:

00000000 00000000 00000000 11111111

When you do a bit wise AND with this value(255) on any number, it is going to mask(make ZEROs) all but the lowest 8 bits of the number (will be as-is).

... 01100100 00000101 & ...00000000 11111111 = 00000000 00000101

& is something like % but not really.

And why 0xff? this in ((power of 2) - 1). All ((power of 2) - 1) (e.g 7, 255...) will behave something like % operator.

Then
In binary, 0 is, all zeros, and 255 looks like this:

00000000 00000000 00000000 11111111

And -1 looks like this

11111111 11111111 11111111 11111111

When you do a bitwise AND of 0xFF and any value from 0 to 255, the result is the exact same as the value. And if any value higher than 255 still the result will be within 0-255.

However, if you do:

-1 & 0xFF

you get

00000000 00000000 00000000 11111111, which does NOT equal the original value of -1 (11111111 is 255 in decimal).


Few more bit manipulation: (Not related to the question)

X >> 1 = X/2
X << 1 = 2X

Check any particular bit is set(1) or not (0) then

 int thirdBitTobeChecked =   1 << 2   (...0000100)
 int onWhichThisHasTobeTested = 5     (.......101)

 int isBitSet = onWhichThisHasTobeTested  & thirdBitTobeChecked;
 if(isBitSet > 0) {
  //Third Bit is set to 1 
 } 

Set(1) a particular bit

 int thirdBitTobeSet =   1 << 2    (...0000100)
 int onWhichThisHasTobeSet = 2     (.......010)
 onWhichThisHasTobeSet |= thirdBitTobeSet;

ReSet(0) a particular bit

int thirdBitTobeReSet =   ~(1 << 2)  ; //(...1111011)
int onWhichThisHasTobeReSet = 6      ;//(.....000110)
onWhichThisHasTobeReSet &= thirdBitTobeReSet;

XOR

Just note that if you perform XOR operation twice, will results the same value.

byte toBeEncrypted = 0010 0110
byte salt          = 0100 1011

byte encryptedVal  =  toBeEncrypted ^ salt == 0110 1101
byte decryptedVal  =  encryptedVal  ^ salt == 0010 0110 == toBeEncrypted :)

One more logic with XOR is

if     A (XOR) B == C (salt)
then   C (XOR) B == A
       C (XOR) A == B

The above is useful to swap two variables without temp like below

a = a ^ b; b = a ^ b; a = a ^ b;

OR

a ^= b ^= a ^= b;

HTTP get with headers using RestTemplate

The RestTemplate getForObject() method does not support setting headers. The solution is to use the exchange() method.

So instead of restTemplate.getForObject(url, String.class, param) (which has no headers), use

HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...

HttpEntity entity = new HttpEntity(headers);

ResponseEntity<String> response = restTemplate.exchange(
    url, HttpMethod.GET, entity, String.class, param);

Finally, use response.getBody() to get your result.

This question is similar to this question.

Map HTML to JSON

Representing complex HTML documents will be difficult and full of corner cases, but I just wanted to share a couple techniques to show how to get this kind of program started. This answer differs in that it uses data abstraction and the toJSON method to recursively build the result

Below, html2json is a tiny function which takes an HTML node as input and it returns a JSON string as the result. Pay particular attention to how the code is quite flat but it's still plenty capable of building a deeply nested tree structure – all possible with virtually zero complexity

_x000D_
_x000D_
// data Elem = Elem Node_x000D_
_x000D_
const Elem = e => ({_x000D_
  toJSON : () => ({_x000D_
    tagName: _x000D_
      e.tagName,_x000D_
    textContent:_x000D_
      e.textContent,_x000D_
    attributes:_x000D_
      Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
    children:_x000D_
      Array.from(e.children, Elem)_x000D_
  })_x000D_
})_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
  JSON.stringify(Elem(e), null, '  ')_x000D_
  _x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
  <h1 class="mainHeading">Some heading</h1>_x000D_
  <ul id="menu">_x000D_
    <li><a href="/a">a</a></li>_x000D_
    <li><a href="/b">b</a></li>_x000D_
    <li><a href="/c">c</a></li>_x000D_
  </ul>_x000D_
  <p>some text</p>_x000D_
</main>
_x000D_
_x000D_
_x000D_

In the previous example, the textContent gets a little butchered. To remedy this, we introduce another data constructor, TextElem. We'll have to map over the childNodes (instead of children) and choose to return the correct data type based on e.nodeType – this gets us a littler closer to what we might need

_x000D_
_x000D_
// data Elem = Elem Node | TextElem Node_x000D_
_x000D_
const TextElem = e => ({_x000D_
  toJSON: () => ({_x000D_
    type:_x000D_
      'TextElem',_x000D_
    textContent:_x000D_
      e.textContent_x000D_
  })_x000D_
})_x000D_
_x000D_
const Elem = e => ({_x000D_
  toJSON : () => ({_x000D_
    type:_x000D_
      'Elem',_x000D_
    tagName: _x000D_
      e.tagName,_x000D_
    attributes:_x000D_
      Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
    children:_x000D_
      Array.from(e.childNodes, fromNode)_x000D_
  })_x000D_
})_x000D_
_x000D_
// fromNode :: Node -> Elem_x000D_
const fromNode = e => {_x000D_
  switch (e.nodeType) {_x000D_
    case 3:  return TextElem(e)_x000D_
    default: return Elem(e)_x000D_
  }_x000D_
}_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
  JSON.stringify(Elem(e), null, '  ')_x000D_
  _x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
  <h1 class="mainHeading">Some heading</h1>_x000D_
  <ul id="menu">_x000D_
    <li><a href="/a">a</a></li>_x000D_
    <li><a href="/b">b</a></li>_x000D_
    <li><a href="/c">c</a></li>_x000D_
  </ul>_x000D_
  <p>some text</p>_x000D_
</main>
_x000D_
_x000D_
_x000D_

Anyway, that's just two iterations on the problem. Of course you'll have to address corner cases where they come up, but what's nice about this approach is that it gives you a lot of flexibility to encode the HTML however you wish in JSON – and without introducing too much complexity

In my experience, you could keep iterating with this technique and achieve really good results. If this answer is interesting to anyone and would like me to expand upon anything, let me know ^_^

Related: Recursive methods using JavaScript: building your own version of JSON.stringify

Order of items in classes: Fields, Properties, Constructors, Methods

According to the StyleCop Rules Documentation the ordering is as follows.

Within a class, struct or interface: (SA1201 and SA1203)

  • Constant Fields
  • Fields
  • Constructors
  • Finalizers (Destructors)
  • Delegates
  • Events
  • Enums
  • Interfaces (interface implementations)
  • Properties
  • Indexers
  • Methods
  • Structs
  • Classes

Within each of these groups order by access: (SA1202)

  • public
  • internal
  • protected internal
  • protected
  • private

Within each of the access groups, order by static, then non-static: (SA1204)

  • static
  • non-static

Within each of the static/non-static groups of fields, order by readonly, then non-readonly : (SA1214 and SA1215)

  • readonly
  • non-readonly

An unrolled list is 130 lines long, so I won't unroll it here. The methods part unrolled is:

  • public static methods
  • public methods
  • internal static methods
  • internal methods
  • protected internal static methods
  • protected internal methods
  • protected static methods
  • protected methods
  • private static methods
  • private methods

The documentation notes that if the prescribed order isn't suitable - say, multiple interfaces are being implemented, and the interface methods and properties should be grouped together - then use a partial class to group the related methods and properties together.

2D Euclidean vector rotations

you should remove the vars from the function:

x = x * cs - y * sn; // now x is something different than original vector x
y = x * sn + y * cs;

create new coordinates becomes, to avoid calculation of x before it reaches the second line:

px = x * cs - y * sn; 
py = x * sn + y * cs;

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

enter image description here

First of all you have to find an image of the back button. I used a nice app called Extractor that extracts all the graphics from iPhone. In iOS7 I managed to retrieve the image called UINavigationBarBackIndicatorDefault and it was in black colour, since I needed a red tint I change the colour to red using Gimp.

EDIT:

As was mentioned by btate in his comment, there is no need to change the color with the image editor. The following code should do the trick:

imageView.tint = [UIColor redColor];
imageView.image = [[UIImage imageNamed:@"UINavigationBarBackIndicatorDefault"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

Then I created a view that contains an imageView with that arrow, a label with the custom text and on top of the view I have a button with an action. Then I added a simple animation (fading and translation).

The following code simulates the behaviour of the back button including animation.

-(void)viewWillAppear:(BOOL)animated{
        UIImageView *imageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UINavigationBarBackIndicatorDefault"]];
        [imageView setTintColor:[UIColor redColor]];
        UILabel *label=[[UILabel alloc] init];
        [label setTextColor:[UIColor redColor]];
        [label setText:@"Blog"];
        [label sizeToFit];

        int space=6;
        label.frame=CGRectMake(imageView.frame.origin.x+imageView.frame.size.width+space, label.frame.origin.y, label.frame.size.width, label.frame.size.height);
        UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, label.frame.size.width+imageView.frame.size.width+space, imageView.frame.size.height)];

        view.bounds=CGRectMake(view.bounds.origin.x+8, view.bounds.origin.y-1, view.bounds.size.width, view.bounds.size.height);
        [view addSubview:imageView];
        [view addSubview:label];

        UIButton *button=[[UIButton alloc] initWithFrame:view.frame];
        [button addTarget:self action:@selector(handleBack:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];

        [UIView animateWithDuration:0.33 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
            label.alpha = 0.0;
            CGRect orig=label.frame;
            label.frame=CGRectMake(label.frame.origin.x+25, label.frame.origin.y, label.frame.size.width, label.frame.size.height);
            label.alpha = 1.0;
            label.frame=orig;
        } completion:nil];

        UIBarButtonItem *backButton =[[UIBarButtonItem alloc] initWithCustomView:view];
}

- (void) handleBack:(id)sender{
}

EDIT:

Instead of adding the button, in my opinion the better approach is to use a gesture recognizer.

UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleBack:)];
[view addGestureRecognizer:tap];
[view setUserInteractionEnabled:YES];

Can't find file executable in your configured search path for gnc gcc compiler

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

Is null check needed before calling instanceof?

Using a null reference as the first operand to instanceof returns false.

Best way to parse command-line parameters?

I am from Java world, I like args4j because its simple, specification is more readable( thanks to annotations) and produces nicely formatted output.

Here is my example snippet:

Specification

import org.kohsuke.args4j.{CmdLineException, CmdLineParser, Option}

object CliArgs {

  @Option(name = "-list", required = true,
    usage = "List of Nutch Segment(s) Part(s)")
  var pathsList: String = null

  @Option(name = "-workdir", required = true,
    usage = "Work directory.")
  var workDir: String = null

  @Option(name = "-master",
    usage = "Spark master url")
  var masterUrl: String = "local[2]"

}

Parse

//var args = "-listt in.txt -workdir out-2".split(" ")
val parser = new CmdLineParser(CliArgs)
try {
  parser.parseArgument(args.toList.asJava)
} catch {
  case e: CmdLineException =>
    print(s"Error:${e.getMessage}\n Usage:\n")
    parser.printUsage(System.out)
    System.exit(1)
}
println("workDir  :" + CliArgs.workDir)
println("listFile :" + CliArgs.pathsList)
println("master   :" + CliArgs.masterUrl)

On invalid arguments

Error:Option "-list" is required
 Usage:
 -list VAL    : List of Nutch Segment(s) Part(s)
 -master VAL  : Spark master url (default: local[2])
 -workdir VAL : Work directory.

create a text file using javascript

From a web page this cannot work since IE restricts the use of that object.

Excel telling me my blank cells aren't blank

Here's how I fixed this problem without any coding.

  1. Select the entire column that I wanted to delete the "blank" cells from.
  2. Click the Conditional Formatting tab up top.
  3. Select "New Rule".
  4. Click "Format only cells that contain".
  5. Change "between" to "equal to".
  6. Click the box next to the "equal to" box.
  7. Click one of the problem "blank" cells.
  8. Click the Format Button.
  9. Pick a random color to fill the box with.
  10. Press "OK".
  11. This should change all of the problem "blank" cells to the color that you chose. Now Right click one of the colored cells, and go to "Sort" and "Put selected cell color on top".
  12. This will put all of the problem cells at the top of the column and now all of your other cells will stay in the original order you put them in. You can now select all of the problem cells in one group and click the delete cell button on top to get rid of them.

Select all 'tr' except the first one

sounds like the 'first line' you're talking of is your table-header - so you realy should think of using thead and tbody in your markup (click here) which would result in 'better' markup (semantically correct, useful for things like screenreaders) and easier, cross-browser-friendly possibilitys for css-selection (table thead ... { ... })

How to get File Created Date and Modified Date

File.GetLastWriteTime Method

Returns the date and time the specified file or directory was last written to.

string path = @"c:\Temp\MyTest.txt";
DateTime dt = File.GetLastWriteTime(path);

For create time File.GetCreationTime Method

DateTime fileCreatedDate = File.GetCreationTime(@"C:\Example\MyTest.txt");
Console.WriteLine("file created: " + fileCreatedDate);

How to customize the configuration file of the official PostgreSQL Docker image?

With Docker Compose

When working with Docker Compose, you can use command: postgres -c option=value in your docker-compose.yml to configure Postgres.

For example, this makes Postgres log to a file:

command: postgres -c logging_collector=on -c log_destination=stderr -c log_directory=/logs

Adapting Vojtech Vitek's answer, you can use

command: postgres -c config_file=/etc/postgresql.conf

to change the config file Postgres will use. You'd mount your custom config file with a volume:

volumes:
   - ./customPostgresql.conf:/etc/postgresql.conf

Here's the docker-compose.yml of my application, showing how to configure Postgres:

# Start the app using docker-compose pull && docker-compose up to make sure you have the latest image
version: '2.1'
services:
  myApp:
    image: registry.gitlab.com/bullbytes/myApp:latest
    networks:
      - myApp-network
  db:
     image: postgres:9.6.1
     # Make Postgres log to a file.
     # More on logging with Postgres: https://www.postgresql.org/docs/current/static/runtime-config-logging.html
     command: postgres -c logging_collector=on -c log_destination=stderr -c log_directory=/logs
     environment:
       # Provide the password via an environment variable. If the variable is unset or empty, use a default password
       - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-4WXUms893U6j4GE&Hvk3S*hqcqebFgo!vZi}
     # If on a non-Linux OS, make sure you share the drive used here. Go to Docker's settings -> Shared Drives
     volumes:
       # Persist the data between container invocations
       - postgresVolume:/var/lib/postgresql/data
       - ./logs:/logs
     networks:
       myApp-network:
         # Our application can communicate with the database using this hostname
         aliases:
           - postgresForMyApp
networks:
  myApp-network:
    driver: bridge
# Creates a named volume to persist our data. When on a non-Linux OS, the volume's data will be in the Docker VM
# (e.g., MobyLinuxVM) in /var/lib/docker/volumes/
volumes:
  postgresVolume:

Permission to write to the log directory

Note that when on Linux, the log directory on the host must have the right permissions. Otherwise you'll get the slightly misleading error

FATAL: could not open log file "/logs/postgresql-2017-02-04_115222.log": Permission denied

I say misleading, since the error message suggests that the directory in the container has the wrong permission, when in reality the directory on the host doesn't permit writing.

To fix this, I set the correct permissions on the host using

chgroup ./logs docker && chmod 770 ./logs

how to convert a string to an array in php

<?php

$str = "Hello Friend";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
print_r($arr2);

?>

Getting the application's directory from a WPF application

String exePath = System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName;
 string dir = Path.GetDirectoryName(exePath);

Try this!

The cause of "bad magic number" error when loading a workspace and how to avoid it?

I got the error when building an R package (using roxygen2)

The cause in my case was that I had saved data/mydata.RData with saveRDS() rather than save(). E.g. save(iris, file="data/iris.RData")

This fixed the issue for me. I found this info here

Also note that with save() / load() the object is loaded in with the same name it is initially saved with (i.e you can't rename it until it's already loaded into the R environment under the name it had when you initially saved it).

Sort Dictionary by keys

let dictionary = [
    "A" : [1, 2],
    "Z" : [3, 4],
    "D" : [5, 6]
]

let sortedKeys = Array(dictionary.keys).sorted(<) // ["A", "D", "Z"]

EDIT:

The sorted array from the above code contains keys only, while values have to be retrieved from the original dictionary. However, 'Dictionary' is also a 'CollectionType' of (key, value) pairs and we can use the global 'sorted' function to get a sorted array containg both keys and values, like this:

let sortedKeysAndValues = sorted(dictionary) { $0.0 < $1.0 }
println(sortedKeysAndValues) // [(A, [1, 2]), (D, [5, 6]), (Z, [3, 4])]

EDIT2: The monthly changing Swift syntax currently prefers

let sortedKeys = Array(dictionary.keys).sort(<) // ["A", "D", "Z"]

The global sorted is deprecated.

Which ChromeDriver version is compatible with which Chrome Browser version?

I found, that chrome and chromedriver versions support policy has changed recently.

As stated on downloads page:

There is general guide to select version of crhomedriver for specific chrome version: https://sites.google.com/a/chromium.org/chromedriver/downloads/version-selection

Here is excerpt:

  • First, find out which version of Chrome you are using. Let's say you have Chrome 72.0.3626.81.
  • Take the Chrome version number, remove the last part, and append the result to URL "https://chromedriver.storage.googleapis.com/LATEST_RELEASE_". For example, with Chrome version 72.0.3626.81, you'd get a URL "https://chromedriver.storage.googleapis.com/LATEST_RELEASE_72.0.3626".
  • Use the URL created in the last step to retrieve a small file containing the version of ChromeDriver to use. For example, the above URL will get your a file containing "72.0.3626.69". (The actual number may change in the future, of course.)
  • Use the version number retrieved from the previous step to construct the URL to download ChromeDriver. With version 72.0.3626.69, the URL would be "https://chromedriver.storage.googleapis.com/index.html?path=72.0.3626.69/".
  • After the initial download, it is recommended that you occasionally go through the above process again to see if there are any bug fix releases.

Note, that this version selection algorithm can be easily automated. For example, simple powershell script in another answer has automated chromedriver updating on windows platform.

Hibernate openSession() vs getCurrentSession()

SessionFactory: "One SessionFactory per application per DataBase" ( e.g., if you use 3 DataBase's in our application , you need to create sessionFactory object per each DB , totally you need to create 3 sessionFactorys . or else if you have only one DataBase One sessionfactory is enough ).

Session: "One session for one request-response cycle". you can open session when request came and you can close session after completion of request process. Note:-Don't use one session for web application.

How to use mod operator in bash?

You must put your mathematical expressions inside $(( )).

One-liner:

for i in {1..600}; do wget http://example.com/search/link$(($i % 5)); done;

Multiple lines:

for i in {1..600}; do
    wget http://example.com/search/link$(($i % 5))
done

Add custom icons to font awesome

Depends on what you have. If your svg icon is just a path, then it's easy enough to add that glyph by just copying the 'd' attribute to a new <glyph> element. However, the path needs to be scaled to the font's coordinate system (the EM-square, which typically is [0,0,2048,2048] - the standard for Truetype fonts) and aligned with the baseline you want.

Not all browsers support svg fonts however, so you're going to have to convert it to other formats too if you want it to work everywhere.

Fontforge can import svg files (select a glyph slot, File > Import and then select your svg image), and you can then convert to all the relevant font formats (svg, truetype, woff etc).

Using a RegEx to match IP addresses in Python

I came across the same situation, I found the answer with use of socket library helpful but it doesn't provide support for ipv6 addresses. Found a better way for it:

Unfortunately it Works for python3 only

import ipaddress

def valid_ip(address):
    try: 
        print ipaddress.ip_address(address)
        return True
    except:
        return False

print valid_ip('10.10.20.30')
print valid_ip('2001:DB8::1')
print valid_ip('gibberish')

Portable way to check if directory exists [Windows/Linux, C]

Use boost::filesystem, that will give you a portable way of doing those kinds of things and abstract away all ugly details for you.

How to remove new line characters from a string?

You want to use String.Replace to remove a character.

s = s.Replace("\n", String.Empty);
s = s.Replace("\r", String.Empty);
s = s.Replace("\t", String.Empty);

Note that String.Trim(params char[] trimChars) only removes leading and trailing characters in trimChars from the instance invoked on.

You could make an extension method, which avoids the performance problems of the above of making lots of temporary strings:

static string RemoveChars(this string s, params char[] removeChars) {
    Contract.Requires<ArgumentNullException>(s != null);
    Contract.Requires<ArgumentNullException>(removeChars != null);
    var sb = new StringBuilder(s.Length);
    foreach(char c in s) { 
        if(!removeChars.Contains(c)) {
            sb.Append(c);
        }
    }
    return sb.ToString();
}

Timing Delays in VBA

I used the answer of Steve Mallory, but I am affraid the timer never or at least sometimes does not go to 86400 nor 0 (zero) sharp (MS Access 2013). So I modified the code. I changed the midnight condition to "If Timer >= 86399 Then" and added the break of the loop "Exit Do" as follows:

Public Function Pause(NumberOfSeconds As Variant)
    On Error GoTo Error_GoTo

    Dim PauseTime As Variant
    Dim Start As Variant
    Dim Elapsed As Variant

    PauseTime = NumberOfSeconds
    Start = Timer
    Elapsed = 0
    Do While Timer < Start + PauseTime
        Elapsed = Elapsed + 1
        If Timer >= 86399
            ' Crossing midnight
            ' PauseTime = PauseTime - Elapsed
            ' Start = 0
            ' Elapsed = 0
            Exit Do
        End If
        DoEvents
    Loop

Exit_GoTo:
    On Error GoTo 0
    Exit Function
Error_GoTo:
    Debug.Print Err.Number, Err.Description, Erl
    GoTo Exit_GoTo
End Function

How to POST request using RestSharp

This way works fine for me:

var request = new RestSharp.RestRequest("RESOURCE", RestSharp.Method.POST) { RequestFormat = RestSharp.DataFormat.Json }
                .AddBody(BODY);

var response = Client.Execute(request);

// Handle response errors
HandleResponseErrors(response);

if (Errors.Length == 0)
{ }
else
{ }

Hope this helps! (Although it is a bit late)

Entity Framework - Linq query with order by and group by

It's method syntax (which I find easier to read) but this might do it

Updated post comment

Use .FirstOrDefault() instead of .First()

With regard to the dates average, you may have to drop that ordering for the moment as I am unable to get to an IDE at the moment

var groupByReference = context.Measurements
                              .GroupBy(m => m.Reference)
                              .Select(g => new {Creation = g.FirstOrDefault().CreationTime, 
//                                              Avg = g.Average(m => m.CreationTime.Ticks),
                                                Items = g })
                              .OrderBy(x => x.Creation)
//                            .ThenBy(x => x.Avg)
                              .Take(numOfEntries)
                              .ToList();

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

I suggest you run:

$ brew update && brew upgrade

Until couple of minutes ago I had this problem, too. Because I have an up to date PHP version, I solved it with:

$ brew reinstall php55

Hope that helps.

Node.js: how to consume SOAP XML web service

You can use wsdlrdr also. EasySoap is basically rewrite of wsdlrdr with some extra methods. Be careful that easysoap doesn't have the getNamespace method which is available at wsdlrdr.

Web scraping with Java

Normally I use selenium, which is software for testing automation. You can control a browser through a webdriver, so you will not have problems with javascripts and it is usually not very detected if you use the full version. Headless browsers can be more identified.

SET NAMES utf8 in MySQL?

Thanks @all!

don't use: query("SET NAMES utf8"); this is setup stuff and not a query. put it right afte a connection start with setCharset() (or similar method)

some little thing in parctice:

status:

  • mysql server by default talks latin1
  • your hole app is in utf8
  • connection is made without any extra (so: latin1) (no SET NAMES utf8 ..., no set_charset() method/function)

Store and read data is no problem as long mysql can handle the characters. if you look in the db you will already see there is crap in it (e.g.using phpmyadmin).

until now this is not a problem! (wrong but works often (in europe)) ..

..unless another client/programm or a changed library, which works correct, will read/save data. then you are in big trouble!

Get current application physical path within Application_Start

Best choice is using

AppDomain.CurrentDomain.BaseDirectory

because it's in the system namespace and there is no dependency to system.web

this way your code will be more portable

How to set min-font-size in CSS

No. While you can set a base font size on body using the font-size property, anything after that that specifies a smaller size will override the base rule for that element. In order to do what you are looking to do you will need to use Javascript.

You could iterate through the elements on the page and change the smaller fonts using something like this:

$("*").each( function () {
    var $this = $(this);
    if (parseInt($this.css("fontSize")) < 12) {
        $this.css({ "font-size": "12px" });   
    }
});

Here is a Fiddle where you can see it done: http://jsfiddle.net/mifi79/LfdL8/2/

How to clear mysql screen console in windows?

just type \system cls

took me a couple hours to get it jejej

'this' is undefined in JavaScript class methods

In ES2015 a.k.a ES6, class is a syntactic sugar for functions.

If you want to force to set a context for this you can use bind() method. As @chetan pointed, on invocation you can set the context as well! Check the example below:

class Form extends React.Component {
constructor() {
    super();
  }
  handleChange(e) {
    switch (e.target.id) {
      case 'owner':
        this.setState({owner: e.target.value});
        break;
      default:
    }
  }
  render() {
    return (
      <form onSubmit={this.handleNewCodeBlock}>
        <p>Owner:</p> <input onChange={this.handleChange.bind(this)} />
      </form>
    );
  }
}

Here we forced the context inside handleChange() to Form.

Retrieve the maximum length of a VARCHAR column in SQL Server

For IBM Db2 its LENGTH, not LEN:

SELECT MAX(LENGTH(Desc)) FROM table_name;

String vs. StringBuilder

If you're doing a lot of string concatenation, use a StringBuilder. When you concatenate with a String, you create a new String each time, using up more memory.

Alex

Error inflating class fragment

I was receiving this error for different reasons.

Steps to reproduce:

~> My issue was that I created a brand new blank application.

~> I then generated a custom fragment from the File ~> New File Menu.

~> Proceeded to customize the fragment by adding layouts and buttons etc.

~> Referenced the new custom fragment in the auto generated activity_my.xml that was generated for me when creating the application. Doing this allowed the XML to generate the objects for me.

Heres is the catch when generating the custom fragment via File ~> New File Menu it auto generates an interface function stub and places it at the bottom of the fragment class file.

This means that your MyActivity class must implement this interface. If it does not then the the above error occurs only when referencing the fragment from xml. By removing the reference for the Fragment in the XML completely, and creating the fragment through code in the MyActivity.java class file Logcat generates a more concise error explaining the issue in detail and complaining about the interface. This is demonstrated in the Project Template Activity+Fragment. Although, <~that Project Template does not generate the interface stub.

Android ADB devices unauthorized

In Android studio, Run menu > Run shows OFFLINE ... for the connected device.

Below is the procedure followed to solve it:

  1. (Read the below note first) Delete the ~/.android/adbkey (or, rename to ~/.android/adbkey2, this is even better incase you want it back for some reason)
    Note: I happened to do this step, but it didn't solve the problem, after doing all the below steps it worked, so unsure if this step is required.

  2. Run locate platform-tools/adb
    Note: use the path that comes from here in below commands

  3. Kill adb server:
    sudo ~/Android/Sdk/platform-tools/adb kill-server

  4. You will get a Allow accept.. message popup on your device. Accept it. This is important, which solves the problem.

  5. Start adb server:
    sudo ~/Android/Sdk/platform-tools/adb start-server

  6. In Android studio, do Run menu > Run again
    It will show something like Samsung ... (your phone manufacture name).
    Also installs the apk on device correctly this time without error.

Hope that helps.

How to rename with prefix/suffix?

In Bash and zsh you can do this with Brace Expansion. This simply expands a list of items in braces. For example:

# echo {vanilla,chocolate,strawberry}-ice-cream
vanilla-ice-cream chocolate-ice-cream strawberry-ice-cream

So you can do your rename as follows:

mv {,new.}original.filename

as this expands to:

mv original.filename new.original.filename

How to add an image to the emulator gallery in android studio?

How to import images into the gallery of an Android Virtual Device using Android Studio: I'm using Android Studio 1.4.1 and a API 15 virtual device.

Warning: This is manual intensive so it is not a good solution for a large number of images.

  1. Create a virtual device using Android's Device Manager (AVD), Menu /Tools/Android/AVD Manager.
  2. Start this virtual device.
  3. Start the Android Device monitor, Menu */Tools/Android/Android Device Monitor. In the Devices tab (upper left) you should see your device. It should be Online (see this screenshot)
  4. On the right window is the File Explorer. Go there and select the /mnt/sdcard/Pictures directory. It should be highlighted (see this screenshot)
  5. Add jpegs to this directory by clicking on the Push a file onto the device icon (the little phone icon I highlighted in the above screenshot. You can add only one photo at a time, dadburnit.
  6. Go to your device and run the Dev Tools app.
  7. Scroll down and select Media Provider.
  8. Click on the Scan SD Card button. This should copy the images you added in step 5 to the gallery. Go to the gallery and look, they should be there.

How can I get the current contents of an element in webdriver

In Java its Webelement.getText() . Not sure about python.

Combine hover and click functions (jQuery)?

$("#target").hover(function(){
  $(this).click();
}).click(function(){
  //common function
});

Converting an integer to a hexadecimal string in Ruby

Just in case you have a preference for how negative numbers are formatted:

p "%x" % -1   #=> "..f"
p -1.to_s(16) #=> "-1"

Apache and Node.js on the Same Server

You can use a different approach such as writing a reverse proxy server with nodejs to proxy both apache and all other nodejs apps.

First you need to make apache run on a different port other than port 80. ex: port 8080

Then you can write a reverse proxy script with nodejs as:

var proxy = require('redbird')({port: 80, xfwd: false);

proxy.register("mydomain.me/blog", "http://mydomain.me:8080/blog");
proxy.register("mydomain.me", "http://mydomain.me:3000");

Following article describes the whole process of making this.

RUN APACHE WITH NODE JS REVERSE PROXY – USING REDBIRD

Visual Studio 2015 Update 3 Offline Installer (ISO)

The ISO file that suggested in the accepted answer is still not complete. The very complete offline installer is about 24GB! There is only one way to get it. follow these steps:

  1. Download Web Installer from Microsoft Web Site
  2. Execute the Installer. NOTE: the installer is still a simple downloader for the real web-installer.
  3. After running the real web installer, Run Windows Task manager and find the real web installer path that is stored in your temp folder
  4. copy the real installer somewhere else. like C:\VS Community\
  5. Open Command Prompt and execute the installer that you copied to C:\VS Community\ with this argument: /Layout .
  6. Now installer will download the FULL offline installer to your selected folder!

Good Luck

What causes: "Notice: Uninitialized string offset" to appear?

It means one of your arrays isn't actually an array.

By the way, your if check is unnecessary. If $varsCount is 0 the for loop won't execute anyway.

In AVD emulator how to see sdcard folder? and Install apk to AVD?

Adding to the usefile DDMS/File Explorer solution, for those that don't know, if you want to read a file you need to select the "Pull File from Device" button on the file viewer toolbar. Unfortunately you can't just drag out, or double click to read.

How to change href attribute using JavaScript after opening the link in a new window?

for example try this :

<a href="http://www.google.com" id="myLink1">open link 1</a><br/> <a href="http://www.youtube.com" id="myLink2">open link 2</a>



    document.getElementById("myLink1").onclick = function() {
    window.open(
    "http://www.facebook.com"
        );
        return false;
      };

      document.getElementById("myLink2").onclick = function() {
    window.open(
    "http://www.yahoo.com"
        );
        return false;
      };

Inline instantiation of a constant List

You are looking for a simple code, like this:

    List<string> tagList = new List<string>(new[]
    {
         "A"
        ,"B"
        ,"C"
        ,"D"
        ,"E"
    });

What is the purpose of using -pedantic in GCC/G++ compiler?

Others have answered sufficiently. I would just like to add a few examples of frequent extensions:

The main function returning void. This is not defined by the standard, meaning it will only work on some compilers (including GCC), but not on others. By the way, int main() and int main(int, char**) are the two signatures that the standard does define.

Another popular extension is being able to declare and define functions inside other functions:

void f()
{
    void g()
    {
       // ...
    }

    // ...
    g();
    // ...
}

This is nonstandard. If you want this kind of behavior, check out C++11 lambdas

jQuery: Selecting by class and input type

Just in case any dummies like me tried the suggestions here with a button and found nothing worked, you probably want this:

$(':button.myclass')

CSS3 opacity gradient?

We can do it by css like.

body {
  background: #000;
  background-image: linear-gradient(90deg, rgba(255, 255, 255, .3) 0%, rgba(231, 231, 231, .3) 22.39%, rgba(209, 209, 209,  .3) 42.6%, rgba(182, 182, 182, .3) 79.19%, rgba(156, 156, 156, .3) 104.86%);
  
}

How to loop in excel without VBA or macros?

Add more columns when you have variable loops that repeat at different rates. I'm not sure explicitly what you're trying to do, but I think I've done something that could apply.

Creating a single loop in Excel is prettty simple. It actually does the work for you. Try this on a new workbook

  1. Enter "1" in A1
  2. Enter "=A1+1" in A2

A3 will automatically be "=A2+1" as you drag down. The first steps don't have to be that explicit. Excel will automatically recognize the pattern and count if you just put "2" in A2, but if we want B1-B5 to be "100" and B5-B10 to be "200" (counting up the same way) you can see why knowing how to do it explicitly matters. In this scenario, You just enter:

  1. "100" in B1, drag through to B5 and
  2. "=B1+100" in B6

B7 will automatically be "=B2+100" etc. as you drag down, so basically it increases every 5 rows infinitely. To make a loop of numbers 1-5 in column A:

  1. Enter "=A1" in cell A6. As you drag down, it will automatically be "=A2" in cell A7, etc. because of the way that Excel does things.

So, now we have column A repeating numbers 1-5 while column B is increasing by 100 every 5 cells.You could make column B repeat, for instance, the numbers 100-900 in using the same method as you did with column A as a way to produce, for instance, each possible combination with multiple variables. Drag down the columns and they'll do it infinitely. I'm not explicitly addressing the scenario given, but if you follow the steps and understand them, the concept should give you an answer to the problem that involves adding more columns and concactinating or using them as your variables.

How do I get a list of installed CPAN modules?

On Linux/Unix I use this simple command:

perl -e 'print qx/find $_ -name "*.pm"/ foreach ( @INC );' 

It scans all folder in @INC and looks for any *.pm file.

When should null values of Boolean be used?

Boolean wrapper is useful when you want to whether value was assigned or not apart from true and false. It has the following three states:

  • True
  • False
  • Not defined which is null

Whereas boolean has only two states:

  • True
  • False

The above difference will make it helpful in Lists of Boolean values, which can have True, False or Null.

How to redirect cin and cout to files?

Just write

#include <cstdio>
#include <iostream>
using namespace std;

int main()
{
    freopen("output.txt","w",stdout);
    cout<<"write in file";
    return 0;
}

How to put a delay on AngularJS instant search?

 <input type="text"
    ng-model ="criteria.searchtext""  
    ng-model-options="{debounce: {'default': 1000, 'blur': 0}}"
    class="form-control" 
    placeholder="Search" >

Now we can set ng-model-options debounce with time and when blur, model need to be changed immediately otherwise on save it will have older value if delay is not completed.

Git: How to find a deleted file in the project commit history?

Could not edit the accepted response so adding it as an answer here,

to restore the file in git, use the following (note the '^' sign just after the SHA)

git checkout <SHA>^ -- /path/to/file

Get height and width of a layout programmatically

try with this metods:

int width = mView.getMeasuredWidth();

int height = mView.getMeasuredHeight();

Or

int width = mTextView.getMeasuredWidth();

int height = mTextView.getMeasuredHeight();

Getting A File's Mime Type In Java

I tried several ways to do it, including the first ones said by @Joshua Fox. But some don't recognize frequent mimetypes like for PDF files, and other could not be trustable with fake files (I tried with a RAR file with extension changed to TIF). The solution I found, as also is said by @Joshua Fox in a superficial way, is to use MimeUtil2, like this:

MimeUtil2 mimeUtil = new MimeUtil2();
mimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
String mimeType = MimeUtil2.getMostSpecificMimeType(mimeUtil.getMimeTypes(file)).toString();

How to drop SQL default constraint without knowing its name?

Expanding on Mitch Wheat's code, the following script will generate the command to drop the constraint and dynamically execute it.

declare @schema_name nvarchar(256)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
declare @Command  nvarchar(1000)

set @schema_name = N'MySchema'
set @table_name = N'Department'
set @col_name = N'ModifiedDate'

select @Command = 'ALTER TABLE ' + @schema_name + '.[' + @table_name + '] DROP CONSTRAINT ' + d.name
 from sys.tables t
  join sys.default_constraints d on d.parent_object_id = t.object_id
  join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id
 where t.name = @table_name
  and t.schema_id = schema_id(@schema_name)
  and c.name = @col_name

--print @Command

execute (@Command)

can you add HTTPS functionality to a python flask web server?

this also works in a pinch

from flask import Flask, jsonify


from OpenSSL import SSL
context = SSL.Context(SSL.PROTOCOL_TLSv1_2)
context.use_privatekey_file('server.key')
context.use_certificate_file('server.crt')   


app = Flask(__name__)


@app.route('/')
def index():
    return 'Flask is running!'


@app.route('/data')
def names():
    data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}
    return jsonify(data)


#if __name__ == '__main__':
#    app.run()
if __name__ == '__main__':  
     app.run(host='127.0.0.1', debug=True, ssl_context=context)

PHP string concatenation

This should be faster.

while ($personCount < 10) {
    $result .= "{$personCount} people ";
    $personCount++;
}

echo $result;

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

You can find all schema related information in the wisely named information_schema table.

You might want to check the table REFERENTIAL_CONSTRAINTS and KEY_COLUMN_USAGE. The former tells you which tables are referenced by others; the latter will tell you how their fields are related.

pull out p-values and r-squared from a linear regression

Notice that summary(fit) generates an object with all the information you need. The beta, se, t and p vectors are stored in it. Get the p-values by selecting the 4th column of the coefficients matrix (stored in the summary object):

summary(fit)$coefficients[,4] 
summary(fit)$r.squared

Try str(summary(fit)) to see all the info that this object contains.

Edit: I had misread Chase's answer which basically tells you how to get to what I give here.

Uncaught TypeError: Cannot read property 'length' of undefined

You are accessing an object that is not defined.

The solution is check for null or undefined (to see whether the object exists) and only then iterate.

failed to open stream: No such file or directory in

include() needs a full file path, relative to the file system's root directory.

This should work:

 include_once("C:/xampp/htdocs/PoliticalForum/headerSite.php");

What are SP (stack) and LR in ARM?

SP is the stack register a shortcut for typing r13. LR is the link register a shortcut for r14. And PC is the program counter a shortcut for typing r15.

When you perform a call, called a branch link instruction, bl, the return address is placed in r14, the link register. the program counter pc is changed to the address you are branching to.

There are a few stack pointers in the traditional ARM cores (the cortex-m series being an exception) when you hit an interrupt for example you are using a different stack than when running in the foreground, you dont have to change your code just use sp or r13 as normal the hardware has done the switch for you and uses the correct one when it decodes the instructions.

The traditional ARM instruction set (not thumb) gives you the freedom to use the stack in a grows up from lower addresses to higher addresses or grows down from high address to low addresses. the compilers and most folks set the stack pointer high and have it grow down from high addresses to lower addresses. For example maybe you have ram from 0x20000000 to 0x20008000 you set your linker script to build your program to run/use 0x20000000 and set your stack pointer to 0x20008000 in your startup code, at least the system/user stack pointer, you have to divide up the memory for other stacks if you need/use them.

Stack is just memory. Processors normally have special memory read/write instructions that are PC based and some that are stack based. The stack ones at a minimum are usually named push and pop but dont have to be (as with the traditional arm instructions).

If you go to http://github.com/lsasim I created a teaching processor and have an assembly language tutorial. Somewhere in there I go through a discussion about stacks. It is NOT an arm processor but the story is the same it should translate directly to what you are trying to understand on the arm or most other processors.

Say for example you have 20 variables you need in your program but only 16 registers minus at least three of them (sp, lr, pc) that are special purpose. You are going to have to keep some of your variables in ram. Lets say that r5 holds a variable that you use often enough that you dont want to keep it in ram, but there is one section of code where you really need another register to do something and r5 is not being used, you can save r5 on the stack with minimal effort while you reuse r5 for something else, then later, easily, restore it.

Traditional (well not all the way back to the beginning) arm syntax:

...
stmdb r13!,{r5}
...temporarily use r5 for something else...
ldmia r13!,{r5}
...

stm is store multiple you can save more than one register at a time, up to all of them in one instruction.

db means decrement before, this is a downward moving stack from high addresses to lower addresses.

You can use r13 or sp here to indicate the stack pointer. This particular instruction is not limited to stack operations, can be used for other things.

The ! means update the r13 register with the new address after it completes, here again stm can be used for non-stack operations so you might not want to change the base address register, leave the ! off in that case.

Then in the brackets { } list the registers you want to save, comma separated.

ldmia is the reverse, ldm means load multiple. ia means increment after and the rest is the same as stm

So if your stack pointer were at 0x20008000 when you hit the stmdb instruction seeing as there is one 32 bit register in the list it will decrement before it uses it the value in r13 so 0x20007FFC then it writes r5 to 0x20007FFC in memory and saves the value 0x20007FFC in r13. Later, assuming you have no bugs when you get to the ldmia instruction r13 has 0x20007FFC in it there is a single register in the list r5. So it reads memory at 0x20007FFC puts that value in r5, ia means increment after so 0x20007FFC increments one register size to 0x20008000 and the ! means write that number to r13 to complete the instruction.

Why would you use the stack instead of just a fixed memory location? Well the beauty of the above is that r13 can be anywhere it could be 0x20007654 when you run that code or 0x20002000 or whatever and the code still functions, even better if you use that code in a loop or with recursion it works and for each level of recursion you go you save a new copy of r5, you might have 30 saved copies depending on where you are in that loop. and as it unrolls it puts all the copies back as desired. with a single fixed memory location that doesnt work. This translates directly to C code as an example:

void myfun ( void )
{
   int somedata;
}

In a C program like that the variable somedata lives on the stack, if you called myfun recursively you would have multiple copies of the value for somedata depending on how deep in the recursion. Also since that variable is only used within the function and is not needed elsewhere then you perhaps dont want to burn an amount of system memory for that variable for the life of the program you only want those bytes when in that function and free that memory when not in that function. that is what a stack is used for.

A global variable would not be found on the stack.

Going back...

Say you wanted to implement and call that function you would have some code/function you are in when you call the myfun function. The myfun function wants to use r5 and r6 when it is operating on something but it doesnt want to trash whatever someone called it was using r5 and r6 for so for the duration of myfun() you would want to save those registers on the stack. Likewise if you look into the branch link instruction (bl) and the link register lr (r14) there is only one link register, if you call a function from a function you will need to save the link register on each call otherwise you cant return.

...
bl myfun
    <--- the return from my fun returns here
...


myfun:
stmdb sp!,{r5,r6,lr}
sub sp,#4 <--- make room for the somedata variable
...
some code here that uses r5 and r6
bl more_fun <-- this modifies lr, if we didnt save lr we wouldnt be able to return from myfun
   <---- more_fun() returns here
...
add sp,#4 <-- take back the stack memory we allocated for the somedata variable
ldmia sp!,{r5,r6,lr}
mov pc,lr <---- return to whomever called myfun.

So hopefully you can see both the stack usage and link register. Other processors do the same kinds of things in a different way. for example some will put the return value on the stack and when you execute the return function it knows where to return to by pulling a value off of the stack. Compilers C/C++, etc will normally have a "calling convention" or application interface (ABI and EABI are names for the ones ARM has defined). if every function follows the calling convention, puts parameters it is passing to functions being called in the right registers or on the stack per the convention. And each function follows the rules as to what registers it does not have to preserve the contents of and what registers it has to preserve the contents of then you can have functions call functions call functions and do recursion and all kinds of things, so long as the stack does not go so deep that it runs into the memory used for globals and the heap and such, you can call functions and return from them all day long. The above implementation of myfun is very similar to what you would see a compiler produce.

ARM has many cores now and a few instruction sets the cortex-m series works a little differently as far as not having a bunch of modes and different stack pointers. And when executing thumb instructions in thumb mode you use the push and pop instructions which do not give you the freedom to use any register like stm it only uses r13 (sp) and you cannot save all the registers only a specific subset of them. the popular arm assemblers allow you to use

push {r5,r6}
...
pop {r5,r6}

in arm code as well as thumb code. For the arm code it encodes the proper stmdb and ldmia. (in thumb mode you also dont have the choice as to when and where you use db, decrement before, and ia, increment after).

No you absolutly do not have to use the same registers and you dont have to pair up the same number of registers.

push {r5,r6,r7}
...
pop {r2,r3}
...
pop {r1}

assuming there is no other stack pointer modifications in between those instructions if you remember the sp is going to be decremented 12 bytes for the push lets say from 0x1000 to 0x0FF4, r5 will be written to 0xFF4, r6 to 0xFF8 and r7 to 0xFFC the stack pointer will change to 0x0FF4. the first pop will take the value at 0x0FF4 and put that in r2 then the value at 0x0FF8 and put that in r3 the stack pointer gets the value 0x0FFC. later the last pop, the sp is 0x0FFC that is read and the value placed in r1, the stack pointer then gets the value 0x1000, where it started.

The ARM ARM, ARM Architectural Reference Manual (infocenter.arm.com, reference manuals, find the one for ARMv5 and download it, this is the traditional ARM ARM with ARM and thumb instructions) contains pseudo code for the ldm and stm ARM istructions for the complete picture as to how these are used. Likewise well the whole book is about the arm and how to program it. Up front the programmers model chapter walks you through all of the registers in all of the modes, etc.

If you are programming an ARM processor you should start by determining (the chip vendor should tell you, ARM does not make chips it makes cores that chip vendors put in their chips) exactly which core you have. Then go to the arm website and find the ARM ARM for that family and find the TRM (technical reference manual) for the specific core including revision if the vendor has supplied that (r2p0 means revision 2.0 (two point zero, 2p0)), even if there is a newer rev, use the manual that goes with the one the vendor used in their design. Not every core supports every instruction or mode the TRM tells you the modes and instructions supported the ARM ARM throws a blanket over the features for the whole family of processors that that core lives in. Note that the ARM7TDMI is an ARMv4 NOT an ARMv7 likewise the ARM9 is not an ARMv9. ARMvNUMBER is the family name ARM7, ARM11 without a v is the core name. The newer cores have names like Cortex and mpcore instead of the ARMNUMBER thing, which reduces confusion. Of course they had to add the confusion back by making an ARMv7-m (cortex-MNUMBER) and the ARMv7-a (Cortex-ANUMBER) which are very different families, one is for heavy loads, desktops, laptops, etc the other is for microcontrollers, clocks and blinking lights on a coffee maker and things like that. google beagleboard (Cortex-A) and the stm32 value line discovery board (Cortex-M) to get a feel for the differences. Or even the open-rd.org board which uses multiple cores at more than a gigahertz or the newer tegra 2 from nvidia, same deal super scaler, muti core, multi gigahertz. A cortex-m barely brakes the 100MHz barrier and has memory measured in kbytes although it probably runs of a battery for months if you wanted it to where a cortex-a not so much.

sorry for the very long post, hope it is useful.

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

I was having the same problem. None of the above solutions worked for me. The key challenge was that I didn't have the root access. So, I first download the source of libffi. Then I compiled it with usual commands:

./configure --prefix=desired_installation_path_to_libffi
make 

Then I recompiled python using

./configure --prefix=/home/user123/Softwares/Python/installation3/  LDFLAGS='-L/home/user123/Softwares/library/libffi/installation/lib64'
make 
make install

In my case, 'home/user123/Softwares/library/libffi/installation/lib64' is path to LIBFFI installation directory where libffi.so is located. And, /home/user123/Softwares/Python/installation3/ is path to Python installation directory. Modify them as per your case.

Can't ping a local VM from the host

try to drop the firewall on your laptop and see if there is difference. Maybe Your laptop is firewall blocking some broadcasts that prevents local network name resolution.

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

I have encountered this problem in Eclipse Luna EE. My solution was simply restart eclipse and it magically started loading servlet properly.

.NET Events - What are object sender & EventArgs e?

sender refers to the object that invoked the event that fired the event handler. This is useful if you have many objects using the same event handler.

EventArgs is something of a dummy base class. In and of itself it's more or less useless, but if you derive from it, you can add whatever data you need to pass to your event handlers.

When you implement your own events, use an EventHandler or EventHandler<T> as their type. This guarantees that you'll have exactly these two parameters for all your events (which is a good thing).

What's the difference between Docker Compose vs. Dockerfile

In my workflow, I add a Dockerfile for each part of my system and configure it that each part could run individually. Then I add a docker-compose.yml to bring them together and link them.

Biggest advantage (in my opinion): when linking the containers, you can define a name and ping your containers with this name. Therefore your database might be accessible with the name db and no longer by its IP.

Combine two pandas Data Frames (join on a common column)

You can use merge to combine two dataframes into one:

import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')

where on specifies field name that exists in both dataframes to join on, and how defines whether its inner/outer/left/right join, with outer using 'union of keys from both frames (SQL: full outer join).' Since you have 'star' column in both dataframes, this by default will create two columns star_x and star_y in the combined dataframe. As @DanAllan mentioned for the join method, you can modify the suffixes for merge by passing it as a kwarg. Default is suffixes=('_x', '_y'). if you wanted to do something like star_restaurant_id and star_restaurant_review, you can do:

 pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer', suffixes=('_restaurant_id', '_restaurant_review'))

The parameters are explained in detail in this link.

Viewing root access files/folders of android on windows

Obviously, you'll need a rooted android device. Then set up an FTP server and transfer the files.

Iterator invalidation rules

Here is a nice summary table from cppreference.com:

enter image description here

Here, insertion refers to any method which adds one or more elements to the container and erasure refers to any method which removes one or more elements from the container.

How do I import a namespace in Razor View Page?

"using MyNamespace" works in MVC3 RTM. Hope this helps.

Append a tuple to a list - what's the difference between two ways?

The tuple function takes only one argument which has to be an iterable

tuple([iterable])

Return a tuple whose items are the same and in the same order as iterable‘s items.

Try making 3,4 an iterable by either using [3,4] (a list) or (3,4) (a tuple)

For example

a_list.append(tuple((3, 4)))

will work

How to enter a series of numbers automatically in Excel

Enter the formula =ROW() into any cell and that cell will show the row number as its value.

If you want 1001, 1002 etc just enter =1000+ROW()

jQuery adding 2 numbers from input fields

<script type="text/javascript">
    $(document).ready(function () {
        $('#btnadd').on('click', function () {
            var n1 = parseInt($('#txtn1').val());
            var n2 = parseInt($('#txtn2').val());
            var r = n1 + n2;
            alert("sum of 2 No= " + r);
            return false;
        });
        $('#btnclear').on('click', function () {
            $('#txtn1').val('');
            $('#txtn2').val('');
            $('#txtn1').focus();
            return false;
        });
    });
</script>

How to force garbage collection in Java?

I would like to add some thing here. Please not that Java runs on Virtual Machine and not actual Machine. The virtual machine has its own way of communication with the machine. It may varry from system to system. Now When we call the GC we ask the Virtual Machine of Java to call the Garbage Collector.

Since the Garbage Collector is with Virtual Machine , we can not force it to do a cleanup there and then. Rather that we queue our request with the Garbage Collector. It depends on the Virtual Machine, after particular time (this may change from system to system, generally when the threshold memory allocated to the JVM is full) the actual machine will free up the space. :D

How to include bootstrap css and js in reactjs app?

Full answer to give you jquery and bootstrap since jquery is a requirement for bootstrap.js:

Install jquery and bootstrap into node_modules:

npm install bootstrap
npm install jquery

Import in your components using this exact filepath:

import 'jquery/src/jquery'; //for bootstrap.min.js
//bootstrap-theme file for bootstrap 3 only
import 'bootstrap/dist/css/bootstrap-theme.min.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.min.js';

Unfinished Stubbing Detected in Mockito

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
E.g. thenReturn() may be missing.

For mocking of void methods try out below:

//Kotlin Syntax

 Mockito.`when`(voidMethodCall())
           .then {
                Unit //Do Nothing
            }