问:
Length of h:outputLabel changes after RichFaces AJAX call
I have been trying to incorporate RichFaces into one of our more complicated pages to make it run a bit more smoothly via AJAX. Everything is working fine and it has solved a few problems I was having using regular form posts so I'd really like to keep it. The only problem in my way is that after pressing an a4j:commandButton most of my h:outputLabels are shortened by 3 pixels (these pixels were to the left of the text, which is unusual since the left padding, margin and border width are all 0px). This causes lots of my controls to shift slightly and looks very unprofessional. It looks to me like the re-rendering has done a more accurate job than the initial render. Here are the relevant parts of my page:

```<code><a4j:form id="mainForm">
    ...
    <fieldset id="illustrationDetails">
        <h:outputLabel for="product" value="Product" />
        <h:selectOneMenu id="product" value="#{illustrationManager.illustration.product}" valueChangeListener="#{illustrationManager.illustration.setProduct}" onchange="submit()">
            <f:selectItems value="#{illustrationManager.illustration.products}" />
        </h:selectOneMenu>
        <h:outputLabel for="paymentFrequency" value="Payment" />
        <h:selectOneMenu id="paymentFrequency" value="#{illustrationManager.illustration.paymentFrequency}">
            <f:selectItems value="#{illustrationManager.illustration.paymentFrequencies}" />
        </h:selectOneMenu>
        <h:outputLabel for="expenseGroup" value="Expense Group" />
        <h:selectOneMenu id="expenseGroup" value="#{illustrationManager.illustration.expenseGroupId}">
            <f:selectItems value="#{illustrationManager.illustration.expenseGroups}" />
        </h:selectOneMenu>
    </fieldset>
    ...
    <a4j:commandButton id="calculateButton" value="Calculate" action="#{illustrationManager.calculatePremium()}" ajaxSingle="true" reRender="mainForm" />
    ...
</a4j:form>
</code>```

In the fieldset above, all but the first label exhibit this problem. The first label is rendered what I would consider to be correctly (with no pixels to the left) by the initial render and as a result is not changed by the re-render.

Any suggestions would be welcome! Also, if you want more info like the css for the relevant controls let me know and I'll post it.

答:
Well, this is a partial answer anyway. The 3 pixels to the left of the h:outputLabels was due to the fact that the Mojarra JSF implementation adds a \n character to the beginning of the label tag body it creates. I'm as baffled as the guy who submitted this bug about it as to why this is done. The \n is converted to a space when displayed and that's what my 3 pixels were.

I do not know why, but the re-render triggered by my RichFaces AJAX call removes these \n characters and so the space is no longer displayed.

As a workaround, I have explicitly put spaces at the front of all my labels so that a space is always displayed. I'm surprised this is not a common problem.

Body:
I have been trying to incorporate RichFaces into one of our more complicated pages to make it run a bit more smoothly via AJAX. Everything is working fine and it has solved a few problems I was having using regular form posts so I'd really like to keep it. The only problem in my way is that after pressing an a4j:commandButton most of my h:outputLabels are shortened by 3 pixels (these pixels were to the left of the text, which is unusual since the left padding, margin and border width are all 0px). This causes lots of my controls to shift slightly and looks very unprofessional. It looks to me like the re-rendering has done a more accurate job than the initial render. Here are the relevant parts of my page:

<a4j:form id="mainForm">
    ...
    <fieldset id="illustrationDetails">
        <h:outputLabel for="product" value="Product" />
        <h:selectOneMenu id="product" value="#{illustrationManager.illustration.product}" valueChangeListener="#{illustrationManager.illustration.setProduct}" onchange="submit()">
            <f:selectItems value="#{illustrationManager.illustration.products}" />
        </h:selectOneMenu>
        <h:outputLabel for="paymentFrequency" value="Payment" />
        <h:selectOneMenu id="paymentFrequency" value="#{illustrationManager.illustration.paymentFrequency}">
            <f:selectItems value="#{illustrationManager.illustration.paymentFrequencies}" />
        </h:selectOneMenu>
        <h:outputLabel for="expenseGroup" value="Expense Group" />
        <h:selectOneMenu id="expenseGroup" value="#{illustrationManager.illustration.expenseGroupId}">
            <f:selectItems value="#{illustrationManager.illustration.expenseGroups}" />
        </h:selectOneMenu>
    </fieldset>
    ...
    <a4j:commandButton id="calculateButton" value="Calculate" action="#{illustrationManager.calculatePremium()}" ajaxSingle="true" reRender="mainForm" />
    ...
</a4j:form>

In the fieldset above, all but the first label exhibit this problem. The first label is rendered what I would consider to be correctly (with no pixels to the left) by the initial render and as a result is not changed by the re-render.

Any suggestions would be welcome! Also, if you want more info like the css for the relevant controls let me know and I'll post it.


来源: stackexchange

问:
Passing google pagespeed using google fonts
is it possible to pass google pagespeed while using google fonts? I've found this peace of code (https://github.com/typekit/webfontloader) which is also recommended by google. But even if I load this script, I can not pass google pagespeed.</p>

答:
WebfontLoader is not compatible with display swap. Not sure that this is the good solution.

Be sure to use the last url from Google Font with display=swap

```<code><!--old code-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<!--new code-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet">
</code>```

The other problem with Google font is that this is using 2 domains. https://fonts.googleapis.com and https://fonts.gstatic.com/

You should use dns prefetch and preconnect in the header:

```<code><link rel="dns-prefetch" href="//fonts.googleapis.com">
</code>```

and

```<code><link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
</code>```

Perhaps, the best solution is to download the font in your server.

Here is an article in french about optimising font for PageSpeed :
Optimiser les fonts pour accélérer son site

ContentLicense: CC BY-SA 3.0

Body:
WebfontLoader is not compatible with display swap. Not sure that this is the good solution.

Be sure to use the last url from Google Font with display=swap

<!--old code-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<!--new code-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet">

The other problem with Google font is that this is using 2 domains. https://fonts.googleapis.com and https://fonts.gstatic.com/

You should use dns prefetch and preconnect in the header:

<link rel="dns-prefetch" href="//fonts.googleapis.com">

and

<link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>

Perhaps, the best solution is to download the font in your server.

Here is an article in french about optimising font for PageSpeed :
Optimiser les fonts pour accélérer son site

ContentLicense: CC BY-SA 4.0


问:
Mockito gives UnfinishedVerificationException when it seems OK
Mockito appears to be throwing an UnfinishedVerificationException when I think I've done everything correctly. Here's my partial test case:

```<code>HttpServletRequest req = mock(HttpServletRequest.class);
when(req.getHeader("Authorization")).thenReturn("foo");

HttpServletResponse res = mock(HttpServletResponse.class);

classUnderTest.doMethod(req, res); // Use the mock

verify(res, never());
verify(req).setAttribute(anyString(), anyObject());
</code>```

And here's the partial class and method:

```<code>class ClassUnderTest extends AnotherClass {
    @Override
    public String doMethod(ServletRequest req, ServletRequest res) {
        // etc.
        return "someString";
    }
}
</code>```

Ignoring the fact that you should never mock interfaces you don't own, why is Mockito giving me the following message?

```<code>org.mockito.exceptions.misusing.UnfinishedVerificationException:
Missing method call for verify(mock) here:
-> at (redacted)

Example of correct verification:
    verify(mock).doSomething()

Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.

at [test method name and class redacted]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
... etc
</code>```

答:
In my case, using kotlin was because the funcion to test was not declared as open.

The exception notices that no final/private/equals/hash methods can be used.

```<code>fun increment(){
        i++
    }
</code>```

to

```<code>open fun increment(){
        i++
    }
</code>```

Body:
Mockito appears to be throwing an UnfinishedVerificationException when I think I've done everything correctly. Here's my partial test case:

HttpServletRequest req = mock(HttpServletRequest.class);
when(req.getHeader("Authorization")).thenReturn("foo");

HttpServletResponse res = mock(HttpServletResponse.class);

classUnderTest.doMethod(req, res); // Use the mock

verify(res, never());
verify(req).setAttribute(anyString(), anyObject());

And here's the partial class and method:

class ClassUnderTest extends AnotherClass {
    @Override
    public String doMethod(ServletRequest req, ServletRequest res) {
        // etc.
        return "someString";
    }
}

Ignoring the fact that you should never mock interfaces you don't own, why is Mockito giving me the following message?

org.mockito.exceptions.misusing.UnfinishedVerificationException:
Missing method call for verify(mock) here:
-> at (redacted)

Example of correct verification:
    verify(mock).doSomething()

Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.

at [test method name and class redacted]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
... etc

Body:
In my case, using kotlin was because the funcion to test was not declared as open.

The exception notices that no final/private/equals/hash methods can be used.

fun increment(){
        i++
    }

to

open fun increment(){
        i++
    }


问:
spring-cloud-dataflow: Stream Deployments Fail on OSX
I am unable to deploy and execute a basic http | log stream following the
getting-started stream guide:

```<code>wget https://raw.githubusercontent.com/spring-cloud/spring-cloud-dataflow/2.1.0.RELEASE/spring-cloud-dataflow-server/docker-compose.yml;
export DATAFLOW_VERSION=2.1.0.RELEASE;
export SKIPPER_VERSION=2.0.2.RELEASE;
docker-compose up;
open http://localhost:9393/dashboard/#/streams/create;
echo "Then, create a stream via text input: `http | log`"
echo "Then, deploy the stream. The deployment fails with exit code 137."
</code>```

I get the green "Successfully deployed stream definition".
The status shows as "Deploying", but it never fully deploys.
There are no ERROR messages in the logs, in the UI, or in the network requests.

Here is the console output of docker-compose up after I deploy the stream.

