问:
Could not initialize plugin: interface org.mockito.plugins.MockMaker
I'm getting following exception once tests is started:

```<code>    Testcase: treeCtorArgumentTest(com.xythos.client.drive.cachedtree.CachedTreeTest):  Caused an ERROR
Could not initialize plugin: interface org.mockito.plugins.MockMaker
java.lang.IllegalStateException: Could not initialize plugin: interface org.mockito.plugins.MockMaker
    at org.mockito.internal.configuration.plugins.PluginLoader$1.invoke(PluginLoader.java:66)
    at com.sun.proxy.$Proxy7.isTypeMockable(Unknown Source)
    at org.mockito.internal.util.MockUtil.typeMockabilityOf(MockUtil.java:29)
    at org.mockito.internal.util.MockCreationValidator.validateType(MockCreationValidator.java:22)
    at org.mockito.internal.creation.MockSettingsImpl.validatedSettings(MockSettingsImpl.java:168)
    at org.mockito.internal.creation.MockSettingsImpl.confirm(MockSettingsImpl.java:162)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:64)
    at org.mockito.Mockito.mock(Mockito.java:1687)
    at org.mockito.Mockito.mock(Mockito.java:1600)
    at com.xythos.client.drive.cachedtree.CachedTreeTest.setUp(CachedTreeTest.java:51)
Caused by: java.lang.NoClassDefFoundError: net/bytebuddy/dynamic/loading/ClassLoadingStrategy
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.<init>(SubclassByteBuddyMockMaker.java:33)
    at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.<init>(ByteBuddyMockMaker.java:22)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at org.mockito.internal.configuration.plugins.PluginLoader.loadPlugin(PluginLoader.java:54)
    at org.mockito.internal.configuration.plugins.PluginRegistry.<init>(PluginRegistry.java:18)
    at org.mockito.internal.configuration.plugins.Plugins.<clinit>(Plugins.java:17)
    at org.mockito.internal.util.MockUtil.<clinit>(MockUtil.java:24)
Caused by: java.lang.ClassNotFoundException: net.bytebuddy.dynamic.loading.ClassLoadingStrategy
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
</code>```

This is my test:

```<code>package com.xythos.client.drive.cachedtree;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)

    public class CachedTreeTest {

        public CachedTreeTest() {
        }

        @Test
        public void treeCtorArgumentTest() {
        somemock m = mock(SomeClass.class);
        }
    }
</code>```

I'm using NetBeans 8.2. I've downloaded mockito-core-2.7.0.jar, and then I select "Test Libraries"->"Add Jar" and added mockito-core-2.7.0.jar.

Classpath and everything looks ok, I',m still getting exception.

Any advice?

答:
If you are using powermock ensure that your dependencies point to:

```<code>org.powermock:powermock-api-mockito2
</code>```

instead of

```<code>org.powermock:powermock-api-mockito
</code>```

Body:
I'm getting following exception once tests is started:

    Testcase: treeCtorArgumentTest(com.xythos.client.drive.cachedtree.CachedTreeTest):  Caused an ERROR
Could not initialize plugin: interface org.mockito.plugins.MockMaker
java.lang.IllegalStateException: Could not initialize plugin: interface org.mockito.plugins.MockMaker
    at org.mockito.internal.configuration.plugins.PluginLoader$1.invoke(PluginLoader.java:66)
    at com.sun.proxy.$Proxy7.isTypeMockable(Unknown Source)
    at org.mockito.internal.util.MockUtil.typeMockabilityOf(MockUtil.java:29)
    at org.mockito.internal.util.MockCreationValidator.validateType(MockCreationValidator.java:22)
    at org.mockito.internal.creation.MockSettingsImpl.validatedSettings(MockSettingsImpl.java:168)
    at org.mockito.internal.creation.MockSettingsImpl.confirm(MockSettingsImpl.java:162)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:64)
    at org.mockito.Mockito.mock(Mockito.java:1687)
    at org.mockito.Mockito.mock(Mockito.java:1600)
    at com.xythos.client.drive.cachedtree.CachedTreeTest.setUp(CachedTreeTest.java:51)
Caused by: java.lang.NoClassDefFoundError: net/bytebuddy/dynamic/loading/ClassLoadingStrategy
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.<init>(SubclassByteBuddyMockMaker.java:33)
    at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.<init>(ByteBuddyMockMaker.java:22)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at org.mockito.internal.configuration.plugins.PluginLoader.loadPlugin(PluginLoader.java:54)
    at org.mockito.internal.configuration.plugins.PluginRegistry.<init>(PluginRegistry.java:18)
    at org.mockito.internal.configuration.plugins.Plugins.<clinit>(Plugins.java:17)
    at org.mockito.internal.util.MockUtil.<clinit>(MockUtil.java:24)
Caused by: java.lang.ClassNotFoundException: net.bytebuddy.dynamic.loading.ClassLoadingStrategy
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

This is my test:

package com.xythos.client.drive.cachedtree;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)

    public class CachedTreeTest {

        public CachedTreeTest() {
        }

        @Test
        public void treeCtorArgumentTest() {
        somemock m = mock(SomeClass.class);
        }
    }

I'm using NetBeans 8.2. I've downloaded mockito-core-2.7.0.jar, and then I select "Test Libraries"->"Add Jar" and added mockito-core-2.7.0.jar.

Classpath and everything looks ok, I',m still getting exception.

Any advice?

Body:
If you are using powermock ensure that your dependencies point to:

org.powermock:powermock-api-mockito2

instead of

org.powermock:powermock-api-mockito


来源: stackexchange

问:
Python - How to convert JSON File to Dataframe
How can I  convert a JSON File as such  into a dataframe to do some transformations.

For Example if the JSON file reads:

```<code>{"FirstName":"John",

"LastName":"Mark",

"MiddleName":"Lewis",

"username":"johnlewis2",

"password":"2910"}
</code>```

How can I convert it to a table like such

```<code>Column -> FirstName | LastName | MiddleName | username | password

Row ----->    John | Mark |Lewis | johnlewis2 |2910
</code>```

答:
```<code>jsondata = '{"0001":{"FirstName":"John","LastName":"Mark","MiddleName":"Lewis","username":"johnlewis2","password":"2910"}}'
import json
import pandas as pd
jdata = json.loads(jsondata)
df = pd.DataFrame(jdata)
print df.T
</code>```

This should look like this:.

```
         FirstName LastName MiddleName password    username
0001      John     Mark      Lewis     2910  johnlewis2
```

ContentLicense: CC BY-SA 3.0

Body:
How can I  convert a JSON File as such  into a dataframe to do some transformations.

For Example if the JSON file reads:

{"FirstName":"John",

"LastName":"Mark",

"MiddleName":"Lewis",

"username":"johnlewis2",

"password":"2910"}

How can I convert it to a table like such

Column -> FirstName | LastName | MiddleName | username | password

Row ----->    John | Mark |Lewis | johnlewis2 |2910

Body:
jsondata = '{"0001":{"FirstName":"John","LastName":"Mark","MiddleName":"Lewis","username":"johnlewis2","password":"2910"}}'
import json
import pandas as pd
jdata = json.loads(jsondata)
df = pd.DataFrame(jdata)
print df.T

This should look like this:.

         FirstName LastName MiddleName password    username
0001      John     Mark      Lewis     2910  johnlewis2


问:
What unit test to write for a class using generics in Java?
Taking the very specific example of the JpaDao class defined in this article:

```<code>public abstract class JpaDao<K, E> implements Dao<K, E> {
    protected Class<E> entityClass;

    @PersistenceContext
    protected EntityManager entityManager;

    public JpaDao() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
    }

    public void persist(E entity) { entityManager.persist(entity); }

    public void remove(E entity) { entityManager.remove(entity); }

    public E findById(K id) { return entityManager.find(entityClass, id); }
}
</code>```

would it be best to write unit tests for all the existing entities in the application (Order, Customer, Book, etc.), or would it be acceptable to write unit tests for just one entity, as hinted by this other question?  Are there any best practice regarding unit testing java classes using generics?

答:
If I would need to test the behaviour of the class with regards to its type semantics, I would go for checking type invariants. In other words, try to establish some assertions that are true for all combination of types, not only those which you expect to use but any type in the universe, including those that are not invented yet. For example:

```<code>private <K, E> void testTypes(K k, E e) {
    JpaDao<K, E> dao = new JpaDaoImpl<K, E>();

    dao.persist(e);

    assertEquals(dao.getById(e.getId()).getClass(), e.getClass());
}

@Test
public void testIntegerAndOrder() {
    this.<Integer, Order>testTypes(10, new Order());
}
</code>```

See, no matter what types K and E are, the assertions are expected to hold (the testIntegerAndOrder() method tests this assertion using a concrete type values).

This, of course, should be using in conjunction with the unit tests, that are actually testing the behaviour for some particular values of type variables. This would be very much the same unit tests that you could find in any JUnit tutorial. Something in the vein of:

```<code>@Test
public void testDao() throws Exception {
    JpaDao<Integer, Order> dao = getDao();

    Order order = ...;
    order.setId(10);

    dao.persist(order);

    assertEquals(order, dao.findById(10));
}
</code>```

See how semantics of assertions differ here: this test test an assertion that stored object holds its ID using a concrete value of variable ID, not the type variable as the test before.

ContentLicense: CC BY-SA 2.5

Body:
Taking the very specific example of the JpaDao class defined in this article:

public abstract class JpaDao<K, E> implements Dao<K, E> {
    protected Class<E> entityClass;

    @PersistenceContext
    protected EntityManager entityManager;

    public JpaDao() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
    }

    public void persist(E entity) { entityManager.persist(entity); }

    public void remove(E entity) { entityManager.remove(entity); }

    public E findById(K id) { return entityManager.find(entityClass, id); }
}

would it be best to write unit tests for all the existing entities in the application (Order, Customer, Book, etc.), or would it be acceptable to write unit tests for just one entity, as hinted by this other question?  Are there any best practice regarding unit testing java classes using generics?

Body:
If I would need to test the behaviour of the class with regards to its type semantics, I would go for checking type invariants. In other words, try to establish some assertions that are true for all combination of types, not only those which you expect to use but any type in the universe, including those that are not invented yet. For example:

private <K, E> void testTypes(K k, E e) {
    JpaDao<K, E> dao = new JpaDaoImpl<K, E>();

    dao.persist(e);

    assertEquals(dao.getById(e.getId()).getClass(), e.getClass());
}

