问:
Are component events documented?
If so, where?

For example, I'm surprised not to find any mention of onFilled and onEmpty in the doc page for InputBase or perhaps FormControl... not sure where these are coming from but they're not native HTML events.

答:
If it isn't documented, then you should consider it an internal implementation detail of Material-UI.

For instance in InputBase you can find the following:

```<code>  /**
   * @ignore
   */
  onFilled: PropTypes.func,
</code>```

The @ignore means that this is intentionally not documented. This means it is probably only for internal mechanisms for communicating information between components within Material-UI for supporting other documented features. It also means that it would not necessarily be considered a "breaking change" (i.e. it could change without a major version number change) if this property were removed or changed significantly since it is not part of the documented API.

Title: Are component events documented?

Body:
If it isn't documented, then you should consider it an internal implementation detail of Material-UI.

For instance in InputBase you can find the following:

  /**
   * @ignore
   */
  onFilled: PropTypes.func,

The @ignore means that this is intentionally not documented. This means it is probably only for internal mechanisms for communicating information between components within Material-UI for supporting other documented features. It also means that it would not necessarily be considered a "breaking change" (i.e. it could change without a major version number change) if this property were removed or changed significantly since it is not part of the documented API.


来源: stackexchange

问:
How to configure gradle to output total number of tests executed?
While tests are running, the number of tests run so far is ephemerally displayed, but how can I print the total number of tests that were run to the console after all tests have run?

Configuring testLogging doesn't help. I can make gradle output a result for every test, like this:

```<code>testLogging {
    events "passed", "skipped", "failed"
}
</code>```

But I want a summary "bottom line", that outputs the total number of tests that were run, even if they all passed.

答:
Here's my Android solution based on @Hubbitus's answer and this answer

```<code>subprojects {
    afterEvaluate { project ->
        if (project.plugins.findPlugin('android') ?: project.plugins.findPlugin('android-library')) {
            tasks.withType(Test) {
                testLogging {
                    events "started", "passed", "skipped", "failed"

                }
                afterSuite { desc, result ->
                    if (!desc.parent) { // will match the outermost suite
                        println "Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} successes, ${result.failedTestCount} failures, ${result.skippedTestCount} skipped)"
                    }
                }
            }
        }
    }
}
</code>```

Which goes in my root build.gradle

ContentLicense: CC BY-SA 3.0

Body:
While tests are running, the number of tests run so far is ephemerally displayed, but how can I print the total number of tests that were run to the console after all tests have run?

Configuring testLogging doesn't help. I can make gradle output a result for every test, like this:

testLogging {
    events "passed", "skipped", "failed"
}

But I want a summary "bottom line", that outputs the total number of tests that were run, even if they all passed.

Body:
Here's my Android solution based on @Hubbitus's answer and this answer

subprojects {
    afterEvaluate { project ->
        if (project.plugins.findPlugin('android') ?: project.plugins.findPlugin('android-library')) {
            tasks.withType(Test) {
                testLogging {
                    events "started", "passed", "skipped", "failed"

                }
                afterSuite { desc, result ->
                    if (!desc.parent) { // will match the outermost suite
                        println "Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} successes, ${result.failedTestCount} failures, ${result.skippedTestCount} skipped)"
                    }
                }
            }
        }
    }
}

Which goes in my root build.gradle

ContentLicense: CC BY-SA 4.0


问:
query to keep partitions separate when physically separated
I have a table that contains order/shipment history.  A basic dummy version is:

```<code>ORDERS
order_no | order_stat | stat_date
 2       | Planned    |  01-Jan-2000
 2       | Picked     |  15-Jan-2000
 2       | Planned    |  17-Jan-2000
 2       | Planned    |  05-Feb-2000
 2       | Planned    |  31-Mar-2000
 2       | Picked     |  05-Apr-2000
 2       | Shipped    |  10-Apr-2000
</code>```

I need to figure out how long each order has been in each order status/phase.  The only problem is when I create a partition on the order_no and order_stat, I get results that make sense but are not what I am looking for.

My sql:

```<code> select
    order_no
    ,order_stat
    ,stat_date
    ,lag(stat_date, 1) over (partition by order_no order by stat_date) prev_stat_date
    ,stat_date - lag(stat_date, 1) over (partition by order_no order by stat_date) date_diff
    ,row_number() over(partition by order_no, order_stat order by stat_date) rnk
 from
    orders
</code>```

Will give me the following results:

```<code>order_no | order_stat | stat_date     | prev_stat_date  |    rnk
 2       | Planned    |  01-Jan-2000  |                 |  1
 2       | Picked     |  15-Jan-2000  |  01-Jan-2000    |  1
 2       | Planned    |  17-Jan-2000  |  15-Jan-2000    |  2
 2       | Planned    |  05-Feb-2000  |  17-Jan-2000    |  3
 2       | Planned    |  31-Mar-2000  |  05-Feb-2000    |  4
 2       | Picked     |  05-Apr-2000  |  31-Mar-2000    |  2
 2       | Shipped    |  10-Apr-2000  |  05-Apr-2000    |  1
</code>```

I would like to have results that look like this (the rnk starts over when it reverts back to a previous order stat):

```<code>order_no | order_stat | stat_date     | prev_stat_date  |    rnk
 2       | Planned    |  01-Jan-2000  |                 |  1
 2       | Picked     |  15-Jan-2000  |  01-Jan-2000    |  1
 2       | Planned    |  17-Jan-2000  |  15-Jan-2000    |  1
 2       | Planned    |  05-Feb-2000  |  17-Jan-2000    |  2
 2       | Planned    |  31-Mar-2000  |  05-Feb-2000    |  3
 2       | Picked     |  05-Apr-2000  |  31-Mar-2000    |  1
 2       | Shipped    |  10-Apr-2000  |  05-Apr-2000    |  1
</code>```

I'm trying to get a running total count of how long it has been in the status (that starts over even if the status it changes to has existed previously instead of being included in the previous partition) but I have no idea how to approach this.  Any and all insight would be greatly appreciated.

答:
If I understand correctly, this is a gaps-and-islands problem.

The difference of row numbers can be used to identify the "island"s and then to enumerate the values:

```<code>select t.*,
       row_number() over (partition by order_no, order_stat, seqnum - seqnum_2 order by stat_date) as your_rank
from (select o.*,
             row_number() over (partition by order_no order by stat_date) as seqnum,
             row_number() over (partition by order_no, order_stat order by stat_date) as seqnum_2
      from orders o
     ) t;
</code>```

I've left out the other columns (like the lag()) so you can see the logic.  It can be a bit hard to follow why this works.  If you stare at some rows from the subquery, you will probably see how the difference of the row numbers defines the groups you want.

Body:
I have a table that contains order/shipment history.  A basic dummy version is:

ORDERS
order_no | order_stat | stat_date
 2       | Planned    |  01-Jan-2000
 2       | Picked     |  15-Jan-2000
 2       | Planned    |  17-Jan-2000
 2       | Planned    |  05-Feb-2000
 2       | Planned    |  31-Mar-2000
 2       | Picked     |  05-Apr-2000
 2       | Shipped    |  10-Apr-2000

I need to figure out how long each order has been in each order status/phase.  The only problem is when I create a partition on the order_no and order_stat, I get results that make sense but are not what I am looking for.

My sql:

 select
    order_no
    ,order_stat
    ,stat_date
    ,lag(stat_date, 1) over (partition by order_no order by stat_date) prev_stat_date
    ,stat_date - lag(stat_date, 1) over (partition by order_no order by stat_date) date_diff
    ,row_number() over(partition by order_no, order_stat order by stat_date) rnk
 from
    orders

Will give me the following results:

order_no | order_stat | stat_date     | prev_stat_date  |    rnk
 2       | Planned    |  01-Jan-2000  |                 |  1
 2       | Picked     |  15-Jan-2000  |  01-Jan-2000    |  1
 2       | Planned    |  17-Jan-2000  |  15-Jan-2000    |  2
 2       | Planned    |  05-Feb-2000  |  17-Jan-2000    |  3
 2       | Planned    |  31-Mar-2000  |  05-Feb-2000    |  4
 2       | Picked     |  05-Apr-2000  |  31-Mar-2000    |  2
 2       | Shipped    |  10-Apr-2000  |  05-Apr-2000    |  1

I would like to have results that look like this (the rnk starts over when it reverts back to a previous order stat):

order_no | order_stat | stat_date     | prev_stat_date  |    rnk
 2       | Planned    |  01-Jan-2000  |                 |  1
 2       | Picked     |  15-Jan-2000  |  01-Jan-2000    |  1
 2       | Planned    |  17-Jan-2000  |  15-Jan-2000    |  1
 2       | Planned    |  05-Feb-2000  |  17-Jan-2000    |  2
 2       | Planned    |  31-Mar-2000  |  05-Feb-2000    |  3
 2       | Picked     |  05-Apr-2000  |  31-Mar-2000    |  1
 2       | Shipped    |  10-Apr-2000  |  05-Apr-2000    |  1

I'm trying to get a running total count of how long it has been in the status (that starts over even if the status it changes to has existed previously instead of being included in the previous partition) but I have no idea how to approach this.  Any and all insight would be greatly appreciated.

Body:
If I understand correctly, this is a gaps-and-islands problem.

The difference of row numbers can be used to identify the "island"s and then to enumerate the values:

select t.*,
       row_number() over (partition by order_no, order_stat, seqnum - seqnum_2 order by stat_date) as your_rank
from (select o.*,
             row_number() over (partition by order_no order by stat_date) as seqnum,
             row_number() over (partition by order_no, order_stat order by stat_date) as seqnum_2
      from orders o
     ) t;

I've left out the other columns (like the lag()) so you can see the logic.  It can be a bit hard to follow why this works.  If you stare at some rows from the subquery, you will probably see how the difference of the row numbers defines the groups you want.


问:
How to read appSettings from a config file where there are multiple appSettings tag inside multiple location tag?
I am suppose to retrieve the appSettings key to read in a text file. now the problem is in my web.config file , there are multiple location tags and inside them we have multiple appSettings tag.Hence my code is failing to target the location tag appSettings which i actually need.</p>

