问:
Is this a valid CSS Selector?
With-respect to the following expression:

```<code>radio:focus > .approve, radio:focus > .dis-approve{/*statements...*/}
</code>```

Is it accepted by CSS interpreter/compiler?

Objective: applies iff both .approve and .dis-approves' radio-typed parents are in-focus.

答:
It is valid (see BoltClock's comment), but you'll find that it will not match anything as it has several problems:

radio isn't a valid HTML element. Did you mean input[type=radio]?

If you did mean input[type=radio], that element cannot have children, so > .approve and > .dis-approve wouldn't select anything. Did you mean + .approve and + .dis-approve, to an element next to this one?

The best way to know if your CSS works is to apply your CSS to a HTML structure which should accompany this and see what happens.

Title: Is this a valid CSS Selector?

Body:
With-respect to the following expression:

radio:focus > .approve, radio:focus > .dis-approve{/*statements...*/}

Is it accepted by CSS interpreter/compiler?

Objective: applies iff both .approve and .dis-approves' radio-typed parents are in-focus.


来源: stackexchange

问:
Trigger a Pull Request after Sprint End in jira
I'm working with Jira Server and Bitbucket Server and i'm wondering if it's possible to trigger a Pull Request automatically after a Sprint has ended ?</p>

答:
You can script behaviour like this using an add-on like Script Runner for jira.

It allows you, for example, to add custom scripts that respond to jira events, or that get executed as part of a workflow transition. From your script you can call Bitbucket's REST API. The Script Runner documentation is available here.

There is also a Script Runner add-on for Bitbucket. Depending on your needs, this might make things easier to implement.

ContentLicense: CC BY-SA 3.0


问:
React Native fixed footer
I'm trying to create a react native app that looks like an existing web app. I have a fixed footer at bottom of the window. Does anyone have an idea how this can be achieved with react native?

In the existing app it's simple:

.footer {
  position: fixed;
  bottom: 0;
}
```

答:
I found using flex to be the simplest solution.</p>

```<code><View style={{flex:1,
    justifyContent: 'space-around',
    alignItems: 'center',
    flexDirection: 'row',}}>

  <View style={{flex:8}}>
    //Main Activity
  </View>
  <View style={{flex:1}}>
    //Footer
  </View>

 </View>
</code>```

ContentLicense: CC BY-SA 4.0

Title: React Native fixed footer

Body:
I found using flex to be the simplest solution.

<View style={{flex:1,
    justifyContent: 'space-around',
    alignItems: 'center',
    flexDirection: 'row',}}>

  <View style={{flex:8}}>
    //Main Activity
  </View>
  <View style={{flex:1}}>
    //Footer
  </View>

 </View>


问:
Filtering data in R
I have a CSV of file of data that I can load in R using read.csv()

Some of the data is missing, so I want to reduce the data frame down to set that consists entirely of non-missing data, i.e. if a NULL appears anywhere, I want to exclude that column and row from the filtered data set.

I know I can probably do this fairly simply with the inbuilt R vector operations, but I am not quite sure how to do this exactly?

To make my question a little more concrete, here is a quick sample of the data so you can see what I want to do.

```<code>DocID       Anno1    Anno7  Anno8
1           7        NULL   8
2           8        NULL   3
44          10       2      3
45          6        6      6
46          1        3      4
49          3        8      5
62          4        NULL   9
63          2        NULL   4
67          11       NULL   3
91          NULL     9      7
92          NULL     7      5
93          NULL     8      8
</code>```

So given this input, I need some code that will reduce the output to this.

```<code>DocID       Anno8
44          3
45          6
46          4
49          5
</code>```

As Anno8 is the only column with non-NULL data, and there are only four rows with non-NULL data.

答:
If x is your data.frame (or matrix) then

```<code>x[ ,apply(x, 2, function(z) !any(is.na(z)))]
</code>```

Since your example uses NULL, is.na(·) will be replaced by is.null(·)

Alternatively you can look at subset(·).

OwnerDisplayName: kaybenleroll

Title: Filtering data in R

Body:
I have a CSV of file of data that I can load in R using read.csv()

Some of the data is missing, so I want to reduce the data frame down to set that consists entirely of non-missing data, i.e. if a NULL appears anywhere, I want to exclude that column and row from the filtered data set.

I know I can probably do this fairly simply with the inbuilt R vector operations, but I am not quite sure how to do this exactly?

To make my question a little more concrete, here is a quick sample of the data so you can see what I want to do.

DocID       Anno1    Anno7  Anno8
1           7        NULL   8
2           8        NULL   3
44          10       2      3
45          6        6      6
46          1        3      4
49          3        8      5
62          4        NULL   9
63          2        NULL   4
67          11       NULL   3
91          NULL     9      7
92          NULL     7      5
93          NULL     8      8

So given this input, I need some code that will reduce the output to this.

DocID       Anno8
44          3
45          6
46          4
49          5

As Anno8 is the only column with non-NULL data, and there are only four rows with non-NULL data.

Body:
If x is your data.frame (or matrix) then

x[ ,apply(x, 2, function(z) !any(is.na(z)))]

Since your example uses NULL, is.na(·) will be replaced by is.null(·)

Alternatively you can look at subset(·).

OwnerDisplayName: rguha


问:
On iOS, how can an app determine if a file is no longer being written to by another process?
My question is very similar to this one: What is the optimal way to monitor changes in a directory with a kqueue()? but I'm not satisfied with the answer there.

I have a kqueue setup to be notified when a file is copied to my app's Documents directory. Of course the notification fires as soon as the copying begins, but I want to know when it's completed. Surely there's a better way than polling modification times?

答:
Do you initiate the copying and have control over the filenames ?
Then the easiest solution could be to just copy to a temp file and then after that rename it to it's final name.that way you would know: if this file is there-it ist no longer written to. </p>

ContentLicense: CC BY-SA 2.5


问:
Export xls for a backend module in typo3
How can we implement export xls click button for a typo3 extbase backend module? My requirement is to fetch data from the database and export that datas as excel file.  Is there any documentation for the export feature? </p>

答:
The export (t3d) is a TYPO3 specific format. but aside of it you can download your data in CSV format:

go to the WEB-> List Module, select your page, start the single-table view by a click on the table name or the adjacent > (which has title-attribute: 'List only this table').

In the following view, beyond the records, you can select the visible fields.

at the top yo u have two download buttons: "Download CSV file" and "Export". With "Export" you start the usual t3d export. with "Downlad CSV file" you can download the visible fields of all records as a CSV file. That would be the nearest you can get to a complete Excel file with TYPO3 core.

If you need more you need to program it or use other tools like phpMyAdmin.


问:
How to load datasource configuration from external file in grails 3.1.8?
I am writing a grails 3.1.8 application. My datasource written in application.groovy file.

I want to load datasource configuration like username,password,DB from an external file. Is there any way to do it in grails 3+ versions.

Here is my datasource configuration in application.groovy:-

```<code>hibernate {
    cache {
        queries = false
        use_second_level_cache = true
        use_query_cache = false
        region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory'
    }
}

dataSource {
    pooled = true
    jmxExport = true
    dialect = 'org.hibernate.dialect.PostgreSQLDialect'
    driverClassName = 'org.postgresql.Driver'
    username = 'postgres'
    password = 'postgres'
    properties = {
        jmxEnabled = true
        initialSize = 5
        maxActive = 50
        minIdle = 5
        maxIdle = 25
        maxWait = 10000
        maxAge = 10 * 60000
        timeBetweenEvictionRunsMillis = 5000
        minEvictableIdleTimeMillis = 60000
        validationQuery = "SELECT 1"
        validationQueryTimeout = 3
        validationInterval = 15000
        testOnBorrow = true
        testWhileIdle = true
        testOnReturn = false
        ignoreExceptionOnPreLoad = true
        jdbcInterceptors = "ConnectionState;StatementCache(max=200)"
        defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED // safe default
        abandonWhenPercentageFull = 100 // settings are active only when pool is full
        removeAbandonedTimeout = 120
        removeAbandoned = true
        logAbandoned = false // causes stacktrace recording overhead, use only for debugging
    }
}

environments {
    development {
        dataSource {
            dbCreate = 'update'
            url = "jdbc:postgresql://localhost:5432/testdb"
            logSql = true
        }
    }
    test {
        dataSource {
            dbCreate = 'update'
            url = "jdbc:postgresql://localhost:5432/testdb"
            logSql = true
        }
    }
    production {
        dataSource {
            dbCreate = 'update'
            url = "jdbc:postgresql://localhost:5432/testdb"
            logSql = true
        }
    }
}
</code>```

答:
Here is the solution that worked for me, you can try.

This solution will work for grails 3.0+

First of all need to add following dependency:

compile 'org.grails.plugins:external-config:1.1.2'

then need to create external configuration groovy file for example:

db-config.groovy

then need to place that config file into outside of the application directory or tomcat library. for example:

D:\apache-tomcat-8.0.47\lib

Then need to read config file from the application.groovy .
In application.groovy need to place following line of code for each environment:

grails.config.locations = ['file:///${catalina.home}/lib/db-config.groovy']

or

grails.config.locations = ['file:///D:/apache-tomcat-8.0.47/lib/db-config.groovy']

You can use ${catalina.home} if you set the environment variable is CATALINA_HOME in your system. Other than you have to use direct path that I showed.

So your application.groovy will be following:

```<code>> environments {
>      development {
>          grails.config.locations = ['file:///${catalina.home}/lib/db-config.groovy']
>      }
>      production {
>           grails.config.locations = ['file:///${catalina.home}/lib/db-config.groovy']
>           ]
>      }
> }
</code>```

and your db-config.groovy file will contain following lines:

```<code>>     dataSource {
>       username = <DB_USER_NAME>
>       password = <DB_PASSWORD>
>       dbCreate = 'update'
>       url = <DB_URL>
>       logSql = true
>     }
</code>```

You can use different db-config.groovy file for each environment.

Body:
I am writing a grails 3.1.8 application. My datasource written in application.groovy file.

I want to load datasource configuration like username,password,DB from an external file. Is there any way to do it in grails 3+ versions.

Here is my datasource configuration in application.groovy:-

hibernate {
    cache {
        queries = false
        use_second_level_cache = true
        use_query_cache = false
        region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory'
    }
}

dataSource {
    pooled = true
    jmxExport = true
    dialect = 'org.hibernate.dialect.PostgreSQLDialect'
    driverClassName = 'org.postgresql.Driver'
    username = 'postgres'
    password = 'postgres'
    properties = {
        jmxEnabled = true
        initialSize = 5
        maxActive = 50
        minIdle = 5
        maxIdle = 25
        maxWait = 10000
        maxAge = 10 * 60000
        timeBetweenEvictionRunsMillis = 5000
        minEvictableIdleTimeMillis = 60000
        validationQuery = "SELECT 1"
        validationQueryTimeout = 3
        validationInterval = 15000
        testOnBorrow = true
        testWhileIdle = true
        testOnReturn = false
        ignoreExceptionOnPreLoad = true
        jdbcInterceptors = "ConnectionState;StatementCache(max=200)"
        defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED // safe default
        abandonWhenPercentageFull = 100 // settings are active only when pool is full
        removeAbandonedTimeout = 120
        removeAbandoned = true
        logAbandoned = false // causes stacktrace recording overhead, use only for debugging
    }
}

environments {
    development {
        dataSource {
            dbCreate = 'update'
            url = "jdbc:postgresql://localhost:5432/testdb"
            logSql = true
        }
    }
    test {
        dataSource {
            dbCreate = 'update'
            url = "jdbc:postgresql://localhost:5432/testdb"
            logSql = true
        }
    }
    production {
        dataSource {
            dbCreate = 'update'
            url = "jdbc:postgresql://localhost:5432/testdb"
            logSql = true
        }
    }
}

Body:
Here is the solution that worked for me, you can try.

This solution will work for grails 3.0+

First of all need to add following dependency:

compile 'org.grails.plugins:external-config:1.1.2'

then need to create external configuration groovy file for example:

db-config.groovy

then need to place that config file into outside of the application directory or tomcat library. for example:

D:\apache-tomcat-8.0.47\lib

Then need to read config file from the application.groovy .
In application.groovy need to place following line of code for each environment:

grails.config.locations = ['file:///${catalina.home}/lib/db-config.groovy']

or

grails.config.locations = ['file:///D:/apache-tomcat-8.0.47/lib/db-config.groovy']

You can use ${catalina.home} if you set the environment variable is CATALINA_HOME in your system. Other than you have to use direct path that I showed.

So your application.groovy will be following:

> environments {
>      development {
>          grails.config.locations = ['file:///${catalina.home}/lib/db-config.groovy']
>      }
>      production {
>           grails.config.locations = ['file:///${catalina.home}/lib/db-config.groovy']
>           ]
>      }
> }

and your db-config.groovy file will contain following lines:

>     dataSource {
>       username = <DB_USER_NAME>
>       password = <DB_PASSWORD>
>       dbCreate = 'update'
>       url = <DB_URL>
>       logSql = true
>     }

You can use different db-config.groovy file for each environment.


问:
Running Python2.7 script in C++ using #include "Python.h"
I would like to run a Python script that uses a library that only works with Python2.7 in a c++ Program.

I run this in Release mode because i don't have python27_d.lib under VS 2015.

```<code>PyObject *pName, *pModule, *pDict, *pFunc, *pValue;
Py_Initialize();
std::string name = "C:/pathToProgamm/pythonHTTPS.py"
pName = PyString_fromString(name.c_strg());
pModule = Pyimport_Import(pName);
pDict = PyModule_GetDict(pModule);
</code>```

Here I get the error python27.pdb not loaded

I tried to solve it by changing to "Only specified modules" (from "All modules, unless excluded") under Debugging->Symbols in VS 2015 but then I get
Symbol loading for python27.dll was skipped because it is not specified in the included modules list. I also tried to download the pdb file and point to it but this also doesn't work.

What I want to do is that:

```<code>if (pName = PyString_FromString(name_i.c_str()))
    {
        if (pModule = PyImport_Import(pName))
        {
            if (pDict = PyModule_GetDict(pModule))
            {
                if (pFunc = PyDict_GetItemString(pDict, NULL))
                {
                    std::cout << "success" << std::endl;
                }
                else
                {
                    std::cout << "failed pFunc" << std::endl;
                    return;
                }
            }
            else
            {
                std::cout << "failed pDict" << std::endl;
                return;
            }
        }
        else
        {
            std::cout << "failed pModule" << std::endl;
            return;
        }
    }
    else
    {
        std::cout << "failed pName" << std::endl;
        return;
    }