@Test
public void testIntegerAndOrder() {
    this.<Integer, Order>testTypes(10, new Order());
}

See, no matter what types K and E are, the assertions are expected to hold (the testIntegerAndOrder() method tests this assertion using a concrete type values).

This, of course, should be using in conjunction with the unit tests, that are actually testing the behaviour for some particular values of type variables. This would be very much the same unit tests that you could find in any JUnit tutorial. Something in the vein of:

@Test
public void testDao() throws Exception {
    JpaDao<Integer, Order> dao = getDao();

    Order order = ...;
    order.setId(10);

    dao.persist(order);

    assertEquals(order, dao.findById(10));
}

See how semantics of assertions differ here: this test test an assertion that stored object holds its ID using a concrete value of variable ID, not the type variable as the test before.


问:
Should I redefine or reassign a variable in a loop?
Supposing I need to iterate over something and set a variable in every cycle, like this:

```<code>for (int i=0; i < list.size(); i++) {
    final Object cur = list.get(i);
}
</code>```

this redefines the variable everytime, so I'm concerned that that might pollute the memory.

The alternate option is to define the variable once and then reassign it every iteration, like this:

```<code>Object cur
for (int i=0; i < list.size(); i++) {
    cur = list.get(i);
}
</code>```

would this be better in terms of memory? Would it make any difference? What if cur is a primitive type instead of an Object?

Don't tell me to use foreach, I need the counter, this is just a simplified example

答: Seriously use whatever you want, it will have no difference. The only difference is the scope of that variable - for example it would be much simpler to reason about the variable GC when it is inside the loop - because it basically can not "escape" the loop.

Body:
Supposing I need to iterate over something and set a variable in every cycle, like this:

for (int i=0; i < list.size(); i++) {
    final Object cur = list.get(i);
}

this redefines the variable everytime, so I'm concerned that that might pollute the memory.

The alternate option is to define the variable once and then reassign it every iteration, like this:

Object cur
for (int i=0; i < list.size(); i++) {
    cur = list.get(i);
}

would this be better in terms of memory? Would it make any difference? What if cur is a primitive type instead of an Object?

Don't tell me to use foreach, I need the counter, this is just a simplified example


问:
Can't expand storage on virtualbox
I am using oracle VirtualBox, my host is ubuntu 16 LTS and my machine is windows 7 ultimate 64bit. I'm trying to add some storage to my machine, but I couldn't find a way to expand the vdi file I currently use, so i tried to add another one, but the machine doesn't seems to recognize it.

Any suggestions?

答: It's not clear what you did to add a vdi file (a "disk") to your vm, nor what you did that you didn't see it where you expected.  Adding a new vdi is the virtual equivilent of plugging in a new, unpartitioned, unformatted hard drive.  In your Win7 vm, open control panel > admin tools > computer management > disk management. You should see a new disk waiting to be partitioned and formatted.</p>

ContentLicense: CC BY-SA 4.0

Title: Can't expand storage on virtualbox


问:
Appending text by column to the same row for a CSV file on Ruby 2.4
I have a CSV file that contains headers and 1 row of data:

I want to append data by the column name (the header) but to the same row (row number 1)

I'm inserting each column data separately.

So at the end, I will have a file that contains headers and 1 row of data

for example:

```<code>header1,header2

data1,data2
</code>```

I'm using

```<code> def insert_info_csv(header,values)
  headers=['1', '2', '3', '4']
  file='report_test.csv'

  CSV.open('report_test.csv','a') do |csv|
    row=CSV::Row.new(headers,[])
    row[header]=values (where I insert the data)
    csv << row
  end
  end
</code>```

my issue is that each data is written in a different row for example:

```<code> Header1, header2

 data1,

       ,data2
</code>```

Thank you for the help.

答:
Based on your example it is clear that you are appending a row to the csv file per method call.

If you want to append data to existing row (by header) you need to add some identifier and fetch by it.

You could add entire row per method call by passing a hash to it.

```<code>hash = {
  header_a: 'value_a',
  header_b: 'value_b'
}

def insert_info_csv(info_hash)
 headers=['header_a', 'header_b']
 file='report_test.csv'

 CSV.open('report_test.csv','a') do |csv|
   row=CSV::Row.new(headers,[])
   info_headers.each do |k,v|
     row[k] = v
     csv << row
   end
 end
end
</code>```

Body:
I have a CSV file that contains headers and 1 row of data:

I want to append data by the column name (the header) but to the same row (row number 1)

I'm inserting each column data separately.

So at the end, I will have a file that contains headers and 1 row of data

for example:

header1,header2

data1,data2

I'm using

 def insert_info_csv(header,values)
  headers=['1', '2', '3', '4']
  file='report_test.csv'

  CSV.open('report_test.csv','a') do |csv|
    row=CSV::Row.new(headers,[])
    row[header]=values (where I insert the data)
    csv << row
  end
  end

my issue is that each data is written in a different row for example:

 Header1, header2

 data1,

       ,data2

Thank you for the help.

Body:
Based on your example it is clear that you are appending a row to the csv file per method call.

If you want to append data to existing row (by header) you need to add some identifier and fetch by it.

You could add entire row per method call by passing a hash to it.

hash = {
  header_a: 'value_a',
  header_b: 'value_b'
}

def insert_info_csv(info_hash)
 headers=['header_a', 'header_b']
 file='report_test.csv'

 CSV.open('report_test.csv','a') do |csv|
   row=CSV::Row.new(headers,[])
   info_headers.each do |k,v|
     row[k] = v
     csv << row
   end
 end
end


问:
CSS3 Animate shapes to specific area on screen
I'm trying to create a little quiz, using CSS animation I want the radio button circle to move from its location down into a little envelop image.

I have the animation working as intended, by I cant get the animation to stop at the same point for each answer. I assume this is because each question is at a lower point on the screen.

My question is, how can I get it so that each circle will always going onto the envelop graphic?

I've included a Codepen link to help get a better understanding of what I have thus far; I feel that when you see it you will know exactly what it is I'm trying to do if I haven't explained it appropriately.

https://codepen.io/MauriceMcErlean/pen/yPoJBE

HTML

```<code><div class="ballcont question1">
<div class="question">
    <h2>This is the first Question.</h2>
</div>
<div class="inputselect">
    <form action="#">
        <div class="option1cont">
            <input type="radio" id="test1" name="test1">
            <label for="test1">
                <p>Mars
                    <p>
            </label>
            <div class="ball"></div>
        </div>

        <div class="option2cont">
            <input type="radio" id="test2" name="radio-group">
            <label for="test2">
                <p>The Moon</p>
            </label>
            <div class="ball"></div>
        </div>

        <div class="option3cont">
            <input type="radio" id="test3" name="radio-group">
            <label for="test3">
                <p>Earth</p>
            </label>
            <div class="ball"></div>
        </div>

        <div class="option4cont">
            <input type="radio" id="test4" name="radio-group">
            <label for="test4">
                <p>Venus</p>
            </label>
            <div class="ball"></div>
        </div>

        <a class="nextquestion">Next Question</a>
    </form>
    <div class="basket">
        <i class="fa fa-envelope-open-o" aria-hidden="true"></i>
    </div>
</div>
</code>```

CSS for keyframes

```<code>@keyframes firstball {
  0% {
    transform: translate(0px, 0px);
    background-color:   white;
  }
45% {
    transform: translate(45vw, 0px);
     background-color:  white;
  }
50% {
    transform: translate(45vw, 5vh);
    background: white;
}
60% {
  transform: translate(45vw, 0vh);
    background:white;
}
70% {
   transform: translate(45vw, 5vh);
    background: white;
}
80% {
    transform: translate(45vw, 0vh);
    background:white;
}
90% {
    transform: translate(45vw, 5vh);
    background:white;
}
100% {
    transform: translate(45vw, 90vh);
     background-color:  white;
}
}

@keyframes secondball {
  0% {
    transform: translate(0px, 0px);
    background-color:   white;
  }
45% {
    transform: translate(45vw, 0px);
     background-color:  white;
  }
50% {
    transform: translate(45vw, 5vh);
    background: white;
}
60% {
  transform: translate(45vw, 0vh);
    background:white;
}
70% {
   transform: translate(45vw, 5vh);
    background: white;
}
80% {
    transform: translate(45vw, 0vh);
    background:white;
}
90% {
    transform: translate(45vw, 5vh);
    background:white;
}
100% {
    transform: translate(45vw, 90vh);
     background-color:  white;
}
}

@keyframes thirdball {
  0% {
    transform: translate(0px, 0px);
    background-color:   white;
  }
45% {
    transform: translate(45vw, 0px);
     background-color:  white;
  }
50% {
    transform: translate(45vw, 5vh);
    background: white;
}
60% {
  transform: translate(45vw, 0vh);
    background:white;
}
70% {
   transform: translate(45vw, 5vh);
    background: white;
}
80% {
    transform: translate(45vw, 0vh);
    background:white;
}
90% {
    transform: translate(45vw, 5vh);
    background:white;
}
100% {
    transform: translate(45vw, 90vh);
     background-color:  white;
}
}

@keyframes fourthball {
  0% {
    transform: translate(0px, 0px);
    background-color:   white;
  }
45% {
    transform: translate(45vw, 0px);
     background-color:  white;
  }
50% {
    transform: translate(45vw, 5vh);
    background: white;
}
60% {
  transform: translate(45vw, 0vh);
    background:white;
}
70% {
   transform: translate(45vw, 5vh);
    background: white;
}
80% {
    transform: translate(45vw, 0vh);
    background:white;
}
90% {
    transform: translate(45vw, 5vh);
    background:white;
}
100% {
    transform: translate(45vw, 52vh);
     background-color:  white;
}
}
</code>```

JS