```<code>  <location path="BidOnline">
    <appSettings/>
    <system.web>
      <authorization>
        <allow users="*"/>
        <!-- Allow all users to the public location -->
      </authorization>
    </system.web>
  </location>
  <location path="Profdev/Public">
    <appSettings/>
    <system.web>
      <authorization>
        <allow users="*"/>
        <!-- Allow all users to the public location -->
      </authorization>
    </system.web>
  </location>

  <location path="Punchout">
    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <clear />
          <add name="X-XSS-Protection" value="0"/>
        </customHeaders>
      </httpProtocol>
    </system.webServer>
  </location>
  <!-- FACTS Service -->
  <location path="Services/Facts">
    <appSettings>
      <!-- Disabeling the security should ONLY be done in test mode. -->
      <add key="DisableSecurity" value="false"/>
      <!--
        The ip addresses listed below are the only address that can
        be used while security is enabled (by default.)  Any other
        ip address attempting to post to the service will not be
        able to.
      -->
      <add key="IPAddresses" value="63.84.95.4;162.40.107.4;207.5.114.131;216.69.96.174"/>
      <!-- Set the ledger that the ar_text_mstr/dtl records will be setup with. -->
      <add key="Ledger" value="GL"/>
    </appSettings>
</code>```

答:
The location tag contains values that override other web.config settings when the path attribute contains the requested page. In most scenarios we don't need to put appSettings inside of it. It's better to put all settings in the top-level appSettings element and only put them in a location element if we need to override them for pages within a particular path.

In this case there is only one appSettings element with values, and it's inside this tag:

```<code><location path="Services/Facts">
    <appSettings>
         <add key="DisableSecurity" value="false"/>
         <!-- other settings -->
    </appSettings>
</location>
</code>```

That means that those settings only "exist" if the requested page is in the /services/facts folder.

If you need an appSettings element that's available to any page, just create one "up a level" in the configuration element:

```<code><configuration>
    <appSettings>
         <add key="YourSetting" value="false"/>
         <!-- other settings -->
    </appSettings>
</configuration>
</code>```

Now it will always be accessible regardless of what page (or other part of the application) you're in.

I don't see this used much with appSettings, although that might just be me. I can see some room for confusion because many developers will assume that if there is a "root" appSettings section, those values will never, ever change while the application is running, and they might store them in a string for some reason (although there's usually no reason to do that.) They might not realize that there are other appSettings inside location tags, and that the first value they read might get reused for other pages in different paths. Or someone could add a location\appSettings later and it wouldn't work.

I guess the conclusion that leads me to is not that location\appSettings is bad, but that we should always make sure we're reading settings on every request and not storing them in a variable that gets reused between requests.

Technically most of the appSettings sections shown in your web.config don't matter, because they're empty.

```<code><appSettings/>
</code>```

Body:
I am suppose to retrieve the appSettings key to read in a text file. now the problem is in my web.config file , there are multiple location tags and inside them we have multiple appSettings tag.Hence my code is failing to target the location tag appSettings which i actually need.

  <location path="BidOnline">
    <appSettings/>
    <system.web>
      <authorization>
        <allow users="*"/>

      </authorization>
    </system.web>
  </location>
  <location path="Profdev/Public">
    <appSettings/>
    <system.web>
      <authorization>
        <allow users="*"/>

      </authorization>
    </system.web>
  </location>

  <location path="Punchout">
    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <clear />
          <add name="X-XSS-Protection" value="0"/>
        </customHeaders>
      </httpProtocol>
    </system.webServer>
  </location>

  <location path="Services/Facts">
    <appSettings>

      <add key="DisableSecurity" value="false"/>

      <add key="IPAddresses" value="63.84.95.4;162.40.107.4;207.5.114.131;216.69.96.174"/>

      <add key="Ledger" value="GL"/>
    </appSettings>

Body:
The location tag contains values that override other web.config settings when the path attribute contains the requested page. In most scenarios we don't need to put appSettings inside of it. It's better to put all settings in the top-level appSettings element and only put them in a location element if we need to override them for pages within a particular path.

In this case there is only one appSettings element with values, and it's inside this tag:

<location path="Services/Facts">
    <appSettings>
         <add key="DisableSecurity" value="false"/>
         <!-- other settings -->
    </appSettings>
</location>

That means that those settings only "exist" if the requested page is in the /services/facts folder.

If you need an appSettings element that's available to any page, just create one "up a level" in the configuration element:

<configuration>
    <appSettings>
         <add key="YourSetting" value="false"/>
         <!-- other settings -->
    </appSettings>
</configuration>

Now it will always be accessible regardless of what page (or other part of the application) you're in.

I don't see this used much with appSettings, although that might just be me. I can see some room for confusion because many developers will assume that if there is a "root" appSettings section, those values will never, ever change while the application is running, and they might store them in a string for some reason (although there's usually no reason to do that.) They might not realize that there are other appSettings inside location tags, and that the first value they read might get reused for other pages in different paths. Or someone could add a location\appSettings later and it wouldn't work.

I guess the conclusion that leads me to is not that location\appSettings is bad, but that we should always make sure we're reading settings on every request and not storing them in a variable that gets reused between requests.

Technically most of the appSettings sections shown in your web.config don't matter, because they're empty.

<appSettings/>


问:
Hibernate: HQL Row Count Subquery issue
I am trying to work with a subquery/sub-select in HQL (Hibernate) but it doesn't work and throws an error...

I wanna know if there is an equivalent in HQL to something like this: ("normal" SQL)

```<code>select count(Z) from (SELECT SUM(existencia), almacen, oficina, fila from re_tinventarioubicacion where inventorybranchto = 2 GROUP BY almacen, oficina, fila, estante, entrepano, casilla, precioetiqueta) as Z
</code>```

I have tried to "translate" it from SQL to HQL, but it doesn't work... it throws this:

org.hibernate.hql.ast.QuerySyntaxException: unexpected token

Basically, I need to get the row count from the resulting subquery.

Any ideas?

答:
You can use native SQL queries with hibernate but you'll need a simple POJO to map the return value to (actually in this case you might try some of the built-in transformers or try setting a Projection, i'm not sure if it would work or not).

POJO return value:

```<code>public class MyCount {
    private Integer count;

    public void setCount(Integer count) {
        this.count = count;
    }

    public Integer getCount() {
        return count;
    }
}
</code>```

Query:

```<code>Query query = getSession().createSQLQuery("select count(*) from dual");
    .addScalar("count")
    .setResultTransformer(Transformers.aliasToBean(MyCount.class));

MyCount count = (MyCount) query.uniqueResult();
</code>```

ContentLicense: CC BY-SA 2.5

Title: Hibernate: HQL Row Count Subquery issue

Body:
I am trying to work with a subquery/sub-select in HQL (Hibernate) but it doesn't work and throws an error...

I wanna know if there is an equivalent in HQL to something like this: ("normal" SQL)

select count(Z) from (SELECT SUM(existencia), almacen, oficina, fila from re_tinventarioubicacion where inventorybranchto = 2 GROUP BY almacen, oficina, fila, estante, entrepano, casilla, precioetiqueta) as Z

I have tried to "translate" it from SQL to HQL, but it doesn't work... it throws this:

org.hibernate.hql.ast.QuerySyntaxException: unexpected token

Basically, I need to get the row count from the resulting subquery.

Any ideas?

Body:
You can use native SQL queries with hibernate but you'll need a simple POJO to map the return value to (actually in this case you might try some of the built-in transformers or try setting a Projection, i'm not sure if it would work or not).

POJO return value:

public class MyCount {
    private Integer count;

    public void setCount(Integer count) {
        this.count = count;
    }

    public Integer getCount() {
        return count;
    }
}

Query:

Query query = getSession().createSQLQuery("select count(*) from dual");
    .addScalar("count")
    .setResultTransformer(Transformers.aliasToBean(MyCount.class));

MyCount count = (MyCount) query.uniqueResult();


问:
cannot find symbol import com.google.firebase.iid.FirebaseInstanceIdService error in ionic3
I Have no idea why I am getting this error whenever I try to create my app's build.I have tried many solutions but  I was unable to solve this.i don't know if any plugins is causing issues or if there's any issue with my Code or firebase or firebase connectivity.I have deleted node modules and run npm install and removed and re-added android platform but still i am getting this error.</p>

```<code>import com.google.firebase.iid.FirebaseInstanceIdService;
                              ^
  symbol:   class FirebaseInstanceIdService
  location: package com.google.firebase.iid
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePluginInstanceIDService.java:9: error: cannot find symbol
public class FirebasePluginInstanceIDService extends FirebaseInstanceIdService {
                                                     ^
  symbol: class FirebaseInstanceIdService
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePlugin.java:508: error: method getByteArray in class FirebaseRemoteConfig cannot be applied to given types;
                            : FirebaseRemoteConfig.getInstance().getByteArray(key, namespace);
                                                                ^
  required: String
  found: String,String
  reason: actual and formal argument lists differ in length
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePlugin.java:525: error: method getValue in class
FirebaseRemoteConfig cannot be applied to given types;
                            : FirebaseRemoteConfig.getInstance().getValue(key, namespace);
                                                                ^
  required: String
  found: String,String
  reason: actual and formal argument lists differ in length
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePlugin.java:579: error: no suitable method found
for setDefaults(Map<String,Object>,String)
                        FirebaseRemoteConfig.getInstance().setDefaults(defaultsToMap(defaults), namespace);
                                                          ^
    method FirebaseRemoteConfig.setDefaults(Map<String,Object>) is not applicable
      (actual and formal argument lists differ in length)
    method FirebaseRemoteConfig.setDefaults(int) is not applicable
      (actual and formal argument lists differ in length)
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePluginInstanceIDService.java:18: error: method does not override or implement a method from a supertype
    @Override
    ^
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\io\card\cordova\sdk\CardIOCordovaPlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
6 errors
:app:compileDebugJavaWithJavac FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
27 actionable tasks: 1 executed, 26 up-to-date
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 54s
cmd: Command failed with exit code 1 Error output:
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePluginInstanceIDService.java:6: error: cannot find symbol
import com.google.firebase.iid.FirebaseInstanceIdService;
                              ^
  symbol:   class FirebaseInstanceIdService
  location: package com.google.firebase.iid
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePluginInstanceIDService.java:9: error: cannot find symbol
public class FirebasePluginInstanceIDService extends FirebaseInstanceIdService {
                                                     ^
  symbol: class FirebaseInstanceIdService
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePlugin.java:508: error: method getByteArray in class FirebaseRemoteConfig cannot be applied to given types;
                            : FirebaseRemoteConfig.getInstance().getByteArray(key, namespace);
                                                                ^
  required: String
  found: String,String
  reason: actual and formal argument lists differ in length
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePlugin.java:525: error: method getValue in class
FirebaseRemoteConfig cannot be applied to given types;
                            : FirebaseRemoteConfig.getInstance().getValue(key, namespace);
                                                                ^
  required: String
  found: String,String
  reason: actual and formal argument lists differ in length
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePlugin.java:579: error: no suitable method found
for setDefaults(Map<String,Object>,String)
                        FirebaseRemoteConfig.getInstance().setDefaults(defaultsToMap(defaults), namespace);
                                                          ^
    method FirebaseRemoteConfig.setDefaults(Map<String,Object>) is not applicable
      (actual and formal argument lists differ in length)
    method FirebaseRemoteConfig.setDefaults(int) is not applicable
      (actual and formal argument lists differ in length)
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePluginInstanceIDService.java:18: error: method does not override or implement a method from a supertype
    @Override
    ^
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\io\card\cordova\sdk\CardIOCordovaPlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
6 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 54s
[ERROR] An error occurred while running subprocess cordova.

        cordova build android exited with exit code 1.
</code>```