</code>```

but the result of this is --> failed pModule

so the error is in pModule=Pyimport_import(pName);

could anybody tell me why this fails and how to get the debugging running for my python version (2.7.14)

答:
```<code>#ifdef _DEBUG
#define _DEBUG_WAS_DEFINED 1
#undef _DEBUG
#endif

#include <Python.h>

#ifdef _DEBUG_WAS_DEFINED 1
#define _DEBUG 1
#endif
</code>```

That solved the Debugging errors for me (I still can't debug in the python script but I don't need to).

It is important to give the name of the python module without .py.

Body:
I would like to run a Python script that uses a library that only works with Python2.7 in a c++ Program.

I run this in Release mode because i don't have python27_d.lib under VS 2015.

PyObject *pName, *pModule, *pDict, *pFunc, *pValue;
Py_Initialize();
std::string name = "C:/pathToProgamm/pythonHTTPS.py"
pName = PyString_fromString(name.c_strg());
pModule = Pyimport_Import(pName);
pDict = PyModule_GetDict(pModule);

Here I get the error python27.pdb not loaded

I tried to solve it by changing to "Only specified modules" (from "All modules, unless excluded") under Debugging->Symbols in VS 2015 but then I get
Symbol loading for python27.dll was skipped because it is not specified in the included modules list. I also tried to download the pdb file and point to it but this also doesn't work.

What I want to do is that:

if (pName = PyString_FromString(name_i.c_str()))
    {
        if (pModule = PyImport_Import(pName))
        {
            if (pDict = PyModule_GetDict(pModule))
            {
                if (pFunc = PyDict_GetItemString(pDict, NULL))
                {
                    std::cout << "success" << std::endl;
                }
                else
                {
                    std::cout << "failed pFunc" << std::endl;
                    return;
                }
            }
            else
            {
                std::cout << "failed pDict" << std::endl;
                return;
            }
        }
        else
        {
            std::cout << "failed pModule" << std::endl;
            return;
        }
    }
    else
    {
        std::cout << "failed pName" << std::endl;
        return;
    }

but the result of this is --> failed pModule

so the error is in pModule=Pyimport_import(pName);

could anybody tell me why this fails and how to get the debugging running for my python version (2.7.14)

Body:
#ifdef _DEBUG
#define _DEBUG_WAS_DEFINED 1
#undef _DEBUG
#endif

#include <Python.h>

#ifdef _DEBUG_WAS_DEFINED 1
#define _DEBUG 1
#endif

That solved the Debugging errors for me (I still can't debug in the python script but I don't need to).

It is important to give the name of the python module without .py.


问:
How to define 'phi' so I don't get an error for trying to multiply a non-int by a complex number in the exponential
Using:

```<code>arr2 = np.array([np.arange(0,20)]*20,dtype=np.complex_)

for a in range(arr2.shape[0]):
 for b in range(arr2.shape[1]):
    if a-b:
        arr2[a,b] =1-(1j/np.sqrt(3))
    else:
        arr2[a,b] = np.e**(1j*phi*abs(a-b))
</code>```

to produce a matrix of size N * N which I have defined as a * b above gives the error 'TypeError: can't multiply sequence by non-int of type 'complex''.

I need to define \phi however I do not want python to solve it numerically.
I want my output to be of the form (this is just an example of the first 3 terms of the first 3 lines of the matrix where i is an imaginary number):

```<code>( 1-(i/sqrt(3)) ,    e^(i{\phi})    ,    e^(2i{\phi})  ,  ... )
( e^(i{\phi})   ,  1-(i/sqrt(3))    ,    e^(i{\phi})   ,  ... )
( e^(2i{\phi})  ,    e^(i{\phi})    ,  1-(i/sqrt(3))   ,  ... )
(     ...       ,       ...         ,      ...         ,  ... )
</code>```

instead of trying to numerically solve this matrix, is there a way to express the matrix in the general form I have displayed above? Would a simple

```<code>arr2inv = inv(np.matrix(arr2))
</code>```

return the inverse of the general form I want or produce an error?

So to summarise:

How do I define phi to remove the complex-non-int error?

How do I get python to produce the general form shown above?

Will it invert without an error?

答: Numpy and related can only handle numerical computations. If you need an output for the matrix as you describe consider using Mathematica or another equivalent symbolic manipulation software.</p>

Body:
Using:

arr2 = np.array([np.arange(0,20)]*20,dtype=np.complex_)

for a in range(arr2.shape[0]):
 for b in range(arr2.shape[1]):
    if a-b:
        arr2[a,b] =1-(1j/np.sqrt(3))
    else:
        arr2[a,b] = np.e**(1j*phi*abs(a-b))

to produce a matrix of size N * N which I have defined as a * b above gives the error 'TypeError: can't multiply sequence by non-int of type 'complex''.

I need to define \phi however I do not want python to solve it numerically.
I want my output to be of the form (this is just an example of the first 3 terms of the first 3 lines of the matrix where i is an imaginary number):

( 1-(i/sqrt(3)) ,    e^(i{\phi})    ,    e^(2i{\phi})  ,  ... )
( e^(i{\phi})   ,  1-(i/sqrt(3))    ,    e^(i{\phi})   ,  ... )
( e^(2i{\phi})  ,    e^(i{\phi})    ,  1-(i/sqrt(3))   ,  ... )
(     ...       ,       ...         ,      ...         ,  ... )

instead of trying to numerically solve this matrix, is there a way to express the matrix in the general form I have displayed above? Would a simple

arr2inv = inv(np.matrix(arr2))

return the inverse of the general form I want or produce an error?

So to summarise:

How do I define phi to remove the complex-non-int error?

How do I get python to produce the general form shown above?

Will it invert without an error?


问:
How to get multiple column's rows value in a single column?
I have two table tblCompany and tblUser
Both table contains email id fields, tblCompany contain 3 column as named contact1Email , contact2Email, contact3Email and tblUser contain a column named emailId. Unique field in both table is companyId. I want to get email of company and user's email those are belongs to that company. all those email ids I want in a single column.
I tried it in basic way using below query:

```<code>SELECT DISTINCT contact1Email , contact2Email, contact3Email, emailId
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33
</code>```

this gives bellow result as shown in image

you can see there emailId column contain user's email and contact1Email , contact2Email, contact3Email contain company email.
I want all email in single column as name emailIds. How can it posible using sql query.?

I want a result like

```<code>|EmailIds         |
|-------------------
|a@a.ll
|-------------------
|asdasdasd@asd.asd
|-------------------
|asdasdasd1@asd.asd
|-------------------
|aaaaa@a.ll
|-------------------
|asd@aswq.km
|-------------------
|aa@asd.ff
|-------------------
</code>```

答:
You can  use concat_ws() to combine all into a single column:

```<code>SELECT DISTINCT CONCAT_WS(';', c.contact1Email , c.contact2Email, c.contact3Email, u.emailId) as emailIds
FROM fm_company c INNER JOIN
     fm_users u
     ON c.companyId = u.companyId