```<code>$( document ).ready(function() {
$("#test1").prop("checked", false);

$("#test1").change(function(){
if($('#test1').is(':checked')){

    $('.option2cont').css('visibility','hidden');
    $('.option3cont').css('visibility','hidden');
    $('.option4cont').css('visibility','hidden');
    $('.option1cont label').css('visibility','hidden');
    $('.option1cont label p').css('visibility','visible');
    $('.option1cont label .ball').css('visibility','visible');

    $('.ball').addClass('question_1_ball_1');

    setTimeout(function(){
    $('.nextquestion').addClass('showquestionbutton');
    console.log('1000');
    }, 4005);
    console.log('checked');

} else {
    console.log('not checked');
}
});

$("#test2").change(function(){
if($('#test2').is(':checked')){
    $('.option1cont').css('visibility','hidden');
    $('.option3cont').css('visibility','hidden');
    $('.option4cont').css('visibility','hidden');
    $('.option2cont label').css('visibility','hidden');
    $('.option2cont label p').css('visibility','visible');
    $('.option2cont label .ball').css('visibility','visible');
    $('.ball').addClass('question_1_ball_2');
     console.log('checked');
} else {
    console.log('not checked');
}
});

$("#test3").change(function(){
if($('#test3').is(':checked')){
    $('.option1cont').css('visibility','hidden');
    $('.option2cont').css('visibility','hidden');
    $('.option4cont').css('visibility','hidden');
    $('.option3cont label').css('visibility','hidden');
    $('.option3cont label p').css('visibility','visible');
    $('.option3cont label .ball').css('visibility','visible');

    $('.ball').addClass('question_1_ball_3');
     console.log('checked');
} else {
    console.log('not checked');
}
});

$("#test4").change(function(){
if($('#test4').is(':checked')){
    $('.option1cont').css('visibility','hidden');
    $('.option2cont').css('visibility','hidden');
    $('.option3cont').css('visibility','hidden');
    $('.option4cont label').css('visibility','hidden');
    $('.option4cont label p').css('visibility','visible');
    $('.option4cont label .ball').css('visibility','visible');

    $('.ball').addClass('question_1_ball_4');
     console.log('checked');
} else {
    console.log('not checked');
}
});

});
</code>```

答:
Just Add Change the css of .basket class:

```<code>.basket {
  position: absolute;
  top: 100vh;
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
  font-size: 7rem;
  color: white;
}
</code>```

if you need more customization please let me know..

I update it for you(only for first ball), i think rest you can:

Update link: https://codepen.io/ziruhel/pen/bYrZGW

Body:
I'm trying to create a little quiz, using CSS animation I want the radio button circle to move from its location down into a little envelop image.

I have the animation working as intended, by I cant get the animation to stop at the same point for each answer. I assume this is because each question is at a lower point on the screen.

My question is, how can I get it so that each circle will always going onto the envelop graphic?

I've included a Codepen link to help get a better understanding of what I have thus far; I feel that when you see it you will know exactly what it is I'm trying to do if I haven't explained it appropriately.

https://codepen.io/MauriceMcErlean/pen/yPoJBE

HTML

This is the first Question.

    <form action="#">

            <input type="radio" id="test1" name="test1">

Mars

            <input type="radio" id="test2" name="radio-group">

The Moon

            <input type="radio" id="test3" name="radio-group">

Earth

            <input type="radio" id="test4" name="radio-group">

Venus

        Next Question
    </form>

CSS for keyframes

@keyframes firstball {
  0% {
    transform: translate(0px, 0px);
    background-color:   white;
  }
45% {
    transform: translate(45vw, 0px);
     background-color:  white;
  }
50% {
    transform: translate(45vw, 5vh);
    background: white;
}
60% {
  transform: translate(45vw, 0vh);
    background:white;
}
70% {
   transform: translate(45vw, 5vh);
    background: white;
}
80% {
    transform: translate(45vw, 0vh);
    background:white;
}
90% {
    transform: translate(45vw, 5vh);
    background:white;
}
100% {
    transform: translate(45vw, 90vh);
     background-color:  white;
}
}

@keyframes secondball {
  0% {
    transform: translate(0px, 0px);
    background-color:   white;
  }
45% {
    transform: translate(45vw, 0px);
     background-color:  white;
  }
50% {
    transform: translate(45vw, 5vh);
    background: white;
}
60% {
  transform: translate(45vw, 0vh);
    background:white;
}
70% {
   transform: translate(45vw, 5vh);
    background: white;
}
80% {
    transform: translate(45vw, 0vh);
    background:white;
}
90% {
    transform: translate(45vw, 5vh);
    background:white;
}
100% {
    transform: translate(45vw, 90vh);
     background-color:  white;
}
}

@keyframes thirdball {
  0% {
    transform: translate(0px, 0px);
    background-color:   white;
  }
45% {
    transform: translate(45vw, 0px);
     background-color:  white;
  }
50% {
    transform: translate(45vw, 5vh);
    background: white;
}
60% {
  transform: translate(45vw, 0vh);
    background:white;
}
70% {
   transform: translate(45vw, 5vh);
    background: white;
}
80% {
    transform: translate(45vw, 0vh);
    background:white;
}
90% {
    transform: translate(45vw, 5vh);
    background:white;
}
100% {
    transform: translate(45vw, 90vh);
     background-color:  white;
}
}

@keyframes fourthball {
  0% {
    transform: translate(0px, 0px);
    background-color:   white;
  }
45% {
    transform: translate(45vw, 0px);
     background-color:  white;
  }
50% {
    transform: translate(45vw, 5vh);
    background: white;
}
60% {
  transform: translate(45vw, 0vh);
    background:white;
}
70% {
   transform: translate(45vw, 5vh);
    background: white;
}
80% {
    transform: translate(45vw, 0vh);
    background:white;
}
90% {
    transform: translate(45vw, 5vh);
    background:white;
}
100% {
    transform: translate(45vw, 52vh);
     background-color:  white;
}
}

JS

$( document ).ready(function() {
$("#test1").prop("checked", false);

$("#test1").change(function(){
if($('#test1').is(':checked')){

    $('.option2cont').css('visibility','hidden');
    $('.option3cont').css('visibility','hidden');
    $('.option4cont').css('visibility','hidden');
    $('.option1cont label').css('visibility','hidden');
    $('.option1cont label p').css('visibility','visible');
    $('.option1cont label .ball').css('visibility','visible');

    $('.ball').addClass('question_1_ball_1');

    setTimeout(function(){
    $('.nextquestion').addClass('showquestionbutton');
    console.log('1000');
    }, 4005);
    console.log('checked');

} else {
    console.log('not checked');
}
});

$("#test2").change(function(){
if($('#test2').is(':checked')){
    $('.option1cont').css('visibility','hidden');
    $('.option3cont').css('visibility','hidden');
    $('.option4cont').css('visibility','hidden');
    $('.option2cont label').css('visibility','hidden');
    $('.option2cont label p').css('visibility','visible');
    $('.option2cont label .ball').css('visibility','visible');
    $('.ball').addClass('question_1_ball_2');
     console.log('checked');
} else {
    console.log('not checked');
}
});

$("#test3").change(function(){
if($('#test3').is(':checked')){
    $('.option1cont').css('visibility','hidden');
    $('.option2cont').css('visibility','hidden');
    $('.option4cont').css('visibility','hidden');
    $('.option3cont label').css('visibility','hidden');
    $('.option3cont label p').css('visibility','visible');
    $('.option3cont label .ball').css('visibility','visible');

    $('.ball').addClass('question_1_ball_3');
     console.log('checked');
} else {
    console.log('not checked');
}
});

$("#test4").change(function(){
if($('#test4').is(':checked')){
    $('.option1cont').css('visibility','hidden');
    $('.option2cont').css('visibility','hidden');
    $('.option3cont').css('visibility','hidden');
    $('.option4cont label').css('visibility','hidden');
    $('.option4cont label p').css('visibility','visible');
    $('.option4cont label .ball').css('visibility','visible');

    $('.ball').addClass('question_1_ball_4');
     console.log('checked');
} else {
    console.log('not checked');
}
});

});

Body:
Just Add Change the css of .basket class:

.basket {
  position: absolute;
  top: 100vh;
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
  font-size: 7rem;
  color: white;
}

if you need more customization please let me know..

I update it for you(only for first ball), i think rest you can:

Update link: https://codepen.io/ziruhel/pen/bYrZGW


问:
How to distribute portable MPI applications?
I am working for a simulation software vendor. We are now starting to implement distributed computing with MPI for our software. I don't really understand how we should distribute our MPI capable software product.

So, MPI is a interface specification, so the actual MPI implementation should be replaceable, right? Whoever runs the cluster can provide a very specialized MPI implementation for the hardware/communication layer they use. This makes sense to me.

On the other hand, when I run ldd mympiapp I see

```<code>libmpi.so.12 => /home/mpiuser/mpich-3.2-install/lib/libmpi.so.12 (0x00007fae34684000)
</code>```

It seems that after building, my application is linked against my specific version of MPI. We already ship our application in different versions for different OSes. Should we now also add combinations for different MPI implementations? Or should we also distribute the shared libraries together with our application? What is expected from the side of users/cluster providers?

I read a lot of web resources, but most stuff I find is written from the standpoint that the one who compiles it also runs it.

答:
There's a reason MPI implementations come with mpicc.

High-performance software differs from ordinary software in that performance is absolutely critical. Compiling a single binary for distribution is generally not acceptable, as hardware abstractions are leaky in terms of high performance.

Many of vendors of large scale high performance software distribute it either via a collection of different binaries for various hardware/software combinations, send an engineer(s) on-site to compile and tune the software for the customer's system, or in some cases I've heard of smaller companies that give the source code to the customer (with very strict contracts).

Three reasons why it needs to be compiled specifically for the customer's system:

So that the correct MPI and OpenMP implementations for the hardware are used,

So that a platform specific compiler can be used to generate the most efficient instructions possible,

So that tuning of compile-time algorithm parameters for the hardware (processors, memory, and interconnect) can be done. The communication pattern your code uses should depend on the interconnect, block sizes should depend on processor cache size, etc..

This need for coupled hardware and compiled bytes generally results in long sales cycles for commercial MPI software.

Body:
I am working for a simulation software vendor. We are now starting to implement distributed computing with MPI for our software. I don't really understand how we should distribute our MPI capable software product.

So, MPI is a interface specification, so the actual MPI implementation should be replaceable, right? Whoever runs the cluster can provide a very specialized MPI implementation for the hardware/communication layer they use. This makes sense to me.

On the other hand, when I run ldd mympiapp I see

libmpi.so.12 => /home/mpiuser/mpich-3.2-install/lib/libmpi.so.12 (0x00007fae34684000)

It seems that after building, my application is linked against my specific version of MPI. We already ship our application in different versions for different OSes. Should we now also add combinations for different MPI implementations? Or should we also distribute the shared libraries together with our application? What is expected from the side of users/cluster providers?

I read a lot of web resources, but most stuff I find is written from the standpoint that the one who compiles it also runs it.


问:
How to use % operator for float values in c
When I use % operator on float values I get error stating that "invalid operands to binary % (have ‘float’ and ‘double’)".I want to enter the integers value only but the numbers are very large(not in the range of int type)so to avoid the inconvenience I use float.Is there any way to use % operator on such large integer values????</p>