答:
This is due to the Firebase updates on April 05. Here https://firebase.google.com/support/release-notes/android#update_-_april_02_2019 96, I found the last working versions and adjusted my project.properties accordingly like so:

```<code>cordova.system.library.4=com.google.firebase:firebase-core:16.0.8

cordova.system.library.5=com.google.firebase:firebase-messaging:17.5.0

cordova.system.library.6=com.google.firebase:firebase-config:16.4.1

cordova.system.library.7=com.google.firebase:firebase-perf:16.2.4
</code>```

Here all dependencies are locked to the specific version (Update - April 02, 2019) instead of +, which would get you the latest version thus breaking the build process.

Now I can build successfully! Hope it helps!

project.properties can be found on platforms/android/project.properties

Body:
I Have no idea why I am getting this error whenever I try to create my app's build.I have tried many solutions but  I was unable to solve this.i don't know if any plugins is causing issues or if there's any issue with my Code or firebase or firebase connectivity.I have deleted node modules and run npm install and removed and re-added android platform but still i am getting this error.

import com.google.firebase.iid.FirebaseInstanceIdService;
                              ^
  symbol:   class FirebaseInstanceIdService
  location: package com.google.firebase.iid
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePluginInstanceIDService.java:9: error: cannot find symbol
public class FirebasePluginInstanceIDService extends FirebaseInstanceIdService {
                                                     ^
  symbol: class FirebaseInstanceIdService
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePlugin.java:508: error: method getByteArray in class FirebaseRemoteConfig cannot be applied to given types;
                            : FirebaseRemoteConfig.getInstance().getByteArray(key, namespace);
                                                                ^
  required: String
  found: String,String
  reason: actual and formal argument lists differ in length
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePlugin.java:525: error: method getValue in class
FirebaseRemoteConfig cannot be applied to given types;
                            : FirebaseRemoteConfig.getInstance().getValue(key, namespace);
                                                                ^
  required: String
  found: String,String
  reason: actual and formal argument lists differ in length
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePlugin.java:579: error: no suitable method found
for setDefaults(Map<String,Object>,String)
                        FirebaseRemoteConfig.getInstance().setDefaults(defaultsToMap(defaults), namespace);
                                                          ^
    method FirebaseRemoteConfig.setDefaults(Map<String,Object>) is not applicable
      (actual and formal argument lists differ in length)
    method FirebaseRemoteConfig.setDefaults(int) is not applicable
      (actual and formal argument lists differ in length)
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePluginInstanceIDService.java:18: error: method does not override or implement a method from a supertype
    @Override
    ^
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\io\card\cordova\sdk\CardIOCordovaPlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
6 errors
:app:compileDebugJavaWithJavac FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
27 actionable tasks: 1 executed, 26 up-to-date
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 54s
cmd: Command failed with exit code 1 Error output:
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePluginInstanceIDService.java:6: error: cannot find symbol
import com.google.firebase.iid.FirebaseInstanceIdService;
                              ^
  symbol:   class FirebaseInstanceIdService
  location: package com.google.firebase.iid
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePluginInstanceIDService.java:9: error: cannot find symbol
public class FirebasePluginInstanceIDService extends FirebaseInstanceIdService {
                                                     ^
  symbol: class FirebaseInstanceIdService
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePlugin.java:508: error: method getByteArray in class FirebaseRemoteConfig cannot be applied to given types;
                            : FirebaseRemoteConfig.getInstance().getByteArray(key, namespace);
                                                                ^
  required: String
  found: String,String
  reason: actual and formal argument lists differ in length
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePlugin.java:525: error: method getValue in class
FirebaseRemoteConfig cannot be applied to given types;
                            : FirebaseRemoteConfig.getInstance().getValue(key, namespace);
                                                                ^
  required: String
  found: String,String
  reason: actual and formal argument lists differ in length
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePlugin.java:579: error: no suitable method found
for setDefaults(Map<String,Object>,String)
                        FirebaseRemoteConfig.getInstance().setDefaults(defaultsToMap(defaults), namespace);
                                                          ^
    method FirebaseRemoteConfig.setDefaults(Map<String,Object>) is not applicable
      (actual and formal argument lists differ in length)
    method FirebaseRemoteConfig.setDefaults(int) is not applicable
      (actual and formal argument lists differ in length)
C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\org\apache\cordova\firebase\FirebasePluginInstanceIDService.java:18: error: method does not override or implement a method from a supertype
    @Override
    ^
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\Users\user\Downloads\mosque\platforms\android\app\src\main\java\io\card\cordova\sdk\CardIOCordovaPlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
6 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 54s
[ERROR] An error occurred while running subprocess cordova.

        cordova build android exited with exit code 1.

Body:
This is due to the Firebase updates on April 05. Here https://firebase.google.com/support/release-notes/android#update_-_april_02_2019 96, I found the last working versions and adjusted my project.properties accordingly like so:

cordova.system.library.4=com.google.firebase:firebase-core:16.0.8

cordova.system.library.5=com.google.firebase:firebase-messaging:17.5.0

cordova.system.library.6=com.google.firebase:firebase-config:16.4.1

cordova.system.library.7=com.google.firebase:firebase-perf:16.2.4

Here all dependencies are locked to the specific version (Update - April 02, 2019) instead of +, which would get you the latest version thus breaking the build process.

Now I can build successfully! Hope it helps!

project.properties can be found on platforms/android/project.properties


问:
ClassLoader.getResource returning null while using File.getAbsolutePath
I have a config.ini file I need to open that is quite far back in directory so I used File.getAbsolutePath() to set the base directory and concatenated the remainder of the path.

Printing the path, I get the correct path that I can paste into file explorer, but the object returned is null.

So I started by initializing my Properties and ClassLoader as such:

```<code>Properties prop = new Properties();
ClassLoader classLoader = Test.class.getClassLoader();
</code>```

Then I create the path. I tried escaping a back slash(1) as well as forward slash(2), both return null but both paths work in file explorer.

```<code>String absPath = new File("").getAbsolutePath();
absPath = absPath.concat("\\resources\\config\\config.ini"); // (1)
absPath = absPath.concat("/resources/config/config.ini"); // (2)
</code>```

then I try to set the URL to open an InputStream

```<code>URL res = Objects.requireNonNull(classLoader.getResource(absPath), "Unable to open config.ini");
InputStream is = new FileInputStream(res.getFile());
</code>```

However, the following returns null.

```<code>classLoader.getResource(absPath)
</code>```

I expected this to properly open the file because the path was correct. I am using Intelij and I read that I needed to add the .ini resource file under settings > compiler, which I did but that did not resolve my issue.

Thank you!

答:
That's not the way to load resources via class-loaders.

If your classpath is something like the following ...

java -cp resources;lib/my.jar ... org.mypack.MyClass

then you load it with this path

```<code>getClassLoader().getResource("/config/config.ini");
</code>```

Your classpath includes the resources folder, and the class-loader loads from there.

The absolute path of the OS is quite certainly not in classpath.

In any case, you must be certain that the resource folder is in classpath.

If your config file is not in classpath then you can't use classloaders to load that file.

Just one more thing, if your configuration is not in classpath, but in a child directory of your working dir, why can't you simply use new FileInputStream("resources/config/config.ini");

Body:
I have a config.ini file I need to open that is quite far back in directory so I used File.getAbsolutePath() to set the base directory and concatenated the remainder of the path.

Printing the path, I get the correct path that I can paste into file explorer, but the object returned is null.

So I started by initializing my Properties and ClassLoader as such:

Properties prop = new Properties();
ClassLoader classLoader = Test.class.getClassLoader();

Then I create the path. I tried escaping a back slash(1) as well as forward slash(2), both return null but both paths work in file explorer.

String absPath = new File("").getAbsolutePath();
absPath = absPath.concat("\\resources\\config\\config.ini"); // (1)
absPath = absPath.concat("/resources/config/config.ini"); // (2)

then I try to set the URL to open an InputStream

URL res = Objects.requireNonNull(classLoader.getResource(absPath), "Unable to open config.ini");
InputStream is = new FileInputStream(res.getFile());

However, the following returns null.

classLoader.getResource(absPath)

I expected this to properly open the file because the path was correct. I am using Intelij and I read that I needed to add the .ini resource file under settings > compiler, which I did but that did not resolve my issue.

Thank you!

Body:
That's not the way to load resources via class-loaders.

If your classpath is something like the following ...

java -cp resources;lib/my.jar ... org.mypack.MyClass

then you load it with this path

getClassLoader().getResource("/config/config.ini");

Your classpath includes the resources folder, and the class-loader loads from there.

The absolute path of the OS is quite certainly not in classpath.

In any case, you must be certain that the resource folder is in classpath.

If your config file is not in classpath then you can't use classloaders to load that file.

Just one more thing, if your configuration is not in classpath, but in a child directory of your working dir, why can't you simply use new FileInputStream("resources/config/config.ini");


问:
Change list to set without changing order of elements
I want to remove those element from list which has repetition more than one it's like set but order should not be change

```<code>[4,6,2,6,1,2] should become [4,6,2,1]
</code>```

I'am looking for any inbuilt method or list comprehension

答:
This should do it: use lambda function and remove duplicates using set. Tested on Python 2.7

```<code>mylist = [4,6,2,6,1,2]
reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, mylist, ([], set()))[0]
</code>```

Body:
I want to remove those element from list which has repetition more than one it's like set but order should not be change

[4,6,2,6,1,2] should become [4,6,2,1]

I'am looking for any inbuilt method or list comprehension

Body:
This should do it: use lambda function and remove duplicates using set. Tested on Python 2.7

mylist = [4,6,2,6,1,2]
reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, mylist, ([], set()))[0]


问:
Merge dataframes with different datetime frequencies without NaNs
I'm trying to merge two dataframes with different datetime frequencies and also filling up missing values with duplicates.

Dataframe df1 with minute frequency:

```<code>    time
0   2017-06-01 00:00:00
1   2017-06-01 00:01:00
2   2017-06-01 00:02:00
3   2017-06-01 00:03:00
4   2017-06-01 00:04:00
</code>```

Dataframe df2 with hourly frequency:

```<code>    time2               temp    hum
1   2017-06-01 00:00:00 13.5    90.0
2   2017-06-01 01:00:00 12.2    95.0
3   2017-06-01 02:00:00 11.7    96.0
4   2017-06-01 03:00:00 11.5    96.0
5   2017-06-01 04:00:00 11.1    97.0
</code>```

So far i merged these dataframe but get NaNs:

```<code>m2o_merge = df1.merge(df2, left_on= 'time', right_on= 'time2', how='outer')
m2o_merge.head()

    time       time2                temp    hum
0   2017-06-01 00:00:00 2017-06-01  13.5    90.0
1   2017-06-01 00:01:00 NaT         NaN     NaN
2   2017-06-01 00:02:00 NaT         NaN     NaN
3   2017-06-01 00:03:00 NaT         NaN     NaN
4   2017-06-01 00:04:00 NaT         NaN     NaN
</code>```

My desired dataframe should look like this (NaN filled up with hourly value df2):

```<code>    time                temp    hum
0   2017-06-01 00:00:00 13.5    90.0
1   2017-06-01 00:01:00 13.5    90.0
2   2017-06-01 00:02:00 13.5    90.0
3   2017-06-01 00:03:00 13.5    90.0
4   2017-06-01 00:04:00 13.5    90.0
...
</code>```

So far i found this solution: merge series/dataframe with different time frequencies in python, but the Datetime column is not my index. Does anyone know how to get there ?

答:
As suggested by Ben Pap i did the following two Steps as a solution:</p>

```<code>import pandas as pd
data1 = {'time':pd.date_range('2017-06-01 00:00:00','2017-06-01 00:09:00', freq='T')}
data2 = {'time2':pd.date_range('2017-06-01 00:00:00','2017-06-01 04:00:00', freq='H'), 'temp':[13.5,12.2,11.7,11.5,11.1], 'hum':[90.0,95.0,96.0,96.0,97.0]}

# Create DataFrame
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)

m2o_merge = df1.merge(df2, left_on= 'time', right_on= 'time2', how='outer')
m2o_merge.head()

m2o_merge.fillna(method='ffill', inplace=True)
filled_df = m2o_merge.drop(['time2'], axis=1)
filled_df.head()
</code>```

Body:
I'm trying to merge two dataframes with different datetime frequencies and also filling up missing values with duplicates.

Dataframe df1 with minute frequency:

    time
0   2017-06-01 00:00:00
1   2017-06-01 00:01:00
2   2017-06-01 00:02:00
3   2017-06-01 00:03:00
4   2017-06-01 00:04:00

Dataframe df2 with hourly frequency:

    time2               temp    hum
1   2017-06-01 00:00:00 13.5    90.0
2   2017-06-01 01:00:00 12.2    95.0
3   2017-06-01 02:00:00 11.7    96.0
4   2017-06-01 03:00:00 11.5    96.0
5   2017-06-01 04:00:00 11.1    97.0

So far i merged these dataframe but get NaNs:

m2o_merge = df1.merge(df2, left_on= 'time', right_on= 'time2', how='outer')
m2o_merge.head()

    time       time2                temp    hum
0   2017-06-01 00:00:00 2017-06-01  13.5    90.0
1   2017-06-01 00:01:00 NaT         NaN     NaN
2   2017-06-01 00:02:00 NaT         NaN     NaN
3   2017-06-01 00:03:00 NaT         NaN     NaN
4   2017-06-01 00:04:00 NaT         NaN     NaN

My desired dataframe should look like this (NaN filled up with hourly value df2):

    time                temp    hum
0   2017-06-01 00:00:00 13.5    90.0
1   2017-06-01 00:01:00 13.5    90.0
2   2017-06-01 00:02:00 13.5    90.0
3   2017-06-01 00:03:00 13.5    90.0
4   2017-06-01 00:04:00 13.5    90.0
...

So far i found this solution: merge series/dataframe with different time frequencies in python, but the Datetime column is not my index. Does anyone know how to get there ?

Body:
As suggested by Ben Pap i did the following two Steps as a solution:

import pandas as pd
data1 = {'time':pd.date_range('2017-06-01 00:00:00','2017-06-01 00:09:00', freq='T')}
data2 = {'time2':pd.date_range('2017-06-01 00:00:00','2017-06-01 04:00:00', freq='H'), 'temp':[13.5,12.2,11.7,11.5,11.1], 'hum':[90.0,95.0,96.0,96.0,97.0]}

# Create DataFrame
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)

m2o_merge = df1.merge(df2, left_on= 'time', right_on= 'time2', how='outer')
m2o_merge.head()

m2o_merge.fillna(method='ffill', inplace=True)
filled_df = m2o_merge.drop(['time2'], axis=1)
filled_df.head()


问:
Google Spreadsheets: How to create an anchor to a row inside the same sheet
is there a way in google spreadsheet to create an anchor text in order to jump from one row to another with a simple click without page reloading?
I'm not able to find a way...
Thank you</p>

答:
This is an old question, but I seem to have found a solution:

Select the Set of Cells you want to link to (Left-click + Drag)

Right-Click the Selected Cells ==> Select "Get link to this range"

The Sheet Link will now be copied to your clipboard and can now be accessed by anybody who has access to the sheet.


问:
How to debounce redux action inside of react component
So I am trying to debounce some actions inside react component.

import React, {Component} from "react";
import debounce from "lodash/debounce";
...

@connect(
  mapStateToProps,
  {someAction}
)
class SomeClass extends Component {
  constructor(props) {
    ...
    this.debouncedAction = debounce(props.someAction, 300);// someAction works ok
  }

  onSomeEvent = (...args) => {
   this.debouncedAction(args); // this does not work
  }
}
```

So the modified debouncedAction is not called. Is there a way to do that without creating extra action in mapStateToProps?
I need to keep both because one for filtering second(debounced) for search.

答:
It's definitely possible to debounce the event handler, which then uses the action.

```<code>class SomeClass extends Component {

  // Debounce the event handler here instead
  onSomeEvent = debounce((...args) => {
    const { someAction } = this.props;
    someAction(...args);
  }, 300)

  // ...
}
</code>```

It also ensures that each time the event callback is executed, it uses the current prop value, so it's always up to date.

Body:
So I am trying to debounce some actions inside react component.

import React, {Component} from "react";
import debounce from "lodash/debounce";
...

@connect(
  mapStateToProps,
  {someAction}
)
class SomeClass extends Component {
  constructor(props) {
    ...
    this.debouncedAction = debounce(props.someAction, 300);// someAction works ok
  }

  onSomeEvent = (...args) => {
   this.debouncedAction(args); // this does not work
  }
}

So the modified debouncedAction is not called. Is there a way to do that without creating extra action in mapStateToProps?
I need to keep both because one for filtering second(debounced) for search.

Body:
It's definitely possible to debounce the event handler, which then uses the action.

class SomeClass extends Component {

  // Debounce the event handler here instead
  onSomeEvent = debounce((...args) => {
    const { someAction } = this.props;
    someAction(...args);
  }, 300)

  // ...
}

It also ensures that each time the event callback is executed, it uses the current prop value, so it's always up to date.


问:
How to return an input within a def function with python
I'm new to python and defining functions!

I'm writing a code and, on it, I'll sometimes ask the same question, this is why I want to use a function for it. I'm trying like this:

```<code>def cont():
  ans = input("Continue? ")
  return ans
</code>```

But it's not storing anything on ans, cause every time I call it, I get an error saying that ans has not been declared!

Could anybody help me?

答:
Your ans is only defined inside the scope of your cont() function, you cannot access it directly from outside that function.  You are most of the way to sending this ans back out to the rest of your code with return ans, now you just need to store that value in something you can access from the rest of your code.  Here is a sample code where I saved the output of cont() in the variable check in each pass of a while loop.

```<code>def cont():
    ans = input("Continue? ")
    return ans

gonna_continue = True

while gonna_continue:
    check = cont()
    if check == "no":
        gonna_continue = False
print("All Done")
</code>```

SAMPLE OUTPUT

```<code>Continue? 1
Continue? 2
Continue? 5
Continue? sbdj2
Continue? no
All Done
</code>```

Body:
I'm new to python and defining functions!

I'm writing a code and, on it, I'll sometimes ask the same question, this is why I want to use a function for it. I'm trying like this:

def cont():
  ans = input("Continue? ")
  return ans

But it's not storing anything on ans, cause every time I call it, I get an error saying that ans has not been declared!

Could anybody help me?

Body:
Your ans is only defined inside the scope of your cont() function, you cannot access it directly from outside that function.  You are most of the way to sending this ans back out to the rest of your code with return ans, now you just need to store that value in something you can access from the rest of your code.  Here is a sample code where I saved the output of cont() in the variable check in each pass of a while loop.

def cont():
    ans = input("Continue? ")
    return ans

gonna_continue = True

while gonna_continue:
    check = cont()
    if check == "no":
        gonna_continue = False
print("All Done")

SAMPLE OUTPUT

Continue? 1
Continue? 2
Continue? 5
Continue? sbdj2
Continue? no
All Done


问:
How use reduce() to concat an array and delete the items duplicated
I have a problem using the reduce function in JavaScript. My goal is to take an array of arrays and, using reduce, then concat all the values and delete the duplicates:

I have an array like this:
firstArray = [[1, 2],[2, 3, 4],[4, 5, 6]]

I need an array like this after apply reduce():
resultArray = [1, 2, 3, 4, 5, 6]

```<code>const arrayElements = [[1,2],[2,3,4],[5,6]];
const newArray = arrayElements.reduce((total, value) => {
    return total.concat(value);
}, []);
</code>```

This is the fragment that I have, this only concat all the values, this is to say, [1, 2, 2, 3, 4, 5, 6]

答:
Your reduce is correct, just add the data to a set, and convert the set to an array using spread syntax ...

const arrayElements = [[1,2],[2,3,4],[5,6]];
const newArray = [...new Set(arrayElements.reduce((total, value) => total.concat(value), []))];

console.log(newArray)```

