问:
How to solve return value of stored function call in Hibernate with MySQL?
I am trying to fetch data from MySQL stored procedure in hibernate . I have a custom_query.xml file , and DAO.java file

stored procedure in MySQL :

```<code>CREATE DEFINER=`root`@`localhost` PROCEDURE `SET_NETWORK`(
    IN TO_CREATE BIGINT,
    OUT CREATED BIGINT
)
BEGIN
     SET CREATED = (SELECT COUNT(VNR.ID) FROM NETWORK_TABLE VNR);
    WHILE (CREATED < TO_CREATE) DO
      INSERT INTO NETWORK_TABLE (ACTIVE) VALUES(0);
      SET CREATED = CREATED + 1;
    END WHILE;
END
</code>```

and i am trying to execute the SQL query from hibernate with following code :

```<code> <sql-query name="Network_getFreeNetworksForDomain" read-only="false" callable="true" cacheable="false"><![CDATA[
        { ? = CALL SET_NETWORK(?,?) }
    ]]></sql-query>
</code>```

and in DAO.java file , i am using Network_getFreeNetworksForDomain for calling the SQL query :

```<code>@Override
    @Transactional(readOnly = true)
    @SuppressWarnings({"unchecked"})
    public List<Network> getNetworksForDomain(Domain domain) throws DataAccessException {
        Long domainId = domain.getId();
        if (domainId == null) {
            domainId = 0L;
        }
        return (List<Network>) getSession().getNamedQuery("Network_getFreeNetworksForDomain")
                .setLong("dId", domainId).list();
    }
</code>```

but i am getting following excretion while deploying the file in to JBoss

```<code> Caused by: java.sql.SQLException: Can't set IN parameter for return value of stored function call.
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055) [mysql-connector-java-5.1.6.jar:]
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) [mysql-connector-java-5.1.6.jar:]
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926) [mysql-connector-java-5.1.6.jar:]
        at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3294) [mysql-connector-java-5.1.6.jar:]
        at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3272) [mysql-connector-java-5.1.6.jar:]
        at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3314) [mysql-connector-java-5.1.6.jar:]
        at com.mysql.jdbc.PreparedStatement.setLong(PreparedStatement.java:3330) [mysql-connector-java-5.1.6.jar:]
        at org.jboss.jca.adapters.jdbc.WrappedPreparedStatement.setLong(WrappedPreparedStatement.java:229)
        at com.dao.entity.NetworkHibernateDAO$1.createCallableStatement(NetworkHibernateDAO.java:169) [dao-impl-6.4.0.jar:]
        at com.dao.hibernate.transaction.HibernateUtils.execute(HibernateUtils.java:106) [dao-impl-6.4.0.jar:]
        at com.dao.hibernate.transaction.HibernateUtils$1.doInConnection(HibernateUtils.java:74) [dao-impl-6.4.0.jar:]
        at com.dao.hibernate.transaction.HibernateUtils$2.execute(HibernateUtils.java:91) [dao-impl-6.4.0.jar:]
        at org.hibernate.impl.SessionImpl.doWork(SessionImpl.java:1987) [hibernate-core-3.5.6-Final.jar:3.5.6-Final]
        ... 51 more
</code>```

and

```<code> Caused by: org.springframework.orm.hibernate3.HibernateJdbcException: JDBC exception on Hibernate data access: SQLException for SQL [???]; SQL state [S1009]; error code [0]; error executing work; nested exception is org.hibernate.exception.GenericJDBCException: error executing work
</code>```

Any suggestion ? How to solve this kind of errors ?

Update :

In DB2 and PostgreSQL this is working fine with

```<code> <sql-query name="Network_getFreeNetworksForDomain" read-only="false" callable="true" cacheable="false"><![CDATA[
            { ? = CALL SET_NETWORK(?) }
        ]]></sql-query>
</code>```

but getting same exception mentioned above . so i have added CALL SET_NETWORK(?,?) with two parameter with mys stored procedure .

答:
{ ? = CALL SET_NETWORK(?,?) }

It' seems you need 2 parameters and you provided only one

.setLong("dId", domainId)

I'm not sure your code is able to find the "dId" parameter, maybe you should use the index instead, you can have some sample in the official documentation

Body:
I am trying to fetch data from MySQL stored procedure in hibernate . I have a custom_query.xml file , and DAO.java file

stored procedure in MySQL :

CREATE DEFINER=`root`@`localhost` PROCEDURE `SET_NETWORK`(
    IN TO_CREATE BIGINT,
    OUT CREATED BIGINT
)
BEGIN
     SET CREATED = (SELECT COUNT(VNR.ID) FROM NETWORK_TABLE VNR);
    WHILE (CREATED < TO_CREATE) DO
      INSERT INTO NETWORK_TABLE (ACTIVE) VALUES(0);
      SET CREATED = CREATED + 1;
    END WHILE;
END

and i am trying to execute the SQL query from hibernate with following code :

 <sql-query name="Network_getFreeNetworksForDomain" read-only="false" callable="true" cacheable="false"><![CDATA[
        { ? = CALL SET_NETWORK(?,?) }
    ]]></sql-query>

and in DAO.java file , i am using Network_getFreeNetworksForDomain for calling the SQL query :

@Override
    @Transactional(readOnly = true)
    @SuppressWarnings({"unchecked"})
    public List<Network> getNetworksForDomain(Domain domain) throws DataAccessException {
        Long domainId = domain.getId();
        if (domainId == null) {
            domainId = 0L;
        }
        return (List<Network>) getSession().getNamedQuery("Network_getFreeNetworksForDomain")
                .setLong("dId", domainId).list();
    }

but i am getting following excretion while deploying the file in to JBoss

 Caused by: java.sql.SQLException: Can't set IN parameter for return value of stored function call.
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055) [mysql-connector-java-5.1.6.jar:]
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) [mysql-connector-java-5.1.6.jar:]
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926) [mysql-connector-java-5.1.6.jar:]
        at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3294) [mysql-connector-java-5.1.6.jar:]
        at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3272) [mysql-connector-java-5.1.6.jar:]
        at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3314) [mysql-connector-java-5.1.6.jar:]
        at com.mysql.jdbc.PreparedStatement.setLong(PreparedStatement.java:3330) [mysql-connector-java-5.1.6.jar:]
        at org.jboss.jca.adapters.jdbc.WrappedPreparedStatement.setLong(WrappedPreparedStatement.java:229)
        at com.dao.entity.NetworkHibernateDAO$1.createCallableStatement(NetworkHibernateDAO.java:169) [dao-impl-6.4.0.jar:]
        at com.dao.hibernate.transaction.HibernateUtils.execute(HibernateUtils.java:106) [dao-impl-6.4.0.jar:]
        at com.dao.hibernate.transaction.HibernateUtils$1.doInConnection(HibernateUtils.java:74) [dao-impl-6.4.0.jar:]
        at com.dao.hibernate.transaction.HibernateUtils$2.execute(HibernateUtils.java:91) [dao-impl-6.4.0.jar:]
        at org.hibernate.impl.SessionImpl.doWork(SessionImpl.java:1987) [hibernate-core-3.5.6-Final.jar:3.5.6-Final]
        ... 51 more

and

 Caused by: org.springframework.orm.hibernate3.HibernateJdbcException: JDBC exception on Hibernate data access: SQLException for SQL [???]; SQL state [S1009]; error code [0]; error executing work; nested exception is org.hibernate.exception.GenericJDBCException: error executing work

Any suggestion ? How to solve this kind of errors ?

Update :

In DB2 and PostgreSQL this is working fine with

 <sql-query name="Network_getFreeNetworksForDomain" read-only="false" callable="true" cacheable="false"><![CDATA[
            { ? = CALL SET_NETWORK(?) }
        ]]></sql-query>

but getting same exception mentioned above . so i have added CALL SET_NETWORK(?,?) with two parameter with mys stored procedure .


来源: stackexchange

问:
Slow queries with preparedStatement but not with executeQuery
I'm having a weird problem with an Grails application accessing data. Going deeper I've isolated the problem to a plain java8 small application using PreparedStatement.executeQuery vs Statement.executeQuery.

Consider the following snippet of code:

```<code>
    // executes in milliseconds
    directSql   = "select top(10) * from vdocuments where codcli = 'CCCC' and             serial = 'SSSS' ORDER BY otherField DESC;";
    stmt = con.createStatement();
    rs = stmt.executeQuery(directSql);

    // More than 10 minutes
    sqlPrepared = "select top(10) * from vdocuments where codCli = ? and  serial = ? ORDER BY otherField DESC;";
    PreparedStatement pStatement = con.prepareStatement( sqlPrepared );
    pStatement.setString(1, "CCCC");
    pStatement.setString(2, "SSSS");
    rsPrepared = pStatement.executeQuery();

</code>```

Same query.

Data comes from a view on SqlServer (2008, I think, have no access right now) from a table with more than 15 Million records. There are indexes for all needed fields and the same query (the first one) executed from console runs also quite fast.

If I execute the slow PreparedStatement query without the ORDER clause it also runs fast.

It looks clear to me that for any cause the database it's not using indexes and make a full scan when using preparedStatement, but maybe I'm wrong so I'm open to any idea.

I thought maybe the driver (sqlserver official latest and jtds has been tested) was holding the data waiting for any kind of EOF from connection but I've checked with tcpdump on my side and no data is received.

I can't find why this is happening so any idea will be welcomed.

Thank you in advanced!

答:
I've finally found a solution, at least in for my case. I got it here http://mehmoodbluffs.blogspot.com.es/2015/03/hibernate-queries-are-slow-sql-servers.html .  Telling (driver? sqlServer?) not to send parameters as Unicode have resolved the problem.

Current connection string it's now:

```<code> String connectionUrl = "jdbc:sqlserver://server:port;databaseName=myDataBase;sendStringParametersAsUnicode=false";
</code>```

And now both direct queries and preparedStatements runs at millisecond speed.

Thank you @DanGuzman for your suggestions!

ContentLicense: CC BY-SA 3.0

Body:
I'm having a weird problem with an Grails application accessing data. Going deeper I've isolated the problem to a plain java8 small application using PreparedStatement.executeQuery vs Statement.executeQuery.

Consider the following snippet of code:

    // executes in milliseconds
    directSql   = "select top(10) * from vdocuments where codcli = 'CCCC' and             serial = 'SSSS' ORDER BY otherField DESC;";
    stmt = con.createStatement();
    rs = stmt.executeQuery(directSql);

    // More than 10 minutes
    sqlPrepared = "select top(10) * from vdocuments where codCli = ? and  serial = ? ORDER BY otherField DESC;";
    PreparedStatement pStatement = con.prepareStatement( sqlPrepared );
    pStatement.setString(1, "CCCC");
    pStatement.setString(2, "SSSS");
    rsPrepared = pStatement.executeQuery();