WHERE c.companyId = 33;
</code>```

EDIT:

It occurs to me that you want a single email in each row, with multiple rows.  If so:

```<code>select contact1Email as email
from company c
where c.companyId = 33
union -- on purpose to remove duplicates
select contact2Email as email
from company c
where c.companyId = 33
union
select contact3Email as email
from company c
where c.companyId = 33
union
select u.emailId
from fm_company c join
     fm_users u
     on c.companyId = u.companyId
where c.companyId = 33;
</code>```

Body:
I have two table tblCompany and tblUser
Both table contains email id fields, tblCompany contain 3 column as named contact1Email , contact2Email, contact3Email and tblUser contain a column named emailId. Unique field in both table is companyId. I want to get email of company and user's email those are belongs to that company. all those email ids I want in a single column.
I tried it in basic way using below query:

SELECT DISTINCT contact1Email , contact2Email, contact3Email, emailId
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33

this gives bellow result as shown in image

you can see there emailId column contain user's email and contact1Email , contact2Email, contact3Email contain company email.
I want all email in single column as name emailIds. How can it posible using sql query.?

I want a result like

|EmailIds         |
|-------------------
|a@a.ll
|-------------------
|asdasdasd@asd.asd
|-------------------
|asdasdasd1@asd.asd
|-------------------
|aaaaa@a.ll
|-------------------
|asd@aswq.km
|-------------------
|aa@asd.ff
|-------------------

Body:
You can  use concat_ws() to combine all into a single column:

SELECT DISTINCT CONCAT_WS(';', c.contact1Email , c.contact2Email, c.contact3Email, u.emailId) as emailIds
FROM fm_company c INNER JOIN
     fm_users u
     ON c.companyId = u.companyId
WHERE c.companyId = 33;

EDIT:

It occurs to me that you want a single email in each row, with multiple rows.  If so:

select contact1Email as email
from company c
where c.companyId = 33
union -- on purpose to remove duplicates
select contact2Email as email
from company c
where c.companyId = 33
union
select contact3Email as email
from company c
where c.companyId = 33
union
select u.emailId
from fm_company c join
     fm_users u
     on c.companyId = u.companyId
where c.companyId = 33;


问:
what is the es5 equivalent of this code

```<code>function handleDeposit (accountNumber, amount) {
  type: 'DEPOSIT',
  accountNumber,
  amount
}
</code>```

it returns undefined when invoked. I'm not sure what feature of es6 is being used here

is it equivalent to...

```<code>function handleDeposit (accountNumber, amount) {
  return {
    type: 'DEPOSIT',
    accountNumber: accountNumber,
    amount: amount
  }
}
</code>```

答:
You need to wrap the properties in an object structure with short hand properties as ES6 example for the given ES5 result.

```<code>function handleDeposit (accountNumber, amount) {
    return {
        type: 'DEPOSIT',
        accountNumber,
        amount
    };
}
</code>```

Your given code

```<code>function handleDeposit (accountNumber, amount) {
     type: 'DEPOSIT',
     accountNumber,
     amount
}
</code>```

has no object inside, but a label type, some comma operators and ends with no return neither some value.

You get the standard return value of a function with undefined.

Title: what is the es5 equivalent of this code

Body:
function handleDeposit (accountNumber, amount) {
  type: 'DEPOSIT',
  accountNumber,
  amount
}

it returns undefined when invoked. I'm not sure what feature of es6 is being used here

is it equivalent to...

function handleDeposit (accountNumber, amount) {
  return {
    type: 'DEPOSIT',
    accountNumber: accountNumber,
    amount: amount
  }
}

Body:
You need to wrap the properties in an object structure with short hand properties as ES6 example for the given ES5 result.

function handleDeposit (accountNumber, amount) {
    return {
        type: 'DEPOSIT',
        accountNumber,
        amount
    };
}

Your given code

function handleDeposit (accountNumber, amount) {
     type: 'DEPOSIT',
     accountNumber,
     amount
}

has no object inside, but a label type, some comma operators and ends with no return neither some value.

You get the standard return value of a function with undefined.


问:
Android Studio Gradle Sync Error using google play-services-maps 11.6.2
I am developing a google map app using Android Studio.  When I sync the project with Gradle Files (Select Tools/Android/Sync Project with Gradle Files on Android Studio), I get the following error:

Could not resolve com.google.android.gms:play-services-maps:11.6.2.
Couold not get resource 'https://dl.google.com/dl/android/maven2/com/google/android/gms/play-services-maps/11.62./play-services-maps-11.6.2.pom

This is the software I am using:

Android Studio 3.0.1

Android Version 7.1.1

Google Play Services 46

Google Repository 58 (under Support Repository)

I've tried using both the google maps project template and the empty activity project but I get the same error.

I am using the http proxy setup I used from earlier projects.  I am able to install the play-services-maps and the google repository.

I also added the maven url to the Gradle Project file in the All Projects/Repositories section.

I have tried the suggestions from Stack Overflow but none have not worked.

Any ideas?

```<code>Gradle Project Build file:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

The gradle app build file:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "hansen.scott.googlemaps"
        minSdkVersion 25
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.google.android.gms:play-services-maps:11.6.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

The error is in the line:
implementation 'com.google.android.gms:play-services-maps:11.6.2'

答:
try adding this in project level gradle file</p>

```<code>allprojects {
    repositories {
        maven {
            url "https://maven.google.com"
        }
    }
}
</code>```

Body:
I am developing a google map app using Android Studio.  When I sync the project with Gradle Files (Select Tools/Android/Sync Project with Gradle Files on Android Studio), I get the following error:

Could not resolve com.google.android.gms:play-services-maps:11.6.2.
Couold not get resource 'https://dl.google.com/dl/android/maven2/com/google/android/gms/play-services-maps/11.62./play-services-maps-11.6.2.pom

This is the software I am using:

Android Studio 3.0.1

Android Version 7.1.1

Google Play Services 46

Google Repository 58 (under Support Repository)

I've tried using both the google maps project template and the empty activity project but I get the same error.

I am using the http proxy setup I used from earlier projects.  I am able to install the play-services-maps and the google repository.

I also added the maven url to the Gradle Project file in the All Projects/Repositories section.

I have tried the suggestions from Stack Overflow but none have not worked.

Any ideas?

Gradle Project Build file:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

The gradle app build file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "hansen.scott.googlemaps"
        minSdkVersion 25
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.google.android.gms:play-services-maps:11.6.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

The error is in the line:
implementation 'com.google.android.gms:play-services-maps:11.6.2'

Body:
try adding this in project level gradle file

allprojects {
    repositories {
        maven {
            url "https://maven.google.com"
        }
    }
}


问:
How to sort nested set elements by rating of root element?
Tree comment system implemented as simple nested set

```
+---------+-----------+---------+---------+-------+--------+
| id      | parent_id | lft     | rgt     | depth | rating |
+---------+-----------+---------+---------+-------+--------+
| 4073406 |           | 1058655 | 1058656 | 0     | 0      |
| 3721850 |           | 1058651 | 1058654 | 0     | 2      |
| 4279470 | 3721850   | 1058652 | 1058653 | 1     | 0      |
| 3682985 |           | 1058649 | 1058650 | 0     | 1      |
| 3643602 |           | 1058647 | 1058648 | 0     | 0      |
| 3182010 |           | 1058643 | 1058646 | 0     | 3      |
+---------+-----------+---------+---------+-------+--------+
```

Sorting by left and right key

```<code>SELECT * FROM COMMENTS ORDER BY rgt DESC; # firstly new
SELECT * FROM COMMENTS ORDER BY lft ASC;  # firstly old
</code>```

That's easy and effectively.

Q: How to sort comments by rating of first [root] comment in thread, and by left or right key for others non root comments?

A similar implementation you can see on YouTube and some others web sites where you can display new or popular comments

答:
The correct SQL query is (pretty close to Hambones answer)</p>

```<code>WITH RECURSIVE r AS (
            SELECT c1.*, rgt AS _rgt, cached_votes_score AS rating
                FROM comments AS c1
                WHERE
                    depth = 0 AND
            UNION ALL
            SELECT c2.*, c2.rgt, rating AS rating
                FROM comments c2
                JOIN r ON c2.parent_id = r.id
        )
        SELECT * FROM r ORDER BY rating desc, _rgt DESC
</code>```

Body:
Tree comment system implemented as simple nested set

+---------+-----------+---------+---------+-------+--------+
| id      | parent_id | lft     | rgt     | depth | rating |
+---------+-----------+---------+---------+-------+--------+
| 4073406 |           | 1058655 | 1058656 | 0     | 0      |
| 3721850 |           | 1058651 | 1058654 | 0     | 2      |
| 4279470 | 3721850   | 1058652 | 1058653 | 1     | 0      |
| 3682985 |           | 1058649 | 1058650 | 0     | 1      |
| 3643602 |           | 1058647 | 1058648 | 0     | 0      |
| 3182010 |           | 1058643 | 1058646 | 0     | 3      |
+---------+-----------+---------+---------+-------+--------+