Body:
I have a problem using the reduce function in JavaScript. My goal is to take an array of arrays and, using reduce, then concat all the values and delete the duplicates:

I have an array like this:
firstArray = [[1, 2],[2, 3, 4],[4, 5, 6]]

I need an array like this after apply reduce():
resultArray = [1, 2, 3, 4, 5, 6]

const arrayElements = [[1,2],[2,3,4],[5,6]];
const newArray = arrayElements.reduce((total, value) => {
    return total.concat(value);
}, []);

This is the fragment that I have, this only concat all the values, this is to say, [1, 2, 2, 3, 4, 5, 6]


问:
Can I use an pointer to "error" to catch the return error?
I am writing some transaction begin/commit/rollback functions, and I want to pair the block to prevent forgot commit

I write like this:

func (foo *Foo) Bar() (err error) {

  foo.Begin()
  defer foo.End(&err)

  //some business code

  return
}

func (foo *Foo) End(eptr *error) {
  // if recover
  if r := recover(); r != nil {
    debug.PrintStack()
    *eptr = r.(error)
  }

  var err = *eptr
  if err != nil {
    foo.Rollback()
  } else {
    foo.Commit()
  }
}

```

<p>It works, but it uses the "pointer to interface", I cannot find the specifications about pointer to interface.</p>

<p>So, I am not sure this code is OK enough. Could you give some suggestions?</p>

<hr>

<p>thanks to teyzer and Corey Ogburn, this is my fixed solution:</p>

<pre class="lang-golang prettyprint-override"><code>
func (foo *Foo) Bar() (err error) {

  foo.Begin()
  defer func() { foo.End(err) }()
  defer func() {
   if r := recover(); r != nil {
      debug.PrintStack()
      err = makeError(r)
   }
  } ()

  //some business code

  return
}

func (foo *Foo) End(err error) {
  if err != nil {
    foo.Rollback()
  } else {
    foo.Commit()
  }
}

</code>```

答:
The usual approach is to use recover() to catch any panics. What you have is very similar to that approach. Check out the Go wiki about Panic and Recover

```<code>func (foo *Foo) Bar() (err error) {

  foo.Begin()
  defer foo.End()

  //some business code
  err = fmt.Errorf("oh no, an error!") // set error so that Bar returns it even though it's caught
  panic(err)

  return
}

func (foo *Foo) End() {
  err := recover()
  if err != nil {
    foo.Rollback()
  } else {
    foo.Commit()
  }
}
</code>```

https://play.golang.org/p/m_kpT5xtwe2

Body:
I am writing some transaction begin/commit/rollback functions, and I want to pair the block to prevent forgot commit

I write like this:

func (foo *Foo) Bar() (err error) {

  foo.Begin()
  defer foo.End(&err)

  //some business code

  return
}

func (foo *Foo) End(eptr *error) {
  // if recover
  if r := recover(); r != nil {
    debug.PrintStack()
    *eptr = r.(error)
  }

  var err = *eptr
  if err != nil {
    foo.Rollback()
  } else {
    foo.Commit()
  }
}

It works, but it uses the "pointer to interface", I cannot find the specifications about pointer to interface.

So, I am not sure this code is OK enough. Could you give some suggestions?

thanks to teyzer and Corey Ogburn, this is my fixed solution:

func (foo *Foo) Bar() (err error) {

  foo.Begin()
  defer func() { foo.End(err) }()
  defer func() {
   if r := recover(); r != nil {
      debug.PrintStack()
      err = makeError(r)
   }
  } ()

  //some business code

  return
}

func (foo *Foo) End(err error) {
  if err != nil {
    foo.Rollback()
  } else {
    foo.Commit()
  }
}

Body:
The usual approach is to use recover() to catch any panics. What you have is very similar to that approach. Check out the Go wiki about Panic and Recover

func (foo *Foo) Bar() (err error) {

  foo.Begin()
  defer foo.End()

  //some business code
  err = fmt.Errorf("oh no, an error!") // set error so that Bar returns it even though it's caught
  panic(err)

  return
}

func (foo *Foo) End() {
  err := recover()
  if err != nil {
    foo.Rollback()
  } else {
    foo.Commit()
  }
}

https://play.golang.org/p/m_kpT5xtwe2


问:
How can I set a string value to the date value in a ContentControl DatePicker in MS-Word using VBA
I have an MS-Word document template that has an existing DatePicker Contentcontrol QuickPart imported from a SharePoint list.

I want to either:

Assign the value of the DatePicker date to a Date variable, - or-

Set a string variable to the string value of the date in the DatePicker

I can then use that data to calculate and place future dates in my document based on the date read from the DatePicker value.

I have researched numerous sites using keywords date picker, content control, VBA, Word. No examples come close to what I am trying to do.

```<code>Sub AddDates()
'
' AddDates Macro
    Dim PODate As Date
    Dim strDate As String
    Set doc = ActiveDocument
    Set ccs = doc.SelectContentControlsByTag("wqgr")
    Set strDate = ccs.ContentControl.Range.Text
    Set PODate = CDate(strDate)
    Selection.GoTo What:=wdGoToBookmark, Name:="Date1"
    Selection.TypeText Text:=Format(PODate + 7, "mm/dd/yyyy")
End Sub
</code>```

Compile error: Object required, highlighting the "strDate = " in the code.

答:
Your routine has a number of issues. The variables doc and ccs are not declared. You are also trying to "Set" strDate but strDate is a string variable and "Set" statements are only used for object variables. The same is true for PODate, you do not use a Set command to load a Date.

Below is revised code for you to review:

```<code>Sub AddDates()
'
' AddDates Macro
    Dim PODate As Date
    Dim strDate As String
    Dim doc As Word.Document
    Dim ccs As Word.contentControl

    Set doc = ActiveDocument
    Set ccs = doc.SelectContentControlsByTag("wqgr").Item(1)
    strDate = ccs.Range.Text
    PODate = CDate(strDate)
    Selection.GoTo What:=wdGoToBookmark, Name:="Date1"
    Selection.TypeText Text:=Format(PODate + 7, "mm/dd/yyyy")
End Sub
</code>```

Body:
I have an MS-Word document template that has an existing DatePicker Contentcontrol QuickPart imported from a SharePoint list.

I want to either:

Assign the value of the DatePicker date to a Date variable, - or-

Set a string variable to the string value of the date in the DatePicker

I can then use that data to calculate and place future dates in my document based on the date read from the DatePicker value.

I have researched numerous sites using keywords date picker, content control, VBA, Word. No examples come close to what I am trying to do.

Sub AddDates()
'
' AddDates Macro
    Dim PODate As Date
    Dim strDate As String
    Set doc = ActiveDocument
    Set ccs = doc.SelectContentControlsByTag("wqgr")
    Set strDate = ccs.ContentControl.Range.Text
    Set PODate = CDate(strDate)
    Selection.GoTo What:=wdGoToBookmark, Name:="Date1"
    Selection.TypeText Text:=Format(PODate + 7, "mm/dd/yyyy")
End Sub

Compile error: Object required, highlighting the "strDate = " in the code.

Body:
Your routine has a number of issues. The variables doc and ccs are not declared. You are also trying to "Set" strDate but strDate is a string variable and "Set" statements are only used for object variables. The same is true for PODate, you do not use a Set command to load a Date.

Below is revised code for you to review:

Sub AddDates()
'
' AddDates Macro
    Dim PODate As Date
    Dim strDate As String
    Dim doc As Word.Document
    Dim ccs As Word.contentControl

    Set doc = ActiveDocument
    Set ccs = doc.SelectContentControlsByTag("wqgr").Item(1)
    strDate = ccs.Range.Text
    PODate = CDate(strDate)
    Selection.GoTo What:=wdGoToBookmark, Name:="Date1"
    Selection.TypeText Text:=Format(PODate + 7, "mm/dd/yyyy")
End Sub


问:
How to query a json column for empty objects?
Looking to find all rows where a certain json column contains an empty object, {}. This is possible with JSON arrays, or if I am looking for a specific key in the object. But I just want to know if the object is empty. Can't seem to find an operator that will do this.

```<code> dev=# \d test
     Table "public.test"
  Column | Type | Modifiers
 --------+------+-----------
  foo    | json |

 dev=# select * from test;
    foo
 ---------
  {"a":1}
  {"b":1}
  {}
 (3 rows)

 dev=# select * from test where foo != '{}';
 ERROR:  operator does not exist: json <> unknown
 LINE 1: select * from test where foo != '{}';
                                      ^
 HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
 dev=# select * from test where foo != to_json('{}'::text);
 ERROR:  operator does not exist: json <> json
 LINE 1: select * from test where foo != to_json('{}'::text);
                                      ^
 HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
 dwv=# select * from test where foo != '{}'::json;
 ERROR:  operator does not exist: json <> json
 LINE 1: select * from test where foo != '{}'::json;
                                      ^
 HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
</code>```

答:
Empty JSON array [] could also be relevant.

Then this could work for both [] and {}:

```<code>select * from test where length(foo::text) > 2 ;
</code>```

Body:
Looking to find all rows where a certain json column contains an empty object, {}. This is possible with JSON arrays, or if I am looking for a specific key in the object. But I just want to know if the object is empty. Can't seem to find an operator that will do this.

 dev=# \d test
     Table "public.test"
  Column | Type | Modifiers
 --------+------+-----------
  foo    | json |

 dev=# select * from test;
    foo
 ---------
  {"a":1}
  {"b":1}
  {}
 (3 rows)

 dev=# select * from test where foo != '{}';
 ERROR:  operator does not exist: json <> unknown
 LINE 1: select * from test where foo != '{}';
                                      ^
 HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
 dev=# select * from test where foo != to_json('{}'::text);
 ERROR:  operator does not exist: json <> json
 LINE 1: select * from test where foo != to_json('{}'::text);
                                      ^
 HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
 dwv=# select * from test where foo != '{}'::json;
 ERROR:  operator does not exist: json <> json
 LINE 1: select * from test where foo != '{}'::json;
                                      ^
 HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

Body:
Empty JSON array [] could also be relevant.

Then this could work for both [] and {}:

select * from test where length(foo::text) > 2 ;


问:
MaterialApp must it be only one in the whole application?
I have an interesting question. Seeing Flutter's MaterialApp class, you will find congruences with an activity on the entire application that we are going to build for Flutter. But my doubt is this. Do I have to enter N MaterialApp for each section where I can't go back? Or is it thought to be unique?</p>