```<code>skipper              | 2019-05-24 22:31:53.363  INFO 1 --- [io-7577-exec-10] o.s.s.support.LifecycleObjectSupport     : started UPGRADE UPGRADE_DEPLOY_TARGET_APPS_SUCCEED UPGRADE_DEPLOY_TARGET_APPS UPGRADE_START UPGRADE_DELETE_SOURCE_APPS UPGRADE_CHECK_TARGET_APPS UPGRADE_WAIT_TARGET_APPS UPGRADE_CANCEL UPGRADE_DEPLOY_TARGET_APPS_FAILED UPGRADE_CHECK_CHOICE UPGRADE_EXIT INSTALL INSTALL_INSTALL INSTALL_EXIT ERROR DELETE DELETE_DELETE DELETE_EXIT ROLLBACK ROLLBACK_START ROLLBACK_EXIT_INSTALL ROLLBACK_EXIT ROLLBACK_EXIT_UPGRADE ROLLBACK_CHOICE INITIAL ERROR_JUNCTION  /  / uuid=f1ca31f2-ddcf-4203-88c8-de367c104151 / id=http-log-ingest-5
skipper              | 2019-05-24 22:31:53.504  INFO 1 --- [eTaskExecutor-1] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INITIAL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1038812346, toString()=AbstractState [id=INITIAL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12280a0a, deferred=[], entryActions=[], exitActions=[org.springframework.cloud.skipper.server.statemachine.ResetVariablesAction@6fd12c5], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:53.540  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state StateMachineState [getIds()=[INSTALL], toString()=AbstractState [id=INSTALL, pseudoState=null, deferred=[], entryActions=[], exitActions=[], stateActions=[], regions=[], submachine=INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5], getClass()=class org.springframework.statemachine.state.StateMachineState]
skipper              | 2019-05-24 22:31:53.576  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INSTALL_INSTALL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1643670584, toString()=AbstractState [id=INSTALL_INSTALL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12493450, deferred=[], entryActions=[org.springframework.cloud.skipper.server.statemachine.InstallInstallAction@149debbb], exitActions=[], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:54.117  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Preparing to run an application from org.springframework.cloud.stream.app:log-sink-kafka:jar:2.1.1.RELEASE. This may take some time if the artifact must be downloaded from a remote host.
skipper              | 2019-05-24 22:31:54.179  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Command to be executed: /opt/openjdk/bin/java -jar /root/.m2/repository/org/springframework/cloud/stream/app/log-sink-kafka/2.1.1.RELEASE/log-sink-kafka-2.1.1.RELEASE.jar
skipper              | 2019-05-24 22:31:54.203  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Deploying app with deploymentId http-log-ingest-5.log-v1 instance 0.
skipper              |    Logs will be in /tmp/spring-cloud-deployer-3633167379998955348/http-log-ingest-5-1558737114000/http-log-ingest-5.log-v1
skipper              | 2019-05-24 22:31:54.310  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Preparing to run an application from org.springframework.cloud.stream.app:http-source-kafka:jar:2.1.0.RELEASE. This may take some time if the artifact must be downloaded from a remote host.
skipper              | 2019-05-24 22:31:54.312  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Command to be executed: /opt/openjdk/bin/java -jar /root/.m2/repository/org/springframework/cloud/stream/app/http-source-kafka/2.1.0.RELEASE/http-source-kafka-2.1.0.RELEASE.jar
skipper              | 2019-05-24 22:31:54.313  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Deploying app with deploymentId http-log-ingest-5.http-v1 instance 0.
skipper              |    Logs will be in /tmp/spring-cloud-deployer-3633167379998955348/http-log-ingest-5-1558737114208/http-log-ingest-5.http-v1
skipper              | 2019-05-24 22:31:54.369  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : stopped org.springframework.statemachine.support.DefaultStateMachineExecutor@2c9d52c5
skipper              | 2019-05-24 22:31:54.370  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : stopped INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5
skipper              | 2019-05-24 22:31:54.371  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INITIAL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1038812346, toString()=AbstractState [id=INITIAL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12280a0a, deferred=[], entryActions=[], exitActions=[org.springframework.cloud.skipper.server.statemachine.ResetVariablesAction@6fd12c5], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:54.372  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.SkipperStateMachineService   : setting future value org.springframework.cloud.skipper.domain.Release@279e0d49
skipper              | 2019-05-24 22:31:54.373  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : started org.springframework.statemachine.support.DefaultStateMachineExecutor@2c9d52c5
skipper              | 2019-05-24 22:31:54.373  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : started INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5
mysql_1              | 2019-05-24T22:32:45.648870Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 4662ms. The settings might not be optimal. (flushed=2 and evicted=0, during the time.)
zookeeper_1          | [2019-05-24 22:32:52,733] INFO Expiring session 0x10001d6560e0001, timeout of 6000ms exceeded (org.apache.zookeeper.server.ZooKeeperServer)
mysql_1              | 2019-05-24T22:33:08.378945Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 7338ms. The settings might not be optimal. (flushed=1 and evicted=0, during the time.)
mysql_1              | 2019-05-24T22:33:24.272169Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 5118ms. The settings might not be optimal. (flushed=0 and evicted=0, during the time.)
zookeeper_1          | [2019-05-24 22:33:28,644] INFO Processed session termination for sessionid: 0x10001d6560e0001 (org.apache.zookeeper.server.PrepRequestProcessor)
kafka_1              | [2019-05-24 22:33:40,709] INFO [GroupMetadataManager brokerId=1001] Removed 0 expired offsets in 2216 milliseconds. (kafka.coordinator.group.GroupMetadataManager)
kafka_1              | [2019-05-24 22:33:49,359] WARN Client session timed out, have not heard from server in 58623ms for sessionid 0x10001d6560e0001 (org.apache.zookeeper.ClientCnxn)
kafka_1              | [2019-05-24 22:33:56,611] TRACE [Controller id=1001] Checking need to trigger auto leader balancing (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:06,529] DEBUG [Controller id=1001] Preferred replicas by broker Map(1001 -> Map(__consumer_offsets-22 -> Vector(1001), __consumer_offsets-30 -> Vector(1001), __consumer_offsets-8 -> Vector(1001), __consumer_offsets-21 -> Vector(1001), __consumer_offsets-4 -> Vector(1001), __consumer_offsets-27 -> Vector(1001), __consumer_offsets-7 -> Vector(1001), __consumer_offsets-9 -> Vector(1001), __consumer_offsets-46 -> Vector(1001), http-ingest-log-4.http-0 -> Vector(1001), __consumer_offsets-25 -> Vector(1001), __consumer_offsets-35 -> Vector(1001), __consumer_offsets-41 -> Vector(1001), __consumer_offsets-33 -> Vector(1001), __consumer_offsets-23 -> Vector(1001), __consumer_offsets-49 -> Vector(1001), __consumer_offsets-47 -> Vector(1001), __consumer_offsets-16 -> Vector(1001), __consumer_offsets-28 -> Vector(1001), __consumer_offsets-31 -> Vector(1001), __consumer_offsets-36 -> Vector(1001), __consumer_offsets-42 -> Vector(1001), __consumer_offsets-3 -> Vector(1001), __consumer_offsets-18 -> Vector(1001), __consumer_offsets-37 -> Vector(1001), http-ingest-log-3.http-0 -> Vector(1001), __consumer_offsets-15 -> Vector(1001), __consumer_offsets-24 -> Vector(1001), __consumer_offsets-38 -> Vector(1001), __consumer_offsets-17 -> Vector(1001), __consumer_offsets-48 -> Vector(1001), __confluent.support.metrics-0 -> Vector(1001), __consumer_offsets-19 -> Vector(1001), __consumer_offsets-11 -> Vector(1001), __consumer_offsets-13 -> Vector(1001), __consumer_offsets-2 -> Vector(1001), __consumer_offsets-43 -> Vector(1001), __consumer_offsets-6 -> Vector(1001), __consumer_offsets-14 -> Vector(1001), __consumer_offsets-20 -> Vector(1001), __consumer_offsets-0 -> Vector(1001), __consumer_offsets-44 -> Vector(1001), __consumer_offsets-39 -> Vector(1001), __consumer_offsets-12 -> Vector(1001), __consumer_offsets-45 -> Vector(1001), __consumer_offsets-1 -> Vector(1001), __consumer_offsets-5 -> Vector(1001), __consumer_offsets-26 -> Vector(1001), __consumer_offsets-29 -> Vector(1001), __consumer_offsets-34 -> Vector(1001), __consumer_offsets-10 -> Vector(1001), __consumer_offsets-32 -> Vector(1001), __consumer_offsets-40 -> Vector(1001))) (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:11,269] DEBUG [Controller id=1001] Topics not in preferred replica for broker 1001 Map() (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:11,993] TRACE [Controller id=1001] Leader imbalance ratio for broker 1001 is 0.0 (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:23,483] INFO Client session timed out, have not heard from server in 58623ms for sessionid 0x10001d6560e0001, closing socket connection and attempting reconnect (org.apache.zookeeper.ClientCnxn)
mysql_1              | 2019-05-24T22:35:19.628193Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 4049ms. The settings might not be optimal. (flushed=0 and evicted=0, during the time.)
...
(several minutes later)
...
dataflow-server exited with code 137
</code>```

I get the same behavior when swapping out different parts of the stack; for example RabbitMQ for Kafka/Zookeeper, Postgres for MySQL.

My local stack:

OSX 10.14

Java openjdk 11.0.2

Docker engine 18.09.2

Docker Compose 1.23.2

Docker Machine 0.16.1

答:
To build on Sabby Anandans answer, if you want to get the logs for a specific cloud stream application, I found that you can mount the volume for the skipper server.  I believe when running on docker, all of the spring data flow stream applications write logs out to a tmp directory. If you open up the application that failed to deploy it will tell you where it logs out the file. It should be something like...

/tmp/[RANDOM ID]/[NAME OF APPLICATION PLUS RUN VERSION]/stdout_0.log

So if you just mount a volume for the tmp folder to your skipper container, it should write out the logs. Make sure you mount to skipper-server and not dataflow-server. Dataflow-server also writes to this directory but it does not write the logs.

In my docker-compose.yml file, under skipper-server:

```<code>volumes:
  - C:\dataflow\output\logs:/tmp
</code>```

So after restarting my dataflow server by doing a docker-compose up, I was able to get logs out for my failing application at...

C:\dataflow\output\logs\1581698212231\streamName.applicationName-v1\

Body:
I am unable to deploy and execute a basic http | log stream following the
getting-started stream guide:

wget https://raw.githubusercontent.com/spring-cloud/spring-cloud-dataflow/2.1.0.RELEASE/spring-cloud-dataflow-server/docker-compose.yml;
export DATAFLOW_VERSION=2.1.0.RELEASE;
export SKIPPER_VERSION=2.0.2.RELEASE;
docker-compose up;
open http://localhost:9393/dashboard/#/streams/create;
echo "Then, create a stream via text input: `http | log`"
echo "Then, deploy the stream. The deployment fails with exit code 137."

I get the green "Successfully deployed stream definition".
The status shows as "Deploying", but it never fully deploys.
There are no ERROR messages in the logs, in the UI, or in the network requests.

Here is the console output of docker-compose up after I deploy the stream.