Same query.

Data comes from a view on SqlServer (2008, I think, have no access right now) from a table with more than 15 Million records. There are indexes for all needed fields and the same query (the first one) executed from console runs also quite fast.

If I execute the slow PreparedStatement query without the ORDER clause it also runs fast.

It looks clear to me that for any cause the database it's not using indexes and make a full scan when using preparedStatement, but maybe I'm wrong so I'm open to any idea.

I thought maybe the driver (sqlserver official latest and jtds has been tested) was holding the data waiting for any kind of EOF from connection but I've checked with tcpdump on my side and no data is received.

I can't find why this is happening so any idea will be welcomed.

Thank you in advanced!

Body:
I've finally found a solution, at least in for my case. I got it here http://mehmoodbluffs.blogspot.com.es/2015/03/hibernate-queries-are-slow-sql-servers.html .  Telling (driver? sqlServer?) not to send parameters as Unicode have resolved the problem.

Current connection string it's now:

 String connectionUrl = "jdbc:sqlserver://server:port;databaseName=myDataBase;sendStringParametersAsUnicode=false";

And now both direct queries and preparedStatements runs at millisecond speed.

Thank you @DanGuzman for your suggestions!


问:
Failed to resolve assembly : 'Java.Interop'
When I try to build the application I get an exception the following exception :

C:\Program Files (x86)\MSBuild\Xamarin\iOS\Xamarin.iOS.Common.targets(681,3): error : Failed to resolve assembly: 'Java.Interop, Version=0.1.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065'

I tried cleaning the project and building it again, also updated the Xamarin.Forms packages but still with no luck.

A little overview on the stack trace :

2>C:\Program Files (x86)\MSBuild\Xamarin\iOS\Xamarin.iOS.Common.targets(681,3): error : Failed to resolve assembly: 'Java.Interop, Version=0.1.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065'
  2>  Tool /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/bin/mtouch execution finished. (TaskId:153)
  2>  MTouch: 2016-07-05T14:27:15.8191415+05:30 - Finished (TaskId:153)
  2>  Output Item(s): _NativeLibrary= (TaskId:153)
  2>Done executing task "MTouch" -- FAILED. (TaskId:153)

Has anyone received this error? I am running the latest Xamarin for Visual Studio.

答:
I had the same problem and when I removed the android.mono reference from pcl project it worked fine.

I think it happens because we are building project in ios and it doesn't have any android libraries


问:
How to assign a variable in the WHERE clause of a sub-query in SQL Server
```<code>SELECT
    Total_Males, SETTLEMENT_ID, URI, _PARENT_AURI
FROM
    (SELECT
         COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID, t1.URI,
         t2._PARENT_AURI
     FROM
         PScData t1
     INNER JOIN
         PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
     WHERE
         t1.SETTLEMENT_ID = '11102002002001'
         AND t2.SEX = '1'
     GROUP BY
         t1.URI, t2._PARENT_AURI, t1.SETTLEMENT_ID) tmp
</code>```

This is the query that I have written. In the WHERE clause, where I have given the exact value - '11102002002001' - I want to compare with each SETTLEMENT_ID from t1. How can I do this? Please provide some solution.

Further, the query is returning count in two rows i.e: count against two different ids right now. How can I add the result of two different ids to get the sum of these two rows returned by the sub-query?

答:
A sub-query is void here. Just perform the join and filter out the settlements if you don't need all of them. But it is not clear from your question if you want to filter them out or just match them. For the purpose of matching use joins.

```<code>SELECT COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID, t1.URI, t2._PARENT_AURI
FROM PScData t1
    INNER JOIN PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE t2.SEX = '1'
GROUP BY t1.URI, t2._PARENT_AURI, t1.SETTLEMENT_ID
</code>```

If you need to filter them out, you need to prepare the list of wanted settlements and use IN in the WHERE clause. You can use a Common Table Expression to spread out the list of wanted settlements and pass it in the WHERE clause:

```<code>WITH cteSettlements AS (
    SELECT SETLLEMENT_ID
    FROM PscData
    WHERE ? -- apply some criteria
)
SELECT COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID, t1.URI, t2._PARENT_AURI
FROM PScData t1
    INNER JOIN PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE t1.SETTLEMENT_ID IN cteSettlements AND t2.SEX = '1'
GROUP BY t1.URI, t2._PARENT_AURI, t1.SETTLEMENT_ID
</code>```

As for the second question - How can I add the result of two different ids to get the sum of these two rows? - you need to play with the GROUP BY clause. As far as I understand, you actually don't need to group be SETTLEMENT_ID so just remove it from the GROUP BY. Just remember that you need to remove it from the SELECT list too.

Body:
SELECT
    Total_Males, SETTLEMENT_ID, URI, _PARENT_AURI
FROM
    (SELECT
         COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID, t1.URI,
         t2._PARENT_AURI
     FROM
         PScData t1
     INNER JOIN
         PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
     WHERE
         t1.SETTLEMENT_ID = '11102002002001'
         AND t2.SEX = '1'
     GROUP BY
         t1.URI, t2._PARENT_AURI, t1.SETTLEMENT_ID) tmp

This is the query that I have written. In the WHERE clause, where I have given the exact value - '11102002002001' - I want to compare with each SETTLEMENT_ID from t1. How can I do this? Please provide some solution.

Further, the query is returning count in two rows i.e: count against two different ids right now. How can I add the result of two different ids to get the sum of these two rows returned by the sub-query?

Body:
A sub-query is void here. Just perform the join and filter out the settlements if you don't need all of them. But it is not clear from your question if you want to filter them out or just match them. For the purpose of matching use joins.

SELECT COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID, t1.URI, t2._PARENT_AURI
FROM PScData t1
    INNER JOIN PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE t2.SEX = '1'
GROUP BY t1.URI, t2._PARENT_AURI, t1.SETTLEMENT_ID

If you need to filter them out, you need to prepare the list of wanted settlements and use IN in the WHERE clause. You can use a Common Table Expression to spread out the list of wanted settlements and pass it in the WHERE clause:

WITH cteSettlements AS (
    SELECT SETLLEMENT_ID
    FROM PscData
    WHERE ? -- apply some criteria
)
SELECT COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID, t1.URI, t2._PARENT_AURI
FROM PScData t1
    INNER JOIN PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE t1.SETTLEMENT_ID IN cteSettlements AND t2.SEX = '1'
GROUP BY t1.URI, t2._PARENT_AURI, t1.SETTLEMENT_ID

As for the second question - How can I add the result of two different ids to get the sum of these two rows? - you need to play with the GROUP BY clause. As far as I understand, you actually don't need to group be SETTLEMENT_ID so just remove it from the GROUP BY. Just remember that you need to remove it from the SELECT list too.


问:
Get dates between 2 dates with equal intervals
I have 2 dates 01/04/2017 and 30/04/2017. I want all the dates between these 2 dates with 7 days interval.

```<code>Expected Output :
01/04/2017
08/04/2017
15/04/2017
22/04/2017
29/04/2017
</code>```

Please help!!

答:
Try this

```<code>DECLARE @STRT DATETIME='04/01/2017',@END DATETIME ='04/30/2017'
;WITH CTE
AS
(
    SELECT
        MyDate = CAST(@STRT AS DATETIME)

    UNION ALL

    SELECT
        MyDate = CAST(MyDate AS DATETIME)+7
        FROM CTE
            WHERE CAST(MyDate AS DATETIME)+7 < CAST(@END AS DATETIME)
)
SELECT
    *
    FROM CTE
</code>```

result

Body:
I have 2 dates 01/04/2017 and 30/04/2017. I want all the dates between these 2 dates with 7 days interval.

Expected Output :
01/04/2017
08/04/2017
15/04/2017
22/04/2017
29/04/2017

Please help!!

Body:
Try this

DECLARE @STRT DATETIME='04/01/2017',@END DATETIME ='04/30/2017'
;WITH CTE
AS
(
    SELECT
        MyDate = CAST(@STRT AS DATETIME)

    UNION ALL

    SELECT
        MyDate = CAST(MyDate AS DATETIME)+7
        FROM CTE
            WHERE CAST(MyDate AS DATETIME)+7 < CAST(@END AS DATETIME)
)
SELECT
    *
    FROM CTE

result


问:
Running JAR file on Windows
I have a JAR file named helloworld.jar.
In order to run it, I'm executing the following command in a command-line window:

java -jar helloworld.jar
```

This works fine, but how do I execute it with double-click instead?
Do I need to install any software?

答:
There are many methods for running .jar file on windows. One of them is using the command prompt.

Steps :

Open command prompt(Run as administrator)

Now write "cd\" command for root directory

Type "java jar filename.jar"
Note: you can also use any third party apps like WinRAR, jarfix, etc.

OwnerDisplayName: BlackPanther

Title: Running JAR file on Windows

Body:
I have a JAR file named helloworld.jar.
In order to run it, I'm executing the following command in a command-line window:

java -jar helloworld.jar

This works fine, but how do I execute it with double-click instead?
Do I need to install any software?


问:
Is there a way to make [incr Tcl] classes friends?
Is there a way to obtain a friendship between classes in incr Tcl?

Consider the code below.

```<code>package require Itcl

::itcl::class A {
   private {
      proc f { } {
         puts "==== A::f"
      }
   }
}

::itcl::class B {
   public {
      proc g { } {
         puts "==== want to be able to call A::f"
      }
   }
}
</code>```

I want A::f to be invisible outside A bur functions of B. How can I achieve this?

答:
Itcl doesn't provide friends.

You can hack around this by constructing a call using namespace inscope, like so:

```<code>namespace inscope A {A::f}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is there a way to obtain a friendship between classes in incr Tcl?

Consider the code below.

package require Itcl

::itcl::class A {
   private {
      proc f { } {
         puts "==== A::f"
      }
   }
}

::itcl::class B {
   public {
      proc g { } {
         puts "==== want to be able to call A::f"
      }
   }
}

I want A::f to be invisible outside A bur functions of B. How can I achieve this?

Body:
Itcl doesn't provide friends.

You can hack around this by constructing a call using namespace inscope, like so:

namespace inscope A {A::f}


问:
Contact Form 7 - How to hide email field in source code / development tools properly?
I'm looking for a way to hide the email adress of the post owner in a contact form 7 formular.