答:
When I haven't had easy access to fmod or other libraries (for example, doing a quick Arduino sketch), I find that the following works well enough:

```<code>float someValue = 0.0;

// later...

// Since someValue = (someValue + 1) % 256 won't work for floats...
someValue += 1.0; // (or whatever increment you want to use)
while (someValue >= 256.0){
    someValue -= 256.0;
}
</code>```

Body:
When I haven't had easy access to fmod or other libraries (for example, doing a quick Arduino sketch), I find that the following works well enough:

float someValue = 0.0;

// later...

// Since someValue = (someValue + 1) % 256 won't work for floats...
someValue += 1.0; // (or whatever increment you want to use)
while (someValue >= 256.0){
    someValue -= 256.0;
}


问:
Matrix Operations in Chisel
Does Chisel support matrix operations such as addition, multiplication, transposition, etc.? If not, what is the best way to implement them?

How about vectors?

答:
Yes, you can do matrix operations in Chisel with the help of vectors. The code I came up with is below (Input matrices are of sizes 3x5 and 5x2). </p>

```<code>package matrixmult

import chisel3._
import chisel3.iotesters.{PeekPokeTester, Driver}
import scala.collection.mutable.ArrayBuffer

class MatMult extends Module {
  val io = IO(new Bundle {
    val matA   = Input(Vec(15, UInt(32.W)))
    val matB   = Input(Vec(10, UInt(32.W)))
    val load  = Input(Bool())
    val matC = Output(Vec(6, UInt(32.W)))
    val valid = Output(Bool())
  })
  var sum = UInt(32.W)
  val matC = new ArrayBuffer[UInt]()

  for(i <- 0 until 6) {
        matC += 0.asUInt(32.W)
  }

  when (io.load) {
    for(i <- 0 until 3) {
        for(j <- 0 until 2) {
            sum = 0.asUInt(32.W)
            for(k <- 0 until 5)
            {
                sum = sum + matA(i*5+k)*io.matB(k*2+j)

            }
            matC(i*2 + j) = sum
        }
    }
  io.valid := true.B
  } .otherwise {
    io.valid := false.B
  }

  val outputMat = Vec(matC)
  io.matC := outputMat

}
</code>```

Title: Matrix Operations in Chisel

Body:
Yes, you can do matrix operations in Chisel with the help of vectors. The code I came up with is below (Input matrices are of sizes 3x5 and 5x2).

package matrixmult

import chisel3._
import chisel3.iotesters.{PeekPokeTester, Driver}
import scala.collection.mutable.ArrayBuffer

class MatMult extends Module {
  val io = IO(new Bundle {
    val matA   = Input(Vec(15, UInt(32.W)))
    val matB   = Input(Vec(10, UInt(32.W)))
    val load  = Input(Bool())
    val matC = Output(Vec(6, UInt(32.W)))
    val valid = Output(Bool())
  })
  var sum = UInt(32.W)
  val matC = new ArrayBuffer[UInt]()

  for(i <- 0 until 6) {
        matC += 0.asUInt(32.W)
  }

  when (io.load) {
    for(i <- 0 until 3) {
        for(j <- 0 until 2) {
            sum = 0.asUInt(32.W)
            for(k <- 0 until 5)
            {
                sum = sum + matA(i*5+k)*io.matB(k*2+j)

            }
            matC(i*2 + j) = sum
        }
    }
  io.valid := true.B
  } .otherwise {
    io.valid := false.B
  }

  val outputMat = Vec(matC)
  io.matC := outputMat

}


问:
React Native - style responsiveness for different screen sizes
We are building an app which is going to run on multiple devices (iOS, Android) and therefore on many screen sizes. After reading about PixelRatio it still doesn't seem as if there is a magic solution to scale automatically all style values according to the different screen sizes.

The only solution I could think of was to override the Stylesheet class to automatically scale all sizes according to the current screen size. For example:

```<code>import {StyleSheet} from ‘react-native’;
import { Dimensions, Platform, PixelRatio } from ‘react-native’;

const {
    width,
    height
} = Dimensions.get(‘window’);

const scale = width / 320;

const ratioKeys = {
    fontSize: true,
    paddingHorizontal: true,
    paddingVertical: true,
    paddingTop: true,
    paddingLeft: true,
    paddingRight: true,
    paddingBottom: true,
    padding: true,
    marginHorizontal: true,
    marginVertical: true,
    marginTop: true,
    marginRight: true,
    marginLeft: true,
    marginBottom: true,
    margin: true,
    width: true,
    height: true,
    lineHeight: true,
}

// automatically scale specific keys (specified above) according to the screen size
const parseKey = (key, value) => {

   if (ratioKeys[key]) {
        value = value * scale;
    }

   return value;
}

export const parseStyle = (style) => {
    console.log(‘style -> ’, style);
    return Object.keys(style).reduce((output, key) => {
        output[key] = parseKey(key, style[key]);
        return output;
    }, {});
}

const parseStyleSheet = (styles) => {
    console.log(‘styles -> ’, styles);
    return Object.keys(styles).reduce((output, key) => {
       output[key] = parseStyle(styles[key]);
       return output;
    }, {});
}

export default {
    create: (style) => {
        return StyleSheet.create(parseStyleSheet(style));
    }
}
</code>```

It seems pretty strange that this wouldn't actually be supported out of the box, so I guess I am missing something?

答: I've seen this library as a solution, it supports media queries, and we may eventually use it if we feel we need more customization than flexbox. I've seen it in action and it looks like it might address some of your needs: https://github.com/vitalets/react-native-extended-stylesheet</p>

Body:
We are building an app which is going to run on multiple devices (iOS, Android) and therefore on many screen sizes. After reading about PixelRatio it still doesn't seem as if there is a magic solution to scale automatically all style values according to the different screen sizes.

The only solution I could think of was to override the Stylesheet class to automatically scale all sizes according to the current screen size. For example:

import {StyleSheet} from ‘react-native’;
import { Dimensions, Platform, PixelRatio } from ‘react-native’;

const {
    width,
    height
} = Dimensions.get(‘window’);

const scale = width / 320;

const ratioKeys = {
    fontSize: true,
    paddingHorizontal: true,
    paddingVertical: true,
    paddingTop: true,
    paddingLeft: true,
    paddingRight: true,
    paddingBottom: true,
    padding: true,
    marginHorizontal: true,
    marginVertical: true,
    marginTop: true,
    marginRight: true,
    marginLeft: true,
    marginBottom: true,
    margin: true,
    width: true,
    height: true,
    lineHeight: true,
}

// automatically scale specific keys (specified above) according to the screen size
const parseKey = (key, value) => {

   if (ratioKeys[key]) {
        value = value * scale;
    }

   return value;
}

export const parseStyle = (style) => {
    console.log(‘style -> ’, style);
    return Object.keys(style).reduce((output, key) => {
        output[key] = parseKey(key, style[key]);
        return output;
    }, {});
}

const parseStyleSheet = (styles) => {
    console.log(‘styles -> ’, styles);
    return Object.keys(styles).reduce((output, key) => {
       output[key] = parseStyle(styles[key]);
       return output;
    }, {});
}

export default {
    create: (style) => {
        return StyleSheet.create(parseStyleSheet(style));
    }
}

It seems pretty strange that this wouldn't actually be supported out of the box, so I guess I am missing something?


问:
Permanently blocking a page/URL out of Google Analytics
I have a question about filtering / segments in Google Analytics for a unique scenario with one of my clients. I essentially want to block a page URL forever out of analytics --- never see it counted page views, top pages, etc. What is the best way to do that?

Developers added a widget to my client's website which uses an iframe URL from their domain. This iframe is on 30+ different URLs which makes this URL seem like it is the #1 top page which is severely skewing their analytics. I am told there is no other way to do it - especially with the budget/scope of work - which means I need to find the best way to filter this out of Google Analytics reporting.

For instance, I am looking at "Behavior - Overview" - this iframe URL is #1. I know I can click into "view full report" and from there hit advanced and exclude this page to get the real results.

However, is there a top-level filter that can be permanently activated to block this page so you do not have to do the advanced filtering every time you are in Google Analytics?

Thank you for your help!

答:
Just to confirm, your issue is this:
https://support.google.com/analytics/answer/1012049?hl=en
"Inflated number of pageviews"

If you just want to block it, would this not work?
In GA, go to Admin -> Filters -> Create new filter -> Custom -> Exclude by Request URL -> use the URI that you refer to.

I'd be interested to know if that works!


问:
How to implemennt OnZoomListener on MapView
I would like to have onZoomListener on my MapView.
The code below is what I have done. It registers if zoom buttons are tapped. Since all new phones now supports pinch to zoom, this is useless. Does anybody have idea how to do real onZoomListener? Thanks.</p>

```<code>   OnZoomListener listener = new OnZoomListener() {
   @Override
   public void onVisibilityChanged(boolean arg0) {
    // TODO Auto-generated method stub

   }
   @Override
   public void onZoom(boolean arg0) {
    Log.d(TAG, "ZOOM CHANGED");
    // TODO Auto-generated method stub

   }
  };

  ZoomButtonsController zoomButton = mapView.getZoomButtonsController();
  zoomButton.setOnZoomListener(listener);
</code>```

答:
MapView provides build-in zoom controls that support pinch.
If it doesn't work out of the box you could try setting mapView.setBuiltInZoomControls(true);
This way you should not need the OnZoomListener.

Body:
I would like to have onZoomListener on my MapView.
The code below is what I have done. It registers if zoom buttons are tapped. Since all new phones now supports pinch to zoom, this is useless. Does anybody have idea how to do real onZoomListener? Thanks.

   OnZoomListener listener = new OnZoomListener() {
   @Override
   public void onVisibilityChanged(boolean arg0) {
    // TODO Auto-generated method stub

   }
   @Override
   public void onZoom(boolean arg0) {
    Log.d(TAG, "ZOOM CHANGED");
    // TODO Auto-generated method stub

   }
  };

  ZoomButtonsController zoomButton = mapView.getZoomButtonsController();
  zoomButton.setOnZoomListener(listener);


问:
Adding new datasources to an existing .rrd
I have a .rrd db which is collecting data from a temperature gauge. Now I have a second gauge so I'd like to add this new gauge to the existing .rrd database. I tried many times with the "rrdtool tune" command, but after that I run a "rrdtool info" on my database, and I see that there's not the last data source (another gauge) that I tried to insert.

How can I do this?