skipper              | 2019-05-24 22:31:53.363  INFO 1 --- [io-7577-exec-10] o.s.s.support.LifecycleObjectSupport     : started UPGRADE UPGRADE_DEPLOY_TARGET_APPS_SUCCEED UPGRADE_DEPLOY_TARGET_APPS UPGRADE_START UPGRADE_DELETE_SOURCE_APPS UPGRADE_CHECK_TARGET_APPS UPGRADE_WAIT_TARGET_APPS UPGRADE_CANCEL UPGRADE_DEPLOY_TARGET_APPS_FAILED UPGRADE_CHECK_CHOICE UPGRADE_EXIT INSTALL INSTALL_INSTALL INSTALL_EXIT ERROR DELETE DELETE_DELETE DELETE_EXIT ROLLBACK ROLLBACK_START ROLLBACK_EXIT_INSTALL ROLLBACK_EXIT ROLLBACK_EXIT_UPGRADE ROLLBACK_CHOICE INITIAL ERROR_JUNCTION  /  / uuid=f1ca31f2-ddcf-4203-88c8-de367c104151 / id=http-log-ingest-5
skipper              | 2019-05-24 22:31:53.504  INFO 1 --- [eTaskExecutor-1] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INITIAL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1038812346, toString()=AbstractState [id=INITIAL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12280a0a, deferred=[], entryActions=[], exitActions=[org.springframework.cloud.skipper.server.statemachine.ResetVariablesAction@6fd12c5], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:53.540  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state StateMachineState [getIds()=[INSTALL], toString()=AbstractState [id=INSTALL, pseudoState=null, deferred=[], entryActions=[], exitActions=[], stateActions=[], regions=[], submachine=INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5], getClass()=class org.springframework.statemachine.state.StateMachineState]
skipper              | 2019-05-24 22:31:53.576  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INSTALL_INSTALL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1643670584, toString()=AbstractState [id=INSTALL_INSTALL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12493450, deferred=[], entryActions=[org.springframework.cloud.skipper.server.statemachine.InstallInstallAction@149debbb], exitActions=[], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:54.117  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Preparing to run an application from org.springframework.cloud.stream.app:log-sink-kafka:jar:2.1.1.RELEASE. This may take some time if the artifact must be downloaded from a remote host.
skipper              | 2019-05-24 22:31:54.179  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Command to be executed: /opt/openjdk/bin/java -jar /root/.m2/repository/org/springframework/cloud/stream/app/log-sink-kafka/2.1.1.RELEASE/log-sink-kafka-2.1.1.RELEASE.jar
skipper              | 2019-05-24 22:31:54.203  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Deploying app with deploymentId http-log-ingest-5.log-v1 instance 0.
skipper              |    Logs will be in /tmp/spring-cloud-deployer-3633167379998955348/http-log-ingest-5-1558737114000/http-log-ingest-5.log-v1
skipper              | 2019-05-24 22:31:54.310  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Preparing to run an application from org.springframework.cloud.stream.app:http-source-kafka:jar:2.1.0.RELEASE. This may take some time if the artifact must be downloaded from a remote host.
skipper              | 2019-05-24 22:31:54.312  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Command to be executed: /opt/openjdk/bin/java -jar /root/.m2/repository/org/springframework/cloud/stream/app/http-source-kafka/2.1.0.RELEASE/http-source-kafka-2.1.0.RELEASE.jar
skipper              | 2019-05-24 22:31:54.313  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Deploying app with deploymentId http-log-ingest-5.http-v1 instance 0.
skipper              |    Logs will be in /tmp/spring-cloud-deployer-3633167379998955348/http-log-ingest-5-1558737114208/http-log-ingest-5.http-v1
skipper              | 2019-05-24 22:31:54.369  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : stopped org.springframework.statemachine.support.DefaultStateMachineExecutor@2c9d52c5
skipper              | 2019-05-24 22:31:54.370  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : stopped INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5
skipper              | 2019-05-24 22:31:54.371  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INITIAL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1038812346, toString()=AbstractState [id=INITIAL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12280a0a, deferred=[], entryActions=[], exitActions=[org.springframework.cloud.skipper.server.statemachine.ResetVariablesAction@6fd12c5], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:54.372  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.SkipperStateMachineService   : setting future value org.springframework.cloud.skipper.domain.Release@279e0d49
skipper              | 2019-05-24 22:31:54.373  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : started org.springframework.statemachine.support.DefaultStateMachineExecutor@2c9d52c5
skipper              | 2019-05-24 22:31:54.373  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : started INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5
mysql_1              | 2019-05-24T22:32:45.648870Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 4662ms. The settings might not be optimal. (flushed=2 and evicted=0, during the time.)
zookeeper_1          | [2019-05-24 22:32:52,733] INFO Expiring session 0x10001d6560e0001, timeout of 6000ms exceeded (org.apache.zookeeper.server.ZooKeeperServer)
mysql_1              | 2019-05-24T22:33:08.378945Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 7338ms. The settings might not be optimal. (flushed=1 and evicted=0, during the time.)
mysql_1              | 2019-05-24T22:33:24.272169Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 5118ms. The settings might not be optimal. (flushed=0 and evicted=0, during the time.)
zookeeper_1          | [2019-05-24 22:33:28,644] INFO Processed session termination for sessionid: 0x10001d6560e0001 (org.apache.zookeeper.server.PrepRequestProcessor)
kafka_1              | [2019-05-24 22:33:40,709] INFO [GroupMetadataManager brokerId=1001] Removed 0 expired offsets in 2216 milliseconds. (kafka.coordinator.group.GroupMetadataManager)
kafka_1              | [2019-05-24 22:33:49,359] WARN Client session timed out, have not heard from server in 58623ms for sessionid 0x10001d6560e0001 (org.apache.zookeeper.ClientCnxn)
kafka_1              | [2019-05-24 22:33:56,611] TRACE [Controller id=1001] Checking need to trigger auto leader balancing (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:06,529] DEBUG [Controller id=1001] Preferred replicas by broker Map(1001 -> Map(__consumer_offsets-22 -> Vector(1001), __consumer_offsets-30 -> Vector(1001), __consumer_offsets-8 -> Vector(1001), __consumer_offsets-21 -> Vector(1001), __consumer_offsets-4 -> Vector(1001), __consumer_offsets-27 -> Vector(1001), __consumer_offsets-7 -> Vector(1001), __consumer_offsets-9 -> Vector(1001), __consumer_offsets-46 -> Vector(1001), http-ingest-log-4.http-0 -> Vector(1001), __consumer_offsets-25 -> Vector(1001), __consumer_offsets-35 -> Vector(1001), __consumer_offsets-41 -> Vector(1001), __consumer_offsets-33 -> Vector(1001), __consumer_offsets-23 -> Vector(1001), __consumer_offsets-49 -> Vector(1001), __consumer_offsets-47 -> Vector(1001), __consumer_offsets-16 -> Vector(1001), __consumer_offsets-28 -> Vector(1001), __consumer_offsets-31 -> Vector(1001), __consumer_offsets-36 -> Vector(1001), __consumer_offsets-42 -> Vector(1001), __consumer_offsets-3 -> Vector(1001), __consumer_offsets-18 -> Vector(1001), __consumer_offsets-37 -> Vector(1001), http-ingest-log-3.http-0 -> Vector(1001), __consumer_offsets-15 -> Vector(1001), __consumer_offsets-24 -> Vector(1001), __consumer_offsets-38 -> Vector(1001), __consumer_offsets-17 -> Vector(1001), __consumer_offsets-48 -> Vector(1001), __confluent.support.metrics-0 -> Vector(1001), __consumer_offsets-19 -> Vector(1001), __consumer_offsets-11 -> Vector(1001), __consumer_offsets-13 -> Vector(1001), __consumer_offsets-2 -> Vector(1001), __consumer_offsets-43 -> Vector(1001), __consumer_offsets-6 -> Vector(1001), __consumer_offsets-14 -> Vector(1001), __consumer_offsets-20 -> Vector(1001), __consumer_offsets-0 -> Vector(1001), __consumer_offsets-44 -> Vector(1001), __consumer_offsets-39 -> Vector(1001), __consumer_offsets-12 -> Vector(1001), __consumer_offsets-45 -> Vector(1001), __consumer_offsets-1 -> Vector(1001), __consumer_offsets-5 -> Vector(1001), __consumer_offsets-26 -> Vector(1001), __consumer_offsets-29 -> Vector(1001), __consumer_offsets-34 -> Vector(1001), __consumer_offsets-10 -> Vector(1001), __consumer_offsets-32 -> Vector(1001), __consumer_offsets-40 -> Vector(1001))) (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:11,269] DEBUG [Controller id=1001] Topics not in preferred replica for broker 1001 Map() (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:11,993] TRACE [Controller id=1001] Leader imbalance ratio for broker 1001 is 0.0 (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:23,483] INFO Client session timed out, have not heard from server in 58623ms for sessionid 0x10001d6560e0001, closing socket connection and attempting reconnect (org.apache.zookeeper.ClientCnxn)
mysql_1              | 2019-05-24T22:35:19.628193Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 4049ms. The settings might not be optimal. (flushed=0 and evicted=0, during the time.)
...
(several minutes later)
...
dataflow-server exited with code 137

I get the same behavior when swapping out different parts of the stack; for example RabbitMQ for Kafka/Zookeeper, Postgres for MySQL.

My local stack:

OSX 10.14

Java openjdk 11.0.2

Docker engine 18.09.2

Docker Compose 1.23.2

Docker Machine 0.16.1

Body:
To build on Sabby Anandans answer, if you want to get the logs for a specific cloud stream application, I found that you can mount the volume for the skipper server.  I believe when running on docker, all of the spring data flow stream applications write logs out to a tmp directory. If you open up the application that failed to deploy it will tell you where it logs out the file. It should be something like...

/tmp/[RANDOM ID]/[NAME OF APPLICATION PLUS RUN VERSION]/stdout_0.log

So if you just mount a volume for the tmp folder to your skipper container, it should write out the logs. Make sure you mount to skipper-server and not dataflow-server. Dataflow-server also writes to this directory but it does not write the logs.

In my docker-compose.yml file, under skipper-server:

volumes:
  - C:\dataflow\output\logs:/tmp

So after restarting my dataflow server by doing a docker-compose up, I was able to get logs out for my failing application at...

C:\dataflow\output\logs\1581698212231\streamName.applicationName-v1\


问:
How to listen to the sound that Windows is currently playing?
I want to build an app that "listens" to any sound (Winamp, Youtube in web browser, etc) that Windows (7 to 10) might be currently playing.
I don't want to intercept, modify or redirect the sound. Only to listen to it and analyze it.

I would prefer to listen only to the music sources... but that's another question :)

What is the API that could do that?

答:
If you simply want to grab the output mix from WASAPI you can follow this guide on MSDN for Loopback Recording.  If you're interested in hooking the output from specific applications only, this question has a number of answers that already touch on this topic.

For loopback recording, do note the caveats about DRM :

Windows Vista provides digital rights management (DRM). Content providers rely on DRM to protect their proprietary music or other content from unauthorized copying and other illegal uses. WASAPI does not permit loopback recording of digital streams that contain DRM-protected content. Similarly, a trusted audio driver does not permit a loopback device to capture digital streams that contain protected content. Windows Vista allows only trusted drivers to play protected content.


问:
Get accessed to plucked object using javascript and lodash
I have an array of users in my javascript. For each user I am comparing if that user appears in another list.

```<code>var users = USERS.getUsers();

for (var i = 0; i < users.length; i++) {
    var u = users[i];
    if (util.pluck(myList.adminUsers, 'email').includes(u.email)) {
        // How do I check the value of the plucked value for myList.adminUsers.locationId ?
        u.status = "admin";
    }
}
</code>```

users is an array of user objects.

```<code>[{...}]
    0:
        id: "1"
        email: "johndoe@gmail.com"
        firstname: "John"
        lastname: "Doe"
        roleid: "1"
        _proto__: Object
    1:
        id: "2"
        email: "janedoe@gmail.com"
        firstname: "Jane"
        lastname: "Doe"
        roleid: "1"
        _proto__: Object
</code>```

myList.adminUsers is also an array of user objects but also with locationId.

```<code>[{...}]
    0:
        id: "1"
        email: "johndoe@gmail.com"
        firstname: "John"
        lastname: "Doe"
        roleid: "1"
        locationId: "123"
        _proto__: Object
</code>```

I need to compare another field in this check. So I need to see if the plucked object from myList.adminUsers has a field locationId that equals x, but I'm not sure how to do this?

How can I get access to the plucked object so I can check the value of locationId?

答:
Use findWhere instead of pluck. You can give it an object containing all the properties you want to match.

```<code>if (util.findWhere(myList.adminUsers, {email: u.email, locationId: u.locationId})) {
    u.status = "admin";
}
</code>```

Body:
I have an array of users in my javascript. For each user I am comparing if that user appears in another list.

var users = USERS.getUsers();

for (var i = 0; i < users.length; i++) {
    var u = users[i];
    if (util.pluck(myList.adminUsers, 'email').includes(u.email)) {
        // How do I check the value of the plucked value for myList.adminUsers.locationId ?
        u.status = "admin";
    }
}

users is an array of user objects.

[{...}]
    0:
        id: "1"
        email: "johndoe@gmail.com"
        firstname: "John"
        lastname: "Doe"
        roleid: "1"
        _proto__: Object
    1:
        id: "2"
        email: "janedoe@gmail.com"
        firstname: "Jane"
        lastname: "Doe"
        roleid: "1"
        _proto__: Object

myList.adminUsers is also an array of user objects but also with locationId.

[{...}]
    0:
        id: "1"
        email: "johndoe@gmail.com"
        firstname: "John"
        lastname: "Doe"
        roleid: "1"
        locationId: "123"
        _proto__: Object

I need to compare another field in this check. So I need to see if the plucked object from myList.adminUsers has a field locationId that equals x, but I'm not sure how to do this?

How can I get access to the plucked object so I can check the value of locationId?

Body:
Use findWhere instead of pluck. You can give it an object containing all the properties you want to match.

if (util.findWhere(myList.adminUsers, {email: u.email, locationId: u.locationId})) {
    u.status = "admin";
}


问:
How can I find the point on a 3D surface closest to a point outside that surface?
I want to find point B on a surface in R3 with an algebraic expression

f(x,y) = x^3 + y^2,

given point A, so that point B is closest in Euclidean distance, and lies on the surface. [Please note that the surface on the plot is not x^3 + y^2, and it is for illustrative purposes only].

I am not a Matlab user, but I see that the function fmincon or fminsearch may be the way to go as suggested in this online accessible paper by J. BAEK, A. DEOPURKAR, AND K. REDFIELD (p. 24, Appendix). Alternatively I thought of parameterizing a sphere by its radius around the point A, and looking for its first tangent point to the surface, but that would spawn many more questions.

For fmincon it seems like the first order of things is to define a function to minimize, and that would be mathematically the Euclidean distance: So if point A is in a matrix, and corresponds to A(:,1) and B is defined as (b1,b2,b3), the formula to minimize would be

(A(1,1) - b1)^2 + (A(2,1) - b2)^2 + (A(3,1) - b3)^2

As in the first comment, since B has to be on the surface, the constraining condition would be

b3= b1^3 + b2^2.

I don't know how to formalize this in Matlab, and whether I would need for some initial point to start the process, or A is a valid starting point.

答:
As you wrote this problem can be solved with fminsearch. Some time ago I wrote a code solving your issue based on the NURB Toolbox for Matlab. I just simplified it a bit for your problem. In this case surf is a function handle to the surface function. If you have a better starting point then [0, 0], you may use it instead.</p>

```<code>function Y = ProjectOnSurf(X,surf)
    %Computes the closest point to given point on a surface.
    f=@(lambda) norm(surf(lambda) - X)
    lambda=fminsearch(f,[0, 0]); %Find parameters for minimal distance
    Y=NurbEval(surf,lambda)'; %Solve function for parameters
end
</code>```

Body:
As you wrote this problem can be solved with fminsearch. Some time ago I wrote a code solving your issue based on the NURB Toolbox for Matlab. I just simplified it a bit for your problem. In this case surf is a function handle to the surface function. If you have a better starting point then [0, 0], you may use it instead.

function Y = ProjectOnSurf(X,surf)
    %Computes the closest point to given point on a surface.
    f=@(lambda) norm(surf(lambda) - X)
    lambda=fminsearch(f,[0, 0]); %Find parameters for minimal distance
    Y=NurbEval(surf,lambda)'; %Solve function for parameters
end


问:
Shiny App Google Analytics API connection does not work: no JSON file found
I want to access data in a Shiny App directly via Google Analytics API and now have an google OAuth 2.0 authentication issue.

My approach was the following one:

1) Created a web aplication project in my Google project and downloaded the json File.

2) I added the json file to my app folder. So the structure of my app folder is the following:

app.r

test.json

3) Then I created a .Renviron file in the same app folder. My assumption for the error lays here, since I am not sure if I created it correctly. I created a txt file and named it .Renviron. And I inserted the following line: GAR_CLIENT_WEB_JSON = "test.json"
So now in my app folder are: app.r, test.json, and .Renviron