Sorting by left and right key

SELECT * FROM COMMENTS ORDER BY rgt DESC; # firstly new
SELECT * FROM COMMENTS ORDER BY lft ASC;  # firstly old

That's easy and effectively.

Q: How to sort comments by rating of first [root] comment in thread, and by left or right key for others non root comments?

A similar implementation you can see on YouTube and some others web sites where you can display new or popular comments

Body:
The correct SQL query is (pretty close to Hambones answer)

WITH RECURSIVE r AS (
            SELECT c1.*, rgt AS _rgt, cached_votes_score AS rating
                FROM comments AS c1
                WHERE
                    depth = 0 AND
            UNION ALL
            SELECT c2.*, c2.rgt, rating AS rating
                FROM comments c2
                JOIN r ON c2.parent_id = r.id
        )
        SELECT * FROM r ORDER BY rating desc, _rgt DESC


问:
The sum of prime numbers
I want to calculate the sum of even prime numbers between 101 and 203. But the output for my code is wrong, the output is 52.
Can anyone help me please to get the correct output, in my code I supposed that the even numbers are sure not prime that's why I escaped them. I want to solve it using this method by the prime function. What should I do? Thank you a lot </p>

```<code>#include <stdio.h>
int prime(int n)
{
    int i=2;
    int n2;
    n2 = n/2;
    while (1<=n2) {
        if (n%i == 0) {
            return 0;
        } else {
            return 1;
        }
        i++;
    }
}

int main()
{
    int sum=0;
    for (int i=101; i<=203; i+=2) {
        if (prime(i)==1) {
        }
        sum+=1;
    }
    printf("%d \n",sum);
    return 0;
}
</code>```

答:
First of all: you do not need 'i++;' in your prime-method because this is unreachable code.

Second: try this function for checking if a number is prime:

```<code>#include <stdio.h>
int prime(int n)
{
    for (int i = 2; i < n; i++) {
        if (n % i == 0 && i != n) return 0;
    }
    return 1;
}

int main()
{
    int sum=0;
    for (int i=101; i<=203; i+=2) {
        if (prime(i)==1){
          sum+=i;
        }
    }
    printf("%d \n",sum);
}
</code>```

Title: The sum of prime numbers

Body:
I want to calculate the sum of even prime numbers between 101 and 203. But the output for my code is wrong, the output is 52.
Can anyone help me please to get the correct output, in my code I supposed that the even numbers are sure not prime that's why I escaped them. I want to solve it using this method by the prime function. What should I do? Thank you a lot

#include <stdio.h>
int prime(int n)
{
    int i=2;
    int n2;
    n2 = n/2;
    while (1<=n2) {
        if (n%i == 0) {
            return 0;
        } else {
            return 1;
        }
        i++;
    }
}

int main()
{
    int sum=0;
    for (int i=101; i<=203; i+=2) {
        if (prime(i)==1) {
        }
        sum+=1;
    }
    printf("%d \n",sum);
    return 0;
}

Body:
First of all: you do not need 'i++;' in your prime-method because this is unreachable code.

Second: try this function for checking if a number is prime:

#include <stdio.h>
int prime(int n)
{
    for (int i = 2; i < n; i++) {
        if (n % i == 0 && i != n) return 0;
    }
    return 1;
}

int main()
{
    int sum=0;
    for (int i=101; i<=203; i+=2) {
        if (prime(i)==1){
          sum+=i;
        }
    }
    printf("%d \n",sum);
}


问:
java.lang.UnsupportedOperationException: For security reasons, WebView is not allowed in privileged processes
I try selecting a subsettings in the settings app of my device, and i see this exception. Does this mean settings is a privileged process and can't access webview?

I tried selecting HDMI option from settings, this is the exception stack:

```<code>03-23 08:45:03.301 E/AndroidRuntime( 3299): Caused by: java.lang.UnsupportedOperationException: For security reasons, WebView is not allowed in privileged processes
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebViewFactory.getProvider(WebViewFactory.java:96)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.getFactory(WebView.java:2194)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.ensureProviderCreated(WebView.java:2189)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.setOverScrollMode(WebView.java:2248)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.view.View.<init>(View.java:3588)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.view.View.<init>(View.java:3682)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.view.ViewGroup.<init>(ViewGroup.java:497)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.widget.AbsoluteLayout.<init>(AbsoluteLayout.java:55)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.<init>(WebView.java:544)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.<init>(WebView.java:489)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.<init>(WebView.java:472)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.<init>(WebView.java:459)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.<init>(WebView.java:449)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at com.android.settings.HDMI3DPlaySettings.onCreate(HDMI3DPlaySettings.java:123)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.Fragment.performCreate(Fragment.java:2031)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:863)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.BackStackRecord.run(BackStackRecord.java:834)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:483)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at com.android.settings.SettingsActivity.switchToFragment(SettingsActivity.java:1002)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at com.android.settings.SettingsActivity.onCreate(SettingsActivity.java:599)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.Activity.performCreate(Activity.java:5990)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2320)
</code>```

答:
This exception is generated by WebViewFactory, here is the code:

```<code> final int uid = android.os.Process.myUid();
        if (uid == android.os.Process.ROOT_UID || uid == android.os.Process.SYSTEM_UID
                || uid == android.os.Process.PHONE_UID || uid == android.os.Process.NFC_UID
                || uid == android.os.Process.BLUETOOTH_UID) {
            throw new UnsupportedOperationException(
                    "For security reasons, WebView is not allowed in privileged processes");
        }
</code>```

so, if you will try to use web view with mentioned UID usage, the app will crash.

I also need to use webView to show html in my app, but can not find some standard solution.

Body:
I try selecting a subsettings in the settings app of my device, and i see this exception. Does this mean settings is a privileged process and can't access webview?

I tried selecting HDMI option from settings, this is the exception stack:

03-23 08:45:03.301 E/AndroidRuntime( 3299): Caused by: java.lang.UnsupportedOperationException: For security reasons, WebView is not allowed in privileged processes
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebViewFactory.getProvider(WebViewFactory.java:96)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.getFactory(WebView.java:2194)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.ensureProviderCreated(WebView.java:2189)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.setOverScrollMode(WebView.java:2248)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.view.View.<init>(View.java:3588)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.view.View.<init>(View.java:3682)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.view.ViewGroup.<init>(ViewGroup.java:497)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.widget.AbsoluteLayout.<init>(AbsoluteLayout.java:55)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.<init>(WebView.java:544)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.<init>(WebView.java:489)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.<init>(WebView.java:472)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.<init>(WebView.java:459)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.webkit.WebView.<init>(WebView.java:449)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at com.android.settings.HDMI3DPlaySettings.onCreate(HDMI3DPlaySettings.java:123)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.Fragment.performCreate(Fragment.java:2031)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:863)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.BackStackRecord.run(BackStackRecord.java:834)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:483)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at com.android.settings.SettingsActivity.switchToFragment(SettingsActivity.java:1002)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at com.android.settings.SettingsActivity.onCreate(SettingsActivity.java:599)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.Activity.performCreate(Activity.java:5990)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
03-23 08:45:03.301 E/AndroidRuntime( 3299):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2320)

Body:
This exception is generated by WebViewFactory, here is the code:

 final int uid = android.os.Process.myUid();
        if (uid == android.os.Process.ROOT_UID || uid == android.os.Process.SYSTEM_UID
                || uid == android.os.Process.PHONE_UID || uid == android.os.Process.NFC_UID
                || uid == android.os.Process.BLUETOOTH_UID) {
            throw new UnsupportedOperationException(
                    "For security reasons, WebView is not allowed in privileged processes");
        }

so, if you will try to use web view with mentioned UID usage, the app will crash.

I also need to use webView to show html in my app, but can not find some standard solution.


问:
Meteor: Force rendering an element
I have a generic template used several times in my app:

```<code><template name="genericCollapse">
  {{data-1}}
  <a href=# class='collapsed' data-toggle='collapse'
     data-target='#uniqueId'>Show/hide data-2</a>
  <div class='collapse' id='uniqueId'>
    {{data-2}}
  </div>
</template>
</code>```

By clicking somewhere else in the app, data-1 and data-2 change simultaneously (using Session Vars). However, in case the template is already on the screen, only data-1 and data-2 are changing but the collapse status of the div remains (obviously) unchanged. If it was open before, it remains open.

I want to achieve, that whenever data-1/data-2 changes, div as well as a are forced to be in status collapsed again.
I tried to add

```<code><a href=# class='{{collapsed}}'

Template.genericCollapse.helpers({
  collapsed () {return "collapsed " + Random.Id()},
})
</code>```

which is not only pretty ugly but also does not help, because the class of div still remains "collapse show" and even with a second helper for div, I can't get rid of "show".

Re-rendering the whole Template would be also acceptable, but I have difficulties to determine the parentNode for calling Blaze.render() - it is never the same - and I'm also not sure where to place such a call correctly.

How is this done?

答:
You could do this the meteor way by returning the class to the element from a helper like so:

template:

```<code><template name="genericCollapse">
  {{data-1}}
  <a href=# class={{isCollapsed}} data-toggle='collapse'
     data-target='#uniqueId'>Show/hide data-2</a>
...
...
</template>
</code>```

Helper:

```<code>Template.genericCollapse.helpers({

isCollapsed: function(){

    if()// logic to check if it needs to be collapsed
       return "collapsed"
    else
       return "collapse"
    }
});
</code>```

Title: Meteor: Force rendering an element

Body:
I have a generic template used several times in my app:

<template name="genericCollapse">
  {{data-1}}
  Show/hide data-2

    {{data-2}}

</template>

By clicking somewhere else in the app, data-1 and data-2 change simultaneously (using Session Vars). However, in case the template is already on the screen, only data-1 and data-2 are changing but the collapse status of the div remains (obviously) unchanged. If it was open before, it remains open.