It works fine to pass the value dynamically by default shortcode attributes (https://contactform7.com/getting-default-values-from-shortcode-attributes/) or with the modules plugin (https://wordpress.org/plugins/contact-form-7-dynamic-text-extension/) and I'm also able to hide the field. The second plugin has also the 'obfuscate' functionality. But it obfuscates only the mail in the source code, not in the development tools.

Edit:
Our website is a classified plattform. Every post has an owner and the customers are able to contact the owner by contact form. I wanted to populate the value of the "hidden" field with the value of the owner-email and use this value in the "To" part. The population works really fine, but the owner email is in the code of the page and everyone with some IT skills is able to see them. I would like to hide this value. Pipes are great, but I'm not able to use following code for the pipes. The values are not populated to the dropdown list:

```<code>echo do_shortcode('[contact-form-7 id="635" title="Contactform1" destination-email="Ownermail|'.get_post_meta( $post_id, "owner_email", true ).'"]'); ?>
</code>```

Any Ideas?

Thanks + Regards,
Waldemar

答:
to send a e-mail to the post author, first set the form recipient to [recipientEMail]

and then use this code to set the value to the e-mail

```<code>add_filter("wpcf7_posted_data", function ($wpcf7_posted_data) {

    if ("15896" === $wpcf7_posted_data["_wpcf7"]) { // test the contact form id

        $post = get_post($wpcf7_posted_data["_wpcf7_container_post"]);
        $post_author = get_userdata($post->post_author);

        $wpcf7_posted_data["recipientEMail"] = $post_author->user_email;

    }

    return $wpcf7_posted_data;

});
</code>```

Body:
I'm looking for a way to hide the email adress of the post owner in a contact form 7 formular.

It works fine to pass the value dynamically by default shortcode attributes (https://contactform7.com/getting-default-values-from-shortcode-attributes/) or with the modules plugin (https://wordpress.org/plugins/contact-form-7-dynamic-text-extension/) and I'm also able to hide the field. The second plugin has also the 'obfuscate' functionality. But it obfuscates only the mail in the source code, not in the development tools.

Edit:
Our website is a classified plattform. Every post has an owner and the customers are able to contact the owner by contact form. I wanted to populate the value of the "hidden" field with the value of the owner-email and use this value in the "To" part. The population works really fine, but the owner email is in the code of the page and everyone with some IT skills is able to see them. I would like to hide this value. Pipes are great, but I'm not able to use following code for the pipes. The values are not populated to the dropdown list:

echo do_shortcode('[contact-form-7 id="635" title="Contactform1" destination-email="Ownermail|'.get_post_meta( $post_id, "owner_email", true ).'"]'); ?>

Any Ideas?

Thanks + Regards,
Waldemar

Body:
to send a e-mail to the post author, first set the form recipient to [recipientEMail]

and then use this code to set the value to the e-mail

add_filter("wpcf7_posted_data", function ($wpcf7_posted_data) {

    if ("15896" === $wpcf7_posted_data["_wpcf7"]) { // test the contact form id

        $post = get_post($wpcf7_posted_data["_wpcf7_container_post"]);
        $post_author = get_userdata($post->post_author);

        $wpcf7_posted_data["recipientEMail"] = $post_author->user_email;

    }

    return $wpcf7_posted_data;

});


问:
Write image downloaded in the media content
I am writing an app who download some images from a remote server. I try to save them in the gallery but I got a android.permission.WRITE_EXTERNAL_STORAGE required due to a Permission Denial.

I do not understand why because I set up the permission in the manifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.seb.sebastien.reddit">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

Any idea why the permission denial happens as I add the permission. For information, I do not have an Android Device, I use the emulator. SDK use is API 26.

Thanks

答:
Add this code for permission to allow run time operation in splash activity in onCreate or before download process of image.

```<code>if (!checkPermission()) {
        openActivity();
    } else {
        if (checkPermission()) {
            requestPermissionAndContinue();
        } else {
            openActivity();
        }
    }
</code>```

Add this method outside onCreate.

```<code>private static final int PERMISSION_REQUEST_CODE = 200;
private boolean checkPermission() {

        return ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                ;
    }

private void requestPermissionAndContinue() {
    if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, WRITE_EXTERNAL_STORAGE)
                && ActivityCompat.shouldShowRequestPermissionRationale(this, READ_EXTERNAL_STORAGE)) {
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
            alertBuilder.setCancelable(true);
            alertBuilder.setTitle(getString(R.string.permission_necessary));
            alertBuilder.setMessage(R.string.storage_permission_is_encessary_to_wrote_event);
            alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE
                            , READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
                }
            });
            AlertDialog alert = alertBuilder.create();
            alert.show();
            Log.e("", "permission denied, show dialog");
        } else {
            ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE,
                    READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    } else {
        openActivity();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    if (requestCode == PERMISSION_REQUEST_CODE) {
        if (permissions.length > 0 && grantResults.length > 0) {

            boolean flag = true;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    flag = false;
                }
            }
            if (flag) {
                openActivity();
            } else {
                finish();
            }

        } else {
            finish();
        }
    } else {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

private void openActivity() {
  //add your further process after giving permission or to download images from remote server.
}
</code>```

happy Coding.

Body:
I am writing an app who download some images from a remote server. I try to save them in the gallery but I got a android.permission.WRITE_EXTERNAL_STORAGE required due to a Permission Denial.

I do not understand why because I set up the permission in the manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.seb.sebastien.reddit">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Any idea why the permission denial happens as I add the permission. For information, I do not have an Android Device, I use the emulator. SDK use is API 26.

Thanks

Body:
Add this code for permission to allow run time operation in splash activity in onCreate or before download process of image.

if (!checkPermission()) {
        openActivity();
    } else {
        if (checkPermission()) {
            requestPermissionAndContinue();
        } else {
            openActivity();
        }
    }

Add this method outside onCreate.

private static final int PERMISSION_REQUEST_CODE = 200;
private boolean checkPermission() {

        return ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                ;
    }

private void requestPermissionAndContinue() {
    if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, WRITE_EXTERNAL_STORAGE)
                && ActivityCompat.shouldShowRequestPermissionRationale(this, READ_EXTERNAL_STORAGE)) {
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
            alertBuilder.setCancelable(true);
            alertBuilder.setTitle(getString(R.string.permission_necessary));
            alertBuilder.setMessage(R.string.storage_permission_is_encessary_to_wrote_event);
            alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE
                            , READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
                }
            });
            AlertDialog alert = alertBuilder.create();
            alert.show();
            Log.e("", "permission denied, show dialog");
        } else {
            ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE,
                    READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    } else {
        openActivity();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    if (requestCode == PERMISSION_REQUEST_CODE) {
        if (permissions.length > 0 && grantResults.length > 0) {

            boolean flag = true;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    flag = false;
                }
            }
            if (flag) {
                openActivity();
            } else {
                finish();
            }

        } else {
            finish();
        }
    } else {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

private void openActivity() {
  //add your further process after giving permission or to download images from remote server.
}

happy Coding.


问:
CollectionView EstimatedItemSize not working for iOS 9 & 10
I am experiencing problem with UICollectionViewFlowLayout.estimatedItemSize. The issue is that it does not work for iOS 9 & 10 but works fine for iOS 11. Here are the snapshots:

ScreenShot iOS-11 -> This is the expected behaviour.

ScreenShot iOS-10 -> There is nothing displayed here as the cell size is Zero. cellForItemAtIndex is never called.

ScreenShot iOS-9 -> Same as in iOS-10

According to https://developer.apple.com/videos/play/wwdc2014/226/,
setting estimatedItemSize to a non-zero value, makes the autolayout to kick in and calls systemLayoutSizeFitting(targetSize:horizontalFittingPriority:verticalFittingPriority:) -> CGSize on UICollectionViewCell to compute size. So sizeForItemAt method need not be implemented.

Scroll Direction is Horizontal.

FYI - I am not using UICollectionViewFlowLayoutAutomaticSize and haven't tried it yet. I am not sure how it works and it got introduced only in iOS-10. But I need to support iOS-9. Also, according to wwdc2014/226 video, setting estimatedItemSize to non-zero value should be sufficient.

This is the code:

UICollectionViewCell:

```<code>class SingleTextCVC: UICollectionViewCell {

    @IBOutlet weak var textlabel: UILabel! {
        didSet {
            textlabel.textColor = UIColor.black
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        backgroundColor = UIColor.white
        layer.cornerRadius = 4
        clipsToBounds = true
    }
}
</code>```

ViewController:

```<code>class CVHorzTextAutoDimenVC: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView! {
        didSet {
            collectionView.delegate = self
            collectionView.dataSource = self
            collectionView.register(nib: SingleTextCVC.self)

            if let _layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {

                _layout.sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
                _layout.minimumInteritemSpacing = 16
                _layout.estimatedItemSize = CGSize(width: 100, height: 52)
            }
        }
    }

    fileprivate var textItems: [String] = [
        "Lorem",
        "Lorem ipsu",
        "Lorem ipsu dolor",
        "Lorem ipsum dolor sit",
        "Lorem ipsum dolor sit amet",
        "Lorem ipsum dolor sit amet, consectetur",
        "Lorem ipsum dolor sit amet, consectetur adipiscing ",
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer",
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer ne."
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

extension CVHorzTextAutoDimenVC : UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return textItems.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SingleTextCVC.reuseIdentifier, for: indexPath) as! SingleTextCVC
        cell.textlabel.text = textItems[indexPath.row]
        return cell
    }
}
</code>```

Please let me know what am I missing here?

Why does it work only for iOS-11?

Is it the expected behaviour. If yes, why?

If not, what's the solution?

答:
```<code>let layout = UICollectionViewFlowLayout()
if #available(iOS 10.0, *) {
layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
 }
else {
layout.estimatedItemSize = CGSize(width: 100, height: 52)
 }
</code>```

Body:
I am experiencing problem with UICollectionViewFlowLayout.estimatedItemSize. The issue is that it does not work for iOS 9 & 10 but works fine for iOS 11. Here are the snapshots:

ScreenShot iOS-11 -> This is the expected behaviour.

ScreenShot iOS-10 -> There is nothing displayed here as the cell size is Zero. cellForItemAtIndex is never called.

ScreenShot iOS-9 -> Same as in iOS-10

According to https://developer.apple.com/videos/play/wwdc2014/226/,
setting estimatedItemSize to a non-zero value, makes the autolayout to kick in and calls systemLayoutSizeFitting(targetSize:horizontalFittingPriority:verticalFittingPriority:) -> CGSize on UICollectionViewCell to compute size. So sizeForItemAt method need not be implemented.

Scroll Direction is Horizontal.

FYI - I am not using UICollectionViewFlowLayoutAutomaticSize and haven't tried it yet. I am not sure how it works and it got introduced only in iOS-10. But I need to support iOS-9. Also, according to wwdc2014/226 video, setting estimatedItemSize to non-zero value should be sufficient.

This is the code:

UICollectionViewCell:

class SingleTextCVC: UICollectionViewCell {

    @IBOutlet weak var textlabel: UILabel! {
        didSet {
            textlabel.textColor = UIColor.black
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        backgroundColor = UIColor.white
        layer.cornerRadius = 4
        clipsToBounds = true
    }
}

ViewController:

class CVHorzTextAutoDimenVC: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView! {
        didSet {
            collectionView.delegate = self
            collectionView.dataSource = self
            collectionView.register(nib: SingleTextCVC.self)

            if let _layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {

                _layout.sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
                _layout.minimumInteritemSpacing = 16
                _layout.estimatedItemSize = CGSize(width: 100, height: 52)
            }
        }
    }

    fileprivate var textItems: [String] = [
        "Lorem",
        "Lorem ipsu",
        "Lorem ipsu dolor",
        "Lorem ipsum dolor sit",
        "Lorem ipsum dolor sit amet",
        "Lorem ipsum dolor sit amet, consectetur",
        "Lorem ipsum dolor sit amet, consectetur adipiscing ",
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer",
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer ne."
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

extension CVHorzTextAutoDimenVC : UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return textItems.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SingleTextCVC.reuseIdentifier, for: indexPath) as! SingleTextCVC
        cell.textlabel.text = textItems[indexPath.row]
        return cell
    }
}