4) in app.R I have the following code:

```<code>library(shiny)
library(googleAuthR)

gar_set_client(scopes = c("https://www.googleapis.com/auth/analytics.readonly"))

# Define UI
ui <- fluidPage(
   gar_auth_jsUI("auth")

)

# Define server logic
server <- function(input, output) {

}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

When testing with Sys.getenv("GAR_CLIENT_WEB_JSON") it always tells me, that it is empty.

And when running the app, I get the following error:

```<code>Error in gar_set_client(scopes = c("https://www.googleapis.com/auth/analytics.readonly")) :
  No client JSON files found
</code>```

Does anybody has an idea what I am doing wrong?

答:
Try stating the full/explicit filepath in the the .Renviron file when assigning both "GAR_CLIENT_WEB_JSON" and "GL_AUTH"

Eg:

```<code>GL_AUTH="/Users/yourUser/Desktop/yourFoldername/yourFilename.json"
GAR_CLIENT_WEB_JSON="/Users/yourUser/Desktop/yourFoldername/yourFilename.json"
</code>```

Solved the error in my case.

Body:
I want to access data in a Shiny App directly via Google Analytics API and now have an google OAuth 2.0 authentication issue.

My approach was the following one:

1) Created a web aplication project in my Google project and downloaded the json File.

2) I added the json file to my app folder. So the structure of my app folder is the following:

app.r

test.json

3) Then I created a .Renviron file in the same app folder. My assumption for the error lays here, since I am not sure if I created it correctly. I created a txt file and named it .Renviron. And I inserted the following line: GAR_CLIENT_WEB_JSON = "test.json"
So now in my app folder are: app.r, test.json, and .Renviron

4) in app.R I have the following code:

library(shiny)
library(googleAuthR)

gar_set_client(scopes = c("https://www.googleapis.com/auth/analytics.readonly"))

# Define UI
ui <- fluidPage(
   gar_auth_jsUI("auth")

)

# Define server logic
server <- function(input, output) {

}

# Run the application
shinyApp(ui = ui, server = server)

When testing with Sys.getenv("GAR_CLIENT_WEB_JSON") it always tells me, that it is empty.

And when running the app, I get the following error:

Error in gar_set_client(scopes = c("https://www.googleapis.com/auth/analytics.readonly")) :
  No client JSON files found

Does anybody has an idea what I am doing wrong?

Body:
Try stating the full/explicit filepath in the the .Renviron file when assigning both "GAR_CLIENT_WEB_JSON" and "GL_AUTH"

Eg:

GL_AUTH="/Users/yourUser/Desktop/yourFoldername/yourFilename.json"
GAR_CLIENT_WEB_JSON="/Users/yourUser/Desktop/yourFoldername/yourFilename.json"

Solved the error in my case.


问:
How to disable ipython prompt blinking?
When I run ipython (7.12.0, this is from the Anaconda distro) in an xterm, the In prompts blink. It's super irritating. How do I turn it off?

The only thing that blinks is the text of the input prompt "In [#]:' at the beginning of every ipython input line. Nothing else in the terminal window blinks. To be specific, I am not asking about the cursor. The cursor is not blinking.

Note, there is a previous question, How to disable ipython prompt blinking?, that purports to answer this exact question. However, it is out-of-date. The answer given there doesn't work. Also, I suspect the answer was meant for the jupyter notebook. I'm asking about the terminal version of ipython.

答:
The blinking can be is suppressed by the xterm cm option.

```<code>xterm +cm &
</code>```

produces an xterm that, when ipython runs in it, has color but no blinking text.

Title: How to disable ipython prompt blinking?

Body:
The blinking can be is suppressed by the xterm cm option.

xterm +cm &

produces an xterm that, when ipython runs in it, has color but no blinking text.


问:
I'm seeing "use of undeclared identifier" error, can someone tell me how to fix it?
I received error messages for the following code. I am new to C++ so I couldn't see what's the problem. Thank you so much.

header file(VGMap.h):

```<code>#ifndef VGMAP_H
#define VGMAP_H

namespace Game
{
 struct AdjListNode{
   int data;
   AdjListNode *next;
  };
 struct AdjList{
   AdjListNode *head;
 };
 struct Graph{
   int V;
   AdjList *arr;
 };
 class vgmap{
   public:
   AdjListNode *newAdjListNode(int);
   Graph *createGraph(int);
   void addEdge(Graph*,int,int);
   void printGraph(Graph*);
 };
</code>```

}#endif

VGMap.cpp:

```<code>#include "VGMap.h"

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::string;

namespace Game
{
  AdjListNode* vgmap::newAdjListNode(int data){
    AdjListNode *nptr=new AdjListNode;
    nptr->data=data;
    nptr->next=NULL;
    return nptr;

  }
  Graph* vgmap::createGraph(int V){
    Graph *graph=new Graph;
    graph->V=V;
    graph->arr=new AdjList[V];
    //initialize with NULL (e.g root=NULL)
    for(int i=0;i<V;i++){
        graph->arr[i].head=NULL;
    }
    return graph;
  }
  void vgmap::addEdge(Game::Graph *graph, int src, int dest){
    AdjListNode *nptr=newAdjListNode(dest);
    nptr->next=graph->arr[src].head;
    graph->arr[src].head=nptr;
    //connect from dest to src (since undirected)
    nptr=newAdjListNode(src);
    nptr->next=graph->arr[dest].head;
    graph->arr[dest].head=nptr;
  }
  void vgmap::printGraph(Game::Graph *graph){
    for(int i=0;i<graph->V;i++){
        AdjListNode *root=graph->arr[i].head;
        if(i==4||(i-4)%5==0){
          cout<<std::endl;
        }
        else if(i%5==0){
          cout<<i<<" ";
        }
        while(root!=NULL){
          if(root->data==i+1){
            cout<<root->data<<" ";
            //i=i+1;
          }
            root=root->next;
        }
    }
  }
}
</code>```

main.cpp:

```<code>#include <iostream>
#include <ctime>

#include "VGMap.h"

using Game::AdjListNode;
using Game::AdjList;
using Game::Graph;
using Game::vgmap;

using std::cout;
using std::cin;
using std::endl;

int main()
{
  int totalVertices=30;
    Graph *graph;
    graph=createGraph(totalVertices);
    //connect edge
    for(int i=0;i<4;i++){
      addEdge(graph,i,i+1);
    }
    for(int i=5;i<9;i++){
      addEdge(graph,i,i+1);
    }
    for(int i=10;i<14;i++){
      addEdge(graph,i,i+1);
    }
    for(int i=15;i<19;i++){
      addEdge(graph,i,i+1);
    }
    for(int i=20;i<24;i++){
      addEdge(graph,i,i+1);
    }
    for(int i=29;i>25;i--){
      addEdge(graph,i,i-1);
    }
    for(int i=0;i<5;i++){
      addEdge(graph,25-i*5,25-(i+1)*5);
    }
    for(int i=0;i<5;i++){
      addEdge(graph,1+i*5,1+(i+1)*5);
    }
    for(int i=0;i<5;i++){
      addEdge(graph,2+i*5,2+(i+1)*5);
    }
    for(int i=0;i<5;i++){
      addEdge(graph,3+i*5,3+(i+1)*5);
    }
    for(int i=0;i<5;i++){
      addEdge(graph,4+i*5,4+(i+1)*5);
    }
    printGraph(graph);
}
</code>```

This is the error message I received:

```<code>main.cpp:47:11: error: use of undeclared identifier 'createGraph'
    graph=createGraph(totalVertices);
          ^
main.cpp:50:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,i,i+1);
      ^