I want to achieve, that whenever data-1/data-2 changes, div as well as a are forced to be in status collapsed again.
I tried to add

<a href=# class='{{collapsed}}'

Template.genericCollapse.helpers({
  collapsed () {return "collapsed " + Random.Id()},
})

which is not only pretty ugly but also does not help, because the class of div still remains "collapse show" and even with a second helper for div, I can't get rid of "show".

Re-rendering the whole Template would be also acceptable, but I have difficulties to determine the parentNode for calling Blaze.render() - it is never the same - and I'm also not sure where to place such a call correctly.

How is this done?

Body:
You could do this the meteor way by returning the class to the element from a helper like so:

template:

<template name="genericCollapse">
  {{data-1}}
  <a href=# class={{isCollapsed}} data-toggle='collapse'
     data-target='#uniqueId'>Show/hide data-2</a>
...
...
</template>

Helper:

Template.genericCollapse.helpers({

isCollapsed: function(){

    if()// logic to check if it needs to be collapsed
       return "collapsed"
    else
       return "collapse"
    }
});


问:
Send HTTPS Request using SSL Socket
Hi:  I am trying to make a small  HTTPS client program mainly usign JAVA.

Below is the code snippet:

```<code>SSLSocket result = (SSLSocket) SSLCont.sslSocketFactory.createSocket(
                    sockfd, "www.facebook.com", 443, false);
result.startHandshake();
result.getOutputStream().write("GET / HTTP/1.1\r\nHost: www.facebook.com\r\n\r\n".getBytes());
String  res=my.getData(result.getInputStream());
print(res);
</code>```

I can print Facebook response properly. There is no issue.

The issue is - when I see the traffic using "TRAFFIC capture" program I see following data  for "TLS:TLS Rec Layer-1 HandShake: Client Hello." part

```<code>TLS:TLS Rec Layer-1 HandShake: Client Hello.
. .....ÿÿÿÿ.............ïM©.LoÓ....??ÞÐJd:Ôn..¡.?ÞÐJd:..ªª.....
.E..ë.×@.@.».À¨.eð.$?6.»§.Îç?ç.?P.ý\?-
......¾...º..???v????{3?¯ß.DÅJ.>?÷®ÿ±û*^».8i1...À+À/Ì©Ì¨À,À0À.À.À
.À..3.9./.5.....s.........www.facebook.com....ÿ.
........................#...............................
..........................
</code>```

But when I  open  the website ( www.facebook.com ) directly in Browser say in CHROME,  I see following traffic :

```<code>TLS:TLS Rec Layer-1 HandShake: Client Hello.
. .....ÿÿÿÿ.............ïM©.LoÓ....??ÞÐJd:Ôn..¡.?ÞÐJd:..ªª.....
.E..ë.×@.@.».À¨.eð.$?6.»§.Îç?ç.?P.ý\?-
......¾...º..???v????{3?¯ß.DÅJ.>?÷®ÿ±û*^».8i1...À+À/Ì©Ì¨À,À0À.À.À
.À..3.9./.5.....s.........www.facebook.com....ÿ.
........................#.........h2.http/1.1...........
..........................
</code>```

If we  compare both traffic data carefully we see ,   in case of Traffic Generated by Chrome browser we  will see  following extra string
"..h2.http/1.1...." appended at last ,which tells it is for HTTP and looks perfect.

But this string is not getting appended  in traffic generated  by  my java program.

Can you please tell me  why  "..h2.http/1.1...."  string not appearing in traffic generated by my java program.
How to modify my java code so that the string appears in the request traffic generated by my java program .

Note:  But when I use java inbuilt class "HttpsURLConnection"  to open that website  I see "..h2.http/1.1...."  is present in traffic.
This issue is applicable for all HTTPS websites.

Can you please tell me What is missing in my Java code.

Thank you in advance

答:
Can you please tell me why "..h2.http/1.1...." string not appearing in traffic generated by my java program.

First, it it not a good idea to treat a binary protocol (as TLS is) like text when analyzing it. If you would look at the traffic with Wireshark instead and dig deeper in the TLS handshake you see that the client is using ALPN to indicate to the server that it does support 'h2' (HTTP/2) and 'http/1.1' (HTTP/1.1). A server supporting HTTP/2 will then probably use this as the protocol for the connection and not HTTP/1.1 since HTTP/2 is more efficient.

How to modify my java code so that the string appears in the request traffic generated by my java program .

Unless you are able to properly communicate using the HTTP/2 protocol to the server you don't want to tell the server that you can do HTTP/2, i.e. you don't want to add this information with ALPN. Given that you just managed to send a HTTP request but failed to handle the response properly (you expect the server to close the connection after the response although you allow the server to keep the connection open by implicitly enabling HTTP keep-alive with using HTTP/1.1) I doubt that you can do the way more complex HTTP/2 protocol.

Title: Send HTTPS Request using SSL Socket

Body:
Hi:  I am trying to make a small  HTTPS client program mainly usign JAVA.

Below is the code snippet:

SSLSocket result = (SSLSocket) SSLCont.sslSocketFactory.createSocket(
                    sockfd, "www.facebook.com", 443, false);
result.startHandshake();
result.getOutputStream().write("GET / HTTP/1.1\r\nHost: www.facebook.com\r\n\r\n".getBytes());
String  res=my.getData(result.getInputStream());
print(res);

I can print Facebook response properly. There is no issue.

The issue is - when I see the traffic using "TRAFFIC capture" program I see following data  for "TLS:TLS Rec Layer-1 HandShake: Client Hello." part