答:
The internal design of MaterialApp indicates that it is designed to be used only once in the application. It has fields like localizationsDelegate,theme, and routes, which will be bad design if it used more than once , because most of these field will resort to default values causing a significant memory waste.

If you just want to use it to prevent navigating back to other screens or "sections", there are plenty of options provided by flutter like Navigator and WillPopScope.


问:
Angular Service for particular NgModule
I'm following the Angular Documentation and trying to provide a service (OrderService) to a particular module (OrdersModule). After importing the service to a component (OrderListComponent), I'm getting an error. Could somebody tell me, what I'm doing wrong here?

Here is a link to my stackblitz code.

order.service.ts

```<code>import { Injectable } from '@angular/core';
import { OrdersModule } from './orders.module';

@Injectable({
  providedIn: OrdersModule
})
export class OrderService {
  constructor() {
  }

  ...
}
</code>```

order-list.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { OrderService } from '../order.service';

@Component({
  selector: 'order-list',
  templateUrl: './order-list.component.html',
  styleUrls: [ './order-list.component.css' ]
})
export class OrderListComponent implements OnInit {
  ...

  constructor(private orderService: OrderService) {
    ...
  }

  ...
}
</code>```

I'm getting following error:

```<code>Error: Uncaught (in promise):
Error: StaticInjectorError(AppModule)[OrderListComponent -> OrderService]:
StaticInjectorError(Platform: core)[OrderListComponent -> OrderService]:
NullInjectorError: No provider for OrderService!
</code>```

答:
Most of the time, use providedIn = 'root' inside your service. It will
register the
service with the root application injector, will be tree shaken, and
will be available to any component that needs it. The tree shaking
will ensure the service is only included in the bundles where it is
used.

Use the providers array in a component if the service only needs to
be provided in the component and its nested children.

It's not advised to use providers array in a module.

Use providedIn='OrdersModule' if you want to
limit access to a service to a particular lazy loaded module(OrdersModule). It
will then require an additional module to prevent the circular
dependency issue.

This provides service isolation at the module
level. If any other component in the application outside of this
lazy loaded module attempts to reference the service an "out of
injector scope" error is generated.

Refer to this answer

Title: Angular Service for particular NgModule

Body:
I'm following the Angular Documentation and trying to provide a service (OrderService) to a particular module (OrdersModule). After importing the service to a component (OrderListComponent), I'm getting an error. Could somebody tell me, what I'm doing wrong here?

Here is a link to my stackblitz code.

order.service.ts

import { Injectable } from '@angular/core';
import { OrdersModule } from './orders.module';

@Injectable({
  providedIn: OrdersModule
})
export class OrderService {
  constructor() {
  }

  ...
}

order-list.component.ts

import { Component, OnInit } from '@angular/core';
import { OrderService } from '../order.service';

@Component({
  selector: 'order-list',
  templateUrl: './order-list.component.html',
  styleUrls: [ './order-list.component.css' ]
})
export class OrderListComponent implements OnInit {
  ...

  constructor(private orderService: OrderService) {
    ...
  }

  ...
}

I'm getting following error:

Error: Uncaught (in promise):
Error: StaticInjectorError(AppModule)[OrderListComponent -> OrderService]:
StaticInjectorError(Platform: core)[OrderListComponent -> OrderService]:
NullInjectorError: No provider for OrderService!


问:
Corda transfer of Linear State, collecting signatures
I've implemented several commands, where the notary signature fulfils the use case. There are 2 cases though where I have open questions:

I have an owner field that changes from input/output state, all fine, but I want the new owner to sign off on it, e.g. I need a mechanism to retrieve the state via the vault (last unconsumed?), I guess I need to authenticate and filter on the participants and make the new owner sign it, e.g. "press a button", how would I do that?

How do I finalize a linear state, e.g. that it cannot take part in any form of transaction/command thereafter?

```<code>@InitiatingFlow
@StartableByRPC
class DeviceFlow(private val deviceState: DeviceState,
                 private val stateAndRef: Optional<StateAndRef<DeviceState>>,
                 private val command: DeviceContract.Commands)
    : FlowLogic<SignedTransaction>() {
    override val progressTracker = tracker()

    companion object {
        object GENERATING_TRANSACTION : Step("Generating transaction based on new IOU.")
        object VERIFYING_TRANSACTION : Step("Verifying contract constraints.")
        object SIGNING_TRANSACTION : Step("Signing transaction with our private key.")
        object GATHERING_SIGS : Step("Gathering the counterparty's signature.") {
            override fun childProgressTracker() = CollectSignaturesFlow.tracker()
        }

        object FINALISING_TRANSACTION : Step("Obtaining notary signature and recording transaction.") {
            override fun childProgressTracker() = FinalityFlow.tracker()
        }

        fun tracker() = ProgressTracker(
                GENERATING_TRANSACTION,
                VERIFYING_TRANSACTION,
                SIGNING_TRANSACTION,
                GATHERING_SIGS,
                FINALISING_TRANSACTION
        )
    }

    @Suspendable
    override fun call(): SignedTransaction {
        progressTracker.currentStep = GENERATING_TRANSACTION
        val notary = serviceHub.networkMapCache.getNotary(CordaX500Name("Notary", "London", "GB"))
        val transactionBuilder = TransactionBuilder(notary = notary)
                .addCommand(command, deviceState.participants.map { it.owningKey })
                .addOutputState(deviceState, DeviceContract.ID)
        if (stateAndRef.isPresent)
            transactionBuilder.addInputState(stateAndRef.get())
        progressTracker.currentStep = VERIFYING_TRANSACTION
        transactionBuilder.verify(serviceHub)
        progressTracker.currentStep = SIGNING_TRANSACTION
        val signedTransaction = serviceHub.signInitialTransaction(transactionBuilder)
        val otherPartySession = initiateFlow(notary!!)
        val fullySignedTx = subFlow(
                CollectSignaturesFlow(signedTransaction, setOf(otherPartySession), GATHERING_SIGS.childProgressTracker()))
        progressTracker.currentStep = FINALISING_TRANSACTION
        return subFlow(FinalityFlow(fullySignedTx, setOf(otherPartySession), FINALISING_TRANSACTION.childProgressTracker()))
    }
}