答:
The command you need is, as you say, rrdtool tune.  The documentation is available online at https://oss.oetiker.ch/rrdtool/doc/rrdtune.en.html

The ability to extend an RRA and to add or remove a DS was only added late in RRDTool 1.4.  Check that you are not using an older version of RRDTool, as if you are, you will not be able to use this feature until you upgrade.


问:
Prevent (Bootstrap) affixed image from resizing
I'm using the Bootstrap affix plugin to affix an img to the top of the viewport once the user scrolls past it.

I have the .img-fluid class applied to the img, and the img is housed within a 3-column container.

The affix works, but when the image affixes, it gets HUGE. I don't want to set a px width for it because I want the image size to flex with the viewport -- and I want it to stay the same size as it is in the 3-column container.

I tried affixing the 3-column container instead, but then it changes positions!

Hayulllppp pls! Here's the HTML + CSS FWIW...

```<code>    <div class="col-sm-12 col-md-3 sms">
    <img src="img/sms/ch1_aug24_dad_sms1.png" data-spy="affix" data-offset-top="300" class="img-fluid">
    </div>

    .sms img {
         margin:1rem 0rem;
         max-width:100%;
          }
    .affix  {
    position:fixed;
    top:.5rem;
    z-index:9999;
          }
</code>```

答: You specify the width in px. The img-fluid class makes the image responsive in the way that it will scale down the image if it is too big for the viewport.

Body:
I'm using the Bootstrap affix plugin to affix an img to the top of the viewport once the user scrolls past it.

I have the .img-fluid class applied to the img, and the img is housed within a 3-column container.

The affix works, but when the image affixes, it gets HUGE. I don't want to set a px width for it because I want the image size to flex with the viewport -- and I want it to stay the same size as it is in the 3-column container.

I tried affixing the 3-column container instead, but then it changes positions!

Hayulllppp pls! Here's the HTML + CSS FWIW...

    .sms img {
         margin:1rem 0rem;
         max-width:100%;
          }
    .affix  {
    position:fixed;
    top:.5rem;
    z-index:9999;
          }


问:
mySQL Returning the top 5 of each category
I want to be able to return 5 menuitem per menu. I've tried this several script but had no luck. here are the tables

```<code>menus
-------
menuid int()
profileName varchar(35)

menuitems
-----------
itemid int()
name varchar(40)
</code>```

Here what I have now. I'm getting the error message with the script below. Error: Subquery returns more then 1 row.

```<code>SELECT m.profilename, name
FROM menus m
WHERE (SELECT name
        from menuitems s
        where m.menuid = s.menuid
        limit 5)
</code>```

Any suggestion is great appreciated.

答:
```<code>SELECT TOP 5 m.profilename, s.name
FROM menus m INNER JOIN menuitems s ON m.menuID = s.menuid
</code>```

Body:
I want to be able to return 5 menuitem per menu. I've tried this several script but had no luck. here are the tables

menus
-------
menuid int()
profileName varchar(35)

menuitems
-----------
itemid int()
name varchar(40)

Here what I have now. I'm getting the error message with the script below. Error: Subquery returns more then 1 row.

SELECT m.profilename, name
FROM menus m
WHERE (SELECT name
        from menuitems s
        where m.menuid = s.menuid
        limit 5)

Any suggestion is great appreciated.


问:
convert a string to a list of object using Java 8
I have a string

```<code>"Red apple, blue banana, orange".
</code>```

How could I split it by ", " first then add "_" between two words (such as Red_apple but not orange) and capitalize all letters. I read a few posts and found a solution but it only has the split part and how could I also add "_" and capitalize all letters? :

```<code>   Pattern pattern = Pattern.compile(", ");
   List<Fruit> f = pattern.splitAsStream(fruitString)
  .map(Fruit::valueOf)
  .collect(Collectors.toList());
</code>```

Fruit is a enum object. So basically if I am able to convert a string to a certain format and I am able get a Enum object based on a Enum name.

答:
Please find the below Code, I have followed the below Steps :

1) Split the String by , first.

2) Again split the result of 1) String by " ".

3) Then if the word counts are more than 1 then only proceed to append the underscore.

Demo:
http://rextester.com/NNDF87070

```<code>import java.util.*;
import java.lang.*;

class Rextester
{
       public static int WordCount(String s){

        int wordCount = 0;

        boolean word = false;
        int endOfLine = s.length() - 1;

        for (int i = 0; i < s.length(); i++) {
            // if the char is a letter, word = true.
            if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
                word = true;
                // if char isn't a letter and there have been letters before,
                // counter goes up.
            } else if (!Character.isLetter(s.charAt(i)) && word) {
                wordCount++;
                word = false;
                // last word of String; if it doesn't end with a non letter, it
                // wouldn't count without this.
            } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
                wordCount++;
            }
        }
        return wordCount;
    }
    public static void main(String args[])
    {
         String cord = "Red apple , blue banana, orange";
        String[] parts = cord.split(",");
        String[] result1 = new String[parts.length];
        for(int i=0; i<parts.length;i++) {

            String[] part2 = parts[i].split(" ");

            if(parts[i].length() > 1 && WordCount(parts[i]) > 1)
            {
                String result = "_";
                String uscore = "_";
                for(int z =0; z < part2.length; z++)
                {
                    if(part2.length > 1 ) {
                        if (z + 1 < part2.length) {
                            result = part2[z] + uscore + part2[z + 1];
                        }
                    }
                }

                result1[i] = result.toUpperCase();
            }
            else
            {
                result1[i] = parts[i];
            }

        }

         for(int j =0 ; j <parts.length; j++)
        {
            System.out.println(result1[j]);
        }

    }
}
</code>```

References for the WordCount Method:  Count words in a string method?

Body:
I have a string

"Red apple, blue banana, orange".

How could I split it by ", " first then add "_" between two words (such as Red_apple but not orange) and capitalize all letters. I read a few posts and found a solution but it only has the split part and how could I also add "_" and capitalize all letters? :

   Pattern pattern = Pattern.compile(", ");
   List<Fruit> f = pattern.splitAsStream(fruitString)
  .map(Fruit::valueOf)
  .collect(Collectors.toList());

Fruit is a enum object. So basically if I am able to convert a string to a certain format and I am able get a Enum object based on a Enum name.

Body:
Please find the below Code, I have followed the below Steps :

1) Split the String by , first.

2) Again split the result of 1) String by " ".

3) Then if the word counts are more than 1 then only proceed to append the underscore.

Demo:
http://rextester.com/NNDF87070

import java.util.*;
import java.lang.*;

class Rextester
{
       public static int WordCount(String s){

        int wordCount = 0;

        boolean word = false;
        int endOfLine = s.length() - 1;

        for (int i = 0; i < s.length(); i++) {
            // if the char is a letter, word = true.
            if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
                word = true;
                // if char isn't a letter and there have been letters before,
                // counter goes up.
            } else if (!Character.isLetter(s.charAt(i)) && word) {
                wordCount++;
                word = false;
                // last word of String; if it doesn't end with a non letter, it
                // wouldn't count without this.
            } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
                wordCount++;
            }
        }
        return wordCount;
    }
    public static void main(String args[])
    {
         String cord = "Red apple , blue banana, orange";
        String[] parts = cord.split(",");
        String[] result1 = new String[parts.length];
        for(int i=0; i<parts.length;i++) {

            String[] part2 = parts[i].split(" ");

            if(parts[i].length() > 1 && WordCount(parts[i]) > 1)
            {
                String result = "_";
                String uscore = "_";
                for(int z =0; z < part2.length; z++)
                {
                    if(part2.length > 1 ) {
                        if (z + 1 < part2.length) {
                            result = part2[z] + uscore + part2[z + 1];
                        }
                    }
                }

                result1[i] = result.toUpperCase();
            }
            else
            {
                result1[i] = parts[i];
            }

        }

         for(int j =0 ; j <parts.length; j++)
        {
            System.out.println(result1[j]);
        }

    }
}

References for the WordCount Method:  Count words in a string method?


问:
Can PDFBox sign all 'Approval Signatures' instead of always making first signature as 'Certified'?
As Adobe article "Digital Signatures in a PDF" stating:

PDF defines two types of signatures: approval and certification.  The
  differences are as follows:
  Approval: There can be any number of approval signatures in a document. The field may optionally be associated with FieldMDP
  permissions.
  Certification: There can be only one certification signature and it must be the first one in a document. The field is always associated
  with DocMDP.

Using PDFBox examples I was able to successfully apply multiple signatures to my document: https://github.com/apache/pdfbox/blob/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateVisibleSignature.java
In order to apply multiple signatures I was just running same code multiple times with different signature placeholders and images.

But what I have distinguished is that, even though I am running same code it always sets first signature as Certified, and all other once as Approval.

But in my case, I don't want a document to be certified, I just need all signatures to be of Apploval type including the first one. I know I can invisible first Certifying signature, but still I do not want to certify document at all.

I was trying to find a way to setup signature, but couldn't figure it out.

Here is my usage of example code (other classes are in the GitHub link above):