TLS:TLS Rec Layer-1 HandShake: Client Hello.
. .....ÿÿÿÿ.............ïM©.LoÓ....??ÞÐJd:Ôn..¡.?ÞÐJd:..ªª.....
.E..ë.×@.@.».À¨.eð.$?6.»§.Îç?ç.?P.ý\?-
......¾...º..???v????{3?¯ß.DÅJ.>?÷®ÿ±û*^».8i1...À+À/Ì©Ì¨À,À0À.À.À
.À..3.9./.5.....s.........www.facebook.com....ÿ.
........................#...............................
..........................

But when I  open  the website ( www.facebook.com ) directly in Browser say in CHROME,  I see following traffic :

TLS:TLS Rec Layer-1 HandShake: Client Hello.
. .....ÿÿÿÿ.............ïM©.LoÓ....??ÞÐJd:Ôn..¡.?ÞÐJd:..ªª.....
.E..ë.×@.@.».À¨.eð.$?6.»§.Îç?ç.?P.ý\?-
......¾...º..???v????{3?¯ß.DÅJ.>?÷®ÿ±û*^».8i1...À+À/Ì©Ì¨À,À0À.À.À
.À..3.9./.5.....s.........www.facebook.com....ÿ.
........................#.........h2.http/1.1...........
..........................

If we  compare both traffic data carefully we see ,   in case of Traffic Generated by Chrome browser we  will see  following extra string
"..h2.http/1.1...." appended at last ,which tells it is for HTTP and looks perfect.

But this string is not getting appended  in traffic generated  by  my java program.

Can you please tell me  why  "..h2.http/1.1...."  string not appearing in traffic generated by my java program.
How to modify my java code so that the string appears in the request traffic generated by my java program .

Note:  But when I use java inbuilt class "HttpsURLConnection"  to open that website  I see "..h2.http/1.1...."  is present in traffic.
This issue is applicable for all HTTPS websites.

Can you please tell me What is missing in my Java code.

Thank you in advance


问:
input and button, same css, different heights
I am having same css properties, yet the button and input fields are different fields

.input-con {
  position: relative;
}

.input-con>* {
  line-height: 1;
  display: inline-block;
  vertical-align: middle;
  padding: 10px;
  border: 0;
  background-color: #ddd;
  color: #444;
  outline: 0;
  cursor: pointer;
  font-size: 15px;
  box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="input-con">
  <input type="text" />
  <button>Search</button>
</div></code>```

pen - https://codepen.io/digitalzoomstudio/pen/LOoVYK

How could I achieve same heights without forcing height property ?

答:
Try with this it may help      </p>

```<code>.input-con {
    position: relative;

    }
.input-con{
  position:relative;

  >*{
    vertical-align:middle;
    padding: 10px;
    border:0;
    background-color: #ddd;
    color: #444;
    outline:0;
    cursor:pointer;
    font-size: 15px;

  }
}
</code>```

Body:
I am having same css properties, yet the button and input fields are different fields

.input-con {
  position: relative;
}

.input-con>* {
  line-height: 1;
  display: inline-block;
  vertical-align: middle;
  padding: 10px;
  border: 0;
  background-color: #ddd;
  color: #444;
  outline: 0;
  cursor: pointer;
  font-size: 15px;
  box-sizing: border-box;
}

  <input type="text" />
  <button>Search</button>

pen - https://codepen.io/digitalzoomstudio/pen/LOoVYK

How could I achieve same heights without forcing height property ?

Body:
Try with this it may help

.input-con {
    position: relative;

    }
.input-con{
  position:relative;

  >*{
    vertical-align:middle;
    padding: 10px;
    border:0;
    background-color: #ddd;
    color: #444;
    outline:0;
    cursor:pointer;
    font-size: 15px;

  }
}


问:
Xcode tables refresh on button click
I have a table which is populated with JSON. It works as a calendar. When the date is clicked, the table below should be populated with the events for that day.

These populate the tables after the data has been found but only does it once.

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return(GlobalVar.TodaysEvents.count)

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "eventCell", for: indexPath) as! WhitelistTableViewCell

    cell.startTime.adjustsFontSizeToFitWidth = true

    print(GlobalVar.TodaysEventsTimes[indexPath.row])

    cell.startTime.text = (GlobalVar.TodaysEventsTimes[indexPath.row] as! String)
    cell.Summary.text = GlobalVar.TodaysEvents[indexPath.row] as? String

    return(cell)
}
</code>```

I have seen other posts like this and they use:

```<code>self.tableView.reload()
</code>```

However, when i try this, it doesn't recognise "tableView" and simply doesn't work.

Any advice would be appreciated, thanks in advance

答:
create a reference to your tableView ( New Referencing Outlet ) and then do this :</p>

```<code>yourTableView.reloadData()
</code>```

Title: Xcode tables refresh on button click

Body:
I have a table which is populated with JSON. It works as a calendar. When the date is clicked, the table below should be populated with the events for that day.

These populate the tables after the data has been found but only does it once.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return(GlobalVar.TodaysEvents.count)

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "eventCell", for: indexPath) as! WhitelistTableViewCell

    cell.startTime.adjustsFontSizeToFitWidth = true

    print(GlobalVar.TodaysEventsTimes[indexPath.row])

    cell.startTime.text = (GlobalVar.TodaysEventsTimes[indexPath.row] as! String)
    cell.Summary.text = GlobalVar.TodaysEvents[indexPath.row] as? String

    return(cell)
}

I have seen other posts like this and they use:

self.tableView.reload()

However, when i try this, it doesn't recognise "tableView" and simply doesn't work.

Any advice would be appreciated, thanks in advance

Body:
create a reference to your tableView ( New Referencing Outlet ) and then do this :

yourTableView.reloadData()


答:
You added line-height: 1; which makes difference

.input-con {
  position: relative;
}

.input-con>* {
  /*line-height: 1;*/
  display: inline-block;
  vertical-align: middle;
  padding: 10px;
  border: 0;
  background-color: #ddd;
  color: #444;
  outline: 0;
  cursor: pointer;
  font-size: 15px;
  box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="input-con">
  <input type="text" />
  <button>Search</button>
  <input type="text" />
</div></code>```

Title: input and button, same css, different heights

Body:
You added line-height: 1; which makes difference

.input-con {
  position: relative;
}

.input-con>* {
  /*line-height: 1;*/
  display: inline-block;
  vertical-align: middle;
  padding: 10px;
  border: 0;
  background-color: #ddd;
  color: #444;
  outline: 0;
  cursor: pointer;
  font-size: 15px;
  box-sizing: border-box;
}

<div class="input-con">
  <input type="text" />
  <button>Search</button>
  <input type="text" />
</div>


问:
XML::Bare Can't locate object method "parse" via package "0"
I have a script as following,
is it asked to do in inside the foreach loop.
The script is as following,

```<code>use XML::Bare;

foreach my $i (1..100){
   my $xml=XML::Bare->new(
    file=>"/tmp/lcms$i.xml"
    );
    my %root=%{ $xml->parse() };
    #..do something with %root...
}
</code>```

and when I try to run it I have the following error,

```<code>Can't locate object method "parse" via package "0" (perhaps you forgot to load "0"?) at telephone.pl line 8
</code>```

I am relatively new to perl XML::Bare module and it would be great if someone would walk me through in this learning curve

答:
Apparently http://p3rl.org/XML::Bare returns 0 if a file was not found/could not be opened.
So the right way to handle this would be:

```<code>my $xml = XML::Bare->new(...) or die "Could not open file: $!";
</code>```

Are you sure the files all exist?

Edit: As @simbabque suggested, I'd also recommend http://p3rl.org/XML::LibXML

Body:
I have a script as following,
is it asked to do in inside the foreach loop.
The script is as following,

use XML::Bare;

foreach my $i (1..100){
   my $xml=XML::Bare->new(
    file=>"/tmp/lcms$i.xml"
    );
    my %root=%{ $xml->parse() };
    #..do something with %root...
}

and when I try to run it I have the following error,

Can't locate object method "parse" via package "0" (perhaps you forgot to load "0"?) at telephone.pl line 8

I am relatively new to perl XML::Bare module and it would be great if someone would walk me through in this learning curve

Body:
Apparently http://p3rl.org/XML::Bare returns 0 if a file was not found/could not be opened.
So the right way to handle this would be:

my $xml = XML::Bare->new(...) or die "Could not open file: $!";

Are you sure the files all exist?

Edit: As @simbabque suggested, I'd also recommend http://p3rl.org/XML::LibXML


答:
I'm not sure what feature of es6 is being used here

None. Passing the function through Babel with the es2017 preset results in nothing more than a reformating of the code.

This is just a function (which takes two arguments) containing a label, followed by a string literal, then two arguments, each separated by comma operators.

There is no return statement.

The function does nothing, returns nothing, and is ES5.

Title: what is the es5 equivalent of this code

Body:
function handleDeposit (accountNumber, amount) {
  type: 'DEPOSIT',
  accountNumber,
  amount
}

it returns undefined when invoked. I'm not sure what feature of es6 is being used here

is it equivalent to...

function handleDeposit (accountNumber, amount) {
  return {
    type: 'DEPOSIT',
    accountNumber: accountNumber,
    amount: amount
  }
}


问:
How to programmatically connect to a WiFi network given the SSID and password
I am trying to replicate an existing Android Application that I made to iOS. In my application, I should be able to connect to a WiFi network given the SSID and the Password. The SSID and the Password can be hardcoded or can be inputted by the user. I was going through the internet to research how this can be done on iOS, however, it seems that this behavior is highly discouraged and that there's no way on doing this using public/documented libraries that won't get your application rejected by the App Store.

The thing is I'll be using this application personally and I don't plan on submitting it to the App Store so it's okay if I use external libraries. If my friends would want to use it, I could export an enterprise ipa and give them instructions on how to install it.

Upon searching, it seemed that MobileWifi.framework was a good candidate. However, it does not seem that there's a straightforward way of using this library to connect to a WiFi network given the SSID and the Password.

Is there anyone who has successfully tried to connect to a Wifi Network given the SSID and Password?

答:
connect wifi networks in iOS 11. You can connect wifi using ssid and password like following.

Enable Hotspot on App Id configure services

After Enable Hotspot Configuration

Swift 4.0 Code for iOS 11 Only:

```<code>import NetworkExtension
</code>```

...

```<code>let configuration = NEHotspotConfiguration.init(ssid: "SSIDname", passphrase: "Password", isWEP: false)
configuration.joinOnce = true

NEHotspotConfigurationManager.shared.apply(configuration) { (error) in
    if error != nil {
        if error?.localizedDescription == "already associated."
        {
            print("Connected")
        }
        else{
            print("No Connected")
        }
    }
    else {
        print("Connected")
    }
}
</code>```

Body:
connect wifi networks in iOS 11. You can connect wifi using ssid and password like following.

Enable Hotspot on App Id configure services

After Enable Hotspot Configuration

Swift 4.0 Code for iOS 11 Only:

import NetworkExtension

...

let configuration = NEHotspotConfiguration.init(ssid: "SSIDname", passphrase: "Password", isWEP: false)
configuration.joinOnce = true

NEHotspotConfigurationManager.shared.apply(configuration) { (error) in
    if error != nil {
        if error?.localizedDescription == "already associated."
        {
            print("Connected")
        }
        else{
            print("No Connected")
        }
    }
    else {
        print("Connected")
    }
}


问:
Angular Post array results in all NULL in database
I am trying to post data to my table (T-SQL/Azure) but all it writes is NULL and just one line, not even the complete array. I have tried numerous variations of the $param, serialize, $httpParamSerializer etc. none of them write the contents inside the table. Even tho the console.log tells me all is ok.

```<code>var data = $scope.test;
console.log(data);
var jsonData = angular.toJson(data);
console.log(jsonData)
var objectToSerialize = { 'object': jsonData };
console.log(objectToSerialize);

$http({
     url: 'http://url/api/UserOrderProductList',
     method: "POST",
     data: $.param(objectToSerialize),
     //data: $.param(data),
     //data: $.param(jsonData),
     //data: $httpParamSerializerJQLike(objectToSerialize),

     headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
     //headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }

      }).success(function (data) {
            alert("done");
      });
</code>```

this is what i am writing:

```<code>    var data = {
        "quantity": 0,
        "title": "string",
        "imageFront": "string"
        }
</code>```

with the same matching table.

in the debugger is get the 201 created and the form-data of the complete array

Form Data from Headers:

```<code>object:[{"count":1,"title":"Lara croft",imageFront":"20170807234015"},
{"count":1,"title":"Dragon Age","imageFront":"20170807231312"},
{"count":2,"title":"Madden","imageFront":"20170807235148"}]
</code>```

This is what is says in the Preview/Response:

```<code>{"id":16,"count":null,"imageFront":null,"title":null}
</code>```

This is the backend section, how the request is recieved:

```<code>  // POST: api/UserOrders
  [ResponseType(typeof(UserOrderProductList))]
  public async Task<IHttpActionResult> PostUserOrderProductList(UserOrderProductList UserOrderProductList)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.UserOrderProductLists.Add(UserOrderProductList);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = UserOrderProductList.id }, UserOrderProductList);
    }
</code>```

what is going on and why does it all write NULL?
When i am writing with swagger is all turns out fine.

答:
To post the contents of an Angular Ng-Repeat into a database table with an WEB API 2 backend, thanks to Arron Chen.

```<code>var data = $scope.test; // CONTENTS OF THE NG-REPEAT
var jsonData = angular.toJson(data);