main.cpp:53:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,i,i+1);
      ^
main.cpp:56:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,i,i+1);
      ^
main.cpp:59:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,i,i+1);
      ^
main.cpp:62:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,i,i+1);
      ^
main.cpp:65:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,i,i-1);
      ^
main.cpp:68:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,25-i*5,25-(i+1)*5);
      ^
main.cpp:71:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,1+i*5,1+(i+1)*5);
      ^
main.cpp:74:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,2+i*5,2+(i+1)*5);
      ^
main.cpp:77:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,3+i*5,3+(i+1)*5);
      ^
main.cpp:80:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,4+i*5,4+(i+1)*5);
      ^
main.cpp:82:5: error: use of undeclared identifier 'printGraph'
    printGraph(graph);
    ^
13 errors generated.
</code>```

答:
There are no functions defined createGraph or addEdge.  There are however methods called vgmap::createGraph and vgmap::addEdge.

Still, you can't call these methods like this because you would need to first create an instance of vgmap, then call the methods on that object.

Since these methods don't act on any internal data, change their definitions to static:

```<code> class vgmap{
   public:
   static AdjListNode *newAdjListNode(int);
   static Graph *createGraph(int);
   static void addEdge(Graph*,int,int);
   static void printGraph(Graph*);
 };
</code>```

And then you can call them with the full name without having to create an instance of vgmap:

```<code>graph=vgmap::createGraph(totalVertices);
...
vgmap::addEdge(graph,i,i-1);
...
</code>```

Body:
I received error messages for the following code. I am new to C++ so I couldn't see what's the problem. Thank you so much.

header file(VGMap.h):

#ifndef VGMAP_H
#define VGMAP_H

namespace Game
{
 struct AdjListNode{
   int data;
   AdjListNode *next;
  };
 struct AdjList{
   AdjListNode *head;
 };
 struct Graph{
   int V;
   AdjList *arr;
 };
 class vgmap{
   public:
   AdjListNode *newAdjListNode(int);
   Graph *createGraph(int);
   void addEdge(Graph*,int,int);
   void printGraph(Graph*);
 };

}#endif

VGMap.cpp:

#include "VGMap.h"

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::string;

namespace Game
{
  AdjListNode* vgmap::newAdjListNode(int data){
    AdjListNode *nptr=new AdjListNode;
    nptr->data=data;
    nptr->next=NULL;
    return nptr;

  }
  Graph* vgmap::createGraph(int V){
    Graph *graph=new Graph;
    graph->V=V;
    graph->arr=new AdjList[V];
    //initialize with NULL (e.g root=NULL)
    for(int i=0;i<V;i++){
        graph->arr[i].head=NULL;
    }
    return graph;
  }
  void vgmap::addEdge(Game::Graph *graph, int src, int dest){
    AdjListNode *nptr=newAdjListNode(dest);
    nptr->next=graph->arr[src].head;
    graph->arr[src].head=nptr;
    //connect from dest to src (since undirected)
    nptr=newAdjListNode(src);
    nptr->next=graph->arr[dest].head;
    graph->arr[dest].head=nptr;
  }
  void vgmap::printGraph(Game::Graph *graph){
    for(int i=0;i<graph->V;i++){
        AdjListNode *root=graph->arr[i].head;
        if(i==4||(i-4)%5==0){
          cout<<std::endl;
        }
        else if(i%5==0){
          cout<<i<<" ";
        }
        while(root!=NULL){
          if(root->data==i+1){
            cout<<root->data<<" ";
            //i=i+1;
          }
            root=root->next;
        }
    }
  }
}

main.cpp:

#include <iostream>
#include <ctime>

#include "VGMap.h"

using Game::AdjListNode;
using Game::AdjList;
using Game::Graph;
using Game::vgmap;

using std::cout;
using std::cin;
using std::endl;

int main()
{
  int totalVertices=30;
    Graph *graph;
    graph=createGraph(totalVertices);
    //connect edge
    for(int i=0;i<4;i++){
      addEdge(graph,i,i+1);
    }
    for(int i=5;i<9;i++){
      addEdge(graph,i,i+1);
    }
    for(int i=10;i<14;i++){
      addEdge(graph,i,i+1);
    }
    for(int i=15;i<19;i++){
      addEdge(graph,i,i+1);
    }
    for(int i=20;i<24;i++){
      addEdge(graph,i,i+1);
    }
    for(int i=29;i>25;i--){
      addEdge(graph,i,i-1);
    }
    for(int i=0;i<5;i++){
      addEdge(graph,25-i*5,25-(i+1)*5);
    }
    for(int i=0;i<5;i++){
      addEdge(graph,1+i*5,1+(i+1)*5);
    }
    for(int i=0;i<5;i++){
      addEdge(graph,2+i*5,2+(i+1)*5);
    }
    for(int i=0;i<5;i++){
      addEdge(graph,3+i*5,3+(i+1)*5);
    }
    for(int i=0;i<5;i++){
      addEdge(graph,4+i*5,4+(i+1)*5);
    }
    printGraph(graph);
}

This is the error message I received:

main.cpp:47:11: error: use of undeclared identifier 'createGraph'
    graph=createGraph(totalVertices);
          ^
main.cpp:50:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,i,i+1);
      ^
main.cpp:53:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,i,i+1);
      ^
main.cpp:56:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,i,i+1);
      ^
main.cpp:59:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,i,i+1);
      ^
main.cpp:62:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,i,i+1);
      ^
main.cpp:65:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,i,i-1);
      ^
main.cpp:68:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,25-i*5,25-(i+1)*5);
      ^
main.cpp:71:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,1+i*5,1+(i+1)*5);
      ^
main.cpp:74:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,2+i*5,2+(i+1)*5);
      ^
main.cpp:77:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,3+i*5,3+(i+1)*5);
      ^
main.cpp:80:7: error: use of undeclared identifier 'addEdge'
      addEdge(graph,4+i*5,4+(i+1)*5);
      ^
main.cpp:82:5: error: use of undeclared identifier 'printGraph'
    printGraph(graph);
    ^
13 errors generated.

Body:
There are no functions defined createGraph or addEdge.  There are however methods called vgmap::createGraph and vgmap::addEdge.

Still, you can't call these methods like this because you would need to first create an instance of vgmap, then call the methods on that object.

Since these methods don't act on any internal data, change their definitions to static:

 class vgmap{
   public:
   static AdjListNode *newAdjListNode(int);
   static Graph *createGraph(int);
   static void addEdge(Graph*,int,int);
   static void printGraph(Graph*);
 };

And then you can call them with the full name without having to create an instance of vgmap:

graph=vgmap::createGraph(totalVertices);
...
vgmap::addEdge(graph,i,i-1);
...


问:
How to pass dynamically generated textbox values to the controller from view?
I have generated dynamic textboxes using jQuery on button click. I want to pass their values to the controller using AJAX. I am using the form.serialize method.
 i can see the value when i alert .But in the controller it becomes null

```<code>$("#add").click(function() {
  $("#mydiv").append($("<div class='row' id='row'> <div class='col-md-4'><div class='form-group'><div class='col-md-10'><input type='text' name='vname[]'class='form-control' placeholder='Vazhipad Name' /></div></div></div><div class='col-md-4'><div class='form-group'><div class='col-md-10'><input type='text' name='vprize[]'class='form-control' placeholder='Vazhipad Prize' /> </div></div> </div><div class='form-group'><div class='col-md-10'><button type='button' id='btnRemove' class='btn btn-primary btnRemove'>-</button></div></div></div></div>"))
});