```<code>public class SignnerPDFBoxExample extends CreateSignatureBase {

    private SignatureOptions signatureOptions;
    private PDVisibleSignDesigner visibleSignDesigner;
    private final PDVisibleSigProperties visibleSignatureProperties = new PDVisibleSigProperties();
    private boolean lateExternalSigning = false;

    public static void main(String[] args) throws Exception {

        File ksFile = new File("keystore.jks");
        KeyStore keystore = KeyStore.getInstance("JKS");
        char[] pin = "123456".toCharArray();
        keystore.load(new FileInputStream(ksFile), pin);

        SignnerPDFBoxExample signer = new SignnerPDFBoxExample(keystore, pin.clone());
        String inputFilename = "Four_Signature_template.pdf";

        File documentFile = new File(inputFilename);
        File signedDocumentFile;
        int page = 1;
        try (FileInputStream imageStream = new FileInputStream("client_signature.jpg"))
        {
            String name = documentFile.getName();
            String substring = name.substring(0, name.lastIndexOf('.'));
            signedDocumentFile = new File(documentFile.getParent(), substring + "_signed.pdf");
            // page is 1-based here
            signer.setVisibleSignDesigner(inputFilename, 0, 0, -50, imageStream, page);
        }
        signer.setVisibleSignatureProperties("name", "location", "Signed using PDFBox", 0, page, true);
        signer.signPDF(documentFile, signedDocumentFile, null, "certifySignature");
    }

    public boolean isLateExternalSigning()
    {
        return lateExternalSigning;
    }

    /**
     * Set late external signing. Enable this if you want to activate the demo code where the
     * signature is kept and added in an extra step without using PDFBox methods. This is disabled
     * by default.
     *
     * @param lateExternalSigning
     */
    public void setLateExternalSigning(boolean lateExternalSigning)
    {
        this.lateExternalSigning = lateExternalSigning;
    }

    /**
     * Set visible signature designer for a new signature field.
     *
     * @param filename
     * @param x position of the signature field
     * @param y position of the signature field
     * @param zoomPercent
     * @param imageStream
     * @param page the signature should be placed on
     * @throws IOException
     */
    public void setVisibleSignDesigner(String filename, int x, int y, int zoomPercent,
            FileInputStream imageStream, int page)
            throws IOException
    {
        visibleSignDesigner = new PDVisibleSignDesigner(filename, imageStream, page);
        visibleSignDesigner.xAxis(x).yAxis(y).zoom(zoomPercent).adjustForRotation();
    }

    /**
     * Set visible signature designer for an existing signature field.
     *
     * @param zoomPercent
     * @param imageStream
     * @throws IOException
     */
    public void setVisibleSignDesigner(int zoomPercent, FileInputStream imageStream)
            throws IOException
    {
        visibleSignDesigner = new PDVisibleSignDesigner(imageStream);
        visibleSignDesigner.zoom(zoomPercent);
    }

    /**
     * Set visible signature properties for new signature fields.
     *
     * @param name
     * @param location
     * @param reason
     * @param preferredSize
     * @param page
     * @param visualSignEnabled
     * @throws IOException
     */
    public void setVisibleSignatureProperties(String name, String location, String reason, int preferredSize,
            int page, boolean visualSignEnabled) throws IOException
    {
        visibleSignatureProperties.signerName(name).signerLocation(location).signatureReason(reason).
                preferredSize(preferredSize).page(page).visualSignEnabled(visualSignEnabled).
                setPdVisibleSignature(visibleSignDesigner);
    }

    /**
     * Set visible signature properties for existing signature fields.
     *
     * @param name
     * @param location
     * @param reason
     * @param visualSignEnabled
     * @throws IOException
     */
    public void setVisibleSignatureProperties(String name, String location, String reason,
            boolean visualSignEnabled) throws IOException
    {
        visibleSignatureProperties.signerName(name).signerLocation(location).signatureReason(reason).
                visualSignEnabled(visualSignEnabled).setPdVisibleSignature(visibleSignDesigner);
    }

    /**
     * Initialize the signature creator with a keystore (pkcs12) and pin that
     * should be used for the signature.
     *
     * @param keystore is a pkcs12 keystore.
     * @param pin is the pin for the keystore / private key
     * @throws KeyStoreException if the keystore has not been initialized (loaded)
     * @throws NoSuchAlgorithmException if the algorithm for recovering the key cannot be found
     * @throws UnrecoverableKeyException if the given password is wrong
     * @throws CertificateException if the certificate is not valid as signing time
     * @throws IOException if no certificate could be found
     */
    public SignnerPDFBoxExample(KeyStore keystore, char[] pin)
            throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, IOException, CertificateException
    {
        super(keystore, pin);
    }

    /**
     * Sign pdf file and create new file that ends with "_signed.pdf".
     *
     * @param inputFile The source pdf document file.
     * @param signedFile The file to be signed.
     * @param tsaClient optional TSA client
     * @throws IOException
     */
    public void signPDF(File inputFile, File signedFile, TSAClient tsaClient) throws IOException
    {
        this.signPDF(inputFile, signedFile, tsaClient, null);
    }

    /**
     * Sign pdf file and create new file that ends with "_signed.pdf".
     *
     * @param inputFile The source pdf document file.
     * @param signedFile The file to be signed.
     * @param tsaClient optional TSA client
     * @param signatureFieldName optional name of an existing (unsigned) signature field
     * @throws IOException
     */
    public void signPDF(File inputFile, File signedFile, TSAClient tsaClient, String signatureFieldName) throws IOException
    {
        setTsaClient(tsaClient);

        if (inputFile == null || !inputFile.exists())
        {
            throw new IOException("Document for signing does not exist");
        }

        // creating output document and prepare the IO streams.
        FileOutputStream fos = new FileOutputStream(signedFile);

        try (PDDocument doc = PDDocument.load(inputFile))
        {
            int accessPermissions = SigUtils.getMDPPermission(doc);
            if (accessPermissions == 1)
            {
                throw new IllegalStateException("No changes to the document are permitted due to DocMDP transform parameters dictionary");
            }
            // Note that PDFBox has a bug that visual signing on certified files with permission 2
            // doesn't work properly, see PDFBOX-3699. As long as this issue is open, you may want to
            // be careful with such files.

            PDSignature signature;

            // sign a PDF with an existing empty signature, as created by the CreateEmptySignatureForm example.
            signature = findExistingSignature(doc, signatureFieldName);

            if (signature == null)
            {
                // create signature dictionary
                signature = new PDSignature();
            }

            // Optional: certify
            // can be done only if version is at least 1.5 and if not already set
            // doing this on a PDF/A-1b file fails validation by Adobe preflight (PDFBOX-3821)
            // PDF/A-1b requires PDF version 1.4 max, so don't increase the version on such files.
            if (doc.getVersion() >= 1.5f && accessPermissions == 0)
            {
                SigUtils.setMDPPermission(doc, signature, 2);
            }

            PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
            if (acroForm != null && acroForm.getNeedAppearances())
            {
                // PDFBOX-3738 NeedAppearances true results in visible signature becoming invisible
                // with Adobe Reader
                if (acroForm.getFields().isEmpty())
                {
                    // we can safely delete it if there are no fields
                    acroForm.getCOSObject().removeItem(COSName.NEED_APPEARANCES);
                    // note that if you've set MDP permissions, the removal of this item
                    // may result in Adobe Reader claiming that the document has been changed.
                    // and/or that field content won't be displayed properly.
                    // ==> decide what you prefer and adjust your code accordingly.
                }
                else
                {
                    System.out.println("/NeedAppearances is set, signature may be ignored by Adobe Reader");
                }
            }

            // default filter
            signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);

            // subfilter for basic and PAdES Part 2 signatures
            signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);

            if (visibleSignatureProperties != null)
            {
                // this builds the signature structures in a separate document
                visibleSignatureProperties.buildSignature();

                signature.setName(visibleSignatureProperties.getSignerName());
                signature.setLocation(visibleSignatureProperties.getSignerLocation());
                signature.setReason(visibleSignatureProperties.getSignatureReason());
            }

            // the signing date, needed for valid signature
            signature.setSignDate(Calendar.getInstance());

            // do not set SignatureInterface instance, if external signing used
            SignatureInterface signatureInterface = isExternalSigning() ? null : this;

            // register signature dictionary and sign interface
            if (visibleSignatureProperties != null && visibleSignatureProperties.isVisualSignEnabled())
            {
                signatureOptions = new SignatureOptions();
                signatureOptions.setVisualSignature(visibleSignatureProperties.getVisibleSignature());
                signatureOptions.setPage(visibleSignatureProperties.getPage() - 1);
                doc.addSignature(signature, signatureInterface, signatureOptions);
            }
            else
            {
                doc.addSignature(signature, signatureInterface);
            }

            if (isExternalSigning())
            {
                System.out.println("Signing externally " + signedFile.getName());
                ExternalSigningSupport externalSigning = doc.saveIncrementalForExternalSigning(fos);
                // invoke external signature service
                byte[] cmsSignature = sign(externalSigning.getContent());

                // Explanation of late external signing (off by default):
                // If you want to add the signature in a separate step, then set an empty byte array
                // and call signature.getByteRange() and remember the offset signature.getByteRange()[1]+1.
                // you can write the ascii hex signature at a later time even if you don't have this
                // PDDocument object anymore, with classic java file random access methods.
                // If you can't remember the offset value from ByteRange because your context has changed,
                // then open the file with PDFBox, find the field with findExistingSignature() or
                // PODDocument.getLastSignatureDictionary() and get the ByteRange from there.
                // Close the file and then write the signature as explained earlier in this comment.
                if (isLateExternalSigning())
                {
                    // this saves the file with a 0 signature
                    externalSigning.setSignature(new byte[0]);

                    // remember the offset (add 1 because of "<")
                    int offset = signature.getByteRange()[1] + 1;

                    // now write the signature at the correct offset without any PDFBox methods
                    try (RandomAccessFile raf = new RandomAccessFile(signedFile, "rw"))
                    {
                        raf.seek(offset);
                        raf.write(Hex.getBytes(cmsSignature));
                    }
                }
                else
                {
                    // set signature bytes received from the service and save the file
                    externalSigning.setSignature(cmsSignature);
                }
            }
            else
            {
                // write incremental (only for signing purpose)
                doc.saveIncremental(fos);
            }
        }

        // Do not close signatureOptions before saving, because some COSStream objects within
        // are transferred to the signed document.
        // Do not allow signatureOptions get out of scope before saving, because then the COSDocument
        // in signature options might by closed by gc, which would close COSStream objects prematurely.
        // See https://issues.apache.org/jira/browse/PDFBOX-3743
        IOUtils.closeQuietly(signatureOptions);
    }

    // Find an existing signature (assumed to be empty). You will usually not need this.
    private PDSignature findExistingSignature(PDDocument doc, String sigFieldName)
    {
        PDSignature signature = null;
        PDSignatureField signatureField;
        PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
        if (acroForm != null)
        {
            signatureField = (PDSignatureField) acroForm.getField(sigFieldName);
            if (signatureField != null)
            {
                // retrieve signature dictionary
                signature = signatureField.getSignature();
                if (signature == null)
                {
                    signature = new PDSignature();
                    // after solving PDFBOX-3524
                    // signatureField.setValue(signature)
                    // until then:
                    signatureField.getCOSObject().setItem(COSName.V, signature);
                }
                else
                {
                    throw new IllegalStateException("The signature field " + sigFieldName + " is already signed.");
                }
            }
        }
        return signature;
    }

    /**
     * This will print the usage for this program.
     */
    private static void usage()
    {
        System.err.println("Usage: java " + CreateVisibleSignature.class.getName()
                + " <pkcs12-keystore-file> <pin> <input-pdf> <sign-image>\n" + "" +
                           "options:\n" +
                           "  -tsa <url>    sign timestamp using the given TSA server\n"+
                           "  -e            sign using external signature creation scenario");
    }

}
</code>```