$http({
    url: 'http://url/api/UserOrderProductList',
    method: "POST",
    data: jsonData,
    headers: { 'Content-Type': 'application/json' }

}).success(function (data) {
   alert("done");
});
</code>```

With the matching backend:

```<code>// POST: api/UserOrders
[Route("api/UserOrderProductList/AddOrderList")]
public HttpResponseMessage PostUserOrderProductList(List<UserOrderProductList> UserOrderProductList)
{

   db.UserOrderProductLists.AddRange(UserOrderProductList);
   db.SaveChangesAsync();

   return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
</code>```

Body:
I am trying to post data to my table (T-SQL/Azure) but all it writes is NULL and just one line, not even the complete array. I have tried numerous variations of the $param, serialize, $httpParamSerializer etc. none of them write the contents inside the table. Even tho the console.log tells me all is ok.

var data = $scope.test;
console.log(data);
var jsonData = angular.toJson(data);
console.log(jsonData)
var objectToSerialize = { 'object': jsonData };
console.log(objectToSerialize);

$http({
     url: 'http://url/api/UserOrderProductList',
     method: "POST",
     data: $.param(objectToSerialize),
     //data: $.param(data),
     //data: $.param(jsonData),
     //data: $httpParamSerializerJQLike(objectToSerialize),

     headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
     //headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }

      }).success(function (data) {
            alert("done");
      });

this is what i am writing:

    var data = {
        "quantity": 0,
        "title": "string",
        "imageFront": "string"
        }

with the same matching table.

in the debugger is get the 201 created and the form-data of the complete array

Form Data from Headers:

object:[{"count":1,"title":"Lara croft",imageFront":"20170807234015"},
{"count":1,"title":"Dragon Age","imageFront":"20170807231312"},
{"count":2,"title":"Madden","imageFront":"20170807235148"}]

This is what is says in the Preview/Response:

{"id":16,"count":null,"imageFront":null,"title":null}

This is the backend section, how the request is recieved:

  // POST: api/UserOrders
  [ResponseType(typeof(UserOrderProductList))]
  public async Task<IHttpActionResult> PostUserOrderProductList(UserOrderProductList UserOrderProductList)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.UserOrderProductLists.Add(UserOrderProductList);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = UserOrderProductList.id }, UserOrderProductList);
    }

what is going on and why does it all write NULL?
When i am writing with swagger is all turns out fine.

Body:
To post the contents of an Angular Ng-Repeat into a database table with an WEB API 2 backend, thanks to Arron Chen.

var data = $scope.test; // CONTENTS OF THE NG-REPEAT
var jsonData = angular.toJson(data);

$http({
    url: 'http://url/api/UserOrderProductList',
    method: "POST",
    data: jsonData,
    headers: { 'Content-Type': 'application/json' }

}).success(function (data) {
   alert("done");
});

With the matching backend:

// POST: api/UserOrders
[Route("api/UserOrderProductList/AddOrderList")]
public HttpResponseMessage PostUserOrderProductList(List<UserOrderProductList> UserOrderProductList)
{

   db.UserOrderProductLists.AddRange(UserOrderProductList);
   db.SaveChangesAsync();

   return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}


问:
sed replace spaces in directory names
I'm trying to replace space with - in directory names, not file names on macOS. I have the following:

```<code>cd ~/foo
for directory in **; do
    if [[ -d $directory ]] && [[ -w $directory ]]; then
        sed -i '' 's/  /-/g' "$directory"
    fi
done
</code>```

However I'm getting an error in-place editing only works for regular files.

How can I replace spaces in directory names?

答:
sed is meant for search and replacement on files and not on directories in  Linux/Unix. The -i flag in sed is used to make the text replacement on-the-fly on a file, the action simply does not make sense for a directory. You probably meant to change the name of the directory using sed on the filename and eventually use mv to rename the actual directory with the replaced string.

But you could just use mv in the first place with shell native features to replace white space with a - character.

```<code>for directory in **; do
    if [[ -d $directory ]] && [[ -w $directory ]]; then
        mv -- "$directory" "${directory// /-}"
    fi
done
</code>```

Title: sed replace spaces in directory names

Body:
I'm trying to replace space with - in directory names, not file names on macOS. I have the following:

cd ~/foo
for directory in **; do
    if [[ -d $directory ]] && [[ -w $directory ]]; then
        sed -i '' 's/  /-/g' "$directory"
    fi
done

However I'm getting an error in-place editing only works for regular files.

How can I replace spaces in directory names?

Body:
sed is meant for search and replacement on files and not on directories in  Linux/Unix. The -i flag in sed is used to make the text replacement on-the-fly on a file, the action simply does not make sense for a directory. You probably meant to change the name of the directory using sed on the filename and eventually use mv to rename the actual directory with the replaced string.

But you could just use mv in the first place with shell native features to replace white space with a - character.

for directory in **; do
    if [[ -d $directory ]] && [[ -w $directory ]]; then
        mv -- "$directory" "${directory// /-}"
    fi
done


问:
Why return sequences in stacked RNNs?
When stacking RNNs, it is mandatory to set return_sequences parameter as True in Keras.

For instance in Keras,

```<code>lstm1 = LSTM(1, return_sequences=True)(inputs1)
lstm2 = LSTM(1)(lstm1)
</code>```

It is somewhat intuitive to preserve the dimensionality of input space for each stacked RNN layer, however, I am not convinced thoroughly.

Can someone (mathematically) explain the reason?

Thanks.

答:
The input shape for recurrent layers is:

(number_of_sequences, time_steps, input_features).

This is absolutely required for recurrent layers because there can only be any recurrency if there are time steps.

Now, compare the "outputs" of the recurrent layers in each case:

with return_sequences=True - (number_of_sequences, time_steps, output_features)

with return_sequences=False - (number_of_sequences, output_features)

Without return_sequences=True, you eliminate the time steps, so, it cannot be fed into a recurrent layer, because there aren't enough dimensions and the most important one, the time_steps is not present.

Title: Why return sequences in stacked RNNs?

Body:
When stacking RNNs, it is mandatory to set return_sequences parameter as True in Keras.

For instance in Keras,

lstm1 = LSTM(1, return_sequences=True)(inputs1)
lstm2 = LSTM(1)(lstm1)

It is somewhat intuitive to preserve the dimensionality of input space for each stacked RNN layer, however, I am not convinced thoroughly.

Can someone (mathematically) explain the reason?

Thanks.


答:
Just add display:flex like this

```<code>    .input-con {
    position: relative;
    display:flex;
    }
</code>```

Learn more about flex

Body:
Just add display:flex like this

    .input-con {
    position: relative;
    display:flex;
    }

Learn more about flex


问:
Copy workbook name to a cell in another workbook
I want to search for an open file named "OTIF"[...].

When the macro finds the workbook, it should paste the file name into "sheet1" Cell A1 in another workbook (wb2).

```<code>Sub Filename()

Dim Wb1 As Workbook, wb2 As Workbook, wB As Workbook

For Each wB In Application.Workbooks
    If Left(wB.Name, 4) = "OTIF" Then
        Set Wb1 = wB
        Exit For
    End If
Next

If Not Wb1 Is Nothing Then
    Set wb2 = ThisWorkbook
End If

With wb2.Sheets("AAA")
    .Range("A1").Value = Dir(Wb1.FullName)
End With

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

MsgBox "DONE!"

End Sub
</code>```

答:
What do you want to achieve with

```<code>Dir(Wb1.FullName)
</code>```

That is the source of your problem. Just delete the Dir and the () and its running: .Range("A1").Value = Wb1.FullName

Body:
I want to search for an open file named "OTIF"[...].

When the macro finds the workbook, it should paste the file name into "sheet1" Cell A1 in another workbook (wb2).

Sub Filename()

Dim Wb1 As Workbook, wb2 As Workbook, wB As Workbook

For Each wB In Application.Workbooks
    If Left(wB.Name, 4) = "OTIF" Then
        Set Wb1 = wB
        Exit For
    End If
Next

If Not Wb1 Is Nothing Then
    Set wb2 = ThisWorkbook
End If

With wb2.Sheets("AAA")
    .Range("A1").Value = Dir(Wb1.FullName)
End With

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

MsgBox "DONE!"

End Sub

Body:
What do you want to achieve with

Dir(Wb1.FullName)

That is the source of your problem. Just delete the Dir and the () and its running: .Range("A1").Value = Wb1.FullName


问:
Grails String to BigDecimal
I can't figure out how to transform a String into a BigDecimal inside a Grails Application.

I'm doing:

```<code>person.salary = params.number
</code>```

But I got a error.

```<code>*salary is a BigDecimal and params.number is always a string.
</code>```

答:
If you really want number parameter to be BigDecimal you can consider to the bind parameter with following method:

Method 1: Bind as Controller Action's argument

Instead of access by params.number you can add number parameter as below:

```<code>def anyAction(double number){
  ...
  person.salary = number
  ...
}
</code>```

Method 2: Data Binding with Domain object

Create a domain

```<code>class SomeClass {
    BigDecimal number
}
</code>```

Data binding in controller action

```<code>// will bind every parameters in params to an object dataBinding
def dataBinding = new SomeClass(params)
person.salary = dataBinding.number // it number are BigDecimal
</code>```

May be there are other way than this, but I hope it can help

Title: Grails String to BigDecimal

Body:
I can't figure out how to transform a String into a BigDecimal inside a Grails Application.

I'm doing:

person.salary = params.number

But I got a error.

*salary is a BigDecimal and params.number is always a string.

Body:
If you really want number parameter to be BigDecimal you can consider to the bind parameter with following method:

Method 1: Bind as Controller Action's argument

Instead of access by params.number you can add number parameter as below:

def anyAction(double number){
  ...
  person.salary = number
  ...
}

Method 2: Data Binding with Domain object

Create a domain

class SomeClass {
    BigDecimal number
}

Data binding in controller action

// will bind every parameters in params to an object dataBinding
def dataBinding = new SomeClass(params)
person.salary = dataBinding.number // it number are BigDecimal

May be there are other way than this, but I hope it can help


问:
Javascript redirect won't work on mobile

I have a piece of Javascript code (below) that redirects a user to the homepage of my website by opening in a new tab. The issue I'm having is that it doesn't work on mobile.

```<code>function redirect(url) {
var win = window.open(url);
win.focus();
}
</code>```

When I click the button that is supposed to open the new tab, nothing happens but it works on desktop in Opera and Chrome.

Does anyone know how to fix this so it will work on mobile?

Edit: HTML added as per request

```<code><!DOCTYPE html>
<html>
<head>
<title>Login</title>
<script src="login.js"></script>
<link rel="stylesheet" type="text/css" href="login.css">
</head>
<body>

<h2>Modal Login Form</h2>

<button onclick="document.getElementById('id01').style.display='block'"
    style="width: auto;">Login</button>

<div id="id01" class="modal">

    <form class="modal-content animate" method=POST>
        <div class="imgcontainer">
            <span onclick="document.getElementById('id01').style.display='none'"
                class="close" title="Close Modal">×</span> <img
                src="loginAvatar.png" alt="Avatar" class="avatar">
        </div>

        <div class="container">
            <label><b>Username</b></label> <input type="text"
                placeholder="Enter Username" name="username" id="uname" required>
            <script>
                var suppliedUsername = document.getElementById("uname").value;
            </script>

            <label><b>Password</b></label> <input type="password"
                placeholder="Enter Password" name="psw" id = "pword" onChange="verify(document.getElementById('uname').value, document.getElementById('pword').value)" required>
            <script>
                var password = document.getElementById("pword").value;
            </script>
            <button id="loginbutton" onClick="verify(document.getElementById('uname').value, document.getElementById('pword').value)">Login</button>
            <input type="checkbox" checked="checked"> Remember me
        </div>

        <div class="container" style="background-color: #f1f1f1">
            <button type="button"
                onclick="document.getElementById('id01').style.display='none'"
                class="cancelbtn">Cancel</button>
            <span class="psw">Forgot <a href="#">password?</a></span>
        </div>
    </form>
</div>

<script>
    // Get the modal
    var modal = document.getElementById('id01');

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
</script>
</body>
</html>
</code>```

答:
Just use a link. If you want, you can style it like a button with CSS.

```<code><a href="url" target="_blank">Text</a>`
</code>```

Why do you have to use fancy Javascript to do something you could otherwise do with a simple link?

And if you need to trigger it within the Javascript code, look at this post. Or if you are using jQuery (which I think you are) look here.

Body:
I have a piece of Javascript code (below) that redirects a user to the homepage of my website by opening in a new tab. The issue I'm having is that it doesn't work on mobile.

function redirect(url) {
var win = window.open(url);
win.focus();
}

When I click the button that is supposed to open the new tab, nothing happens but it works on desktop in Opera and Chrome.

Does anyone know how to fix this so it will work on mobile?

Edit: HTML added as per request

<!DOCTYPE html>

<title>Login</title>

<link rel="stylesheet" type="text/css" href="login.css">

Modal Login Form

<button onclick="document.getElementById('id01').style.display='block'"
    style="width: auto;">Login</button>

    <form class="modal-content animate" method=POST>

            ×

            Username <input type="text"
                placeholder="Enter Username" name="username" id="uname" required>

            Password <input type="password"
                placeholder="Enter Password" name="psw" id = "pword" onChange="verify(document.getElementById('uname').value, document.getElementById('pword').value)" required>

            <button id="loginbutton" onClick="verify(document.getElementById('uname').value, document.getElementById('pword').value)">Login</button>
            <input type="checkbox" checked="checked"> Remember me

            <button type="button"
                onclick="document.getElementById('id01').style.display='none'"
                class="cancelbtn">Cancel</button>
            Forgot password?

    </form>

Body:
Just use a link. If you want, you can style it like a button with CSS.

<a href="url" target="_blank">Text</a>`

Why do you have to use fancy Javascript to do something you could otherwise do with a simple link?

And if you need to trigger it within the Javascript code, look at this post. Or if you are using jQuery (which I think you are) look here.


答:
The reason you are seeing a discrepancy in the height is due - I think - to the font property, which includes shorthand for font-weight, font-size and font-family.

If you explicitly override this property for both input and button the height will match up.

.input-con {
  position: relative;
}

.input-con>* {
  line-height: 1;
  display: inline-block;
  vertical-align: middle;
  padding: 10px;
  border: 0;
  background-color: #ddd;
  color: #444;
  outline: 0;
  cursor: pointer;
  font-size: 15px;
  box-sizing: border-box;
}

input,
button {
  font: 400 15px Arial !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="input-con">
  <input type="text" />
  <button>Search</button>
</div></code>```

updated as per comment

It will not work to declare font-weight, font-size and font-family separately, as this does not override the font shorthand completely.

The full shorthand is:

```<code>font: font-style font-variant font-weight font-size/line-height font-family;
</code>```

Only if each of these properties is declared will the font property be overridden.

Note that font contains three separate properties for font-variant (ligatures, caps and numeric) - it seems that using font-variant is sufficient.

demo

.input-con {
  position: relative;
}

.input-con>* {

  /* override all properties of the 'font' shorthand */
  font-style: normal;
  font-variant: normal;
  font-weight: 400;
  font-size: 18px;
  line-height: normal;
  font-family: Arial, sans-serif;

  display: inline-block;
  vertical-align: middle;
  padding: 10px;
  border: 0;
  background-color: #ddd;
  color: #444;
  outline: 0;
  cursor: pointer;
  box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="input-con">
  <input type="text" />
  <button>Search</button>
</div></code>```

Body:
I am having same css properties, yet the button and input fields are different fields

.input-con {
  position: relative;
}

.input-con>* {
  line-height: 1;
  display: inline-block;
  vertical-align: middle;
  padding: 10px;
  border: 0;
  background-color: #ddd;
  color: #444;
  outline: 0;
  cursor: pointer;
  font-size: 15px;
  box-sizing: border-box;
}

  <input type="text" />
  <button>Search</button>

pen - https://codepen.io/digitalzoomstudio/pen/LOoVYK

How could I achieve same heights without forcing height property ?

Body:
The reason you are seeing a discrepancy in the height is due - I think - to the font property, which includes shorthand for font-weight, font-size and font-family.

If you explicitly override this property for both input and button the height will match up.

.input-con {
  position: relative;
}

.input-con>* {
  line-height: 1;
  display: inline-block;
  vertical-align: middle;
  padding: 10px;
  border: 0;
  background-color: #ddd;
  color: #444;
  outline: 0;
  cursor: pointer;
  font-size: 15px;
  box-sizing: border-box;
}

input,
button {
  font: 400 15px Arial !important;
}

<div class="input-con">
  <input type="text" />
  <button>Search</button>
</div>

updated as per comment

It will not work to declare font-weight, font-size and font-family separately, as this does not override the font shorthand completely.

The full shorthand is:

font: font-style font-variant font-weight font-size/line-height font-family;

Only if each of these properties is declared will the font property be overridden.

Note that font contains three separate properties for font-variant (ligatures, caps and numeric) - it seems that using font-variant is sufficient.

demo

.input-con {
  position: relative;
}

.input-con>* {

  /* override all properties of the 'font' shorthand */
  font-style: normal;
  font-variant: normal;
  font-weight: 400;
  font-size: 18px;
  line-height: normal;
  font-family: Arial, sans-serif;

  display: inline-block;
  vertical-align: middle;
  padding: 10px;
  border: 0;
  background-color: #ddd;
  color: #444;
  outline: 0;
  cursor: pointer;
  box-sizing: border-box;
}

<div class="input-con">
  <input type="text" />
  <button>Search</button>
</div>


问:
call api response on getting in react js
I'm beginner in redux and ReactJs. I have issue with when i trying to call login api the response not getting.

```<code>import { CALL_API } from 'redux-api-middleware';
export function login(toSend) {
    return function(dispatch, getState) {
        dispatch(mopetsLogin(toSend)).then(() =>
        {
            console.log(getState().mopets_api.token.access_token);
            dispatch(mopetsMe(getState().mopets_api.token.access_token));
        });
    }
}

export function mopetsLogin(toSend) {
    console.log('toSend');
    console.log(toSend);
    return {
        [CALL_API]: {
            endpoint: 'http://api.mopets.com/app_dev.php/login',
            method: 'POST',
            /*headers: { 'Content-Type': 'application/json' },*/
            body: JSON.stringify(toSend),
            types: [
                'INITIAL_LOGIN_MOPETS_REQUEST',
                {
                    type: 'INITIAL_LOGIN_MOPETS_SUCCESS',
                    payload: (action, state, res) => {
                        const contentType = res.headers.get('Content-Type');
                        if (contentType && ~contentType.indexOf('json')) {
                            // Just making sure res.json() does not raise an error
                            const contentType = res.headers.get('Content-Type');
                            if (contentType && ~contentType.indexOf('json')) {
                                // Just making sure res.json() does not raise an error
                                return res.json().then((json) => {
                                        var o = new Object();
                                        o["token"] = json;
                                        return o;
                                    }
                                )
                            }
                            ;
                        }
                    }
                },
                'INITIAL_LOGIN_MOPETS_FAILURE'
            ]
        }
    }
}
</code>```

main.bundle.js:42605 Uncaught (in promise) TypeError: Cannot read property 'access_token' of undefined

this type error showing
can please look the code and provide some information to solve this.

答:
This appens firs because your

```<code>getState().mopets_api.token
</code>```

is undefined.

Maybe it is only a path problem, try to console.log your res to check if the object gets correctly populated.

Body:
I'm beginner in redux and ReactJs. I have issue with when i trying to call login api the response not getting.

import { CALL_API } from 'redux-api-middleware';
export function login(toSend) {
    return function(dispatch, getState) {
        dispatch(mopetsLogin(toSend)).then(() =>
        {
            console.log(getState().mopets_api.token.access_token);
            dispatch(mopetsMe(getState().mopets_api.token.access_token));
        });
    }
}

export function mopetsLogin(toSend) {
    console.log('toSend');
    console.log(toSend);
    return {
        [CALL_API]: {
            endpoint: 'http://api.mopets.com/app_dev.php/login',
            method: 'POST',
            /*headers: { 'Content-Type': 'application/json' },*/
            body: JSON.stringify(toSend),
            types: [
                'INITIAL_LOGIN_MOPETS_REQUEST',
                {
                    type: 'INITIAL_LOGIN_MOPETS_SUCCESS',
                    payload: (action, state, res) => {
                        const contentType = res.headers.get('Content-Type');
                        if (contentType && ~contentType.indexOf('json')) {
                            // Just making sure res.json() does not raise an error
                            const contentType = res.headers.get('Content-Type');
                            if (contentType && ~contentType.indexOf('json')) {
                                // Just making sure res.json() does not raise an error
                                return res.json().then((json) => {
                                        var o = new Object();
                                        o["token"] = json;
                                        return o;
                                    }
                                )
                            }
                            ;
                        }
                    }
                },
                'INITIAL_LOGIN_MOPETS_FAILURE'
            ]
        }
    }
}

main.bundle.js:42605 Uncaught (in promise) TypeError: Cannot read property 'access_token' of undefined

this type error showing
can please look the code and provide some information to solve this.

Body:
This appens firs because your

getState().mopets_api.token

is undefined.

Maybe it is only a path problem, try to console.log your res to check if the object gets correctly populated.