Please let me know what am I missing here?

Why does it work only for iOS-11?

Is it the expected behaviour. If yes, why?

If not, what's the solution?


问:
didSelectRowAtIndexPath doesn't work on xCode 9
So I have to work on this really big project, it's still on objective C.

I was just ask to make a really small change (hide a button) so I did that and it's building fine and everything looks normal but then all of the tableView in the project won't react as in didSelectRowAtIndexPath is never called (scrolling work and the data are correctly displayed)

The only thing that changed compared to before is that I used xCode 9.

Now when I build it using xCode 8 it's working again so at least we can go ahead but I still am wondering what is happening.

I made a smaller project using exactly the same logic as the main project (the cell are custom, you can swipe etc)
and when I did it from scratch, it's working fine.

So I fell like it's more of an xCode bug/error than one with the code.
would someone have any idea ?

答:
Have you used tap anywhere on that UI??
because when tap: UITapGestureRecognizer is there in UI didselect work after only at longpress of cell

or you can just set in your viewdidload function

```<code>UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
[self.tableView addGestureRecognizer:gestureRecognizer];
gestureRecognizer.cancelsTouchesInView = NO;
</code>```

Body:
Have you used tap anywhere on that UI??
because when tap: UITapGestureRecognizer is there in UI didselect work after only at longpress of cell

or you can just set in your viewdidload function

UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
[self.tableView addGestureRecognizer:gestureRecognizer];
gestureRecognizer.cancelsTouchesInView = NO;


问:
Find all stored procedures including a text in their body
I saw some answers about search text in stored procedures name, Id and etc. But I don't find out that what is the good way to find all stored procedures including the SQL of their body

More info: I have a table called X; I wand to drop it and I want to be sure that it has not been used in stored procedures.

答:
this will find all procedures, functions, triggers, etc with the text Xin it

```<code>SELECT DISTINCT
       o.name AS Object_Name,
       o.type_desc,
       m.*
FROM   sys.sql_modules m
  INNER JOIN sys.objects o ON m.object_id = o.object_id
WHERE m.definition Like '%X%'
</code>```

It is easy to alter so you only get procedures, or whatever you need

Body:
this will find all procedures, functions, triggers, etc with the text Xin it

SELECT DISTINCT
       o.name AS Object_Name,
       o.type_desc,
       m.*
FROM   sys.sql_modules m
  INNER JOIN sys.objects o ON m.object_id = o.object_id
WHERE m.definition Like '%X%'

It is easy to alter so you only get procedures, or whatever you need


问:
Connect Visual Studio with MySQL database using Server Explorer
I would like to connect the Visual Studio (2015) Server Explorer with a MySQL-DB. Having installed the latest MySQL for Visual Studio and Connector/NET, I still get the following error:

When I connect a C#-application in Visual Studio to a MySQL-DB on the same server through commands, e.g.

```<code>MySqlConnection conn = null;
conn = new MySqlConnection();
conn.ConnectionString = getConnection();
</code>```

that and following queries work just fine.

What do I have to do, please?
(I looked around for about 2h regarding possible solutions, but I cannot find anything which solves my case)

答:
We had the same issue and it was caused by different version of MySql data inside to connector and IDE plugin.
So We don't use the last version; our configuration is: Connector 6.9.9 and MySql for visual studio 2.0.5.</p>

Body:
I would like to connect the Visual Studio (2015) Server Explorer with a MySQL-DB. Having installed the latest MySQL for Visual Studio and Connector/NET, I still get the following error:

When I connect a C#-application in Visual Studio to a MySQL-DB on the same server through commands, e.g.

MySqlConnection conn = null;
conn = new MySqlConnection();
conn.ConnectionString = getConnection();

that and following queries work just fine.

What do I have to do, please?
(I looked around for about 2h regarding possible solutions, but I cannot find anything which solves my case)


问:
Order object by enum in custom order
I'm trying to rearrange a list of animals in order from medium, large, small. I've been trying to do this with IComparable.CompareTo but I can't figure out how to order it in this specific way. I can only find ways to order by Ascending or Descending values.

My enum:

```<code>public enum AnimalSize
    {
        Small = 1, Medium = 3, Large = 5,
    }
</code>```

My Animal class:

```<code>public class Animal : IComparable<Animal>
{
    public bool IsCarnivore;
    public AnimalSize Size;

    public Animal(bool isCarnivore, AnimalSize size)
    {
        this.IsCarnivore = isCarnivore;
        this.Size = size;
    }

    public int CompareTo(Animal other)
    {
        return this.Size.CompareTo(other.Size);
    }
</code>```

I call the CompareTo from another class where I have a private list of animals.

How can I arrange the animals in order of Medium, Large, Small?

答:
You could create a custom Comparer<Animal>:

```<code>public class AnimalSizeComparer : Comparer<Animal>
{
    private readonly IList<AnimalSize> _order;

    public AnimalSizeComparer():this(Enum.GetValues(typeof(AnimalSize)).Cast<AnimalSize>().ToArray())
    {
    }
    public AnimalSizeComparer(IList<AnimalSize> order)
    {
        _order = order;
    }

    public override int Compare(Animal x, Animal y)
    {
        if (x == null && y == null) return 0;
        if (x == null) return -1;
        if (y == null) return 1;

        return _order.IndexOf(x.Size).CompareTo(_order.IndexOf(y.Size));
    }
}
</code>```

You initialize it with your sample order in this way:

```<code>var comparer = new AnimalSizeComparer(new[] { AnimalSize.Medium, AnimalSize.Large, AnimalSize.Small });
yourAminalList.Sort(comparer);
</code>```

Title: Order object by enum in custom order

Body:
I'm trying to rearrange a list of animals in order from medium, large, small. I've been trying to do this with IComparable.CompareTo but I can't figure out how to order it in this specific way. I can only find ways to order by Ascending or Descending values.

My enum:

public enum AnimalSize
    {
        Small = 1, Medium = 3, Large = 5,
    }

My Animal class:

public class Animal : IComparable<Animal>
{
    public bool IsCarnivore;
    public AnimalSize Size;

    public Animal(bool isCarnivore, AnimalSize size)
    {
        this.IsCarnivore = isCarnivore;
        this.Size = size;
    }

    public int CompareTo(Animal other)
    {
        return this.Size.CompareTo(other.Size);
    }

I call the CompareTo from another class where I have a private list of animals.

How can I arrange the animals in order of Medium, Large, Small?

Body:
You could create a custom Comparer<Animal>:

public class AnimalSizeComparer : Comparer<Animal>
{
    private readonly IList<AnimalSize> _order;

    public AnimalSizeComparer():this(Enum.GetValues(typeof(AnimalSize)).Cast<AnimalSize>().ToArray())
    {
    }
    public AnimalSizeComparer(IList<AnimalSize> order)
    {
        _order = order;
    }