答:
Your signPDF method contains this code:

```<code>        // Optional: certify
        // can be done only if version is at least 1.5 and if not already set
        // doing this on a PDF/A-1b file fails validation by Adobe preflight (PDFBOX-3821)
        // PDF/A-1b requires PDF version 1.4 max, so don't increase the version on such files.
        if (doc.getVersion() >= 1.5f && accessPermissions == 0)
        {
            SigUtils.setMDPPermission(doc, signature, 2);
        }
</code>```

If you don't want a certification signature to start with, remove this setMDPPermission call.

Body:
As Adobe article "Digital Signatures in a PDF" stating:

PDF defines two types of signatures: approval and certification.  The
  differences are as follows:
  Approval: There can be any number of approval signatures in a document. The field may optionally be associated with FieldMDP
  permissions.
  Certification: There can be only one certification signature and it must be the first one in a document. The field is always associated
  with DocMDP.

Using PDFBox examples I was able to successfully apply multiple signatures to my document: https://github.com/apache/pdfbox/blob/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateVisibleSignature.java
In order to apply multiple signatures I was just running same code multiple times with different signature placeholders and images.

But what I have distinguished is that, even though I am running same code it always sets first signature as Certified, and all other once as Approval.

But in my case, I don't want a document to be certified, I just need all signatures to be of Apploval type including the first one. I know I can invisible first Certifying signature, but still I do not want to certify document at all.

I was trying to find a way to setup signature, but couldn't figure it out.

Here is my usage of example code (other classes are in the GitHub link above):

public class SignnerPDFBoxExample extends CreateSignatureBase {

    private SignatureOptions signatureOptions;
    private PDVisibleSignDesigner visibleSignDesigner;
    private final PDVisibleSigProperties visibleSignatureProperties = new PDVisibleSigProperties();
    private boolean lateExternalSigning = false;

    public static void main(String[] args) throws Exception {

        File ksFile = new File("keystore.jks");
        KeyStore keystore = KeyStore.getInstance("JKS");
        char[] pin = "123456".toCharArray();
        keystore.load(new FileInputStream(ksFile), pin);

        SignnerPDFBoxExample signer = new SignnerPDFBoxExample(keystore, pin.clone());
        String inputFilename = "Four_Signature_template.pdf";

        File documentFile = new File(inputFilename);
        File signedDocumentFile;
        int page = 1;
        try (FileInputStream imageStream = new FileInputStream("client_signature.jpg"))
        {
            String name = documentFile.getName();
            String substring = name.substring(0, name.lastIndexOf('.'));
            signedDocumentFile = new File(documentFile.getParent(), substring + "_signed.pdf");
            // page is 1-based here
            signer.setVisibleSignDesigner(inputFilename, 0, 0, -50, imageStream, page);
        }
        signer.setVisibleSignatureProperties("name", "location", "Signed using PDFBox", 0, page, true);
        signer.signPDF(documentFile, signedDocumentFile, null, "certifySignature");
    }

    public boolean isLateExternalSigning()
    {
        return lateExternalSigning;
    }

    /**
     * Set late external signing. Enable this if you want to activate the demo code where the
     * signature is kept and added in an extra step without using PDFBox methods. This is disabled
     * by default.
     *
     * @param lateExternalSigning
     */
    public void setLateExternalSigning(boolean lateExternalSigning)
    {
        this.lateExternalSigning = lateExternalSigning;
    }

    /**
     * Set visible signature designer for a new signature field.
     *
     * @param filename
     * @param x position of the signature field
     * @param y position of the signature field
     * @param zoomPercent
     * @param imageStream
     * @param page the signature should be placed on
     * @throws IOException
     */
    public void setVisibleSignDesigner(String filename, int x, int y, int zoomPercent,
            FileInputStream imageStream, int page)
            throws IOException
    {
        visibleSignDesigner = new PDVisibleSignDesigner(filename, imageStream, page);
        visibleSignDesigner.xAxis(x).yAxis(y).zoom(zoomPercent).adjustForRotation();
    }

    /**
     * Set visible signature designer for an existing signature field.
     *
     * @param zoomPercent
     * @param imageStream
     * @throws IOException
     */
    public void setVisibleSignDesigner(int zoomPercent, FileInputStream imageStream)
            throws IOException
    {
        visibleSignDesigner = new PDVisibleSignDesigner(imageStream);
        visibleSignDesigner.zoom(zoomPercent);
    }

    /**
     * Set visible signature properties for new signature fields.
     *
     * @param name
     * @param location
     * @param reason
     * @param preferredSize
     * @param page
     * @param visualSignEnabled
     * @throws IOException
     */
    public void setVisibleSignatureProperties(String name, String location, String reason, int preferredSize,
            int page, boolean visualSignEnabled) throws IOException
    {
        visibleSignatureProperties.signerName(name).signerLocation(location).signatureReason(reason).
                preferredSize(preferredSize).page(page).visualSignEnabled(visualSignEnabled).
                setPdVisibleSignature(visibleSignDesigner);
    }

    /**
     * Set visible signature properties for existing signature fields.
     *
     * @param name
     * @param location
     * @param reason
     * @param visualSignEnabled
     * @throws IOException
     */
    public void setVisibleSignatureProperties(String name, String location, String reason,
            boolean visualSignEnabled) throws IOException
    {
        visibleSignatureProperties.signerName(name).signerLocation(location).signatureReason(reason).
                visualSignEnabled(visualSignEnabled).setPdVisibleSignature(visibleSignDesigner);
    }

    /**
     * Initialize the signature creator with a keystore (pkcs12) and pin that
     * should be used for the signature.
     *
     * @param keystore is a pkcs12 keystore.
     * @param pin is the pin for the keystore / private key
     * @throws KeyStoreException if the keystore has not been initialized (loaded)
     * @throws NoSuchAlgorithmException if the algorithm for recovering the key cannot be found
     * @throws UnrecoverableKeyException if the given password is wrong
     * @throws CertificateException if the certificate is not valid as signing time
     * @throws IOException if no certificate could be found
     */
    public SignnerPDFBoxExample(KeyStore keystore, char[] pin)
            throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, IOException, CertificateException
    {
        super(keystore, pin);
    }

    /**
     * Sign pdf file and create new file that ends with "_signed.pdf".
     *
     * @param inputFile The source pdf document file.
     * @param signedFile The file to be signed.
     * @param tsaClient optional TSA client
     * @throws IOException
     */
    public void signPDF(File inputFile, File signedFile, TSAClient tsaClient) throws IOException
    {
        this.signPDF(inputFile, signedFile, tsaClient, null);
    }

    /**
     * Sign pdf file and create new file that ends with "_signed.pdf".
     *
     * @param inputFile The source pdf document file.
     * @param signedFile The file to be signed.
     * @param tsaClient optional TSA client
     * @param signatureFieldName optional name of an existing (unsigned) signature field
     * @throws IOException
     */
    public void signPDF(File inputFile, File signedFile, TSAClient tsaClient, String signatureFieldName) throws IOException
    {
        setTsaClient(tsaClient);

        if (inputFile == null || !inputFile.exists())
        {
            throw new IOException("Document for signing does not exist");
        }

        // creating output document and prepare the IO streams.
        FileOutputStream fos = new FileOutputStream(signedFile);

        try (PDDocument doc = PDDocument.load(inputFile))
        {
            int accessPermissions = SigUtils.getMDPPermission(doc);
            if (accessPermissions == 1)
            {
                throw new IllegalStateException("No changes to the document are permitted due to DocMDP transform parameters dictionary");
            }
            // Note that PDFBox has a bug that visual signing on certified files with permission 2
            // doesn't work properly, see PDFBOX-3699. As long as this issue is open, you may want to
            // be careful with such files.

            PDSignature signature;

            // sign a PDF with an existing empty signature, as created by the CreateEmptySignatureForm example.
            signature = findExistingSignature(doc, signatureFieldName);

            if (signature == null)
            {
                // create signature dictionary
                signature = new PDSignature();
            }

            // Optional: certify
            // can be done only if version is at least 1.5 and if not already set
            // doing this on a PDF/A-1b file fails validation by Adobe preflight (PDFBOX-3821)
            // PDF/A-1b requires PDF version 1.4 max, so don't increase the version on such files.
            if (doc.getVersion() >= 1.5f && accessPermissions == 0)
            {
                SigUtils.setMDPPermission(doc, signature, 2);
            }

            PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
            if (acroForm != null && acroForm.getNeedAppearances())
            {
                // PDFBOX-3738 NeedAppearances true results in visible signature becoming invisible
                // with Adobe Reader
                if (acroForm.getFields().isEmpty())
                {
                    // we can safely delete it if there are no fields
                    acroForm.getCOSObject().removeItem(COSName.NEED_APPEARANCES);
                    // note that if you've set MDP permissions, the removal of this item
                    // may result in Adobe Reader claiming that the document has been changed.
                    // and/or that field content won't be displayed properly.
                    // ==> decide what you prefer and adjust your code accordingly.
                }
                else
                {
                    System.out.println("/NeedAppearances is set, signature may be ignored by Adobe Reader");
                }
            }

            // default filter
            signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);

            // subfilter for basic and PAdES Part 2 signatures
            signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);

            if (visibleSignatureProperties != null)
            {
                // this builds the signature structures in a separate document
                visibleSignatureProperties.buildSignature();

                signature.setName(visibleSignatureProperties.getSignerName());
                signature.setLocation(visibleSignatureProperties.getSignerLocation());
                signature.setReason(visibleSignatureProperties.getSignatureReason());
            }

            // the signing date, needed for valid signature
            signature.setSignDate(Calendar.getInstance());

            // do not set SignatureInterface instance, if external signing used
            SignatureInterface signatureInterface = isExternalSigning() ? null : this;

            // register signature dictionary and sign interface
            if (visibleSignatureProperties != null && visibleSignatureProperties.isVisualSignEnabled())
            {
                signatureOptions = new SignatureOptions();
                signatureOptions.setVisualSignature(visibleSignatureProperties.getVisibleSignature());
                signatureOptions.setPage(visibleSignatureProperties.getPage() - 1);
                doc.addSignature(signature, signatureInterface, signatureOptions);
            }
            else
            {
                doc.addSignature(signature, signatureInterface);
            }