@InitiatedBy(DeviceFlow::class)
class DeviceCreateFlowResponder(val flowSession: FlowSession) : FlowLogic<SignedTransaction>() {
    @Suspendable
    override fun call(): SignedTransaction {
        val signTransactionFlow = object : SignTransactionFlow(flowSession) {
            override fun checkTransaction(stx: SignedTransaction) = requireThat {
                val output = stx.tx.outputs.single().data
                "This must be a Device transaction." using (output is DeviceState)
            }
        }
        val txId = subFlow(signTransactionFlow).id
        return subFlow(ReceiveFinalityFlow(flowSession, expectedTxId = txId))
    }
}
</code>```

答:
New owner sign off

You would retrieve the latest version of the state from the vault. The latest version should be unconsumed.

Create a TransactionBuilder and add this state as input.

Create a replica of this state, but change the owner property to reflect the new owner. Add this as an output to the TransactionBuilder.

Ensure your contract rules governing the state enforce that the previous owner and new owner are both required signers.

Finalising a linear (or any state)

You could add a property to the state and have your contract enforce that the state can no longer evolve once this property has been set.

You can consume the state by adding it to a transaction as an input and not adding an output. (Again, your contact would have to allow this)

Body:
I've implemented several commands, where the notary signature fulfils the use case. There are 2 cases though where I have open questions:

I have an owner field that changes from input/output state, all fine, but I want the new owner to sign off on it, e.g. I need a mechanism to retrieve the state via the vault (last unconsumed?), I guess I need to authenticate and filter on the participants and make the new owner sign it, e.g. "press a button", how would I do that?

How do I finalize a linear state, e.g. that it cannot take part in any form of transaction/command thereafter?

@InitiatingFlow
@StartableByRPC
class DeviceFlow(private val deviceState: DeviceState,
                 private val stateAndRef: Optional<StateAndRef<DeviceState>>,
                 private val command: DeviceContract.Commands)
    : FlowLogic<SignedTransaction>() {
    override val progressTracker = tracker()

    companion object {
        object GENERATING_TRANSACTION : Step("Generating transaction based on new IOU.")
        object VERIFYING_TRANSACTION : Step("Verifying contract constraints.")
        object SIGNING_TRANSACTION : Step("Signing transaction with our private key.")
        object GATHERING_SIGS : Step("Gathering the counterparty's signature.") {
            override fun childProgressTracker() = CollectSignaturesFlow.tracker()
        }

        object FINALISING_TRANSACTION : Step("Obtaining notary signature and recording transaction.") {
            override fun childProgressTracker() = FinalityFlow.tracker()
        }

        fun tracker() = ProgressTracker(
                GENERATING_TRANSACTION,
                VERIFYING_TRANSACTION,
                SIGNING_TRANSACTION,
                GATHERING_SIGS,
                FINALISING_TRANSACTION
        )
    }

    @Suspendable
    override fun call(): SignedTransaction {
        progressTracker.currentStep = GENERATING_TRANSACTION
        val notary = serviceHub.networkMapCache.getNotary(CordaX500Name("Notary", "London", "GB"))
        val transactionBuilder = TransactionBuilder(notary = notary)
                .addCommand(command, deviceState.participants.map { it.owningKey })
                .addOutputState(deviceState, DeviceContract.ID)
        if (stateAndRef.isPresent)
            transactionBuilder.addInputState(stateAndRef.get())
        progressTracker.currentStep = VERIFYING_TRANSACTION
        transactionBuilder.verify(serviceHub)
        progressTracker.currentStep = SIGNING_TRANSACTION
        val signedTransaction = serviceHub.signInitialTransaction(transactionBuilder)
        val otherPartySession = initiateFlow(notary!!)
        val fullySignedTx = subFlow(
                CollectSignaturesFlow(signedTransaction, setOf(otherPartySession), GATHERING_SIGS.childProgressTracker()))
        progressTracker.currentStep = FINALISING_TRANSACTION
        return subFlow(FinalityFlow(fullySignedTx, setOf(otherPartySession), FINALISING_TRANSACTION.childProgressTracker()))
    }
}

@InitiatedBy(DeviceFlow::class)
class DeviceCreateFlowResponder(val flowSession: FlowSession) : FlowLogic<SignedTransaction>() {
    @Suspendable
    override fun call(): SignedTransaction {
        val signTransactionFlow = object : SignTransactionFlow(flowSession) {
            override fun checkTransaction(stx: SignedTransaction) = requireThat {
                val output = stx.tx.outputs.single().data
                "This must be a Device transaction." using (output is DeviceState)
            }
        }
        val txId = subFlow(signTransactionFlow).id
        return subFlow(ReceiveFinalityFlow(flowSession, expectedTxId = txId))
    }
}


问:
Best way to retire an index
I am retiring an old elastic search index in AWS that has not received a new document since 2016. However, something is still trying to search it.

I still want deprecate this index in a manner manner where I can get back to the original state quickly.  I have created a manual snapshot of the index and it is sitting in S3.  I was planning on deleting the domain, but, from what I understand, that deletes everything billable under AWS including the end point.  As I mentioned above, I want to be able to get back to the original state of the index.  So this domain contains a series of indexes. The largest index is 20.5 Gb.  I was going to delete the large index and resize the cluster to a smaller instance size and footprint.  Will this work or will it be unsearchable?

答:
TL;DR -> yes!

The backup to S3 will work, but the documents will be unsearchable because in order to downsize the storage you have to delete the index.
But if someday you want to restore the data from S3 back to the index, you can.

You can resize instances and storage sizes with no downtime, however, that takes a long time and you pay extra for the machines while they are resizing.
Example:
you change your storage size from 100gb to 99gb

elasticsearch service will spin up another instance, copy all your data from the old instance to the new one and then delete the old one.

same for instance sizes.

machine up, cluster sync, machine down.

while they are syncing, you pay for them.

your plan will work, es is very flexible.
if you really don't trust aws, just make a json export from the index and keep it on s3 too, just in case things go south.

Title: Best way to retire an index


问:
.xcdatamodel: cdtool cannot compile
This problem occurred right after the last update of OS X El Capitan 10.11 beta 6, Xcode 7 beta 4 compiles my projects with the error in .xcdatamodel file saying:
cdtool cannot compile.
I tried to compile the same projects on OS X Yosemite and with Xcode 7.0 beta 4 I get always the same compilation error.
Any idea on how to clear this issue?
I'd appreciate any help.

答:
In my case, I got this error because of wrongly configured Constraints for properties. I'm not sure about what was wrong, but remove and re-add the constraints, the error disappear.

Obs: When i say constraints for properties, i'm telling about this:

Title: .xcdatamodel: cdtool cannot compile


问:
How to delegate back to the previous veiwcontroller
here is my navigation on my app

1) homescreenview controller-->composemessageviewcontroller (i am able to use delegate to send data back to homescreenview)

2)homescreenview controller -->messageslistcontroller(tableview)-->detailmessageviewcontroller(which is where my reply button is).

my problem is when i hit reply i want to send back information to homescreenviewcontroller with delegate . how can i do this?

Thanks in advance.

----UPDATE

@XJones, thanks for the detailed explanaion. is this what is should be doing in when i push detailview? please correct me if i am wrong.

(void)pushDetailMessageController{
DetailMessagetController *detailmessage = [[DetailMessagetController alloc] init];
detailmessage.delegate = self;
// push messageListController onto navigation controller here
[detail release];
}

答:
One approach (without delegation)

as you are using navigationController, so
[[self.navigationController viewControllers]objectAtIndex:0] will always return you homeScreenViewController.....you can use this object....

Thanks,


问:
How to count no of rows in Google Spreadsheet and check if it contains a emailId value in the required column
Cant work out how to count the number of rows that have an email address in them, to populate the number of rows to process. I have a spreadsheet with a list of emails, the number of emailable rows changes regularly, so I'd like to count emailable rows, and instead of manually typing "28" or whatever, I'd like it to automatically find that number :) </p>

```<code>function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 28;  // Number of rows to process
  // Fetch the range of cells
  var dataRange = sheet.getRange(startRow, 1, numRows, 4)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (i in data) {
    var row = data[i];
    var emailAddress = row[0];  // First column
    var message = row[1];       // Second column
    var subject = "membership number"
    MailApp.sendEmail(emailAddress, subject, message);
  }
}
</code>```

答:
for counting email addresses in a range you can use simply:

```<code>=COUNTIF(A:C, "*@*")
</code>```

or the proper way:

```<code>=ARRAYFORMULA(COUNTIF(ISEMAIL(A:C), TRUE))
</code>```

Body:
Cant work out how to count the number of rows that have an email address in them, to populate the number of rows to process. I have a spreadsheet with a list of emails, the number of emailable rows changes regularly, so I'd like to count emailable rows, and instead of manually typing "28" or whatever, I'd like it to automatically find that number :)

function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 28;  // Number of rows to process
  // Fetch the range of cells
  var dataRange = sheet.getRange(startRow, 1, numRows, 4)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (i in data) {
    var row = data[i];
    var emailAddress = row[0];  // First column
    var message = row[1];       // Second column
    var subject = "membership number"
    MailApp.sendEmail(emailAddress, subject, message);
  }
}

Body:
for counting email addresses in a range you can use simply:

=COUNTIF(A:C, "*@*")

or the proper way:

=ARRAYFORMULA(COUNTIF(ISEMAIL(A:C), TRUE))


答:
It looks like there is an open issue on this.

And if you need to provide a service strictly into a lazy-loaded module as you have in your example, then you have two options:

https://stackblitz.com/edit/angular-pzwmza?file=src/app/orders/orders.module.ts

https://stackblitz.com/edit/angular-lazy-load-jxjhfw?file=app%2Fabout%2Fabout.service.ts

Title: Angular Service for particular NgModule


问:
Jekyll: ERROR files not found
I just setup a local jekyll instance for github pages.  After following all the instructions on GitHub and getting all the files into the local repository, I ran jekyll (sudo bundle exec jekyll serve).

I get the following errors:

```<code>^CSeans-MacBook-Air:docs-gh-pages seanmcintyre$ sudo bundle exec jekyll serve
Password:
Configuration file: none
Configuration file: none
            Source: /Users/SnapRouteDocs/docs-gh-pages
       Destination: /Users/SnapRouteDocs/docs-gh-pages/_site
 Incremental build: disabled. Enable with --incremental
      Generating...
                    done in 0.82 seconds.
 Auto-regeneration: enabled for '/Users/SnapRouteDocs/docs-gh-pages'
Configuration file: none
    Server address: http://127.0.0.1:4000/
  Server running... press ctrl-c to stop.
[2017-04-13 13:35:12] ERROR `/_static/js/modernizr.min.js' not found.
[2017-04-13 13:35:12] ERROR `/_static/js/theme.js' not found.
[2017-04-13 13:35:12] ERROR `/_static/doctools.js' not found.
[2017-04-13 13:35:12] ERROR `/_static/jquery.js' not found.
[2017-04-13 13:35:12] ERROR `/_static/underscore.js' not found.
[2017-04-13 13:35:17] ERROR `/_static/css/theme.css' not found.
[2017-04-13 13:35:17] ERROR `/_static/jquery.js' not found.
[2017-04-13 13:35:17] ERROR `/_static/underscore.js' not found.
[2017-04-13 13:35:17] ERROR `/_static/doctools.js' not found.
[2017-04-13 13:35:17] ERROR `/_static/js/theme.js' not found.
</code>```

I've checked and all the files are actually there.

How do I go about fixing this?

答:
In addition to @keruilin's answer, Jekyll errors such as

```<code>ERROR `/resources/biokdd-review-nlp.htm' not found.
</code>```

are sometimes simply due to a malformed web URL, in one of your Jekyll-built site pages that are open in your browser.  Check the open webpages, and reload.

In my case (for instance) if I manually / erroneously open the malformed URL

```<code>127.0.0.1:4000/resources/biokdd-review-nlp. html
</code>```