    public override int Compare(Animal x, Animal y)
    {
        if (x == null && y == null) return 0;
        if (x == null) return -1;
        if (y == null) return 1;

        return _order.IndexOf(x.Size).CompareTo(_order.IndexOf(y.Size));
    }
}

You initialize it with your sample order in this way:

var comparer = new AnimalSizeComparer(new[] { AnimalSize.Medium, AnimalSize.Large, AnimalSize.Small });
yourAminalList.Sort(comparer);


问:
Count the occurrence of one vector's values in another vector including non match values in R
I have 2 vectors:

```<code>v1 <- c(1, 2, 3, 4, 1, 3, 5, 6, 4)
v2 <- c(1, 2, 3, 4, 5, 6, 7)
</code>```

I want to calculate the occurrence of values of v1 in v2. The expected result is:

```<code>1 2 3 4 5 6 7
2 1 2 2 1 1 0
</code>```

I know there is a function can do this:

```<code>table(v1[v1 %in% v2])
</code>```

However, it only list the matched values:

```<code>1 2 3 4 5 6
2 1 2 2 1 1
</code>```

How can I show all the values in v2?

答:
You can do</p>

```<code>table(factor(v1, levels=unique(v2)))
# 1 2 3 4 5 6 7
# 2 1 2 2 1 1 0
</code>```

Body:
I have 2 vectors:

v1 <- c(1, 2, 3, 4, 1, 3, 5, 6, 4)
v2 <- c(1, 2, 3, 4, 5, 6, 7)

I want to calculate the occurrence of values of v1 in v2. The expected result is:

1 2 3 4 5 6 7
2 1 2 2 1 1 0

I know there is a function can do this:

table(v1[v1 %in% v2])

However, it only list the matched values:

1 2 3 4 5 6
2 1 2 2 1 1

How can I show all the values in v2?

Body:
You can do

table(factor(v1, levels=unique(v2)))
# 1 2 3 4 5 6 7
# 2 1 2 2 1 1 0


问:
Partial regular expression match
I have a regular expression that I'm testing a input stream of characters. I wonder if there is a way to  match the regular expression against the input and determine if it is a partial match that consumes the entire input buffer? I.e. the end of the input buffer is reached before the regexp completes. I would like the implementation to decide whether to wait for more input characters, or abort the operation.

In other words, I need to determine which one is true:

The end of the input buffer was reached before the regexp was matched

E.g. "foo" =~ /^foobar/

The regular expression matches completely

E.g. "foobar" =~ /^foobar/

The regular expression failed to match

E.g. "fuubar" =~ /^foobar

The input is not packetized.

答:
I'm not sure if this is your question but.

Regular expressions either match or not. And the expression will match a variable amount   of input. So, it can't be determined directly.

However, it is possible, if you believe there is a possibility of overlap, to use a smart  buffering scheme to accomplish the same thing.

There are many ways to do this.

One way is to match all that does not match via assertions, up until you get the start
of a match (but not the full match you seek).
These you simple throw away and clear from your buffer. When you get a match you seek,   clear the buffer of that data and data before it.

Example: /(<function.*?>)|([^<]*)/ The part you throw away/clear from the buffer is in group 2 capture buffer.

Another way is if you are matching finite length strings, if you don't match anything in
the buffer, you can safely throw away all from the beginning of the buffer to the end of the buffer minus the length of the finite string you are searching for.

Example: Your buffer is 64k in size. You are searching for a string of length 10. It was not found in the buffer. You can safely clear (64k - 10) bytes, retaining the last 10 bytes. Then append (64k-10) bytes to the end of the buffer. Of course you only need a buffer of size 10 bytes, constantly removing/adding 1 character but a larger buffer is more
efficient and you could use thresholds to reload more data.

If you can create a buffer that easily contracts/expands, more buffering options are available.

Title: Partial regular expression match


问:
How do you find the average of a dictionary?
So let's say I have this dictionary

```<code>{'Taylor Swift': ['Kanye West']}
</code>```

I would expect 1.0 from this as there is one value (which is 'Kanye West') divided by one key (which is 'Taylor Swift') to get the average of 1.0.

And let's say I have this dictionary

```<code>{'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler': ['Johnny Depp', 'Tom Hanks']}
</code>```

I would expect the average of 2.0 from this as there are 4 values divided by 2 keys.

This is the code I have tried:

```<code>average = 0
sum = 0
for n in data:
    sum = sum + n
average = sum / len(data)
</code>```

I have tried many other ways too through online search and the common error I get is this:

```<code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code>```

答:
Get the length of values first and divide it by the length of keys.

```<code>sum(len(i) for i in data.values())/float(len(data.keys()))
</code>```

and this gives the same result as well,

```<code>sum(len(i) for i in x.values())/float(len(x))
</code>```

Body:
So let's say I have this dictionary

{'Taylor Swift': ['Kanye West']}

I would expect 1.0 from this as there is one value (which is 'Kanye West') divided by one key (which is 'Taylor Swift') to get the average of 1.0.

And let's say I have this dictionary

{'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler': ['Johnny Depp', 'Tom Hanks']}

I would expect the average of 2.0 from this as there are 4 values divided by 2 keys.

This is the code I have tried:

average = 0
sum = 0
for n in data:
    sum = sum + n
average = sum / len(data)

I have tried many other ways too through online search and the common error I get is this:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Body:
Get the length of values first and divide it by the length of keys.

sum(len(i) for i in data.values())/float(len(data.keys()))

and this gives the same result as well,

sum(len(i) for i in x.values())/float(len(x))


问:
Exclude a WooCommerce product category from a WP_Query
I've got the following args defined as a part of my query:

```<code>$args = apply_filters('woocommerce_related_products_args', array(
        'post_type'             => 'product',
        'author'                => $artist,
        'post_status'           => 'publish',
        'meta_query'            => array(
            array(
                'key'           => '_visibility',
                'value'         => array('catalog', 'visible'),
                'compare'       => 'IN'
        )
    )
) );
$products = new WP_Query( $args );
</code>```

I need to exclude a category called Magazines (slug "magazines") or ID 351 from the query.

I've been trying to include 'category__not_in' => array('magazines'), so it looks like this:

```<code>$args = apply_filters('woocommerce_related_products_args', array(
            'post_type'             => 'product',
            'author'                => $artist,
            'post_status'           => 'publish',
            'category__not_in'      => array('magazines'),
            'meta_query'            => array(
                array(
                    'key'           => '_visibility',
                    'value'         => array('catalog', 'visible'),
                    'compare'       => 'IN'
            )
        )
    ) );
    $products = new WP_Query( $args );
</code>```

But that just doesn't seem to be working.

What am I doing wrong here?

答:
Product categories are a custom taxonomy product_cat.

So you need to do it in a simple tax_query this way:

```<code>$args = apply_filters('woocommerce_related_products_args',
    array(
        'post_type'             => 'product',
        'author'                => $artist,
        'post_status'           => 'publish',
        'meta_query'            => array(
             array(
                'key'           => '_visibility',
                'value'         => array('catalog', 'visible'),
                'compare'       => 'IN'
            ),
        ),
        'tax_query'            => array(
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug', // Or 'name' or 'term_id'
                'terms'    => array('magazines'),
                'operator' => 'NOT IN', // Excluded
            )
        )
    )
);

$products = new WP_Query( $args );
</code>```

Body:
I've got the following args defined as a part of my query:

$args = apply_filters('woocommerce_related_products_args', array(
        'post_type'             => 'product',
        'author'                => $artist,
        'post_status'           => 'publish',
        'meta_query'            => array(
            array(
                'key'           => '_visibility',
                'value'         => array('catalog', 'visible'),
                'compare'       => 'IN'
        )
    )
) );
$products = new WP_Query( $args );

I need to exclude a category called Magazines (slug "magazines") or ID 351 from the query.

I've been trying to include 'category__not_in' => array('magazines'), so it looks like this:

$args = apply_filters('woocommerce_related_products_args', array(
            'post_type'             => 'product',
            'author'                => $artist,
            'post_status'           => 'publish',
            'category__not_in'      => array('magazines'),
            'meta_query'            => array(
                array(
                    'key'           => '_visibility',
                    'value'         => array('catalog', 'visible'),
                    'compare'       => 'IN'
            )
        )
    ) );
    $products = new WP_Query( $args );

But that just doesn't seem to be working.

What am I doing wrong here?

Body:
Product categories are a custom taxonomy product_cat.

So you need to do it in a simple tax_query this way:

$args = apply_filters('woocommerce_related_products_args',
    array(
        'post_type'             => 'product',
        'author'                => $artist,
        'post_status'           => 'publish',
        'meta_query'            => array(
             array(
                'key'           => '_visibility',
                'value'         => array('catalog', 'visible'),
                'compare'       => 'IN'
            ),
        ),
        'tax_query'            => array(
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug', // Or 'name' or 'term_id'
                'terms'    => array('magazines'),
                'operator' => 'NOT IN', // Excluded
            )
        )
    )
);

$products = new WP_Query( $args );


问:
How to show the content of a list in a second table once the first table has no more space
I want to pull data from DB and list it in a table.
The screen size is fixed and they shall not be extended(no scrolling).
Once there is no more "space" for table1, I want that the following items to be listed on a sided table2. So I don't want that the screen gets extended, scrolled.

This is how my code is.

```<code><html>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-6">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="background-color: transparent">TIME</th>
                            <th style="background-color: transparent">LOCATION</th>
                            <th style="background-color: transparent">MESSAGE</th>
                        </tr>
                    </thead>
                </table>
            </div>
            <div class="col-md-6">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="background-color: transparent">TIME</th>
                            <th style="background-color: transparent">LOCATION</th>
                            <th style="background-color: transparent">MESSAGE</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>
</body>
</code>```

This picture shows how I want my implementation:

Thanks in advance.

答:
I'd like you to try this "column-count"-techique:

```<code>div {
  column-count: 4;
  column-width: 150px;
  column-rule: 1px solid slategrey;
}
</code>```

https://codepen.io/rinatoptimus/pen/qqgBMN

Body:
I want to pull data from DB and list it in a table.
The screen size is fixed and they shall not be extended(no scrolling).
Once there is no more "space" for table1, I want that the following items to be listed on a sided table2. So I don't want that the screen gets extended, scrolled.

This is how my code is.

                            TIME
                            LOCATION
                            MESSAGE

                            TIME
                            LOCATION
                            MESSAGE

This picture shows how I want my implementation:

Thanks in advance.

Body:
I'd like you to try this "column-count"-techique:

div {
  column-count: 4;
  column-width: 150px;
  column-rule: 1px solid slategrey;
}

https://codepen.io/rinatoptimus/pen/qqgBMN


问:
Unable to center content of a div
I'm creating a table with divs. I'm able to create it, but there is this instance where in there is a row where I need to do a merge and center.

Here is my code.

.divTable {
  display: table;
  width: 100%;
}

.divTableRow {
  display: table-row;
}

.divTableCell {
  border: 1px solid #999999;
  display: table-cell;
  padding: 3px 10px;
}