            if (isExternalSigning())
            {
                System.out.println("Signing externally " + signedFile.getName());
                ExternalSigningSupport externalSigning = doc.saveIncrementalForExternalSigning(fos);
                // invoke external signature service
                byte[] cmsSignature = sign(externalSigning.getContent());

                // Explanation of late external signing (off by default):
                // If you want to add the signature in a separate step, then set an empty byte array
                // and call signature.getByteRange() and remember the offset signature.getByteRange()[1]+1.
                // you can write the ascii hex signature at a later time even if you don't have this
                // PDDocument object anymore, with classic java file random access methods.
                // If you can't remember the offset value from ByteRange because your context has changed,
                // then open the file with PDFBox, find the field with findExistingSignature() or
                // PODDocument.getLastSignatureDictionary() and get the ByteRange from there.
                // Close the file and then write the signature as explained earlier in this comment.
                if (isLateExternalSigning())
                {
                    // this saves the file with a 0 signature
                    externalSigning.setSignature(new byte[0]);

                    // remember the offset (add 1 because of "<")
                    int offset = signature.getByteRange()[1] + 1;

                    // now write the signature at the correct offset without any PDFBox methods
                    try (RandomAccessFile raf = new RandomAccessFile(signedFile, "rw"))
                    {
                        raf.seek(offset);
                        raf.write(Hex.getBytes(cmsSignature));
                    }
                }
                else
                {
                    // set signature bytes received from the service and save the file
                    externalSigning.setSignature(cmsSignature);
                }
            }
            else
            {
                // write incremental (only for signing purpose)
                doc.saveIncremental(fos);
            }
        }

        // Do not close signatureOptions before saving, because some COSStream objects within
        // are transferred to the signed document.
        // Do not allow signatureOptions get out of scope before saving, because then the COSDocument
        // in signature options might by closed by gc, which would close COSStream objects prematurely.
        // See https://issues.apache.org/jira/browse/PDFBOX-3743
        IOUtils.closeQuietly(signatureOptions);
    }

    // Find an existing signature (assumed to be empty). You will usually not need this.
    private PDSignature findExistingSignature(PDDocument doc, String sigFieldName)
    {
        PDSignature signature = null;
        PDSignatureField signatureField;
        PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
        if (acroForm != null)
        {
            signatureField = (PDSignatureField) acroForm.getField(sigFieldName);
            if (signatureField != null)
            {
                // retrieve signature dictionary
                signature = signatureField.getSignature();
                if (signature == null)
                {
                    signature = new PDSignature();
                    // after solving PDFBOX-3524
                    // signatureField.setValue(signature)
                    // until then:
                    signatureField.getCOSObject().setItem(COSName.V, signature);
                }
                else
                {
                    throw new IllegalStateException("The signature field " + sigFieldName + " is already signed.");
                }
            }
        }
        return signature;
    }

    /**
     * This will print the usage for this program.
     */
    private static void usage()
    {
        System.err.println("Usage: java " + CreateVisibleSignature.class.getName()
                + " <pkcs12-keystore-file> <pin> <input-pdf> <sign-image>\n" + "" +
                           "options:\n" +
                           "  -tsa <url>    sign timestamp using the given TSA server\n"+
                           "  -e            sign using external signature creation scenario");
    }

}

Body:
Your signPDF method contains this code:

        // Optional: certify
        // can be done only if version is at least 1.5 and if not already set
        // doing this on a PDF/A-1b file fails validation by Adobe preflight (PDFBOX-3821)
        // PDF/A-1b requires PDF version 1.4 max, so don't increase the version on such files.
        if (doc.getVersion() >= 1.5f && accessPermissions == 0)
        {
            SigUtils.setMDPPermission(doc, signature, 2);
        }

If you don't want a certification signature to start with, remove this setMDPPermission call.


问:
Corrupt Text File read/write/open
I have a large text file that I take notes in; Recently, after saving it, it won't open and gives following error. I tried a few things on web that didn't work---opening in different encoding format, etc. Nothing worked. Any idea how I can open it again? Is there a language I can use from bash? I'm very familiar with PHP. Any ideas? Different text editor?

Error:

"The document “ToDo.txt” could not be opened. Text encoding Unicode (UTF-8) isn’t applicable."

"The file may have been saved using a different text encoding, or it may not be a text file."

答: cat the file from the CLI and make sure your data is still there. Then you could simply copy and paste the output into a new file and hopefully get rid of whatever weird encodings are causing that text editor to not read the file.</p>

Title: Corrupt Text File read/write/open


问:
Axios not catching Network Offline
Challenge is to catch network offline status error during POST request using AXIOS library in React-Native.

```<code>axios.post(Constants.API.LOGIN, {
  username: email,
  password: password
})
.then(function (response) {
  console.log('SUCCESS!');
  loginUserSuccess(dispatch, user);
})
.catch(function (error) {
  if(!error.response){
    networkError(dispatch);
  } else {
    loginUserFail(dispatch);
  }
});
</code>```

but when I switch off WiFi getting error

```<code>Possible Unhandled Promise Rejection (id:0)
</code>```

What is the way to handle network statuses with AXIOS?

Thanks!

答:
Check out NetInfo:

```<code>import { NetInfo } from 'react-native'
</code>```

https://facebook.github.io/react-native/docs/netinfo.html

isConnected

Available on all platforms. Asynchronously fetch a boolean to determine internet connectivity.

```<code>NetInfo.isConnected.fetch().then(isConnected => {
  console.log('First, is ' + (isConnected ? 'online' : 'offline'));
});
function handleFirstConnectivityChange(isConnected) {
  console.log('Then, is ' + (isConnected ? 'online' : 'offline'));
  NetInfo.isConnected.removeEventListener(
    'change',
    handleFirstConnectivityChange
  );
}
NetInfo.isConnected.addEventListener(
  'change',
  handleFirstConnectivityChange
);
</code>```

You may have a bit of extra issue there with your handling. I can't see exactly what is triggering the unhandled rejection in your code, but I can assume it is making it into the catch block.

If so, that currently means that either networkError() or loginUserFail() are failing, which is what is actually generating the unhandled rejection.

Take a look at those functions and make sure they have catch blocks inside them if they are asynchronous. Ask yourself where exactly is that error coming from, and answer that first, then look at NetInfo. Otherwise, the unhandled rejection may still be able to occur. Make sure you test all the different ways the code could fail :)

With NetInfo, you could set up something near the root-level in your app architecture, by way of that event listener. This could allow you to manage a setting in something like Redux. If the app detects offline, you could set the value to false and the entire app would know it is offline. You could probably make a middleware.

The code might look something like:

middleware:

```<code>`store.dispatch(changeConnectivityState())`
</code>```

or you could have an action creator (shown with redux-thunk):

```<code>export function onAppConnectivityChange(newState) {
    return (dispatch) {
        dispatch({
            type: APP_CONNECTIVITY_CHANGE,
            payload: newState
        })
    }
}
</code>```

Redux reducer:

```<code>case APP_CONNECTIVITY_CHANGE:
    return {
        ...state,
        isConnected: action.payload
    }
</code>```

In your components:

```<code>render() {
    if (this.props.isConnected === true) {
        return <View><Text>We are connected.</Text></View>
    }
}

const mapStateToProps = (state) => {
    const isConnected = state.someReducer.isConnected
    return {
        isConnected
    }
}

export default connect(mapStateToProps, null)(SomeComponent)
</code>```

Hopefully that gives you some ideas. Axios shouldn't be responsible for checking if the app is online or offline (except for quickly checking against a boolean). Your app should always know if it online or offline, and your components should be able to detect the state. You will find that much more scalable and easier to work with.

If I saw where you were calling Axios from, I could give you a more specific answer.

Title: Axios not catching Network Offline

Body:
Challenge is to catch network offline status error during POST request using AXIOS library in React-Native.

axios.post(Constants.API.LOGIN, {
  username: email,
  password: password
})
.then(function (response) {
  console.log('SUCCESS!');
  loginUserSuccess(dispatch, user);
})
.catch(function (error) {
  if(!error.response){
    networkError(dispatch);
  } else {
    loginUserFail(dispatch);
  }
});

but when I switch off WiFi getting error

Possible Unhandled Promise Rejection (id:0)

What is the way to handle network statuses with AXIOS?

Thanks!

Body:
Check out NetInfo:

import { NetInfo } from 'react-native'

https://facebook.github.io/react-native/docs/netinfo.html

isConnected

Available on all platforms. Asynchronously fetch a boolean to determine internet connectivity.

NetInfo.isConnected.fetch().then(isConnected => {
  console.log('First, is ' + (isConnected ? 'online' : 'offline'));
});
function handleFirstConnectivityChange(isConnected) {
  console.log('Then, is ' + (isConnected ? 'online' : 'offline'));
  NetInfo.isConnected.removeEventListener(
    'change',
    handleFirstConnectivityChange
  );
}
NetInfo.isConnected.addEventListener(
  'change',
  handleFirstConnectivityChange
);

You may have a bit of extra issue there with your handling. I can't see exactly what is triggering the unhandled rejection in your code, but I can assume it is making it into the catch block.

If so, that currently means that either networkError() or loginUserFail() are failing, which is what is actually generating the unhandled rejection.

Take a look at those functions and make sure they have catch blocks inside them if they are asynchronous. Ask yourself where exactly is that error coming from, and answer that first, then look at NetInfo. Otherwise, the unhandled rejection may still be able to occur. Make sure you test all the different ways the code could fail :)

With NetInfo, you could set up something near the root-level in your app architecture, by way of that event listener. This could allow you to manage a setting in something like Redux. If the app detects offline, you could set the value to false and the entire app would know it is offline. You could probably make a middleware.

The code might look something like:

middleware:

`store.dispatch(changeConnectivityState())`

or you could have an action creator (shown with redux-thunk):

export function onAppConnectivityChange(newState) {
    return (dispatch) {
        dispatch({
            type: APP_CONNECTIVITY_CHANGE,
            payload: newState
        })
    }
}

Redux reducer:

case APP_CONNECTIVITY_CHANGE:
    return {
        ...state,
        isConnected: action.payload
    }

In your components:

render() {
    if (this.props.isConnected === true) {
        return <View><Text>We are connected.</Text></View>
    }
}

const mapStateToProps = (state) => {
    const isConnected = state.someReducer.isConnected
    return {
        isConnected
    }
}

export default connect(mapStateToProps, null)(SomeComponent)

Hopefully that gives you some ideas. Axios shouldn't be responsible for checking if the app is online or offline (except for quickly checking against a boolean). Your app should always know if it online or offline, and your components should be able to detect the state. You will find that much more scalable and easier to work with.

If I saw where you were calling Axios from, I could give you a more specific answer.