(note the space before .html I get that Jekyll error, until I correct the URL and reload the page.

Title: Jekyll: ERROR files not found

Body:
I just setup a local jekyll instance for github pages.  After following all the instructions on GitHub and getting all the files into the local repository, I ran jekyll (sudo bundle exec jekyll serve).

I get the following errors:

^CSeans-MacBook-Air:docs-gh-pages seanmcintyre$ sudo bundle exec jekyll serve
Password:
Configuration file: none
Configuration file: none
            Source: /Users/SnapRouteDocs/docs-gh-pages
       Destination: /Users/SnapRouteDocs/docs-gh-pages/_site
 Incremental build: disabled. Enable with --incremental
      Generating...
                    done in 0.82 seconds.
 Auto-regeneration: enabled for '/Users/SnapRouteDocs/docs-gh-pages'
Configuration file: none
    Server address: http://127.0.0.1:4000/
  Server running... press ctrl-c to stop.
[2017-04-13 13:35:12] ERROR `/_static/js/modernizr.min.js' not found.
[2017-04-13 13:35:12] ERROR `/_static/js/theme.js' not found.
[2017-04-13 13:35:12] ERROR `/_static/doctools.js' not found.
[2017-04-13 13:35:12] ERROR `/_static/jquery.js' not found.
[2017-04-13 13:35:12] ERROR `/_static/underscore.js' not found.
[2017-04-13 13:35:17] ERROR `/_static/css/theme.css' not found.
[2017-04-13 13:35:17] ERROR `/_static/jquery.js' not found.
[2017-04-13 13:35:17] ERROR `/_static/underscore.js' not found.
[2017-04-13 13:35:17] ERROR `/_static/doctools.js' not found.
[2017-04-13 13:35:17] ERROR `/_static/js/theme.js' not found.

I've checked and all the files are actually there.

How do I go about fixing this?

Body:
In addition to @keruilin's answer, Jekyll errors such as

ERROR `/resources/biokdd-review-nlp.htm' not found.

are sometimes simply due to a malformed web URL, in one of your Jekyll-built site pages that are open in your browser.  Check the open webpages, and reload.

In my case (for instance) if I manually / erroneously open the malformed URL

127.0.0.1:4000/resources/biokdd-review-nlp. html

(note the space before .html I get that Jekyll error, until I correct the URL and reload the page.


答:
The parameters to a deferred function are immediately evaluated when defer is reached. Thats why you have to use a pointer if you defer End itself.

Instead you can use a closure. Your Bar() function would look like this:

func (foo *Foo) Bar() (err error) {
    foo.Begin()
    defer func() { foo.End(err) }()
    //some business code
    return
}

```

Here the value of err is evaluated once the deferred closure is executed.

If you're not stuck on using error returns, using panic and recover is the more idiomatic way in Go to handle such errors that require a rollback (like  Corey Ogburn recommended).

Title: Can I use an pointer to "error" to catch the return error?

Body:
The parameters to a deferred function are immediately evaluated when defer is reached. Thats why you have to use a pointer if you defer End itself.

Instead you can use a closure. Your Bar() function would look like this:

func (foo *Foo) Bar() (err error) {
    foo.Begin()
    defer func() { foo.End(err) }()
    //some business code
    return
}

Here the value of err is evaluated once the deferred closure is executed.

If you're not stuck on using error returns, using panic and recover is the more idiomatic way in Go to handle such errors that require a rollback (like  Corey Ogburn recommended).


问:
Implementing OAuth on Dropbox API Python
I'm trying to add a user to the development users of my dropbox app. In order to do so, it seems like I have to connect to the endpoints /token/from_oauth1 or/and /oauth2/token to generate their access token. I'm new with using APIs and struggling to understand how to implement OAuth/OAuth2 into my code. I'm using the requests library do so.

Here is a sample of what I've tried but hasn't been working for me:

```<code>import requests
import json

url = "https://api.dropboxapi.com/2/auth/token/from_oauth1"

headers = {
    "Authorization": "Basic <APP_KEY>:<APP_SECRET>",
    "Content-Type": "application/json"
}

data = {
    "oauth1_token": "<DROPBOX_USERNAME>",
    "oauth1_token_secret": "<DROPBOX_PASSWORD>"
}

r = requests.post(url, headers=headers, data=json.dumps(data))
</code>```

But I receive the error b'Error in call to API function "auth/token/from_oauth1": Invalid value in HTTP header "Authorization": "Basic <APP_KEY>:<APP_SECRET>"'

APP_KEY and APP_SECRET are obviously replaced with their corresponding strings.

Am I right to be calling /token/from_oauth1 rather than /oauth2/token. If so, where am I going wrong with this request?

答:
If you're starting a new integration with the Dropbox API, you should not use /2/auth/token/from_oauth1. That's only for use with existing OAuth 1 access tokens, which you would only have received from an old integration with Dropbox API v1, which is now retired.

If you're starting now, you'll just be using Dropbox API v2 with OAuth 2 access tokens only.

To implement the OAuth app authorization flow to get OAuth 2 access tokens for use with Dropbox API v2, you should use the following:

https://www.dropbox.com/oauth2/authorize (documented here)

https://api.dropboxapi.com/oauth2/token (documented here)

I also recommend reviewing the OAuth Guide.

In any case, you should never directly handle the Dropbox username and password directly.

Also, since you're using Python, I highly recommend using the official Dropbox API v2 Python SDK, as it will do most of the work for you. It has helpers for processing the OAuth flow, such as DropboxOAuth2Flow and DropboxOAuth2FlowNoRedirect.

Here's a minimal example of processing the Dropbox OAuth 2 "code" flow using just requests:

import requests

app_key = "APP_KEY_HERE"
app_secret = "APP_SECRET_HERE"

# build the authorization URL:
authorization_url = "https://www.dropbox.com/oauth2/authorize?client_id=%s&response_type=code" % app_key

# send the user to the authorization URL:
print 'Go to the following URL and allow access:'
print(authorization_url)

# get the authorization code from the user:
authorization_code = raw_input('Enter the code:\n')

# exchange the authorization code for an access token:
token_url = "https://api.dropboxapi.com/oauth2/token"
params = {
    "code": authorization_code,
    "grant_type": "authorization_code",
    "client_id": app_key,
    "client_secret": app_secret
}
r = requests.post(token_url, data=params)
print(r.text)
```

Body:
I'm trying to add a user to the development users of my dropbox app. In order to do so, it seems like I have to connect to the endpoints /token/from_oauth1 or/and /oauth2/token to generate their access token. I'm new with using APIs and struggling to understand how to implement OAuth/OAuth2 into my code. I'm using the requests library do so.

Here is a sample of what I've tried but hasn't been working for me:

import requests
import json

url = "https://api.dropboxapi.com/2/auth/token/from_oauth1"

headers = {
    "Authorization": "Basic <APP_KEY>:<APP_SECRET>",
    "Content-Type": "application/json"
}

data = {
    "oauth1_token": "<DROPBOX_USERNAME>",
    "oauth1_token_secret": "<DROPBOX_PASSWORD>"
}

r = requests.post(url, headers=headers, data=json.dumps(data))

But I receive the error b'Error in call to API function "auth/token/from_oauth1": Invalid value in HTTP header "Authorization": "Basic <APP_KEY>:<APP_SECRET>"'

APP_KEY and APP_SECRET are obviously replaced with their corresponding strings.

Am I right to be calling /token/from_oauth1 rather than /oauth2/token. If so, where am I going wrong with this request?


问:
Close ReactModal from ReactComponent
I have a React.Component inside a ReactModal.

```<code>class Course extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isModalOpen: false,
    }
  }
  handleModalOpen = event => {
    this.setState({ isModalOpen: true })
  }

  handleModalClose = event => {
    this.setState({ isModalOpen: false })
  }

  render() {
     <ReactModal
          isOpen={this.state.isModalOpen}
          onRequestClose={this.handleModalClose}
          contentLabel="Purchase a Course"
          style={customStyles}>
        <CheckoutComponent handleClose={this.handleModalClose}/>
     </ReactModal>

   class CheckoutForm extends React.Component {
    constructor(props) {
        super(props);
    }

    handleSubmit = (ev) => {
       axios.post(`${process.env.API_URL}purchase`, charge)
          .then(function (response) {
              this.props.handleClose();
          }
  }
</code>```

I would like to close the react modal upon successful post of the http request.

However, this is undefined.

How can I do it?

答:
The problem is in here

```<code>axios.post(`${process.env.API_URL}purchase`, charge)
          // here
    .then(function (response) {
        this.props.handleClose();
    })
</code>```

You need to use arrow functions. With normal functions, this will the the annonimous function's this. Using arrow functions solve this problem and you get the component's this.

```<code>axios.post(`${process.env.API_URL}purchase`, charge)
          // arrow function
    .then(response => {
        this.props.handleClose();
    })
</code>```

This answer explain it well.

Title: Close ReactModal from ReactComponent

Body:
I have a React.Component inside a ReactModal.

class Course extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isModalOpen: false,
    }
  }
  handleModalOpen = event => {
    this.setState({ isModalOpen: true })
  }

  handleModalClose = event => {
    this.setState({ isModalOpen: false })
  }

  render() {
     <ReactModal
          isOpen={this.state.isModalOpen}
          onRequestClose={this.handleModalClose}
          contentLabel="Purchase a Course"
          style={customStyles}>
        <CheckoutComponent handleClose={this.handleModalClose}/>
     </ReactModal>

   class CheckoutForm extends React.Component {
    constructor(props) {
        super(props);
    }

    handleSubmit = (ev) => {
       axios.post(`${process.env.API_URL}purchase`, charge)
          .then(function (response) {
              this.props.handleClose();
          }
  }

I would like to close the react modal upon successful post of the http request.

However, this is undefined.

How can I do it?

Body:
The problem is in here

axios.post(`${process.env.API_URL}purchase`, charge)
          // here
    .then(function (response) {
        this.props.handleClose();
    })

You need to use arrow functions. With normal functions, this will the the annonimous function's this. Using arrow functions solve this problem and you get the component's this.

axios.post(`${process.env.API_URL}purchase`, charge)
          // arrow function
    .then(response => {
        this.props.handleClose();
    })

This answer explain it well.


问:
Why does my website scroll slowly, and why are its hover effects laggy? How can I fix this?
So I have this site here which has major performance issues. Scrolling is very slow, hover effects have a bit of lag and other similar issue. Unfortunately right now I am working off a cheap host so I don't have the option to gzip my files and I am not sure how big a contributing factor that is, though. For what it's worth, I am using Drupal as a CMS.

I would like to know the various reasons for the lag and what I can do to fix it.

Some about:memory stats for the homepage :

Memory:

- Private:49664k

- Shared:13052k

- Total: 62716k

Virtual Memory:

- Private : 53400k

- Mapped : 10412;

Let me know if you need any more information.

答:
It seems fine on my machine (2009 MacBook Pro running Chrome 10), but I think you need to pick apart the idea of “performance”.

gzipping reduces the size of the text files that make up your site, so it reduces the time required for them to get from your web server to end users’ machines. That happens before the page loads in the user’s browser. It doesn’t affect the scrolling speed of the page once it’s loaded.

There does seem to be a metric crap-ton of JavaScript files included on the page, a few of which have “scroll” in their name. I’m not sure if any of them are running when the user scrolls, and thus slowing the browser down, but it seems like the most likely candidate for slow scrolling. (Ooh — unless meagar’s comment about background-size: cover; is right.)

Edit: as background-size: cover seems to be the issue, I’d suggest removing it, and making your background image reasonably big, so that it looks acceptable at most screen resolutions. You might want to get whoever made the image to edit it so that it fades out to a single color at the edges, so that it blends into your background-color for users on higher resolutions.


问:
Checking for null and empty values in javascript
What is wrong with this if statement? If i pass not empty values i still don't get in to the if block

Both val1 and val2 have values:

let val1 = 'category'
let val2 = 'medical'

if ((val1 !== null || val1 !== '') && (val2 !== null || val2 !== '')) {

  console.log(val1, val2);
}```
</div>
</div>
</p>

<p><code>val1</code> is empty and <code>val2</code> has a value:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let val1 = ''
let val2 = 'medical'

if ((val1 !== null || val1 !== '') && (val2 !== null || val2 !== '')) {

  console.log(val1, val2);
}</code>```

答:
Just say if. For example:

var x = "";
var y = null;
var z;
var argArray = [x,y,z];

function hasValue(arg){
  if(arg){
    console.log("arg has some value");
  } else {
    console.log("arg has no value and is " + arg);
  }
}

for (var i = 0; i < argArray.length; i++) {
  hasValue(argArray[i]);
}```

Body:
What is wrong with this if statement? If i pass not empty values i still don't get in to the if block

Both val1 and val2 have values:

let val1 = 'category'
let val2 = 'medical'

if ((val1 !== null || val1 !== '') && (val2 !== null || val2 !== '')) {

  console.log(val1, val2);
}

val1 is empty and val2 has a value:

let val1 = ''
let val2 = 'medical'

if ((val1 !== null || val1 !== '') && (val2 !== null || val2 !== '')) {

  console.log(val1, val2);
}