.divTableBody {
  display: table-row-group;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="divTable">
  <div class="divTableBody">
    <div class="divTableRow">
      <div class="divTableCell">$2</div>
      <div class="divTableCell">1</div>
    </div>
    <div class="divTableRow">
      <div class="divTableCell"> 6</div>
    </div>
  </div>
</div></code>```

Here I want 6 to be in center. How can I achieve this?

basically like below table

```<code><table border="1px solid black">
  <tr>
    <td>$2</td>
    <td>1</td>
  </tr>
  <tr>
    <td colspan="2" align="center">6</td>
  </tr>
</table>
</code>```

答:
There is no colspan in CSS.
(html-colspan-in-css)

A solution

.tr {
  width: 100%;
}

.tr:after {
  content: " ";
  display: table;
  clear: both;
}

.td {
  border: 1px solid;
  float: left;
  box-sizing: border-box;
  padding: 3px 10px;
}

.col-6 {
  width: 50%;
}

.col-12 {
  width: 100%;
}

.text-center {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="table">
  <div class="tbody">
    <div class="tr">
      <div class="td col-6">$2</div>
      <div class="td col-6">1</div>
    </div>
    <div class="tr">
      <div class="td col-12 text-center">6</div>
    </div>
  </div>
</div></code>```

Bootstraps' grid layout provides that.

Bootstrap solution

.bordered>div[class^=col-] {
  border: 1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container">
  <div class="row bordered">
    <div class="col-xs-6">A</div>
    <div class="col-xs-6">B</div>
  </div>
  <div class="row bordered">
    <div class="col-xs-12 text-center">C</div>
  </div>
</div></code>```

Title: Unable to center content of a div

Body:
I'm creating a table with divs. I'm able to create it, but there is this instance where in there is a row where I need to do a merge and center.

Here is my code.

.divTable {
  display: table;
  width: 100%;
}

.divTableRow {
  display: table-row;
}

.divTableCell {
  border: 1px solid #999999;
  display: table-cell;
  padding: 3px 10px;
}

.divTableBody {
  display: table-row-group;
}

$2

1

 6

Here I want 6 to be in center. How can I achieve this?

basically like below table

    $2
    1

    6

Body:
There is no colspan in CSS.
(html-colspan-in-css)

A solution

.tr {
  width: 100%;
}

.tr:after {
  content: " ";
  display: table;
  clear: both;
}

.td {
  border: 1px solid;
  float: left;
  box-sizing: border-box;
  padding: 3px 10px;
}

.col-6 {
  width: 50%;
}

.col-12 {
  width: 100%;
}

.text-center {
  text-align: center;
}

<div class="table">
  <div class="tbody">
    <div class="tr">
      <div class="td col-6">$2</div>
      <div class="td col-6">1</div>
    </div>
    <div class="tr">
      <div class="td col-12 text-center">6</div>
    </div>
  </div>
</div>

Bootstraps' grid layout provides that.

Bootstrap solution

.bordered>div[class^=col-] {
  border: 1px solid;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container">
  <div class="row bordered">
    <div class="col-xs-6">A</div>
    <div class="col-xs-6">B</div>
  </div>
  <div class="row bordered">
    <div class="col-xs-12 text-center">C</div>
  </div>
</div>


问:
How to have Mysql query (with multiple join) faster and more efficient
I have a big problem with the execution of a MySql query that is very slow.. too slow... unusable!

To read 1000 products with their prices it takes more than 20 seconds!!!

```<code>$dati = mysqli_query($mysqli_connect, "
SELECT      *
FROM        $tb_products
LEFT JOIN   $tb_categories ON $tb_products.product_category = $tb_categories.category_id_master
LEFT JOIN   $tb_subcategories ON $tb_products.product_subcategory = $tb_subcategories.subcategory_id_master
LEFT JOIN   $tb_logos ON $tb_products.product_logo = $tb_logos.logo_id_master

LEFT JOIN   $tb_prices ON (
            $tb_products.product_brand = $tb_prices.price_brand
            AND $tb_products.product_code = $tb_prices.price_code
            AND $tb_prices.price_validity = (
                SELECT  MAX($tb_prices.price_validity)
                FROM    $tb_prices
                WHERE   $tb_prices.price_validity<=DATE_ADD(CURDATE(), INTERVAL +0 DAY)
                        AND $tb_products.product_code = $tb_prices.price_code
            )
        )

WHERE       $tb_products.product_language='$activeLanguage' AND $tb_products.product_category!=0
GROUP BY    $tb_products.product_code
ORDER BY    $tb_products.product_brand, $tb_categories.category_rank, $tb_subcategories.subcategory_rank, $tb_products.product_subcategory, $tb_products.product_rank
");
</code>```

EDIT:

I've changed, as suggested from Mr.Alvaro, the SELECT * with a more efficient SELECT [list of values] and the execution time dropped from 20 seconds to 14 seconds. Still too slow...

END EDIT

Each product can have different prices, so I use the (select max...) to take the most recent (but not future) price.
Maybe is this function that slow down everything? Are there better solutions in your opinion?

Consider that the same query without the join with the prices it takes only 0.2 seconds.
So I'm convinced that the problem is all in that part of the code.

```<code>$dati = mysqli_query($mysqli_connect, "
SELECT      *
FROM        $tb_products
LEFT JOIN   $tb_categories ON $tb_products.product_category = $tb_categories.category_id_master
LEFT JOIN   $tb_subcategories ON $tb_products.product_subcategory = $tb_subcategories.subcategory_id_master
LEFT JOIN   $tb_logos ON $tb_products.product_logo = $tb_logos.logo_id_master

WHERE       $tb_products.product_language='$activeLanguage' AND $tb_products.product_category!=0
GROUP BY    $tb_products.product_code
ORDER BY    $tb_products.product_brand, $tb_categories.category_rank, $tb_subcategories.subcategory_rank, $tb_products.product_subcategory, $tb_products.product_rank
");
</code>```

I also considered the fact that it could depend on the power of the server but I would tend to exclude it because the second query (without prices) is quite acceptable as speed.

The prices table is as following

```<code>+----------------+-------------+
| price_id       | int(3)      |
| price_brand    | varchar(5)  |
| price_code     | varchar(50) |
| price_value    | float(10,2) |
| price_validity | date        |
| price_language | varchar(2)  |
+----------------+-------------+
</code>```

答:
Maybe is because you are using SELECT *, this is known as bad practice.  Check this question in stack overflow.

Is there a difference between Select * and Select [list each col]

There, Mitch Wheat wrote:

You should specify an explicit column list. SELECT * will bring back more columns than you need creating more IO and network traffic, but more importantly it might require extra lookups even though a non-clustered covering index exists (On SQL Server).
  Blockquote

Body:
I have a big problem with the execution of a MySql query that is very slow.. too slow... unusable!

To read 1000 products with their prices it takes more than 20 seconds!!!

$dati = mysqli_query($mysqli_connect, "
SELECT      *
FROM        $tb_products
LEFT JOIN   $tb_categories ON $tb_products.product_category = $tb_categories.category_id_master
LEFT JOIN   $tb_subcategories ON $tb_products.product_subcategory = $tb_subcategories.subcategory_id_master
LEFT JOIN   $tb_logos ON $tb_products.product_logo = $tb_logos.logo_id_master

LEFT JOIN   $tb_prices ON (
            $tb_products.product_brand = $tb_prices.price_brand
            AND $tb_products.product_code = $tb_prices.price_code
            AND $tb_prices.price_validity = (
                SELECT  MAX($tb_prices.price_validity)
                FROM    $tb_prices
                WHERE   $tb_prices.price_validity<=DATE_ADD(CURDATE(), INTERVAL +0 DAY)
                        AND $tb_products.product_code = $tb_prices.price_code
            )
        )

WHERE       $tb_products.product_language='$activeLanguage' AND $tb_products.product_category!=0
GROUP BY    $tb_products.product_code
ORDER BY    $tb_products.product_brand, $tb_categories.category_rank, $tb_subcategories.subcategory_rank, $tb_products.product_subcategory, $tb_products.product_rank
");

EDIT:

I've changed, as suggested from Mr.Alvaro, the SELECT * with a more efficient SELECT [list of values] and the execution time dropped from 20 seconds to 14 seconds. Still too slow...

END EDIT

Each product can have different prices, so I use the (select max...) to take the most recent (but not future) price.
Maybe is this function that slow down everything? Are there better solutions in your opinion?

Consider that the same query without the join with the prices it takes only 0.2 seconds.
So I'm convinced that the problem is all in that part of the code.

$dati = mysqli_query($mysqli_connect, "
SELECT      *
FROM        $tb_products
LEFT JOIN   $tb_categories ON $tb_products.product_category = $tb_categories.category_id_master
LEFT JOIN   $tb_subcategories ON $tb_products.product_subcategory = $tb_subcategories.subcategory_id_master
LEFT JOIN   $tb_logos ON $tb_products.product_logo = $tb_logos.logo_id_master

WHERE       $tb_products.product_language='$activeLanguage' AND $tb_products.product_category!=0
GROUP BY    $tb_products.product_code
ORDER BY    $tb_products.product_brand, $tb_categories.category_rank, $tb_subcategories.subcategory_rank, $tb_products.product_subcategory, $tb_products.product_rank
");

I also considered the fact that it could depend on the power of the server but I would tend to exclude it because the second query (without prices) is quite acceptable as speed.

The prices table is as following

+----------------+-------------+
| price_id       | int(3)      |
| price_brand    | varchar(5)  |
| price_code     | varchar(50) |
| price_value    | float(10,2) |
| price_validity | date        |
| price_language | varchar(2)  |
+----------------+-------------+


问:
Zip and unzip files
I am a programmer using VS2012. I am wanting to unzip a zip file (made with Winzip, filzip or other zip compression routines) and then also be able to zip the files back up into a zip file.

What is the best library to use for this and can I please have some sample code on how to use the library?

EDIT

I am using VB.net, here is my code:

```<code>Public Function extractZipArchive() As Boolean
    Dim zipPath As String = "c:\example\start.zip"
    Dim extractPath As String = "c:\example\extract"

    Using archive As ZipArchive = ZipFile.OpenRead(zipPath)
        For Each entry As ZipArchiveEntry In archive.Entries
            If entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) Then
                entry.ExtractToFile(Path.Combine(extractPath, entry.FullName))
            End If
        Next
    End Using
End Function
</code>```

What import statements do I need to use?
Currently I have added the following:

```<code>Imports System.IO
Imports System.IO.Compression
</code>```

I am getting the error:

Type 'ZipArchive' is not defined

How can I fix this error?

答:
As mentioned in https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile(v=vs.110).aspx

You can use ZipFile.ExtractToDirectory and CreateFromDirectory

This is the example:

Imports System.IO

Imports System.IO.Compression

Module Module1

Sub Main()

```<code>   Dim startPath As String = "c:\example\start"
   Dim zipPath As String = "c:\example\result.zip"
   Dim extractPath As String = "c:\example\extract"

   ZipFile.CreateFromDirectory(startPath, zipPath)
   ZipFile.ExtractToDirectory(zipPath, extractPath)
</code>```

End Sub

End Module

Make sure you have referenced System.IO.Compression.FileSystem for using this function.

Title: Zip and unzip files

Body:
I am a programmer using VS2012. I am wanting to unzip a zip file (made with Winzip, filzip or other zip compression routines) and then also be able to zip the files back up into a zip file.

What is the best library to use for this and can I please have some sample code on how to use the library?

EDIT

I am using VB.net, here is my code:

Public Function extractZipArchive() As Boolean
    Dim zipPath As String = "c:\example\start.zip"
    Dim extractPath As String = "c:\example\extract"

    Using archive As ZipArchive = ZipFile.OpenRead(zipPath)
        For Each entry As ZipArchiveEntry In archive.Entries
            If entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) Then
                entry.ExtractToFile(Path.Combine(extractPath, entry.FullName))
            End If
        Next
    End Using
End Function

What import statements do I need to use?
Currently I have added the following:

Imports System.IO
Imports System.IO.Compression

I am getting the error:

Type 'ZipArchive' is not defined

How can I fix this error?

Body:
As mentioned in https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile(v=vs.110).aspx

You can use ZipFile.ExtractToDirectory and CreateFromDirectory

This is the example:

Imports System.IO

Imports System.IO.Compression

Module Module1

Sub Main()

   Dim startPath As String = "c:\example\start"
   Dim zipPath As String = "c:\example\result.zip"
   Dim extractPath As String = "c:\example\extract"

   ZipFile.CreateFromDirectory(startPath, zipPath)
   ZipFile.ExtractToDirectory(zipPath, extractPath)

End Sub

End Module

Make sure you have referenced System.IO.Compression.FileSystem for using this function.


问:
How to create threads in nodejs
Is there any way to create threads for running multiple methods at a time?

That way, if any method fails in between all the other threads should be killed.

答:
I needed real multithreading in Node.js and what worked for me was the threads package. It spawns another process having it's own Node.js message loop, so they don't block each other. The setup is easy and the documentation get's you up and running fast. Your main program and the workers can communicate in both ways and worker "threads" can be killed if needed.

Since multithreading and Node.js is a complicated and widely discussed topic it was quite difficult to find a package that works for my specific requirement. For the record these did not work for me:

tiny-worker allowed spawning workers, but they seemed to share the same message loop (but it might be I did something wrong - threads had more documentation giving me confidence it really used multiple processes, so I kept going until it worked)

webworker-threads didn't allow require-ing modules in workers which I needed

And for those asking why I needed real multi-threading: For an application involving the Raspberry Pi and interrupts. One thread is handling those interrupts and another takes care of storing the data (and more).

ContentLicense: CC BY-SA 4.0

Title: How to create threads in nodejs


问:
How do I assign a value, to a 2D array location in C?
So I'm quite a newbie, so please go soft.

I have created a 2D array, 60x30 and want to display it on the screen as a grid, by doing a double for loop. I am using a simple character '.' for each slot of the grid just for a test.

```<code>char FrameBuffer[29][59];
for (int i = 0; i <= 29; i++)
{
    for (int j = 0; j <= 59; j++)
    {
        FrameBuffer[i, j] = '.';
        printf("%c ", FrameBuffer[i,j]);
    }
    printf("\n");
}
</code>```

However, whenever I try and assign a value to a position in my 2D array, e.g.

```<code>FrameBuffer[0,1] = '.',
</code>```

I am greeted with an error:

```<code>Expression must be a modifiable lvalue
</code>```

答:
FrameBuffer[i,j] = '.';

printf("%c ", FrameBuffer[i,j]);

modify these two statements to

```<code>FrameBuffer[i][j] = '.';

printf("%c ", FrameBuffer[i][j]);
</code>```

[i,j] means nothing to the compiler. It's nothing but an invalid syntax.

also correct you array.

FrameBuffer[29][59]it is an array of row=29 and col=59

change it to FrameBuffer[60][30];

Body:
So I'm quite a newbie, so please go soft.

I have created a 2D array, 60x30 and want to display it on the screen as a grid, by doing a double for loop. I am using a simple character '.' for each slot of the grid just for a test.

char FrameBuffer[29][59];
for (int i = 0; i <= 29; i++)
{
    for (int j = 0; j <= 59; j++)
    {
        FrameBuffer[i, j] = '.';
        printf("%c ", FrameBuffer[i,j]);
    }
    printf("\n");
}

However, whenever I try and assign a value to a position in my 2D array, e.g.

FrameBuffer[0,1] = '.',

I am greeted with an error:

Expression must be a modifiable lvalue

Body:
FrameBuffer[i,j] = '.';

printf("%c ", FrameBuffer[i,j]);

modify these two statements to

FrameBuffer[i][j] = '.';

printf("%c ", FrameBuffer[i][j]);

[i,j] means nothing to the compiler. It's nothing but an invalid syntax.

also correct you array.

FrameBuffer[29][59]it is an array of row=29 and col=59

change it to FrameBuffer[60][30];


问:
Is there a benefit to padding with random data in AES encryption?
When using AES encryption, plaintext must be padded to the cipher block size.  Most libraries and standards use padding where the padding bytes can be determined from the unpadded plaintext length.  Is there a benefit to using random padding bytes when possible?

I'm implementing a scheme for storing sensitive per-user and per-session data.  The data will usually be JSON-encoded key-value pairs, and can be potentially short and repetitive.  I'm looking to PKCS#5 for guidance, but I planned on using AES for the encryption algorithm rather than DES3.  I was planning on a random IV per data item, and a key determined by the user ID and password or a session ID, as appropriate.

One thing that surprised me is the PKCS#5 padding scheme for the plaintext.  To pad the ciphertext to 8-byte blocks, 1 to 8 bytes are added at the end, with the padding byte content reflecting the number of padding bytes (i.e. 01, 0202, 030303, up to 0808080808080808).  My own padding scheme was to use random bytes at the front of the plaintext, and the last character of the plaintext would be the number of padding bytes added.

My reasoning was that in AES-CBC mode, each block is a function of the ciphertext of the preceding block.  This way, each plaintext would have an element of randomness, giving me another layer of protection from known plaintext attacks, as well as IV and key issues.  Since my plaintext is expected to be short, I don't mind holding the whole decrypted string in memory, and slicing padding off the front and back.

One drawback would be the same unpadded plaintext, IV, and key would result in different ciphertext, making unit testing difficult (but not impossible - I can use a pseudo-random padding generator for testing, and a cryptographically strong one for production).

Another would be that, to enforce random padding, I'd have to add a minimum of two bytes - a count and one random byte.  For deterministic padding, the minimum is one byte, either stored with the plaintext or in the ciphertext wrapper.

Since a well-regarded standard like PKCS#5 decided to use deterministic padding, I'm wondering if there is something else I missed, or I'm judging the benefits too high.

答:
Both, I suspect. The benefit is fairly minimal.

You have forgotten about the runtime cost of acquiring or generating cryptographic-quality random numbers. at one extreme, when a finite supply of randomness is available (/dev/random on some systems for instance), your code may have to wait a long time for more random bytes.

At the other extreme, when you are getting your random bytes from a PRNG, you could expose yourself to problems if you're using the same random source to generate your keys. If you're sending encrypted data to multiple recipients one after another, you have given the previous recipient a whole bunch of information about the state of the PRNG which will be used to pick the key for your next comms session. If your PRNG algorithm is ever broken, which is IMO more likely than a good plaintext attack on full AES, you're much worse off than if you had used deliberately-deterministic padding.

In either case, however you get the padding, it's more computationally intensive than PKCS#5 padding.

As an aside, it is fairly standard to compress potentially-repetitive data with e.g. deflate before encrypting it; this reduces the redundancy in the data, which can make certain attacks more difficult to perform.

One last recommendation: deriving the key with a mechanism in which only the username and password vary is very dangerous. If you are going to use it, make sure you use a Hash algorithm with no known flaws (not SHA-1, not MD-5). cf this slashdot story

Hope this helps.


问:
const correctness and member reference
I have the following class:

```<code>class DataBuilder
{
public:
    DataBuilder(Data& data): data_(data){}

    //Fun modify data_, uses private methods
    void Fun(std::string name, int id) //const ?
    {
        //calculate newInfo based on params (uses private methods)
        auto& info = data_.GetInfo();
        info = newInfo;
    }
private:
    //some private methods
    Data& data_;
};
</code>```

Theoretically Fun can be const but I wonder if it is correct (logical constness) ?

Edit1 I added a very simplified Fun implementation.
Edit2 Data has two GetInfo overloads:

```<code>Info& Data::GetInfo();
const Info& Data::GetInfo() const;
</code>```

答:
const in this context means "does not modify the object", which is enforced by treating the implicit this as pointer-to-const. For this reason it is common to see overloads like

```<code>Data       & getData();
Data const & getData() const;
</code>```

This preserves the constness of the calling context, and allows for modifying the Data when called in a non-const context.

In your case, you don't have a Info & Data::getInfo const; (which would be rather suspect, where does const Data get a non-const Info from?) Fun is modifying the data_ member of DataBuilder.

Aside:
I would write the assignment as data.GetInfo() = newInfo;

Title: const correctness and member reference

Body:
I have the following class:

class DataBuilder
{
public:
    DataBuilder(Data& data): data_(data){}

    //Fun modify data_, uses private methods
    void Fun(std::string name, int id) //const ?
    {
        //calculate newInfo based on params (uses private methods)
        auto& info = data_.GetInfo();
        info = newInfo;
    }
private:
    //some private methods
    Data& data_;
};

Theoretically Fun can be const but I wonder if it is correct (logical constness) ?

Edit1 I added a very simplified Fun implementation.
Edit2 Data has two GetInfo overloads:

Info& Data::GetInfo();
const Info& Data::GetInfo() const;

Body:
const in this context means "does not modify the object", which is enforced by treating the implicit this as pointer-to-const. For this reason it is common to see overloads like

Data       & getData();
Data const & getData() const;

This preserves the constness of the calling context, and allows for modifying the Data when called in a non-const context.

In your case, you don't have a Info & Data::getInfo const; (which would be rather suspect, where does const Data get a non-const Info from?) Fun is modifying the data_ member of DataBuilder.

Aside:
I would write the assignment as data.GetInfo() = newInfo;


问:
R: Dplyr 'group_by' does not seem to work in Shiny
I just started experimenting with Shiny and I have a problem getting the dplyr 'group_by' function to work.

My general idea is that I have a dataset with a number of numerical variables and a variable by which these variables can be grouped (in my case 19 countries, so a variable ranging from 1 to 19).
Now I want to run a meta-analysis using the metafor package on the correlation between two variables for each country.
So I want to calculate the correlation between the two selected variables for each country separately and then put these together in a meta-analysis and finally show a forest plot of these effects.

I have used the mtcars dataset as an example for how far I have come:

UI:

```<code>library(shiny)
library(metafor)
library(dplyr)

ui <- fluidPage(
  sidebarPanel(

    selectInput("x", label = "Choose Variable I",
    choices = c("Displacement (cu.in.)", "Horsepower", "Rear axle ratio",
    "Weight (1000lbs)", "1/4 mile time"), selected = "Displacement (cu.in.)"),

    selectInput("y", label = "Choose Variable II",
    choices = c("Displacement (cu.in.)", "Horsepower", "Rear axle ratio",
    "Weight (1000lbs)", "1/4 mile time"), selected = "Horsepower")
  ),

  mainPanel(
    plotOutput(outputId = "plot")
    )
  )
</code>```

SERVER:

```<code> server <- function(input, output) {

  output$plot <-renderPlot({

    data_x <- switch(input$x,
                     "Displacement (cu.in.)" = mtcars$disp,
                     "Horsepower" = mtcars$hp,
                     "Rear axle ratio" = mtcars$drat,
                     "Weight (1000lbs)" = mtcars$wt,
                     "1/4 mile time" = mtcars$qsec)

    data_y <- switch(input$y,
                     "Displacement (cu.in.)" = mtcars$disp,
                     "Horsepower" = mtcars$hp,
                     "Rear axle ratio" = mtcars$drat,
                     "Weight (1000lbs)" = mtcars$wt,
                     "1/4 mile time" = mtcars$qsec)

    meta_main <- mtcars %>%
      group_by(gear) %>%
      summarise(participantID = n(),
                correlation = cor(data_x, data_y, use = "complete.obs"))

    meta <- rma(ni=participantID, ri=correlation,
                method="REML", measure="COR", data=meta_main)

    forest(meta)

  })

}

shinyApp(ui = ui, server = server)
</code>```

In the example I have grouped by 'gear' (which has 3 levels) and selected the variables 'Displacement', 'Horsepower', 'Rear axle ratio', 'Weight', and '1/4 mile time'.

The final output shows the selection widgets and also the forest plot.
However, the correlation is the same for all levels of 'gear'. I therefore suspect that the 'group_by' function does not work as intended.

I have tried to use 'group_by_' as suggested online, but it does not change much.

Any ideas on how 'group_by' might work with Shiny?

答:
try this server function, first you should load lazyeval package.

```<code>server <- function(input, output) {

output$plot <-renderPlot({

data_x <- switch(input$x,
                 "Displacement (cu.in.)" = "disp",
                 "Horsepower" = "hp",
                 "Rear axle ratio" = "drat",
                 "Weight (1000lbs)" = "wt",
                 "1/4 mile time" = "qsec")

data_y <- switch(input$y,
                 "Displacement (cu.in.)" = "disp",
                 "Horsepower" = "hp",
                 "Rear axle ratio" = "drat",
                 "Weight (1000lbs)" = "wt",
                 "1/4 mile time" = "qsec")

meta_main <- mtcars %>%
  group_by(gear) %>%
  mutate(participantID = n()) %>%
  group_by(gear, participantID) %>%
  summarise_(correlation = interp(~cor(x, y, use = "complete.obs"), x = as.name(data_x), y = as.name(data_y)))

meta <- rma(ni=participantID, ri=correlation,
            method="REML", measure="COR", data=meta_main)

forest(meta)

})

}
</code>```

Body:
I just started experimenting with Shiny and I have a problem getting the dplyr 'group_by' function to work.

My general idea is that I have a dataset with a number of numerical variables and a variable by which these variables can be grouped (in my case 19 countries, so a variable ranging from 1 to 19).
Now I want to run a meta-analysis using the metafor package on the correlation between two variables for each country.
So I want to calculate the correlation between the two selected variables for each country separately and then put these together in a meta-analysis and finally show a forest plot of these effects.

I have used the mtcars dataset as an example for how far I have come:

UI:

library(shiny)
library(metafor)
library(dplyr)

ui <- fluidPage(
  sidebarPanel(

    selectInput("x", label = "Choose Variable I",
    choices = c("Displacement (cu.in.)", "Horsepower", "Rear axle ratio",
    "Weight (1000lbs)", "1/4 mile time"), selected = "Displacement (cu.in.)"),

    selectInput("y", label = "Choose Variable II",
    choices = c("Displacement (cu.in.)", "Horsepower", "Rear axle ratio",
    "Weight (1000lbs)", "1/4 mile time"), selected = "Horsepower")
  ),

  mainPanel(
    plotOutput(outputId = "plot")
    )
  )

SERVER:

 server <- function(input, output) {

  output$plot <-renderPlot({

    data_x <- switch(input$x,
                     "Displacement (cu.in.)" = mtcars$disp,
                     "Horsepower" = mtcars$hp,
                     "Rear axle ratio" = mtcars$drat,
                     "Weight (1000lbs)" = mtcars$wt,
                     "1/4 mile time" = mtcars$qsec)

    data_y <- switch(input$y,
                     "Displacement (cu.in.)" = mtcars$disp,
                     "Horsepower" = mtcars$hp,
                     "Rear axle ratio" = mtcars$drat,
                     "Weight (1000lbs)" = mtcars$wt,
                     "1/4 mile time" = mtcars$qsec)

    meta_main <- mtcars %>%
      group_by(gear) %>%
      summarise(participantID = n(),
                correlation = cor(data_x, data_y, use = "complete.obs"))

    meta <- rma(ni=participantID, ri=correlation,
                method="REML", measure="COR", data=meta_main)

    forest(meta)

  })

}

shinyApp(ui = ui, server = server)

In the example I have grouped by 'gear' (which has 3 levels) and selected the variables 'Displacement', 'Horsepower', 'Rear axle ratio', 'Weight', and '1/4 mile time'.

The final output shows the selection widgets and also the forest plot.
However, the correlation is the same for all levels of 'gear'. I therefore suspect that the 'group_by' function does not work as intended.

I have tried to use 'group_by_' as suggested online, but it does not change much.

Any ideas on how 'group_by' might work with Shiny?

Body:
try this server function, first you should load lazyeval package.

server <- function(input, output) {

output$plot <-renderPlot({

data_x <- switch(input$x,
                 "Displacement (cu.in.)" = "disp",
                 "Horsepower" = "hp",
                 "Rear axle ratio" = "drat",
                 "Weight (1000lbs)" = "wt",
                 "1/4 mile time" = "qsec")

data_y <- switch(input$y,
                 "Displacement (cu.in.)" = "disp",
                 "Horsepower" = "hp",
                 "Rear axle ratio" = "drat",
                 "Weight (1000lbs)" = "wt",
                 "1/4 mile time" = "qsec")

meta_main <- mtcars %>%
  group_by(gear) %>%
  mutate(participantID = n()) %>%
  group_by(gear, participantID) %>%
  summarise_(correlation = interp(~cor(x, y, use = "complete.obs"), x = as.name(data_x), y = as.name(data_y)))

meta <- rma(ni=participantID, ri=correlation,
            method="REML", measure="COR", data=meta_main)

forest(meta)

})

}


问:
GATE Loading Processing Resources / Pronoun Resolution
I'm trying to load the pronomial coreference module using ANNIE (in Java) but I'm having some issues with the following code:

```<code>FeatureMap params = Factory.newFeatureMap();

params.put("resolveIt", "true");
ProcessingResource coref = (ProcessingResource) Factory.createResource("gate.creole.coref.Coreferencer", params);
Collection<ProcessingResource> processingResources = new ArrayList<ProcessingResource>();
processingResources.add(coref);
pipelineController.setPRs(processingResources);

params.clear();
params.put("sourceUrl", url); # this is the url of a test document
params.put("collectRepositioningInfo", new Boolean(true));
Document doc = (Document) Factory.createResource("gate.corpora.DocumentImpl", params);
corpus.add(doc);

pipelineController.setCorpus(corpus);
pipelineController.execute();
</code>```

After executing the pipelineController, I try to access the "MatchesAnnots" feature, or any other features, but I get an error saying Coref Warning: No annotations found for processing!. Can anyone point me in the direction of my error? Should I not be using pipelineController.setPRs()?

答:
Your code is almost correct. The document needs pre-processing usually done by the ANNIE GATE application. That's why it is complaining about "No annotations found for processing!".

In the code bellow, I first load ANNIE and then I add the Coreferencer as the last PR.

```<code>import java.io.File;
import gate.*;
import gate.creole.ConditionalSerialAnalyserController;
import gate.util.persistence.PersistenceManager;

public class CoreferencerTest {
    public static void main(String[] args) throws Exception {
        Gate.setGateHome(new File("C:\\Program Files\\GATE_Developer_8.4"));
        Gate.init();

        //load ANNIE GATE app
        Object gapp = PersistenceManager.loadObjectFromFile(
                new File(Gate.getPluginsHome(), "ANNIE/ANNIE_with_defaults.gapp"));
        ConditionalSerialAnalyserController pipelineController = (ConditionalSerialAnalyserController) gapp;

        //add Coreferencer to the end of ANNIE
        ProcessingResource coref = (ProcessingResource) Factory.createResource(
                "gate.creole.coref.Coreferencer", Utils.featureMap("resolveIt", true));
        pipelineController.add(coref);

        //execute it
        Corpus corpus = Factory.newCorpus("corpus name");
        Document doc = Factory.newDocument("Peter was driving his car.");
        corpus.add(doc);
        pipelineController.setCorpus(corpus);
        pipelineController.execute();

        //see the result
        System.err.println(doc.getFeatures().get("MatchesAnnots"));
    }
}
</code>```

Body:
I'm trying to load the pronomial coreference module using ANNIE (in Java) but I'm having some issues with the following code:

FeatureMap params = Factory.newFeatureMap();

params.put("resolveIt", "true");
ProcessingResource coref = (ProcessingResource) Factory.createResource("gate.creole.coref.Coreferencer", params);
Collection<ProcessingResource> processingResources = new ArrayList<ProcessingResource>();
processingResources.add(coref);
pipelineController.setPRs(processingResources);

params.clear();
params.put("sourceUrl", url); # this is the url of a test document
params.put("collectRepositioningInfo", new Boolean(true));
Document doc = (Document) Factory.createResource("gate.corpora.DocumentImpl", params);
corpus.add(doc);

pipelineController.setCorpus(corpus);
pipelineController.execute();

After executing the pipelineController, I try to access the "MatchesAnnots" feature, or any other features, but I get an error saying Coref Warning: No annotations found for processing!. Can anyone point me in the direction of my error? Should I not be using pipelineController.setPRs()?

Body:
Your code is almost correct. The document needs pre-processing usually done by the ANNIE GATE application. That's why it is complaining about "No annotations found for processing!".

In the code bellow, I first load ANNIE and then I add the Coreferencer as the last PR.

import java.io.File;
import gate.*;
import gate.creole.ConditionalSerialAnalyserController;
import gate.util.persistence.PersistenceManager;

public class CoreferencerTest {
    public static void main(String[] args) throws Exception {
        Gate.setGateHome(new File("C:\\Program Files\\GATE_Developer_8.4"));
        Gate.init();

        //load ANNIE GATE app
        Object gapp = PersistenceManager.loadObjectFromFile(
                new File(Gate.getPluginsHome(), "ANNIE/ANNIE_with_defaults.gapp"));
        ConditionalSerialAnalyserController pipelineController = (ConditionalSerialAnalyserController) gapp;

        //add Coreferencer to the end of ANNIE
        ProcessingResource coref = (ProcessingResource) Factory.createResource(
                "gate.creole.coref.Coreferencer", Utils.featureMap("resolveIt", true));
        pipelineController.add(coref);

        //execute it
        Corpus corpus = Factory.newCorpus("corpus name");
        Document doc = Factory.newDocument("Peter was driving his car.");
        corpus.add(doc);
        pipelineController.setCorpus(corpus);
        pipelineController.execute();

        //see the result
        System.err.println(doc.getFeatures().get("MatchesAnnots"));
    }
}