$("#sub").click(function() {
  $.ajax({
    url: "/Admin/AddVazhipad",
    type: "POST",
    data: $('#myForm').serialize(),
    success: function(data) {
      alert("Success");
    },
    failure: function(data) {
      alert("Failed");
    },
  });
</code>```

public class Vazhipad
{
  [Required] public int vid { get; set; }
  [Required] public int templeid { get; set; }
  [Required] public List<string> vname { get; set; }
  [Required] public List<float> vprize { get; set; }
}
```

答: i got the answer.What i did is named the Textbox name "vname[]" to "vname".It works perfectly now</p>

Body:
I have generated dynamic textboxes using jQuery on button click. I want to pass their values to the controller using AJAX. I am using the form.serialize method.
 i can see the value when i alert .But in the controller it becomes null

$("#add").click(function() {
  $("#mydiv").append($("

<input type='text' name='vname[]'class='form-control' placeholder='Vazhipad Name' />

<input type='text' name='vprize[]'class='form-control' placeholder='Vazhipad Prize' />

<button type='button' id='btnRemove' class='btn btn-primary btnRemove'>-</button>

"))
});

$("#sub").click(function() {
  $.ajax({
    url: "/Admin/AddVazhipad",
    type: "POST",
    data: $('#myForm').serialize(),
    success: function(data) {
      alert("Success");
    },
    failure: function(data) {
      alert("Failed");
    },
  });

public class Vazhipad
{
  [Required] public int vid { get; set; }
  [Required] public int templeid { get; set; }
  [Required] public List<string> vname { get; set; }
  [Required] public List<float> vprize { get; set; }
}


问:
Can I use stat to show human readable size of file?
I'm trying to use stat command to display a list of files in the current directory, sorted by largest  to smallest.
my script is

```<code>filelist=$(ls -p | grep -v/)
filesize=$(stat -c "%s : %n" $filelist | sort -nr)
</code>```

It works however it displays the size in bytes. Is there a way to show it in a human readable format using stat? or do i have to try something else. thank you for the help.

答:
But ls can do that:

```<code>ls --human-readable --kibibytes -Sl
</code>```

If you don't want a full ls output can use it with du:

```<code>for FILE in `ls -S`; do du -sh $FILE ; done
</code>```

Body:
I'm trying to use stat command to display a list of files in the current directory, sorted by largest  to smallest.
my script is

filelist=$(ls -p | grep -v/)
filesize=$(stat -c "%s : %n" $filelist | sort -nr)

It works however it displays the size in bytes. Is there a way to show it in a human readable format using stat? or do i have to try something else. thank you for the help.

Body:
But ls can do that:

ls --human-readable --kibibytes -Sl

If you don't want a full ls output can use it with du:

for FILE in `ls -S`; do du -sh $FILE ; done


问:
Sum Opportunity Line Quantity Dynamics CRM
I have a list of opportunity product lines associated to the opportunity. The products in the opportunity lines are labor based, engineering services. For projecting resource requirements I want to add two fields to my opportunity entity.

Total Labor Effort

This field would be populated by the total quantity of all "labor based" products in the opportunity product lines.

Weighted Labor Effort

Same as Total Labor Effort, except the value will be multiplied by the probability of closing the deal. This is a separate custom field in the opportunity.

I have tried a roll up field, but I can't seem to get it to sum up the quantity of the products in the product lines. It will only look at the product lines themselves. Calculated field seem to be more limited even.

What features of Dynamics CRM could help me achieve this?

答:
Ultimately I solved this using MS Flow to retrieve all the Opportunity Line from an "updated" Opportunity and summing them up before finally writing to the Opportunity field. For weighted value I made a simple calculated field based on the close probability and total labor effort.

MS FLow Screen Shot


问:
jquery help with css() and animate()
I have this nav system,

```<code><nav id="mainnav">
    <ul>
        <li<?php if ( $this->uri->segment(1) == '' ): ?> class="active" <?php endif; ?>><a href="">Jobwall</a></li>
        <li<?php if ( $this->uri->segment(1) == 'jobfeed' ): ?> class="active" <?php endif; ?>><a href="">Live Job Feed</a></li>
        <li<?php if ( $this->uri->segment(1) == 'tutorials' ): ?> class="active" <?php endif; ?>><a href="">Tutorials</a></li>
        <li<?php if ( $this->uri->segment(1) == 'services' ): ?> class="active" <?php endif; ?>><a href="">Employer Services</a></li>
    </ul>
    <section id="progress"></section>
</nav>
</code>```

based on the uri the li gets an active class, and based on that active a background image moves to show which page is active, however this only works when I use the CSS function jquery link so,

```<code>if($("#mainnav li:eq(0)").hasClass('active'))
{
    $("#progress").css({backgroundPosition: '-883px 0px'})
}

if($("#mainnav li:eq(1)").hasClass('active'))
{
    alert("hello");
    $("#progress").css({backgroundPosition: '-783px 0px'})
}

if($("#mainnav li:eq(2)").hasClass('active'))
{
    $("#progress").css({backgroundPosition: '-702px 0px'})
}

if($("#mainnav li:eq(3)").hasClass('active'))
{
    $("#progress").css({backgroundPosition: '-567px 0px'})
}
</code>```

If I use,

```<code>if($("#mainnav li:eq(0)").hasClass('active'))
{
    $("#progress").animate({backgroundPosition: '-883px 0px'})
}

if($("#mainnav li:eq(1)").hasClass('active'))
{
    alert("hello");
    $("#progress").animate({backgroundPosition: '-783px 0px'})
}

if($("#mainnav li:eq(2)").hasClass('active'))
{
    $("#progress").animate({backgroundPosition: '-702px 0px'})
}

if($("#mainnav li:eq(3)").hasClass('active'))
{
    $("#progress").animate({backgroundPosition: '-567px 0px'})
}
</code>```

then nothing happens and my background-position is 0px 0px why?

答:
background-position isn't built into jQuery's core animate functionality.  You can add it with background-position plugin:

http://plugins.jquery.com/project/backgroundPosition-Effect

Title: jquery help with css() and animate()

Body:
I have this nav system,

        <li<?php if ( $this->uri->segment(1) == '' ): ?> class="active" <?php endif; ?>>Jobwall

        <li<?php if ( $this->uri->segment(1) == 'jobfeed' ): ?> class="active" <?php endif; ?>>Live Job Feed

        <li<?php if ( $this->uri->segment(1) == 'tutorials' ): ?> class="active" <?php endif; ?>>Tutorials

        <li<?php if ( $this->uri->segment(1) == 'services' ): ?> class="active" <?php endif; ?>>Employer Services

based on the uri the li gets an active class, and based on that active a background image moves to show which page is active, however this only works when I use the CSS function jquery link so,

if($("#mainnav li:eq(0)").hasClass('active'))
{
    $("#progress").css({backgroundPosition: '-883px 0px'})
}

if($("#mainnav li:eq(1)").hasClass('active'))
{
    alert("hello");
    $("#progress").css({backgroundPosition: '-783px 0px'})
}

if($("#mainnav li:eq(2)").hasClass('active'))
{
    $("#progress").css({backgroundPosition: '-702px 0px'})
}

if($("#mainnav li:eq(3)").hasClass('active'))
{
    $("#progress").css({backgroundPosition: '-567px 0px'})
}

If I use,

if($("#mainnav li:eq(0)").hasClass('active'))
{
    $("#progress").animate({backgroundPosition: '-883px 0px'})
}

if($("#mainnav li:eq(1)").hasClass('active'))
{
    alert("hello");
    $("#progress").animate({backgroundPosition: '-783px 0px'})
}

if($("#mainnav li:eq(2)").hasClass('active'))
{
    $("#progress").animate({backgroundPosition: '-702px 0px'})
}

if($("#mainnav li:eq(3)").hasClass('active'))
{
    $("#progress").animate({backgroundPosition: '-567px 0px'})
}

then nothing happens and my background-position is 0px 0px why?


问:
How do I convert an audio mp3 file to audio type raw in iOS using Swift?
What is the most effective way to convert an audio mp3 file to audio type raw with the following characteristics in iOS using Swift?</p>

```<code>single-channel (monaural)
little-endian
unheadered
16-bit signed
PCM
sampled at 16000 Hz
</code>```

答:
I don't know this will help or this is what you after.

There is a solution related to this question related to what you after here

I modified the answer for what you after, I'm not expert in this but I try my best

```<code>import AVFoundation

public final class AVAudioFileConverter {

  var rwAudioSerializationQueue: DispatchQueue!
  var asset:AVAsset!
  var assetReader:AVAssetReader!
  var assetReaderAudioOutput:AVAssetReaderTrackOutput!
  var assetWriter:AVAssetWriter!
  var assetWriterAudioInput:AVAssetWriterInput!
  var outputURL:URL
  var inputURL:URL

    public init?(inputFileURL: URL, outputFileURL: URL) {
    inputURL = inputFileURL
    outputURL = outputFileURL

    if (FileManager.default.fileExists(atPath: inputURL.absoluteString)) {
      print("Input file does not exist at file path \(inputURL.absoluteString)")
      return nil
    }
  }

  public func convert() {
    let rwAudioSerializationQueueDescription = " rw audio serialization queue"
    // Create the serialization queue to use for reading and writing the audio data.
    rwAudioSerializationQueue = DispatchQueue(label: rwAudioSerializationQueueDescription)
    assert(rwAudioSerializationQueue != nil, "Failed to initialize Dispatch Queue")

    asset = AVAsset(url: inputURL)
    assert(asset != nil, "Error creating AVAsset from input URL")
    print("Output file path -> ", outputURL.absoluteString)

    asset.loadValuesAsynchronously(forKeys: ["tracks"], completionHandler: {
      var success = true
      var localError:NSError?
      success = (self.asset.statusOfValue(forKey: "tracks", error: &localError) == AVKeyValueStatus.loaded)
      // Check for success of loading the assets tracks.
      if (success) {
        // If the tracks loaded successfully, make sure that no file exists at the output path for the asset writer.
        let fm = FileManager.default
        let localOutputPath = self.outputURL.path
        if (fm.fileExists(atPath: localOutputPath)) {
          do {
            try fm.removeItem(atPath: localOutputPath)
            success = true
          } catch {
            print("Error trying to remove output file at path -> \(localOutputPath)")
          }
        }
      }

      if (success) {
        success = self.setupAssetReaderAndAssetWriter()
      } else {
        print("Failed setting up Asset Reader and Writer")
      }
      if (success) {
        success = self.startAssetReaderAndWriter()
        return
      } else {
        print("Failed to start Asset Reader and Writer")
      }

    })
  }

  func setupAssetReaderAndAssetWriter() -> Bool {
    do {
      assetReader = try AVAssetReader(asset: asset)
    } catch {
      print("Error Creating AVAssetReader")
    }

    do {
      assetWriter = try AVAssetWriter(outputURL: outputURL, fileType: AVFileType.wav)
    } catch {
      print("Error Creating AVAssetWriter")
    }

    var assetAudioTrack:AVAssetTrack? = nil
    let audioTracks = asset.tracks(withMediaType: AVMediaType.audio)

    if (audioTracks.count > 0) {
      assetAudioTrack = audioTracks[0]
    }

    if (assetAudioTrack != nil) {

      let decompressionAudioSettings:[String : Any] = [
        AVFormatIDKey:Int(kAudioFormatLinearPCM)
      ]

      assetReaderAudioOutput = AVAssetReaderTrackOutput(track: assetAudioTrack!, outputSettings: decompressionAudioSettings)
      assert(assetReaderAudioOutput != nil, "Failed to initialize AVAssetReaderTrackOutout")
      assetReader.add(assetReaderAudioOutput)

      var channelLayout = AudioChannelLayout()
      memset(&channelLayout, 0, MemoryLayout<AudioChannelLayout>.size);
      channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;

        let outputSettings:[String : Any] = [
            AVFormatIDKey: Int(kAudioFormatLinearPCM),
            AVSampleRateKey: 44100,
            AVNumberOfChannelsKey: 2,
            AVChannelLayoutKey: NSData(bytes:&channelLayout, length:  MemoryLayout.size(ofValue: AudioChannelLayout.self)),
            AVLinearPCMBitDepthKey: 16,
            AVLinearPCMIsNonInterleaved: false,
            AVLinearPCMIsFloatKey: false,
            AVLinearPCMIsBigEndianKey: false,

        ]

      assetWriterAudioInput = AVAssetWriterInput(mediaType: AVMediaType.audio, outputSettings: outputSettings)
      assert(rwAudioSerializationQueue != nil, "Failed to initialize AVAssetWriterInput")
      assetWriter.add(assetWriterAudioInput)

    }
    print("Finsihed Setup of AVAssetReader and AVAssetWriter")
    return true
  }

  func startAssetReaderAndWriter() -> Bool {
    print("STARTING ASSET WRITER")
    assetWriter.startWriting()
    assetReader.startReading()
    assetWriter.startSession(atSourceTime: CMTime.zero)

    assetWriterAudioInput.requestMediaDataWhenReady(on: rwAudioSerializationQueue, using: {

      while(self.assetWriterAudioInput.isReadyForMoreMediaData ) {
        var sampleBuffer = self.assetReaderAudioOutput.copyNextSampleBuffer()
        if(sampleBuffer != nil) {
          self.assetWriterAudioInput.append(sampleBuffer!)
          sampleBuffer = nil
        } else {
          self.assetWriterAudioInput.markAsFinished()
          self.assetReader.cancelReading()
          self.assetWriter.finishWriting {
            print("Asset Writer Finished Writing")
          }
          break
        }
      }
    })
    return true
  }
}
</code>```

usage

```<code>let inputFilePath = URL(fileURLWithPath: "/path/to/file.mp3")
let outputFileURL = URL(fileURLWithPath: "/path/to/output/output.wav")

if let audioConverter = AVAudioFileConverter(inputFileURL: inputFilePath,
    outputFileURL: outputFileURL) {
    audioConverter.convert()
}
</code>```

Input file info

```<code>File:           /path/12.mp3
File type ID:   MPG3
Num Tracks:     1
----
Data format:     2 ch,  44100 Hz, '.mp3' (0x00000000) 0 bits/channel, 0 bytes/packet, 1152 frames/packet, 0 bytes/frame
                no channel layout.
estimated duration: 1.149375 sec
audio bytes: 18390
audio packets: 44
bit rate: 128000 bits per second
packet size upper bound: 1052
maximum packet size: 418
audio data file offset: 417
optimized
audio 48510 valid frames + 576 priming + 1602 remainder = 50688
</code>```

Output file info

```<code>File type ID:   WAVE
Num Tracks:     1
----
Data format:     2 ch,  44100 Hz, 'lpcm' (0x0000000C) 16-bit little-endian signed integer
                no channel layout.
estimated duration: 1.136327 sec
audio bytes: 200448
audio packets: 50112
bit rate: 1411200 bits per second
packet size upper bound: 4
maximum packet size: 4
audio data file offset: 4096
optimized
source bit depth: I16
</code>```

and this the Info from output file from metadata2go

```<code>File Name: output.wav
File Size: 200 kB
File Type: WAV
File Type Extension: wav
MimeType: audio/x-wav
Encoding: Microsoft PCM
Num Channels: 2
Sample Rate: 44100
Avg Bytes Per Sec: 176400
Bits Per Sample: 16
Duration: 1.16 s
Category: audio
</code>```

If you want to change the settings just change outputSettings this portion

```<code>let outputSettings:[String : Any] = [
    AVFormatIDKey: Int(kAudioFormatLinearPCM),
    AVSampleRateKey: 44100,
    AVNumberOfChannelsKey: 2,
    AVChannelLayoutKey: NSData(bytes:&channelLayout, length:  MemoryLayout.size(ofValue: AudioChannelLayout.self)),
    AVLinearPCMBitDepthKey: 16,
    AVLinearPCMIsNonInterleaved: false,
    AVLinearPCMIsFloatKey: false,
    AVLinearPCMIsBigEndianKey: false,
]
</code>```

I hope this will help.

Body:
What is the most effective way to convert an audio mp3 file to audio type raw with the following characteristics in iOS using Swift?

single-channel (monaural)
little-endian
unheadered
16-bit signed
PCM
sampled at 16000 Hz

Body:
I don't know this will help or this is what you after.

There is a solution related to this question related to what you after here

I modified the answer for what you after, I'm not expert in this but I try my best

import AVFoundation

public final class AVAudioFileConverter {

  var rwAudioSerializationQueue: DispatchQueue!
  var asset:AVAsset!
  var assetReader:AVAssetReader!
  var assetReaderAudioOutput:AVAssetReaderTrackOutput!
  var assetWriter:AVAssetWriter!
  var assetWriterAudioInput:AVAssetWriterInput!
  var outputURL:URL
  var inputURL:URL

    public init?(inputFileURL: URL, outputFileURL: URL) {
    inputURL = inputFileURL
    outputURL = outputFileURL

    if (FileManager.default.fileExists(atPath: inputURL.absoluteString)) {
      print("Input file does not exist at file path \(inputURL.absoluteString)")
      return nil
    }
  }

  public func convert() {
    let rwAudioSerializationQueueDescription = " rw audio serialization queue"
    // Create the serialization queue to use for reading and writing the audio data.
    rwAudioSerializationQueue = DispatchQueue(label: rwAudioSerializationQueueDescription)
    assert(rwAudioSerializationQueue != nil, "Failed to initialize Dispatch Queue")

    asset = AVAsset(url: inputURL)
    assert(asset != nil, "Error creating AVAsset from input URL")
    print("Output file path -> ", outputURL.absoluteString)

    asset.loadValuesAsynchronously(forKeys: ["tracks"], completionHandler: {
      var success = true
      var localError:NSError?
      success = (self.asset.statusOfValue(forKey: "tracks", error: &localError) == AVKeyValueStatus.loaded)
      // Check for success of loading the assets tracks.
      if (success) {
        // If the tracks loaded successfully, make sure that no file exists at the output path for the asset writer.
        let fm = FileManager.default
        let localOutputPath = self.outputURL.path
        if (fm.fileExists(atPath: localOutputPath)) {
          do {
            try fm.removeItem(atPath: localOutputPath)
            success = true
          } catch {
            print("Error trying to remove output file at path -> \(localOutputPath)")
          }
        }
      }

      if (success) {
        success = self.setupAssetReaderAndAssetWriter()
      } else {
        print("Failed setting up Asset Reader and Writer")
      }
      if (success) {
        success = self.startAssetReaderAndWriter()
        return
      } else {
        print("Failed to start Asset Reader and Writer")
      }

    })
  }

  func setupAssetReaderAndAssetWriter() -> Bool {
    do {
      assetReader = try AVAssetReader(asset: asset)
    } catch {
      print("Error Creating AVAssetReader")
    }

    do {
      assetWriter = try AVAssetWriter(outputURL: outputURL, fileType: AVFileType.wav)
    } catch {
      print("Error Creating AVAssetWriter")
    }

    var assetAudioTrack:AVAssetTrack? = nil
    let audioTracks = asset.tracks(withMediaType: AVMediaType.audio)

    if (audioTracks.count > 0) {
      assetAudioTrack = audioTracks[0]
    }

    if (assetAudioTrack != nil) {

      let decompressionAudioSettings:[String : Any] = [
        AVFormatIDKey:Int(kAudioFormatLinearPCM)
      ]

      assetReaderAudioOutput = AVAssetReaderTrackOutput(track: assetAudioTrack!, outputSettings: decompressionAudioSettings)
      assert(assetReaderAudioOutput != nil, "Failed to initialize AVAssetReaderTrackOutout")
      assetReader.add(assetReaderAudioOutput)

      var channelLayout = AudioChannelLayout()
      memset(&channelLayout, 0, MemoryLayout<AudioChannelLayout>.size);
      channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;

        let outputSettings:[String : Any] = [
            AVFormatIDKey: Int(kAudioFormatLinearPCM),
            AVSampleRateKey: 44100,
            AVNumberOfChannelsKey: 2,
            AVChannelLayoutKey: NSData(bytes:&channelLayout, length:  MemoryLayout.size(ofValue: AudioChannelLayout.self)),
            AVLinearPCMBitDepthKey: 16,
            AVLinearPCMIsNonInterleaved: false,
            AVLinearPCMIsFloatKey: false,
            AVLinearPCMIsBigEndianKey: false,

        ]

      assetWriterAudioInput = AVAssetWriterInput(mediaType: AVMediaType.audio, outputSettings: outputSettings)
      assert(rwAudioSerializationQueue != nil, "Failed to initialize AVAssetWriterInput")
      assetWriter.add(assetWriterAudioInput)

    }
    print("Finsihed Setup of AVAssetReader and AVAssetWriter")
    return true
  }

  func startAssetReaderAndWriter() -> Bool {
    print("STARTING ASSET WRITER")
    assetWriter.startWriting()
    assetReader.startReading()
    assetWriter.startSession(atSourceTime: CMTime.zero)

    assetWriterAudioInput.requestMediaDataWhenReady(on: rwAudioSerializationQueue, using: {

      while(self.assetWriterAudioInput.isReadyForMoreMediaData ) {
        var sampleBuffer = self.assetReaderAudioOutput.copyNextSampleBuffer()
        if(sampleBuffer != nil) {
          self.assetWriterAudioInput.append(sampleBuffer!)
          sampleBuffer = nil
        } else {
          self.assetWriterAudioInput.markAsFinished()
          self.assetReader.cancelReading()
          self.assetWriter.finishWriting {
            print("Asset Writer Finished Writing")
          }
          break
        }
      }
    })
    return true
  }
}

usage

let inputFilePath = URL(fileURLWithPath: "/path/to/file.mp3")
let outputFileURL = URL(fileURLWithPath: "/path/to/output/output.wav")

if let audioConverter = AVAudioFileConverter(inputFileURL: inputFilePath,
    outputFileURL: outputFileURL) {
    audioConverter.convert()
}

Input file info

File:           /path/12.mp3
File type ID:   MPG3
Num Tracks:     1
----
Data format:     2 ch,  44100 Hz, '.mp3' (0x00000000) 0 bits/channel, 0 bytes/packet, 1152 frames/packet, 0 bytes/frame
                no channel layout.
estimated duration: 1.149375 sec
audio bytes: 18390
audio packets: 44
bit rate: 128000 bits per second
packet size upper bound: 1052
maximum packet size: 418
audio data file offset: 417
optimized
audio 48510 valid frames + 576 priming + 1602 remainder = 50688

Output file info

File type ID:   WAVE
Num Tracks:     1
----
Data format:     2 ch,  44100 Hz, 'lpcm' (0x0000000C) 16-bit little-endian signed integer
                no channel layout.
estimated duration: 1.136327 sec
audio bytes: 200448
audio packets: 50112
bit rate: 1411200 bits per second
packet size upper bound: 4
maximum packet size: 4
audio data file offset: 4096
optimized
source bit depth: I16

and this the Info from output file from metadata2go

File Name: output.wav
File Size: 200 kB
File Type: WAV
File Type Extension: wav
MimeType: audio/x-wav
Encoding: Microsoft PCM
Num Channels: 2
Sample Rate: 44100
Avg Bytes Per Sec: 176400
Bits Per Sample: 16
Duration: 1.16 s
Category: audio

If you want to change the settings just change outputSettings this portion

let outputSettings:[String : Any] = [
    AVFormatIDKey: Int(kAudioFormatLinearPCM),
    AVSampleRateKey: 44100,
    AVNumberOfChannelsKey: 2,
    AVChannelLayoutKey: NSData(bytes:&channelLayout, length:  MemoryLayout.size(ofValue: AudioChannelLayout.self)),
    AVLinearPCMBitDepthKey: 16,
    AVLinearPCMIsNonInterleaved: false,
    AVLinearPCMIsFloatKey: false,
    AVLinearPCMIsBigEndianKey: false,
]

I hope this will help.


Title: grep specific section or number/word, with R, contained in a text file

Body:
I have a text file that contains a lot of different output sections from a research analysis. the text file looks like this...

Zone  1

Dist.   Time         Amb.   Time         Ster.  Time         Vert.  Vert.        Zone       Zone
Tr.(cm) Amb.         Cnts.  Ster.        Cnts.  Rest.        Cnts.  Time         Entries    Time
======= ============ ====== ============ ====== ============ ====== ============ ========== ============
 626.29 000:00:29.90    480 000:00:05.25     52 000:00:24.85     11 000:00:11.75          1 000:01:00.00
 489.99 000:00:23.20    401 000:00:07.30     75 000:00:29.45      5 000:00:11.65          0 000:01:00.00
-----------------------------------------------------------------------------------------------------

Zone Totals

Dist.   Time         Amb.   Time         Ster.  Time         Vert.  Vert.        Zone       Zone
Tr.(cm) Amb.         Cnts.  Ster.        Cnts.  Rest.        Cnts.  Time         Entries    Time
======= ============ ====== ============ ====== ============ ====== ============ ========== ============
5661.08 000:04:39.30   4360 000:00:55.35    572 000:04:25.35     81 000:02:23.85          1 000:10:00.00
======= ============ ====== ============ ====== ============ ====== ============ ==========
-----------------------------------------------------------------------------------------------------

Block Summary
-------------
Dist.      Time         Amb.   Time         Ster.  Time         Vert.  Vert.        Zone
Trav.(cm)  Amb.         Cnts.  Ster.        Cnts.  Rest.        Cnts.  Time         Entries
========== ============ ====== ============ ====== ============ ====== ============ ==========
    626.29 000:00:29.90    480 000:00:05.25     52 000:00:24.85     11 000:00:11.75          1
    489.99 000:00:23.20    401 000:00:07.30     75 000:00:29.45      5 000:00:11.65          0

How can I grep just the zone total section? More specifically, I would like to grep just the "Dist. Tr." number from the "zone totals" section. But I would be happy with just getting the whole section and then cropping the lines where needed.

I was thinking of something like this...

dist_move = apply(data.frame(grep("Totals",dat)+1, grep("Block",dat)-2),1,function(x) (dat[x[1]:x[2]]))

But it was just grabbing all of the lines

Body:
Assuming the file created in the Note at the end, read it in, find the Zone Totals line and read the first number in the 5th next line.  No packages are used and it works for both single and multiple Zone Total sections.

L <- trimws(readLines("test-file.dat"))
scan(text = sub(" .*", "", L[grep("Zone Totals", L) + 5]), quiet = TRUE)
## [1] 5661.08

or this slightly shorter variation:

L <- readLines("test-file.dat")
read.table(text = L[grep("Zone Totals", L) + 5])[[1]]
## [1] 5661.08

Note

Lines <- "Zone  1

Dist.   Time         Amb.   Time         Ster.  Time         Vert.  Vert.        Zone       Zone
Tr.(cm) Amb.         Cnts.  Ster.        Cnts.  Rest.        Cnts.  Time         Entries    Time
======= ============ ====== ============ ====== ============ ====== ============ ========== ============
 626.29 000:00:29.90    480 000:00:05.25     52 000:00:24.85     11 000:00:11.75          1 000:01:00.00
 489.99 000:00:23.20    401 000:00:07.30     75 000:00:29.45      5 000:00:11.65          0 000:01:00.00
-----------------------------------------------------------------------------------------------------

Zone Totals

Dist.   Time         Amb.   Time         Ster.  Time         Vert.  Vert.        Zone       Zone
Tr.(cm) Amb.         Cnts.  Ster.        Cnts.  Rest.        Cnts.  Time         Entries    Time
======= ============ ====== ============ ====== ============ ====== ============ ========== ============
5661.08 000:04:39.30   4360 000:00:55.35    572 000:04:25.35     81 000:02:23.85          1 000:10:00.00
======= ============ ====== ============ ====== ============ ====== ============ ==========
-----------------------------------------------------------------------------------------------------

Block Summary
-------------
Dist.      Time         Amb.   Time         Ster.  Time         Vert.  Vert.        Zone
Trav.(cm)  Amb.         Cnts.  Ster.        Cnts.  Rest.        Cnts.  Time         Entries
========== ============ ====== ============ ====== ============ ====== ============ ==========
    626.29 000:00:29.90    480 000:00:05.25     52 000:00:24.85     11 000:00:11.75          1
    489.99 000:00:23.20    401 000:00:07.30     75 000:00:29.45      5 000:00:11.65
"
cat(Lines, file = "test-file.dat")


问:
How to pull the key and value of an item with the maximum value out of a python dictionary
The following code creates a dictionary of email addresses and how frequently each email appears.  What is the best way to pull out the key and value for the email with the max frequency?</p>

```<code>fname = input("Enter file:")
try:
    fhand = open(fname)
except:
    print('File cannot be opened:')
    exit()
counts = dict()
for line in fhand:
    if line.startswith('From:'):
         words = line.split(' ', 1)[1]
         words = words.rstrip('\n')

         counts[words] = counts.get(words,0)+1

print(counts)
</code>```

答:
Based on Getting key with maximum value in dictionary?

```<code>import operator
max(counts.iteritems(), key=operator.itemgetter(1))[0]
</code>```

Or you can define two variables

```<code>max_count = 0
frequent = None
</code>```

and append the following to the if clause

```<code>if counts[words] > max_count
    max_count = counts[words]
    frequent = words
</code>```

At the end frequent would contain most frequent email (or None if there is no email in file).

Body:
The following code creates a dictionary of email addresses and how frequently each email appears.  What is the best way to pull out the key and value for the email with the max frequency?

fname = input("Enter file:")
try:
    fhand = open(fname)
except:
    print('File cannot be opened:')
    exit()
counts = dict()
for line in fhand:
    if line.startswith('From:'):
         words = line.split(' ', 1)[1]
         words = words.rstrip('\n')

         counts[words] = counts.get(words,0)+1

print(counts)

Body:
Based on Getting key with maximum value in dictionary?

import operator
max(counts.iteritems(), key=operator.itemgetter(1))[0]

Or you can define two variables

max_count = 0
frequent = None

and append the following to the if clause

if counts[words] > max_count
    max_count = counts[words]
    frequent = words

At the end frequent would contain most frequent email (or None if there is no email in file).


问:
Is there a way to exclude certain elements using the `in` operator?
I was wondering if it was possible to figure out if any
 tags are inside the  or  tags on the page using something like this:

```<code>$("p").each(function() {
  if (!($(this) in $("footer") || $(this) in $("header")) {
    // logic
  }
});
</code>```

My goal is to select the
 tags that are not inside the  or

答:
Firstly, don't use in to enumerate jQuery objects. There are other properties and methods in the object which will interfere.

If you want to find the p elements which are not in a given container you can use filter():

```<code>var $p = $('p').filter(function() {
  return $(this).closest('header, footer').length === 0;
});
</code>```

However a simpler method, if possible in your case, would be to structure your HTML so that all the p elements you want to target are in a common container. Then your code becomes much more straightforward, for example:

Header p

Main p

Footer p

```

<pre class="lang-js prettyprint-override"><code>var $p = $('main p');
</code>```

Body:
I was wondering if it was possible to figure out if any
 tags are inside the  or  tags on the page using something like this:

$("p").each(function() {
  if (!($(this) in $("footer") || $(this) in $("header")) {
    // logic
  }
});

My goal is to select the
 tags that are not inside the  or

Body:
Firstly, don't use in to enumerate jQuery objects. There are other properties and methods in the object which will interfere.

If you want to find the p elements which are not in a given container you can use filter():

var $p = $('p').filter(function() {
  return $(this).closest('header, footer').length === 0;
});

However a simpler method, if possible in your case, would be to structure your HTML so that all the p elements you want to target are in a common container. Then your code becomes much more straightforward, for example:

<header>
   <p>Header p</p>
</header>
<main>
   <p>Main p</p>
</main>
<footer>
   <p>Footer p</p>
</footer>

var $p = $('main p');


问:
Rails Choose 3 different posts randomly
hey everyone so I'm working on a small blog and there is a new section a want to add. An "editor's choice" section so basically i want to add a small div that contains 3 randomly pick posts from the blog. The problem is I do not know how to show only three randomely select titles from all the posts. I tried @posts.sample(3) and that shows the entire record of the Post. I just want to show the title only.
I want to show the editors choice on the posts index view
Schema

```<code>  create_table "posts", force: :cascade do |t|
    t.string "title"
    t.text "content"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.integer "user_id"
    t.string "nickname"
  end
</code>```

Posts_controller

```<code>class PostsController < ApplicationController
  before_action :current, only: [:show, :edit, :update, :destroy]
  def index
    @posts = Post.all
  end

  def show
  end

  def new
    @post = Post.new
  end

  def create
    @post = Post.new(posts_params)
    @post.user = current_user
    if @post.save
      redirect_to posts_path
    else
      render :new
    end
  end

  def edit
  end

  def update
    @post.user = current_user
    @post.update(posts_params)
    @post.save
    redirect_to posts_path
  end

  def destroy
    if @post.destroy
      redirect_to posts_path
    end
  end

  private

  def posts_params
    params.require(:post).permit(:title, :content, :user_id, :image, :nickname)
  end

  def current
    @post = Post.find_by(id: params[:id])
  end

end
</code>```

post_index.html.erb

```<code><%= render "layouts/blog_header" %>
<% @posts.each do |post| %>
  <div class="posts">
    <div>
      <% unless !post.image.attached? %>
        <%= image_tag post.image, class: "post-index-image" %><br>
      <% end %>
    </div>
    <p class="post-index-title"><%= link_to post.title, post_path(post.id), class: "post-index-title" %></p>
    <p>Published by: <strong><%= post.user.nickname %></strong></p>
  </div>
<% end %>
<%= @posts.sample(3) %>
</code>```

Thanks!

答:
I'd go with

@posts.pluck(:title).sample(3)

More efficient than

@posts.sample(3).pluck(:title)

Title: Rails Choose 3 different posts randomly

Body:
hey everyone so I'm working on a small blog and there is a new section a want to add. An "editor's choice" section so basically i want to add a small div that contains 3 randomly pick posts from the blog. The problem is I do not know how to show only three randomely select titles from all the posts. I tried @posts.sample(3) and that shows the entire record of the Post. I just want to show the title only.
I want to show the editors choice on the posts index view
Schema

  create_table "posts", force: :cascade do |t|
    t.string "title"
    t.text "content"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.integer "user_id"
    t.string "nickname"
  end

Posts_controller

class PostsController < ApplicationController
  before_action :current, only: [:show, :edit, :update, :destroy]
  def index
    @posts = Post.all
  end

  def show
  end

  def new
    @post = Post.new
  end

  def create
    @post = Post.new(posts_params)
    @post.user = current_user
    if @post.save
      redirect_to posts_path
    else
      render :new
    end
  end

  def edit
  end

  def update
    @post.user = current_user
    @post.update(posts_params)
    @post.save
    redirect_to posts_path
  end

  def destroy
    if @post.destroy
      redirect_to posts_path
    end
  end

  private

  def posts_params
    params.require(:post).permit(:title, :content, :user_id, :image, :nickname)
  end

  def current
    @post = Post.find_by(id: params[:id])
  end

end

post_index.html.erb

<%= render "layouts/blog_header" %>
<% @posts.each do |post| %>

      <% unless !post.image.attached? %>
        <%= image_tag post.image, class: "post-index-image" %>

      <% end %>

<%= link_to post.title, post_path(post.id), class: "post-index-title" %>

Published by: <%= post.user.nickname %>

<% end %>
<%= @posts.sample(3) %>

Thanks!


问:
Cloning a DOM node list and accessing members are undefined
I have a DOM node list arr1 that is being cloned arr2 and I wonder whether it has been cloned properly as both behave differently. I cannot seem to access the members of arr2 as they return undefined.

Why does this happen, and how can it be fixed?

Note that I tried cloning the same array via arr.slice but this errors with Uncaught TypeError: arr.slice is not a function

Thanks for any help here - the code is below:

var arr = document.querySelectorAll('li');
console.log(arr[1]); // works

var arr2 = [].concat(arr);
console.log(arr2[1]); // undefined, & logs twice```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul></code>```

答:
var arr = Array.from( document.querySelectorAll('li'));
var arr2 = [...arr];
```

Body:
I have a DOM node list arr1 that is being cloned arr2 and I wonder whether it has been cloned properly as both behave differently. I cannot seem to access the members of arr2 as they return undefined.

Why does this happen, and how can it be fixed?

Note that I tried cloning the same array via arr.slice but this errors with Uncaught TypeError: arr.slice is not a function

Thanks for any help here - the code is below:

var arr = document.querySelectorAll('li');
console.log(arr[1]); // works

var arr2 = [].concat(arr);
console.log(arr2[1]); // undefined, & logs twice

test

test

test

test

test


问:
java design problem for validations
I have the following requirement:
I have a validation system.  One of the things that I need to do is perform validations on XML files, meaning validating that tag X equals a given value.  I have more than one possible scenario, and in each scenario there is a different set of tags that need to be validated.

I don't want to repeat same code when testing same tags in different scenarios.

I'm trying to figure out a design that will solve this issue.

Any ideas?

Thanks.

答:
I'd define pairs of XPath expressions and expected results for the scenarios. </p>

<p>The validator then would take a scenario (object), compile and apply the associated  expressions to the xml document. This would select an element and the validator would check, if the element's content matches the expected value. </p>

Title: java design problem for validations

Body:
I'd define pairs of XPath expressions and expected results for the scenarios.

The validator then would take a scenario (object), compile and apply the associated  expressions to the xml document. This would select an element and the validator would check, if the element's content matches the expected value.