问:
Library installed and shown in conda, but not usable in Jupyter Notebook
The pillow library is installed via conda, and the status is verified in the jupyter notebook.  However when I try to import pillow library in the same jupyter notebook instance, I cannot find this library.

I tried to manually run jupyter notebook cli in conda environment (with pillow installed), as well using anaconda GUI shortcuts, none of them could find pillow library.

!conda list pillow
import pillow
```

<p>Output</p>

<pre class="lang-py prettyprint-override"><code># packages in environment at C:\ProgramData\Anaconda3\envs\jupyter:
#
# Name                    Version                   Build  Channel
pillow                    6.0.0            py37h9a613e6_0    conda-forge
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-6-dc0fbd63c36f> in <module>
      1 get_ipython().system('conda list pillow')
----> 2 import pillow

ModuleNotFoundError: No module named 'pillow'
</code>```

答:
pillow is a fork of PIL (Python Imaging Library) so it can't be imported, it's PIL that is imported.

Use:-

```<code>import PIL
</code>```

or import any specific module by

```<code>from PIL import Module_name
</code>```

Body:
The pillow library is installed via conda, and the status is verified in the jupyter notebook.  However when I try to import pillow library in the same jupyter notebook instance, I cannot find this library.

I tried to manually run jupyter notebook cli in conda environment (with pillow installed), as well using anaconda GUI shortcuts, none of them could find pillow library.

!conda list pillow
import pillow

Output

# packages in environment at C:\ProgramData\Anaconda3\envs\jupyter:
#
# Name                    Version                   Build  Channel
pillow                    6.0.0            py37h9a613e6_0    conda-forge
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-6-dc0fbd63c36f> in <module>
      1 get_ipython().system('conda list pillow')
----> 2 import pillow

ModuleNotFoundError: No module named 'pillow'

Body:
pillow is a fork of PIL (Python Imaging Library) so it can't be imported, it's PIL that is imported.

Use:-

import PIL

or import any specific module by

from PIL import Module_name


来源: stackexchange

问:
How to open json file dynamically?
I have a json file within a folder that I want to open dynamically within my main app.py, is there a way to do this?

This is what my folders look like

```<code>C:.
|   app.py
|   README.txt
|   tree.txt
|
+---resources
|       stores.json
|
+---templates
|       Tails.html
|
+---test
|       Unit_Test.py
|
\---__pycache__
        app.cpython-37.pyc
        Tails.cpython-37.pyc
</code>```

I currently have this is app.py which gives me an error; expected str, bytes or os.PathLike object, not NoneType

```<code>from pydoc import locate

def read_jsonfile():
    with open(locate('resources.stores.json')) as f:
        stpres = json.load(f)

    return stores
</code>```

Any help or suggestions would be appreciated.

答:
If you are sure that stores.json has fixed path relative to C drive you in you getJSON function you can change working dir to that path like:

Since I am using linux as assuming my file is at /home/user/resource/store.json and I am working from some other file path:

```<code>import os

def getJSON():
    curr = os.getcwd()
    csvFilePath = os.chdir("/home/user/resource")
    with open("store.json") as f:
        print("do something")
    os.chdir(curr)
</code>```

See if this helps.

ContentLicense: CC BY-SA 4.0

Title: How to open json file dynamically?

Body:
I have a json file within a folder that I want to open dynamically within my main app.py, is there a way to do this?

This is what my folders look like

C:.
|   app.py
|   README.txt
|   tree.txt
|
+---resources
|       stores.json
|
+---templates
|       Tails.html
|
+---test
|       Unit_Test.py
|
\---__pycache__
        app.cpython-37.pyc
        Tails.cpython-37.pyc

I currently have this is app.py which gives me an error; expected str, bytes or os.PathLike object, not NoneType

from pydoc import locate

def read_jsonfile():
    with open(locate('resources.stores.json')) as f:
        stpres = json.load(f)

    return stores

Any help or suggestions would be appreciated.

Body:
If you are sure that stores.json has fixed path relative to C drive you in you getJSON function you can change working dir to that path like:

Since I am using linux as assuming my file is at /home/user/resource/store.json and I am working from some other file path:

import os

def getJSON():
    curr = os.getcwd()
    csvFilePath = os.chdir("/home/user/resource")
    with open("store.json") as f:
        print("do something")
    os.chdir(curr)

See if this helps.


问:
MySQL JDBC driver failed to create schema with hyphen
I have an application with schema per tenant architecture. But when the tentant name contains hyphen, schema creation failed.
The datasource creation:

```<code>HikariDataSource ds = new HikariDataSource();
ds.setUsername(username);
ds.setPassword(password);
ds.setJdbcUrl("jdbc:mysql://localhost:3306/tenant-test");
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
ds.addDataSourceProperty( "allowMultiQueries" , "true" );
ds.addDataSourceProperty( "autoReconnect" , "true" );
ds.addDataSourceProperty( "characterEncoding" , "UTF-8" );
ds.addDataSourceProperty( "useUnicode" , "true" );
ds.addDataSourceProperty( "createDatabaseIfNotExist" , "true" );
ds.getConnection(); // exception thrown here
</code>```

Is there any property I have to set? When schema exists, everything works fine. Also schema without hyphen is created successfully. Based on the stack trace, it looks like an issue in mysql jdbc driver.

Exception stack trace:

```<code>Caused by: java.sql.SQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:110) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:905) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:830) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:136) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:369) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:198) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:467) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:541) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-3.2.0.jar:na]
    at org.flywaydb.core.internal.jdbc.JdbcUtils.openConnection(JdbcUtils.java:56) ~[flyway-core-5.2.4.jar:na]
    ... 54 common frames omitted
Caused by: com.mysql.cj.exceptions.CJException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-test' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_144]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_144]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_144]
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:129) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.protocol.a.NativeProtocol.checkErrorMessage(NativeProtocol.java:816) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.protocol.a.NativeProtocol.checkErrorMessage(NativeProtocol.java:741) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.protocol.a.NativeProtocol.sendCommand(NativeProtocol.java:671) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.protocol.a.NativeProtocol.changeDatabase(NativeProtocol.java:543) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.protocol.a.NativeAuthenticationProvider.proceedHandshakeWithPluggableAuthentication(NativeAuthenticationProvider.java:706) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.protocol.a.NativeAuthenticationProvider.connect(NativeAuthenticationProvider.java:202) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.protocol.a.NativeProtocol.connect(NativeProtocol.java:1449) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.NativeSession.connect(NativeSession.java:165) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:849) ~[mysql-connector-java-8.0.14.jar:8.0.14]
</code>```

EDIT:

I think it's a bug. I looked into mysql connector sources and I found out that the db name is not quoted...

NativeProtocol.java, row 542:

```<code>if (this.getPropertySet().getBooleanProperty(PropertyKey.createDatabaseIfNotExist).getValue()) {
                sendCommand(this.commandBuilder.buildComQuery(getSharedSendPacket(), "CREATE DATABASE IF NOT EXISTS " + database), false, 0);
...
</code>```

答:
In MySQL, the dash (hyphen) character is not a permitted character in an unquoted identifier.

Rules for identifiers are documented here in the MySQL Reference Manual:

https://dev.mysql.com/doc/refman/8.0/en/identifiers.html

To use the hyphen character, the identifier must be quoted. Normally we use backtick characters, e.g.

```<code> SELECT `foo` FROM `bar`
</code>```

If sql_mode includes ANSI_QUOTES, we can use double quotes to escaped identifiers.

MySQL is reporting  ubiquitous error 1064. That's getting reported in the stack trace:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-test' at line 1

Body:
I have an application with schema per tenant architecture. But when the tentant name contains hyphen, schema creation failed.
The datasource creation:

HikariDataSource ds = new HikariDataSource();
ds.setUsername(username);
ds.setPassword(password);
ds.setJdbcUrl("jdbc:mysql://localhost:3306/tenant-test");
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
ds.addDataSourceProperty( "allowMultiQueries" , "true" );
ds.addDataSourceProperty( "autoReconnect" , "true" );
ds.addDataSourceProperty( "characterEncoding" , "UTF-8" );
ds.addDataSourceProperty( "useUnicode" , "true" );
ds.addDataSourceProperty( "createDatabaseIfNotExist" , "true" );
ds.getConnection(); // exception thrown here

Is there any property I have to set? When schema exists, everything works fine. Also schema without hyphen is created successfully. Based on the stack trace, it looks like an issue in mysql jdbc driver.

Exception stack trace:

Caused by: java.sql.SQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:110) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:905) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:830) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:136) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:369) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:198) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:467) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:541) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-3.2.0.jar:na]
    at org.flywaydb.core.internal.jdbc.JdbcUtils.openConnection(JdbcUtils.java:56) ~[flyway-core-5.2.4.jar:na]
    ... 54 common frames omitted
Caused by: com.mysql.cj.exceptions.CJException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-test' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_144]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_144]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_144]
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:129) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.protocol.a.NativeProtocol.checkErrorMessage(NativeProtocol.java:816) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.protocol.a.NativeProtocol.checkErrorMessage(NativeProtocol.java:741) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.protocol.a.NativeProtocol.sendCommand(NativeProtocol.java:671) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.protocol.a.NativeProtocol.changeDatabase(NativeProtocol.java:543) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.protocol.a.NativeAuthenticationProvider.proceedHandshakeWithPluggableAuthentication(NativeAuthenticationProvider.java:706) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.protocol.a.NativeAuthenticationProvider.connect(NativeAuthenticationProvider.java:202) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.protocol.a.NativeProtocol.connect(NativeProtocol.java:1449) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.NativeSession.connect(NativeSession.java:165) ~[mysql-connector-java-8.0.14.jar:8.0.14]
    at com.mysql.cj.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:849) ~[mysql-connector-java-8.0.14.jar:8.0.14]

EDIT:

I think it's a bug. I looked into mysql connector sources and I found out that the db name is not quoted...

NativeProtocol.java, row 542:

if (this.getPropertySet().getBooleanProperty(PropertyKey.createDatabaseIfNotExist).getValue()) {
                sendCommand(this.commandBuilder.buildComQuery(getSharedSendPacket(), "CREATE DATABASE IF NOT EXISTS " + database), false, 0);
...

Body:
In MySQL, the dash (hyphen) character is not a permitted character in an unquoted identifier.

Rules for identifiers are documented here in the MySQL Reference Manual:

https://dev.mysql.com/doc/refman/8.0/en/identifiers.html

To use the hyphen character, the identifier must be quoted. Normally we use backtick characters, e.g.

 SELECT `foo` FROM `bar`

If sql_mode includes ANSI_QUOTES, we can use double quotes to escaped identifiers.

MySQL is reporting  ubiquitous error 1064. That's getting reported in the stack trace:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-test' at line 1


问:
When changing one value in cell, automatically fill out other cells
I would like to make a cell (B7) be able to automatically input value in cells B10:B12 based on the data from B2:D2 (that are put in manually)

Example: When putting in the ID 000100, B10:B12 should have the dates: 01-feb.2019, 10-feb.-2019, 12-feb.-2019

&

ID 000200 will then put in 01-mar.2019, 10-mar.-2019, 12-mar.-2019 in cell B10:B12

答:
Slightly shorter and should preserve the formatting:</p>

```<code>=transpose(offset(A1,match(B7,A:A,0)-1,1,1,3))
</code>```

Body:
Slightly shorter and should preserve the formatting:

=transpose(offset(A1,match(B7,A:A,0)-1,1,1,3))


答:
Here is REDUCE solution, REDUCE operator is iavailable since ABAP 7.40 SP08.

```<code>TYPES: BEGIN OF ty_s_value,
        sparte TYPE char2,
        vkont  TYPE char12,
        exbel  TYPE char16,
       END OF ty_s_value.
TYPES: ty_t_value TYPE STANDARD TABLE OF ty_s_value WITH EMPTY KEY.

DATA(lt_tab) =
VALUE ty_t_value(
                 ( sparte = '05' vkont = '800000008422' exbel = '1NSN150900000058')
                 ( sparte = 'L2' vkont = '800000008422' exbel = '1NSN150900000058')
                 ( sparte = '05' vkont = '800000008422' exbel = '1NSN150900000037')
                 ( sparte = 'L2' vkont = '800000008422' exbel = '1NSN150900000037')
                 ( sparte = '05' vkont = '800000008422' exbel = '1NSN150900000013')
                 ( sparte = 'L2' vkont = '800000008422' exbel = '1NSN150900000013')
                 ( sparte = '05' vkont = '800000008415' exbel = '1HSN151200000009')
                 ( sparte = 'S1' vkont = '800000008415' exbel = '1HSN151200000009')
                 ( sparte = '05' vkont = '800000008415' exbel = '1HSN151200000008')
                 ( sparte = 'S1' vkont = '800000008415' exbel = '1HSN151200000008')
                 ( sparte = 'L1' vkont = '800000008422' exbel = '1NSN150900000050')
                 ( sparte = 'L1' vkont = '800000008422' exbel = '1NSN150900000029')
                ...
                ).

DATA(lt_result) =
VALUE ty_t_value( FOR GROUPS <group_key> OF <wa> IN lt_tab
                  GROUP BY ( sparte = <wa>-sparte vkont = <wa>-vkont )
                  LET max2 =
                  REDUCE #( INIT max =
                            VALUE ty_s_value( )
                            FOR <m> IN GROUP <group_key>
                            NEXT max = COND #( WHEN <m>-exbel > max-exbel THEN <m> ELSE max ) )
                  IN ( max2 ) ).
</code>```

BTW, your expected resultset is missing L1 line, I assume in your selection you respect not only VKONT but SPARTE too.

Title: Select max field value from a group of records?

Body:
I need to get the lines with the highest EXBEL registers from an itab for every different VKONT.

The result table may contain several lines for the same VKONT value if this latter one has several lines in the source table with the same highest EXBEL value.

Actual source table:

SPARTE  VKONT         EXBEL
05      800000008422  1NSN150900000058
L2      800000008422  1NSN150900000058
05      800000008422  1NSN150900000037
L2      800000008422  1NSN150900000037
05      800000008422  1NSN150900000013
L2      800000008422  1NSN150900000013
05      800000008415  1HSN151200000009
S1      800000008415  1HSN151200000009
05      800000008415  1HSN151200000008
S1      800000008415  1HSN151200000008
L1      800000008422  1NSN150900000050
L1      800000008422  1NSN150900000029
L1      800000008422  1NSN150900000023
05      800000008415  1HSN151200000012
S1      800000008415  1HSN151200000012
05      800000008422  1NSN150900000058
L2      800000008422  1NSN150900000058
05      800000008415  1HSN151200000009
S1      800000008415  1HSN151200000009

Expected result table:

SPARTE  VKONT         EXBEL
05      800000008422  1NSN150900000058
L2      800000008422  1NSN150900000058
05      800000008415  1HSN151200000012
S1      800000008415  1HSN151200000012

I tried different solutions but didn't work.

Any help will be appreciated.

Raúl.

Body:
Here is REDUCE solution, REDUCE operator is iavailable since ABAP 7.40 SP08.

TYPES: BEGIN OF ty_s_value,
        sparte TYPE char2,
        vkont  TYPE char12,
        exbel  TYPE char16,
       END OF ty_s_value.
TYPES: ty_t_value TYPE STANDARD TABLE OF ty_s_value WITH EMPTY KEY.

DATA(lt_tab) =
VALUE ty_t_value(
                 ( sparte = '05' vkont = '800000008422' exbel = '1NSN150900000058')
                 ( sparte = 'L2' vkont = '800000008422' exbel = '1NSN150900000058')
                 ( sparte = '05' vkont = '800000008422' exbel = '1NSN150900000037')
                 ( sparte = 'L2' vkont = '800000008422' exbel = '1NSN150900000037')
                 ( sparte = '05' vkont = '800000008422' exbel = '1NSN150900000013')
                 ( sparte = 'L2' vkont = '800000008422' exbel = '1NSN150900000013')
                 ( sparte = '05' vkont = '800000008415' exbel = '1HSN151200000009')
                 ( sparte = 'S1' vkont = '800000008415' exbel = '1HSN151200000009')
                 ( sparte = '05' vkont = '800000008415' exbel = '1HSN151200000008')
                 ( sparte = 'S1' vkont = '800000008415' exbel = '1HSN151200000008')
                 ( sparte = 'L1' vkont = '800000008422' exbel = '1NSN150900000050')
                 ( sparte = 'L1' vkont = '800000008422' exbel = '1NSN150900000029')
                ...
                ).

DATA(lt_result) =
VALUE ty_t_value( FOR GROUPS <group_key> OF <wa> IN lt_tab
                  GROUP BY ( sparte = <wa>-sparte vkont = <wa>-vkont )
                  LET max2 =
                  REDUCE #( INIT max =
                            VALUE ty_s_value( )
                            FOR <m> IN GROUP <group_key>
                            NEXT max = COND #( WHEN <m>-exbel > max-exbel THEN <m> ELSE max ) )
                  IN ( max2 ) ).

BTW, your expected resultset is missing L1 line, I assume in your selection you respect not only VKONT but SPARTE too.


问:
Remove HTML paragraph using removeChild
I wrote a code like below:

```<code>     <input type="button" value="remove" onclick="remove()"/>

     <p id="p2">
        before hr
        <hr/>
        after hr
     </p>

  <script>
     function remove() {
        var p = document.getElementById('p2');
        p.parentNode.removeChild(p);
     }
  </script>
</code>```

When I hit the button, only "before hr" disappear - hr and "after hr" text don't.

If I change
 to
 :

```<code><div id="p2">
    before hr
    <hr/>
    after hr
 </div>
</code>```

everything works properly (i.e. like I supposed it should works ;) )

Could somebody explain me the reasons, please?

答:
Your problem is expected... due to P tag can only contain Phrasing content. Semantically is incorrect and the browser automatically adds a new P element after the HR tag...
https://stackoverflow.com/a/23536324/2894798

As you said with a div this will work.. that would be the correct answer..

<input type="button" value="remove" onclick="remove()"/>

        before hr

        after hr

  ```

Title: Remove HTML paragraph using removeChild

Body:
I wrote a code like below:

     <input type="button" value="remove" onclick="remove()"/>

        before hr

        after hr

When I hit the button, only "before hr" disappear - hr and "after hr" text don't.

If I change
 to
 :

    before hr

    after hr

everything works properly (i.e. like I supposed it should works ;) )

Could somebody explain me the reasons, please?

Body:
Your problem is expected... due to P tag can only contain Phrasing content. Semantically is incorrect and the browser automatically adds a new P element after the HR tag...
https://stackoverflow.com/a/23536324/2894798

As you said with a div this will work.. that would be the correct answer..

<input type="button" value="remove" onclick="remove()"/>

     <div id="p2">
        before hr
       <hr/>

        after hr
     </div>

  <script>
     function remove() {
        var p = document.getElementById('p2');
        p.parentNode.removeChild(p);
     }
  </script>


问:
if/else do nothing for class inside td
I am trying the make the else do nothing. I would like to know if there's something wrong with this code? Any help?

```<code>if ($("div.pl_media_folder:first")){
    $('#pl_medias tr').attr('id', 'table-row-id');
    $('#pl_medias tr').attr('class', 'table-row-class');
} else {
    // Do nothing..
}
</code>```

It's adding the id and the class attribute for all the tr, I want to add them just for the ones that contain the class pl_media_folder inside the TD

答:
Firstly if you don't want the else statement to do anything you can simply remove it. Secondly, your logic isn't quite right as the if condition will always be true (due to objects coercing to true) and you don't need the if statement anyway.

To add the id and class to tr elements which contain a div.pl_media_folder then you can use has() like this:

```<code>$('#pl_medias tr').has('div.pl_media_folder').prop({
  'id': 'table-row-id',
  'class': 'table-row-class'
});
</code>```

Note that you will need to be careful with this logic as if there are multiple tr found you will be duplicating the same id, which is invalid.

Title: if/else do nothing for class inside td

Body:
I am trying the make the else do nothing. I would like to know if there's something wrong with this code? Any help?

if ($("div.pl_media_folder:first")){
    $('#pl_medias tr').attr('id', 'table-row-id');
    $('#pl_medias tr').attr('class', 'table-row-class');
} else {
    // Do nothing..
}

It's adding the id and the class attribute for all the tr, I want to add them just for the ones that contain the class pl_media_folder inside the TD

Body:
Firstly if you don't want the else statement to do anything you can simply remove it. Secondly, your logic isn't quite right as the if condition will always be true (due to objects coercing to true) and you don't need the if statement anyway.

To add the id and class to tr elements which contain a div.pl_media_folder then you can use has() like this:

$('#pl_medias tr').has('div.pl_media_folder').prop({
  'id': 'table-row-id',
  'class': 'table-row-class'
});

Note that you will need to be careful with this logic as if there are multiple tr found you will be duplicating the same id, which is invalid.


问:
Fill out empty spaces with underscore
I have a telegram that i have to send to the PLC, 1 substring of that telegram provides the barcodeID. It has 6 spaces and it starts with 1 and it is counting up.

For the PLC to work i have to fill up to empty spots wit an underscore. F.E.

_____1

____22

___333

Is there a way i can fix this?

I know that i can fill up the empty spaces with zero's like this: %06d

000001

000022

000333

```<code>gLog.LogPrintf(Info, "customerlog", "Storage Out Ready: %02d%02d%02d%s%04d%010d%02d%010d%010d%06d%06d%06d%06d%06d%06d%010d",
        (*inMessage)["sender"].asInt(), (*inMessage)["reciever"].asInt(), (*inMessage)["series"].asInt(), (*inMessage)["type"].asString().c_str(),
        (*inMessage)["command"].asInt(), (*inMessage)["id"].asInt(), (*inMessage)["priority"].asInt(), (*inMessage)["source"].asInt(),
        (*inMessage)["target"].asInt(), (*inMessage)["height"].asInt(), (*inMessage)["width"].asInt(), (*inMessage)["length"].asInt(),
        (*inMessage)["weight"].asInt(), (*inMessage)["status"].asInt(), (*inMessage)["error"].asInt(), (*inMessage)["data"].asInt());
        gLog.LogPrintf(Info, "Barcode ID: ", (*inMessage)["id"].asCString());
        gLog.LogPrintf(Info, "error: ", (*inMessage)["error"].asInt());
</code>```

答:
If you are able to use the standard library, you can use the formatting capabilities it provides. Here a mini demo of that:

```<code>#include <iostream>
#include <iomanip>
#include <sstream>

#define BUFFER_SIZE (10)
int main() {
  std::stringstream buffer;
  buffer << std::right << std::setw(BUFFER_SIZE) << std::setfill('_') << 1;
  std::cout << buffer.str() << std::endl;
  buffer.str(std::string());
  buffer << std::right << std::setw(BUFFER_SIZE) << std::setfill('_') << 1234;
  std::cout << buffer.str() << std::endl;
  buffer.str(std::string());
  buffer << std::right << std::setw(BUFFER_SIZE) << std::setfill('_') << 1234567;
  std::cout << buffer.str() << std::endl;
  buffer.str(std::string());
  return 0;
}
</code>```

std::right makes the formatting to align to right, std::setfill sets '_' as padding character and std::setw sets the width required.
Best regards.

Title: Fill out empty spaces with underscore

Body:
I have a telegram that i have to send to the PLC, 1 substring of that telegram provides the barcodeID. It has 6 spaces and it starts with 1 and it is counting up.

For the PLC to work i have to fill up to empty spots wit an underscore. F.E.

_____1

____22

___333

Is there a way i can fix this?

I know that i can fill up the empty spaces with zero's like this: %06d

000001

000022

000333

gLog.LogPrintf(Info, "customerlog", "Storage Out Ready: %02d%02d%02d%s%04d%010d%02d%010d%010d%06d%06d%06d%06d%06d%06d%010d",
        (*inMessage)["sender"].asInt(), (*inMessage)["reciever"].asInt(), (*inMessage)["series"].asInt(), (*inMessage)["type"].asString().c_str(),
        (*inMessage)["command"].asInt(), (*inMessage)["id"].asInt(), (*inMessage)["priority"].asInt(), (*inMessage)["source"].asInt(),
        (*inMessage)["target"].asInt(), (*inMessage)["height"].asInt(), (*inMessage)["width"].asInt(), (*inMessage)["length"].asInt(),
        (*inMessage)["weight"].asInt(), (*inMessage)["status"].asInt(), (*inMessage)["error"].asInt(), (*inMessage)["data"].asInt());
        gLog.LogPrintf(Info, "Barcode ID: ", (*inMessage)["id"].asCString());
        gLog.LogPrintf(Info, "error: ", (*inMessage)["error"].asInt());

Body:
If you are able to use the standard library, you can use the formatting capabilities it provides. Here a mini demo of that:

#include <iostream>
#include <iomanip>
#include <sstream>

#define BUFFER_SIZE (10)
int main() {
  std::stringstream buffer;
  buffer << std::right << std::setw(BUFFER_SIZE) << std::setfill('_') << 1;
  std::cout << buffer.str() << std::endl;
  buffer.str(std::string());
  buffer << std::right << std::setw(BUFFER_SIZE) << std::setfill('_') << 1234;
  std::cout << buffer.str() << std::endl;
  buffer.str(std::string());
  buffer << std::right << std::setw(BUFFER_SIZE) << std::setfill('_') << 1234567;
  std::cout << buffer.str() << std::endl;
  buffer.str(std::string());
  return 0;
}

std::right makes the formatting to align to right, std::setfill sets '_' as padding character and std::setw sets the width required.
Best regards.


问:
Is there an "easy way" of adding custom UI to a Qt application when using QGraphicsView?
I'm using QGraphicsView to show randomly generated polygons in a QGraphicsScene and it's all working fine and dandy, but now I want to add custom UI styling to my application and it's proving to be quite annoying to do everything by hand, while there are so many wonderful options out there like QtQuick. It is possible at all to use QtQuick or something like it together with a graphicsView?

Quick note:
I'm new to Qt so I might be missing something obvious here!

EDIT:

Added an image for clarification, I just want to modify the sliders and buttons to have a custom texture!

答:
Romha Korev's answer is correct when you want to use QML for that part of the UI.

Another option for styling is by using stylesheets. See the Qt stylesheet reference

If it's cumbersome for you to setup the widgets in code, try Qt Designer.

I use these 2 tools for making styled UI apps with Qt, and find it very handy


问:
is there a nice output of Keras model.summary( )?
is it possible to have a nice output of keras model.summary(), that can be included in paper, or can be ploted in a nice table like this.

答:
You need to install graphvis and pydot, but you might like the results from this. It doesn't make a table but the graph is much better in my opinion.

    from keras.utils import plot_model
    plot_model(model, to_file='model.png', show_shapes=True,show_layer_names=True)
```

But you would have to make properly named sub models if you want to nest the several layers together.

Body:
You need to install graphvis and pydot, but you might like the results from this. It doesn't make a table but the graph is much better in my opinion.

    from keras.utils import plot_model
    plot_model(model, to_file='model.png', show_shapes=True,show_layer_names=True)

But you would have to make properly named sub models if you want to nest the several layers together.


问:
What is meant by the fact that dictionaries in python don't retain order? What is exactly meant by order in this case?
I am learning python basics, and trying to understand the logic of programming fully. In the tutorial about dictionaries it says that they don't follow order, which I don't really get but feel like is an important part to understand.</p>

答:
Consider two dict instances in Python 3.7:

```<code>>>> d1 = {'a': 1, 'b': 2}
>>> d2 = {'b': 2, 'a': 1}
</code>```

A dict remembers the order in which the keys were inserted, but only uses that information for purpose of iterating over the keys. As long as the set of keys are identical, and each key maps to the same value, two dicts are considered equal, regardless of their iteration order.

```<code>>>> d1 == d2
True
>>> list(d1)
['a', 'b']
>>> list(d2)
['b', 'a']
</code>```

An OrderedDict, though, treats the insertion order as an integral property of the value itself.

```<code>>>> from collections import OrderedDict
>>> od1 = OrderedDict(d1)
>>> od2 = OrderedDict(d2)
>>> list(od1)
['a', 'b']
>>> list(od2)
['b', 'a']
>>> od1 == od2
False
</code>```

Body:
Consider two dict instances in Python 3.7:

>>> d1 = {'a': 1, 'b': 2}
>>> d2 = {'b': 2, 'a': 1}

A dict remembers the order in which the keys were inserted, but only uses that information for purpose of iterating over the keys. As long as the set of keys are identical, and each key maps to the same value, two dicts are considered equal, regardless of their iteration order.

>>> d1 == d2
True
>>> list(d1)
['a', 'b']
>>> list(d2)
['b', 'a']

An OrderedDict, though, treats the insertion order as an integral property of the value itself.

>>> from collections import OrderedDict
>>> od1 = OrderedDict(d1)
>>> od2 = OrderedDict(d2)
>>> list(od1)
['a', 'b']
>>> list(od2)
['b', 'a']
>>> od1 == od2
False


问:
ARD Unix Command Help - Answer Yes? - Automate Domain Unjoin / Rejoin
We had a bunch of Macs come up with no network access this morning, and unjoining and rejoining the domain fixes that. I'm trying to make this as automated as possible.

The following works great from Terminal with "yes | sudo sh myscript.sh", but I'm not sure how to make the UNIX Command answer yes when prompted when it says "Computer account already exists! Bind to Existing? (y/n):"

Here's what I have, and any advice is appreciated:

```<code>domain="mydomain"

username="myusername" password="mypassword"

olddomain=$( dsconfigad -show | awk '/Active Directory Domain/{print $NF}' ) computername=$( scutil --get ComputerName ) adcomputerid=$( echo "${computername}" | tr [:lower:] [:upper:] ) prefix="${adcomputerid:0:6}"

dsconfigad -remove -force -u "${username}" -p "${password}"

dsconfigad -add "${domain}" -username "${username}" -password "${password}"
</code>```

答:
The full answer would be:

```<code># ...
dsconfigad -add "${domain}" -force -username "${username}" -password "${password}"
</code>```

The -force forces the action (skips asking for user confirmation).

Relevant portion of the helptext below:

```<code>$ dsconfigad
Usage: dsconfigad -add domain -username value [-computer value] [-force]
                  [-password value] [-ou dn] [-preferred server]
                  [-localuser value] [-localpassword value]

# ...

  -force                force the process (i.e., join the existing account)

# ...
</code>```

Body:
We had a bunch of Macs come up with no network access this morning, and unjoining and rejoining the domain fixes that. I'm trying to make this as automated as possible.

The following works great from Terminal with "yes | sudo sh myscript.sh", but I'm not sure how to make the UNIX Command answer yes when prompted when it says "Computer account already exists! Bind to Existing? (y/n):"

Here's what I have, and any advice is appreciated:

domain="mydomain"

username="myusername" password="mypassword"

olddomain=$( dsconfigad -show | awk '/Active Directory Domain/{print $NF}' ) computername=$( scutil --get ComputerName ) adcomputerid=$( echo "${computername}" | tr [:lower:] [:upper:] ) prefix="${adcomputerid:0:6}"

dsconfigad -remove -force -u "${username}" -p "${password}"

dsconfigad -add "${domain}" -username "${username}" -password "${password}"

Body:
The full answer would be:

# ...
dsconfigad -add "${domain}" -force -username "${username}" -password "${password}"

The -force forces the action (skips asking for user confirmation).

Relevant portion of the helptext below:

$ dsconfigad
Usage: dsconfigad -add domain -username value [-computer value] [-force]
                  [-password value] [-ou dn] [-preferred server]
                  [-localuser value] [-localpassword value]

# ...

  -force                force the process (i.e., join the existing account)

# ...


问:
How to load images anync for TimelineQueueNavigator of ExoPlayer?
I am using MediaSessionConnector to manage media session. I have playlist that need to played. To control playlist and show metadata on bluetooth devices i used TimelineQueueNavigator. It also suppose to show metadata on lock screen of the device.

```<code>
val navigator = object: TimelineQueueNavigator(mediaSession) {

       override fun getMediaDescription(player: Player?, windowIndex: Int): MediaDescriptionCompat {
         val song = mPlaylist[windowIndex]
         val bitmap = // get bitmap from somwhere
         return MediaMetadataCompat.Builder()
            .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, song.id)
            .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, song.artist)
            .putString(MediaMetadataCompat.METADATA_KEY_TITLE, song.name)
            .putBitmap(MediaMetadataCompat.METADATA_KEY_ART, bitmap)
            .putBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON, bitmap)
            .build()
       }
  }

mediaSessionConnector.setQueueNavigator(navigator)
</code>```

This approach is good but require to have image already loaded so you can assign bitmap.

Does anyone know how to manage getMediaDescription where image is loaded async? Example will much appreciated. Or maybe it require different approach?

答:
This has been asked as a GitHub issue on the project repository, see this link for the full conversation.

To sum it up, this is how you can do it:

In getMediaDescription, provide the info you already have. If you don't have the images, start fetching them asynchronically.

When you have all the images, call mediaSessionConnector.invalidateMediaSessionQueue() and mediaSessionConnector.invalidateMediaSessionMetadata(). This will re-call getMediaDescription, where you should provide the images you now have.

Body:
I am using MediaSessionConnector to manage media session. I have playlist that need to played. To control playlist and show metadata on bluetooth devices i used TimelineQueueNavigator. It also suppose to show metadata on lock screen of the device.

val navigator = object: TimelineQueueNavigator(mediaSession) {

       override fun getMediaDescription(player: Player?, windowIndex: Int): MediaDescriptionCompat {
         val song = mPlaylist[windowIndex]
         val bitmap = // get bitmap from somwhere
         return MediaMetadataCompat.Builder()
            .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, song.id)
            .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, song.artist)
            .putString(MediaMetadataCompat.METADATA_KEY_TITLE, song.name)
            .putBitmap(MediaMetadataCompat.METADATA_KEY_ART, bitmap)
            .putBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON, bitmap)
            .build()
       }
  }

mediaSessionConnector.setQueueNavigator(navigator)

This approach is good but require to have image already loaded so you can assign bitmap.

Does anyone know how to manage getMediaDescription where image is loaded async? Example will much appreciated. Or maybe it require different approach?


问:
How to Change User Control to Another User Control in UltraTab?
UltraTabControl in the Form. UltraTabControl has several Tabs. Each tab assigns each TabPageControl. Each TabPageControl was added using Form Designer.

Each page has a User Control assigned to it. In User Control called A, I want to open User Control called B, using a function.

I tried, but B does not open and stays at A.
Below is the code I tried.

Function in From,

```<code>public void Open_B()
    {
        uTabMain.SelectedTab = uTabMain.Tabs["B"];
        customArgs = new ItemEventArgs(uExplorerBar.Groups[9].Items["B"]);
        uExplorerBar_ItemClick(uExplorerBar, customArgs);
    }
</code>```

Use Function in A,

```<code>Form.Open_B();
</code>```

What should I do?

I am sorry that my English is not good.

答:
Hard to understand what you want.

To change Tabs for infragistics--

In VB:

```<code> Me.uTabMain.Tabs("B").Selected = True
</code>```

Ill correct this part but I think C# would be

```<code>Me.uTabMain.Tabs["B"].Selected = True;
</code>```

Body:
UltraTabControl in the Form. UltraTabControl has several Tabs. Each tab assigns each TabPageControl. Each TabPageControl was added using Form Designer.

Each page has a User Control assigned to it. In User Control called A, I want to open User Control called B, using a function.

I tried, but B does not open and stays at A.
Below is the code I tried.

Function in From,

public void Open_B()
    {
        uTabMain.SelectedTab = uTabMain.Tabs["B"];
        customArgs = new ItemEventArgs(uExplorerBar.Groups[9].Items["B"]);
        uExplorerBar_ItemClick(uExplorerBar, customArgs);
    }

Use Function in A,

Form.Open_B();

What should I do?

I am sorry that my English is not good.

Body:
Hard to understand what you want.

To change Tabs for infragistics--

In VB:

 Me.uTabMain.Tabs("B").Selected = True

Ill correct this part but I think C# would be

Me.uTabMain.Tabs["B"].Selected = True;


问:
Daemon and Service Difference
What is the difference between daemon and service ? (In windows or Linux).</p>

答:
A daemon is a computer program that runs as a background process, rather than being under the direct control of an interactive user.
A daemon is a subset of services that always run in memory waiting to service a request.
For example - crond , ftpd ,etc

Whereas, a Service is a server application or set of applications that runs in the background waiting to be used, or carrying out essential task. They are basically called in inter-process communication.
For example - httpd

Title: Daemon and Service Difference


问:
Know if express app is running as firebase cloud function
I have an express app that I want to run locally as a standalone server in my machine however, when deploying it to firebase cloud functions I need to set it as a cloud function.

Is there a reliable way to know in which environment the app is running without manually setting env variables or what is the best practice?

eg:

```<code>if(isRunningInFirebase()){
  exports.myFun=functions.https.onRequest(app)
} else app.listen(3030)
</code>```

答:
I did some exploring by logging the process.env

When running functions locally using firebase functions:shell or firebase serve --only functions there are a bunch of local machine type node variables.

When running the deployed function sitting in Firebase Cloud Functions. There is a new node environment variable that is not set when running locally:

```<code>NODE_ENV: 'production'
</code>```

So to use it:

```<code>if (process.env.NODE_ENV === 'production') {
    // running in production cloud environment
} else {
    // running locally (shell or serve)
}
</code>```

Body:
I have an express app that I want to run locally as a standalone server in my machine however, when deploying it to firebase cloud functions I need to set it as a cloud function.

Is there a reliable way to know in which environment the app is running without manually setting env variables or what is the best practice?

eg:

if(isRunningInFirebase()){
  exports.myFun=functions.https.onRequest(app)
} else app.listen(3030)

Body:
I did some exploring by logging the process.env

When running functions locally using firebase functions:shell or firebase serve --only functions there are a bunch of local machine type node variables.

When running the deployed function sitting in Firebase Cloud Functions. There is a new node environment variable that is not set when running locally:

NODE_ENV: 'production'

So to use it:

if (process.env.NODE_ENV === 'production') {
    // running in production cloud environment
} else {
    // running locally (shell or serve)
}


问:
How to fix ModuleNotFoundError: No module named 'pip._internal' with python source code installation
I have installed python3.7 on redhat machine by compiling source code but I have a problem when dealing with pip3. I have made this steps after installation:

sudo ln /usr/local/bin/python3.7 /usr/bin/python3

sudo ln /usr/local/bin/pip3.7 /usr/bin/pip3
```

<p>python3 -- version gives Python 3.7.3</p>

<p>But I have this errors by running these commands :</p>

<pre class="lang-sh prettyprint-override"><code>python3 -m pip install requests
</code>```

gives /usr/bin/python3: No module named pip.__main__; 'pip' is a package and cannot be directly executed

pip3 install requests
```

gives ModuleNotFoundError: No module named 'pip._internal'

答:
Try to reinstall the pip as follows :

```<code>curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py --force-reinstall
</code>```

Body:
I have installed python3.7 on redhat machine by compiling source code but I have a problem when dealing with pip3. I have made this steps after installation:

sudo ln /usr/local/bin/python3.7 /usr/bin/python3

sudo ln /usr/local/bin/pip3.7 /usr/bin/pip3

python3 -- version gives Python 3.7.3

But I have this errors by running these commands :

python3 -m pip install requests

gives /usr/bin/python3: No module named pip.__main__; 'pip' is a package and cannot be directly executed

pip3 install requests

gives ModuleNotFoundError: No module named 'pip._internal'

Body:
Try to reinstall the pip as follows :

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py --force-reinstall


问:
Detecting a smaller image (.png) within a larger image retrieved with ImageGrab?
I've spent the past hour researching this simple topic, but all of the answers I've come across have been very complex and, as a noob to Python, I've been unable to incorporate any of them into my program.

I am trying to make an AI play a browser version of the Piano Tiles Game. As of now, I'm simply trying to take a capture of the games window (a small portion of my computer screen), and then check that games window with a .png of the game's start button. From there I will go on to CLICK that start button, but that's a problem for another time.

How can I check to see if a Image contains a .png file?

Here is my current code:

```<code>from PIL import ImageGrab as ig, ImageOps as io, Image
import pyautogui
import bbox

def grabStart(window):
    #The start button
    start = Image.open("res/StartButton.PNG")
    start = io.grayscale(start)

    #This is the part I need to figure out. The following is just pseudocode
    if window.contains(start): #I know that this doesn't actually work. Just pseudocode
        #I'd like to return the location of 'start' in one of the following forms
        return either: (x1, y1, x2, y2), (x1, y1, width, height), (a coordinate within 'start'))

def grabGame():
    #The coordinates of the entire game window
    x1 = 2222
    y1 = 320
    x2 = 2850
    y2 = 1105

    #The entire screen of the game
    window = ig.grab(bbox = (x1, y1, x2, y2))
    window = io.grayscale(window)

    return window

grabStart(grabGame())
</code>```

答:
Here's a way of doing it. I just leave the program running and open/close and move a preview of the button around the screen seeing if it spots the button and reports the coordinates correctly.</p>

```<code>#!/usr/bin/env python3

from PIL import ImageGrab as ig, Image
import pyautogui as ag

def checkButton(button, window):
    try:
        location = ag.locate(button, window, confidence=0.8)
        print(f'location: {location[0]},{location[1]},{location[2]},{location[3]}')
    except:
        print('Not found')

# Load button just once at startup
button = Image.open("button.png")

# Loop, looking for button
while True:
    window = ig.grab()
    checkButton(button, window)
</code>```

Body:
I've spent the past hour researching this simple topic, but all of the answers I've come across have been very complex and, as a noob to Python, I've been unable to incorporate any of them into my program.

I am trying to make an AI play a browser version of the Piano Tiles Game. As of now, I'm simply trying to take a capture of the games window (a small portion of my computer screen), and then check that games window with a .png of the game's start button. From there I will go on to CLICK that start button, but that's a problem for another time.

How can I check to see if a Image contains a .png file?

Here is my current code:

from PIL import ImageGrab as ig, ImageOps as io, Image
import pyautogui
import bbox

def grabStart(window):
    #The start button
    start = Image.open("res/StartButton.PNG")
    start = io.grayscale(start)

    #This is the part I need to figure out. The following is just pseudocode
    if window.contains(start): #I know that this doesn't actually work. Just pseudocode
        #I'd like to return the location of 'start' in one of the following forms
        return either: (x1, y1, x2, y2), (x1, y1, width, height), (a coordinate within 'start'))

def grabGame():
    #The coordinates of the entire game window
    x1 = 2222
    y1 = 320
    x2 = 2850
    y2 = 1105

    #The entire screen of the game
    window = ig.grab(bbox = (x1, y1, x2, y2))
    window = io.grayscale(window)

    return window

grabStart(grabGame())

Body:
Here's a way of doing it. I just leave the program running and open/close and move a preview of the button around the screen seeing if it spots the button and reports the coordinates correctly.

#!/usr/bin/env python3

from PIL import ImageGrab as ig, Image
import pyautogui as ag

def checkButton(button, window):
    try:
        location = ag.locate(button, window, confidence=0.8)
        print(f'location: {location[0]},{location[1]},{location[2]},{location[3]}')
    except:
        print('Not found')

# Load button just once at startup
button = Image.open("button.png")

# Loop, looking for button
while True:
    window = ig.grab()
    checkButton(button, window)


问:
TypeError: Value passed to parameter 'indices' has DataType float32 not in list of allowed values: int32, int64
I use Keras to build my model, there are two inputs in my model, whose datatype is 'int32'. And then I use keras Lamba layer to look up in the embedding matric with K.gather(reference, indices). I see that indices should be tensor of int, and I think my code meets that, I do not know why about the error. I really need help!</p>

```<code>    input_A = Input(batch_shape=(128,1),name='A_input',dtype='int32')
    input_B = Input(batch_shape=(128,1),name='B_input',dtype='int32')

    input_A_ = Lambda(lambda x:K.reshape(x,(-1,)))(input_A)
    input_B_ = Lambda(lambda x:K.reshape(x, (-1,)))(input_B)

    input_A__ = Lambda(lambda x:K.cast(x,dtype='int32'))(input_A_)
    input_B__ = Lambda(lambda x:K.cast(x,dtype='int32'))(input_B_)

    embedded_text_A = Lambda(lambda x:K.gather(M1,x))(input_A__)
    embedded_text_B = Lambda(lambda x:K.gather(M1,x))(input_B__)
</code>```

答:
For some enigmatic reason it will work properly if one places K.cast() inside the lambda:

```<code>input_A = Input(batch_shape=(128,1), name='A_input', dtype='int32')
input_B = Input(batch_shape=(128,1), name='B_input', dtype='int32')

input_A_ = Lambda(lambda x: K.reshape(x, (-1,)))(input_A)
input_B_ = Lambda(lambda x: K.reshape(x, (-1,)))(input_B)

embedded_text_A = Lambda(lambda x: K.gather(M1, K.cast(x, dtype='int32')))(input_A_)
embedded_text_B = Lambda(lambda x: K.gather(M1, K.cast(x, dtype='int32')))(input_B_)
</code>```

Hence, Lambda layer makes some strange dtype conversion within.

I suppose it is some kind of bug, and my hypothesis is that implicit conversion takes place inside the Lambda's __call__ (which is inherited from Layer.__call__). I can't track it, but I guess 'implicit conversion' bug is somewhere in Layer.__call__, but before the line 451, where the Lambda.call is actually invoked.

Body:
I use Keras to build my model, there are two inputs in my model, whose datatype is 'int32'. And then I use keras Lamba layer to look up in the embedding matric with K.gather(reference, indices). I see that indices should be tensor of int, and I think my code meets that, I do not know why about the error. I really need help!

    input_A = Input(batch_shape=(128,1),name='A_input',dtype='int32')
    input_B = Input(batch_shape=(128,1),name='B_input',dtype='int32')

    input_A_ = Lambda(lambda x:K.reshape(x,(-1,)))(input_A)
    input_B_ = Lambda(lambda x:K.reshape(x, (-1,)))(input_B)

    input_A__ = Lambda(lambda x:K.cast(x,dtype='int32'))(input_A_)
    input_B__ = Lambda(lambda x:K.cast(x,dtype='int32'))(input_B_)

    embedded_text_A = Lambda(lambda x:K.gather(M1,x))(input_A__)
    embedded_text_B = Lambda(lambda x:K.gather(M1,x))(input_B__)

Body:
For some enigmatic reason it will work properly if one places K.cast() inside the lambda:

input_A = Input(batch_shape=(128,1), name='A_input', dtype='int32')
input_B = Input(batch_shape=(128,1), name='B_input', dtype='int32')

input_A_ = Lambda(lambda x: K.reshape(x, (-1,)))(input_A)
input_B_ = Lambda(lambda x: K.reshape(x, (-1,)))(input_B)

embedded_text_A = Lambda(lambda x: K.gather(M1, K.cast(x, dtype='int32')))(input_A_)
embedded_text_B = Lambda(lambda x: K.gather(M1, K.cast(x, dtype='int32')))(input_B_)

Hence, Lambda layer makes some strange dtype conversion within.

I suppose it is some kind of bug, and my hypothesis is that implicit conversion takes place inside the Lambda's __call__ (which is inherited from Layer.__call__). I can't track it, but I guess 'implicit conversion' bug is somewhere in Layer.__call__, but before the line 451, where the Lambda.call is actually invoked.


问:
Syntax to pass dynamic variables to include_tasks along with with_item in Ansible playbook
Executing parent.yml which in turn calls child.yml playbook for execution with dynamic variables.

Variables from parent.yml aren`t interpolated inside child.yml playbook. Correct me if I am using correct syntax?

Parent.yml

```<code>- name: Main playbook to call MySQL backup
  hosts: localhost
  gather_facts: no

  tasks:
  - include_task: child.yml
    vars:
      var1: "{{ item.name }}"
      var2: "{{ item.db_name }}"
    with_items:
       - { name: '10.10.10.01', db_name: 'prod1' }
       - { name: '10.10.10.02', db_name: 'prod2' }
</code>```

child.yml (Takes mysqldump from managed DB)

```<code>- name: MySQL dump
  hosts: localhost
  #gather_facts: no
  #vars:
  #      v1: "{{ var1 }}"
  #      v2: "{{ var2 }}"

  tasks:
  - name: Executing the shell script
    shell: 'mysqldump -h "{{ var1 }}" -u"ansi" -p"*****" "{{ var2 }}"| gzip > /tmp/mysql_dump/"{{ var2 }}"_`date +%Y%m%d-%H%M`.gz'
</code>```

fatal: [127.0.0.1]: FAILED! => {"reason": "no action detected in task. This often indicates a misspelled module name, or incorrect module path.\n\nThe error appears to be in '/home/ansible/playbooks/DBpatch/Linux/child.yml': line 1, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: MySQL dump\n  ^ here\n"}

答:
include_task expects a list of tasks but you give it a complete playbook.
Child.yml should only contain what is currently below the line "tasks:".
See also https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_includes.html</p>

Body:
Executing parent.yml which in turn calls child.yml playbook for execution with dynamic variables.

Variables from parent.yml aren`t interpolated inside child.yml playbook. Correct me if I am using correct syntax?

Parent.yml

- name: Main playbook to call MySQL backup
  hosts: localhost
  gather_facts: no

  tasks:
  - include_task: child.yml
    vars:
      var1: "{{ item.name }}"
      var2: "{{ item.db_name }}"
    with_items:
       - { name: '10.10.10.01', db_name: 'prod1' }
       - { name: '10.10.10.02', db_name: 'prod2' }

child.yml (Takes mysqldump from managed DB)

- name: MySQL dump
  hosts: localhost
  #gather_facts: no
  #vars:
  #      v1: "{{ var1 }}"
  #      v2: "{{ var2 }}"

  tasks:
  - name: Executing the shell script
    shell: 'mysqldump -h "{{ var1 }}" -u"ansi" -p"*****" "{{ var2 }}"| gzip > /tmp/mysql_dump/"{{ var2 }}"_`date +%Y%m%d-%H%M`.gz'

fatal: [127.0.0.1]: FAILED! => {"reason": "no action detected in task. This often indicates a misspelled module name, or incorrect module path.\n\nThe error appears to be in '/home/ansible/playbooks/DBpatch/Linux/child.yml': line 1, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: MySQL dump\n  ^ here\n"}


问:
AndroidDriver is not generic, it cannot be parameterised
I want to automate a simple appium script to open the play store app from the home screen. When i try to run the script, i'm getting the following error:

The type AppiumDriver is not generic; it cannot be parameterized with arguments
    The type AndroidDriver is not generic; it cannot be parameterized with arguments

the dependencies i have installed are:

selenium-server-standalone-3.141.59.jar, commons-lang3-3.9.jar, client-combined-3.141.59.jar, client-combined-3.141.59-sources.jar, java-client-2.1.0.jar, java-client-7.0.0.jar, java-client-4.1.2.jar

package tests;

```<code>import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.remote.DesiredCapabilities;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;

public class AppiumTest {

    public static void main(String[] args) {

        //Set the Desired Capabilities
        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setCapability("deviceName", "My Phone");
        caps.setCapability("udid", "RZ8M41XNX1E"); //Give Device ID of your mobile phone
        caps.setCapability("platformName", "Android");
        caps.setCapability("platformVersion", "6.0");
        caps.setCapability("appPackage", "com.android.vending");
        caps.setCapability("appActivity", "com.google.android.finsky.activities.MainActivity");
        caps.setCapability("noReset", "true");

        //Instantiate Appium Driver
        try {
                AppiumDriver<MobileElement> driver = new AndroidDriver<MobileElement>(new URL("http://0.0.0.0:4723/wd/hub"), caps);

        } catch (MalformedURLException e) {
            System.out.println(e.getMessage());
        }
    }
}
</code>```

答:
If this is the only class in your project you need only one dependency: Appium java-client-7.0.0.

You don't need others as they're resolved via Maven's transitive dependencies mechanism. In your situation you're suffering from a Jar Hell caused my multiple different clashing Appium Java Client libraries in the Classpath

So given this pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>testing.appium</groupId>
    <artifactId>appium-java</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>

        <dependency>
            <groupId>io.appium</groupId>
            <artifactId>java-client</artifactId>
            <version>7.0.0</version>
        </dependency>
    </dependencies>

</project>
</code>```

You will get the following dependencies:

```<code>>mvn dependency:tree
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< testing.appium:appium-java >---------------------
[INFO] Building appium-java 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ appium-java ---
[INFO] testing.appium:appium-java:jar:0.0.1-SNAPSHOT
[INFO] \- io.appium:java-client:jar:7.0.0:compile
[INFO]    +- org.seleniumhq.selenium:selenium-java:jar:3.141.59:compile
[INFO]    |  +- org.seleniumhq.selenium:selenium-chrome-driver:jar:3.141.59:compile
[INFO]    |  +- org.seleniumhq.selenium:selenium-edge-driver:jar:3.141.59:compile
[INFO]    |  +- org.seleniumhq.selenium:selenium-firefox-driver:jar:3.141.59:compile
[INFO]    |  +- org.seleniumhq.selenium:selenium-ie-driver:jar:3.141.59:compile
[INFO]    |  +- org.seleniumhq.selenium:selenium-opera-driver:jar:3.141.59:compile
[INFO]    |  +- org.seleniumhq.selenium:selenium-remote-driver:jar:3.141.59:compile
[INFO]    |  +- org.seleniumhq.selenium:selenium-safari-driver:jar:3.141.59:compile
[INFO]    |  +- net.bytebuddy:byte-buddy:jar:1.8.15:compile
[INFO]    |  +- org.apache.commons:commons-exec:jar:1.3:compile
[INFO]    |  +- com.google.guava:guava:jar:25.0-jre:compile
[INFO]    |  |  +- com.google.code.findbugs:jsr305:jar:1.3.9:compile
[INFO]    |  |  +- org.checkerframework:checker-compat-qual:jar:2.0.0:compile
[INFO]    |  |  +- com.google.errorprone:error_prone_annotations:jar:2.1.3:compile
[INFO]    |  |  +- com.google.j2objc:j2objc-annotations:jar:1.1:compile
[INFO]    |  |  \- org.codehaus.mojo:animal-sniffer-annotations:jar:1.14:compile
[INFO]    |  +- com.squareup.okhttp3:okhttp:jar:3.11.0:compile
[INFO]    |  \- com.squareup.okio:okio:jar:1.14.0:compile
[INFO]    +- org.seleniumhq.selenium:selenium-support:jar:3.141.59:compile
[INFO]    +- org.seleniumhq.selenium:selenium-api:jar:3.141.59:compile
[INFO]    +- com.google.code.gson:gson:jar:2.8.5:compile
[INFO]    +- org.apache.httpcomponents:httpclient:jar:4.5.6:compile
[INFO]    |  +- org.apache.httpcomponents:httpcore:jar:4.4.10:compile
[INFO]    |  +- commons-logging:commons-logging:jar:1.2:compile
[INFO]    |  \- commons-codec:commons-codec:jar:1.10:compile
[INFO]    +- cglib:cglib:jar:3.2.8:compile
[INFO]    |  +- org.ow2.asm:asm:jar:6.2.1:compile
[INFO]    |  \- org.apache.ant:ant:jar:1.10.3:compile
[INFO]    |     \- org.apache.ant:ant-launcher:jar:1.10.3:compile
[INFO]    +- commons-validator:commons-validator:jar:1.6:compile
[INFO]    |  +- commons-beanutils:commons-beanutils:jar:1.9.2:compile
[INFO]    |  +- commons-digester:commons-digester:jar:1.8.1:compile
[INFO]    |  \- commons-collections:commons-collections:jar:3.2.2:compile
[INFO]    +- org.apache.commons:commons-lang3:jar:3.8:compile
[INFO]    +- commons-io:commons-io:jar:2.6:compile
[INFO]    +- org.springframework:spring-context:jar:5.1.0.RELEASE:compile
[INFO]    |  +- org.springframework:spring-aop:jar:5.1.0.RELEASE:compile
[INFO]    |  +- org.springframework:spring-beans:jar:5.1.0.RELEASE:compile
[INFO]    |  +- org.springframework:spring-core:jar:5.1.0.RELEASE:compile
[INFO]    |  |  \- org.springframework:spring-jcl:jar:5.1.0.RELEASE:compile
[INFO]    |  \- org.springframework:spring-expression:jar:5.1.0.RELEASE:compile
[INFO]    +- org.aspectj:aspectjweaver:jar:1.9.1:compile
[INFO]    \- org.slf4j:slf4j-api:jar:1.7.25:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.801 s
[INFO] Finished at: 2019-05-29T15:00:39+02:00
[INFO] ------------------------------------------------------------------------
</code>```

You can also check out appium-java-testng sample project and get familiarized with Parallel Tests - Best Practices article.

Body:
I want to automate a simple appium script to open the play store app from the home screen. When i try to run the script, i'm getting the following error:

The type AppiumDriver is not generic; it cannot be parameterized with arguments
    The type AndroidDriver is not generic; it cannot be parameterized with arguments

the dependencies i have installed are:

selenium-server-standalone-3.141.59.jar, commons-lang3-3.9.jar, client-combined-3.141.59.jar, client-combined-3.141.59-sources.jar, java-client-2.1.0.jar, java-client-7.0.0.jar, java-client-4.1.2.jar

package tests;

import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.remote.DesiredCapabilities;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;

public class AppiumTest {

    public static void main(String[] args) {

        //Set the Desired Capabilities
        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setCapability("deviceName", "My Phone");
        caps.setCapability("udid", "RZ8M41XNX1E"); //Give Device ID of your mobile phone
        caps.setCapability("platformName", "Android");
        caps.setCapability("platformVersion", "6.0");
        caps.setCapability("appPackage", "com.android.vending");
        caps.setCapability("appActivity", "com.google.android.finsky.activities.MainActivity");
        caps.setCapability("noReset", "true");

        //Instantiate Appium Driver
        try {
                AppiumDriver<MobileElement> driver = new AndroidDriver<MobileElement>(new URL("http://0.0.0.0:4723/wd/hub"), caps);

        } catch (MalformedURLException e) {
            System.out.println(e.getMessage());
        }
    }
}

Body:
If this is the only class in your project you need only one dependency: Appium java-client-7.0.0.

You don't need others as they're resolved via Maven's transitive dependencies mechanism. In your situation you're suffering from a Jar Hell caused my multiple different clashing Appium Java Client libraries in the Classpath

So given this pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>testing.appium</groupId>
    <artifactId>appium-java</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>

        <dependency>
            <groupId>io.appium</groupId>
            <artifactId>java-client</artifactId>
            <version>7.0.0</version>
        </dependency>
    </dependencies>

</project>

You will get the following dependencies:

>mvn dependency:tree
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------< testing.appium:appium-java >---------------------
[INFO] Building appium-java 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ appium-java ---
[INFO] testing.appium:appium-java:jar:0.0.1-SNAPSHOT
[INFO] \- io.appium:java-client:jar:7.0.0:compile
[INFO]    +- org.seleniumhq.selenium:selenium-java:jar:3.141.59:compile
[INFO]    |  +- org.seleniumhq.selenium:selenium-chrome-driver:jar:3.141.59:compile
[INFO]    |  +- org.seleniumhq.selenium:selenium-edge-driver:jar:3.141.59:compile
[INFO]    |  +- org.seleniumhq.selenium:selenium-firefox-driver:jar:3.141.59:compile
[INFO]    |  +- org.seleniumhq.selenium:selenium-ie-driver:jar:3.141.59:compile
[INFO]    |  +- org.seleniumhq.selenium:selenium-opera-driver:jar:3.141.59:compile
[INFO]    |  +- org.seleniumhq.selenium:selenium-remote-driver:jar:3.141.59:compile
[INFO]    |  +- org.seleniumhq.selenium:selenium-safari-driver:jar:3.141.59:compile
[INFO]    |  +- net.bytebuddy:byte-buddy:jar:1.8.15:compile
[INFO]    |  +- org.apache.commons:commons-exec:jar:1.3:compile
[INFO]    |  +- com.google.guava:guava:jar:25.0-jre:compile
[INFO]    |  |  +- com.google.code.findbugs:jsr305:jar:1.3.9:compile
[INFO]    |  |  +- org.checkerframework:checker-compat-qual:jar:2.0.0:compile
[INFO]    |  |  +- com.google.errorprone:error_prone_annotations:jar:2.1.3:compile
[INFO]    |  |  +- com.google.j2objc:j2objc-annotations:jar:1.1:compile
[INFO]    |  |  \- org.codehaus.mojo:animal-sniffer-annotations:jar:1.14:compile
[INFO]    |  +- com.squareup.okhttp3:okhttp:jar:3.11.0:compile
[INFO]    |  \- com.squareup.okio:okio:jar:1.14.0:compile
[INFO]    +- org.seleniumhq.selenium:selenium-support:jar:3.141.59:compile
[INFO]    +- org.seleniumhq.selenium:selenium-api:jar:3.141.59:compile
[INFO]    +- com.google.code.gson:gson:jar:2.8.5:compile
[INFO]    +- org.apache.httpcomponents:httpclient:jar:4.5.6:compile
[INFO]    |  +- org.apache.httpcomponents:httpcore:jar:4.4.10:compile
[INFO]    |  +- commons-logging:commons-logging:jar:1.2:compile
[INFO]    |  \- commons-codec:commons-codec:jar:1.10:compile
[INFO]    +- cglib:cglib:jar:3.2.8:compile
[INFO]    |  +- org.ow2.asm:asm:jar:6.2.1:compile
[INFO]    |  \- org.apache.ant:ant:jar:1.10.3:compile
[INFO]    |     \- org.apache.ant:ant-launcher:jar:1.10.3:compile
[INFO]    +- commons-validator:commons-validator:jar:1.6:compile
[INFO]    |  +- commons-beanutils:commons-beanutils:jar:1.9.2:compile
[INFO]    |  +- commons-digester:commons-digester:jar:1.8.1:compile
[INFO]    |  \- commons-collections:commons-collections:jar:3.2.2:compile
[INFO]    +- org.apache.commons:commons-lang3:jar:3.8:compile
[INFO]    +- commons-io:commons-io:jar:2.6:compile
[INFO]    +- org.springframework:spring-context:jar:5.1.0.RELEASE:compile
[INFO]    |  +- org.springframework:spring-aop:jar:5.1.0.RELEASE:compile
[INFO]    |  +- org.springframework:spring-beans:jar:5.1.0.RELEASE:compile
[INFO]    |  +- org.springframework:spring-core:jar:5.1.0.RELEASE:compile
[INFO]    |  |  \- org.springframework:spring-jcl:jar:5.1.0.RELEASE:compile
[INFO]    |  \- org.springframework:spring-expression:jar:5.1.0.RELEASE:compile
[INFO]    +- org.aspectj:aspectjweaver:jar:1.9.1:compile
[INFO]    \- org.slf4j:slf4j-api:jar:1.7.25:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.801 s
[INFO] Finished at: 2019-05-29T15:00:39+02:00
[INFO] ------------------------------------------------------------------------

You can also check out appium-java-testng sample project and get familiarized with Parallel Tests - Best Practices article.


问:
How to add header to the ngbtypeahead window?
I am trying to implement typeahead functionality in Angular. I am using ngbTypeahead from ng-bootstrap for this as shown below.

```<code> <input id="typeahead-template" type="text" class="form-control form-rounded" [ngbTypeahead]="search" [resultTemplate]="rt" [inputFormatter]="formatter"  />

 <ng-template #rt let-r="result" let-t="term">
 <img [src]="'https://upload.wikimedia.org/wikipedia/commons/thumb/'+r['flag']" class="mr-1" style="width: 16px">
 <ngb-highlight [result]="r.name" [term]="t"></ngb-highlight>
 </ng-template>
</code>```

This is displaying result like

result1

result2

result3

but I want a header to be added and the result should be in the format

The results are

result1

result2

result3

Can someone please help with this?

答:
This isn't supported by ng-bootstrap's Typeahead component, however you can use CSS to insert text before the results. The only problem with this solution is that you need to use ::ng-deep which is deprecated and likely to be dropped by Angular soon.

Add this to your component's CSS:

```<code>::ng-deep ngb-typeahead-window:before {
  content: "The results are:";
}
</code>```

and you should see the following when results are displayed:

This will prepend the typeahead results with the text specified as the value of the content property.

Please see this StackBlitz for a demo

Body:
I am trying to implement typeahead functionality in Angular. I am using ngbTypeahead from ng-bootstrap for this as shown below.

 <input id="typeahead-template" type="text" class="form-control form-rounded" [ngbTypeahead]="search" [resultTemplate]="rt" [inputFormatter]="formatter"  />

 <ng-template #rt let-r="result" let-t="term">

 <ngb-highlight [result]="r.name" [term]="t"></ngb-highlight>
 </ng-template>

This is displaying result like

result1

result2

result3

but I want a header to be added and the result should be in the format

The results are

result1

result2

result3

Can someone please help with this?

Body:
This isn't supported by ng-bootstrap's Typeahead component, however you can use CSS to insert text before the results. The only problem with this solution is that you need to use ::ng-deep which is deprecated and likely to be dropped by Angular soon.

Add this to your component's CSS:

::ng-deep ngb-typeahead-window:before {
  content: "The results are:";
}

and you should see the following when results are displayed:

This will prepend the typeahead results with the text specified as the value of the content property.

Please see this StackBlitz for a demo


问:
Optional route stop others route with same pattern
The following is my route to define the optional variable, and I will have a middleware to process the optional variable. I not sure why this make the testing page inaccessible and I believe it is interpreted as the invite code. What's the workaround for this? </p>

```<code>Route::group(['middleware' => ['friend']], function() {

    Route::get('/{invite_code?}', 'IndexController@index')->name('home')->middleware('firsttime'); // 首页

    Route::get('/testing/{invite_code?}', 'IndexController@testing')->name('testing');
});
</code>```

答:
For Example i have these three route

```<code>Route::get('/{invite_code?}', function () {
    dd('i am invite code Route');
})->name('invitecode');
Route::get('/myCustomRoute', function () {
    dd( 'i am myCustomRoute');
});
Route::get('/testing/{invite_code?}', function(){
    dd( 'i am testing invite code Route');
})->name('invitecodetest');
</code>```

Now I am serving my app in 8000 Port so http://localhost:8000/ is my app url

Now when i hit the myCustomRoute it Wont actually hit myCustomRoute that's because the Router is thing that  myCustomRoute as invite_code
hit http://localhost:8000/myCustomRoute So the result will be i am invite code Route

How to fix that

There are two ways

Way 1 Reorder Routes

```<code>Route::get('/myCustomRoute', function () {
    dd( 'i am myCustomRoute');
});
Route::get('/testing/{invite_code?}', function(){
    dd( 'i am testing invite code Route');
})->name('invitecodetest');

Route::get('/{invite_code?}', function () {
    dd('i am invite code Route');
})->name('invitecode');
</code>```

Now try again to hit the route add {invite_code?} at the end of web.php

hit http://localhost:8000/myCustomRoute result will be i am myCustomRoute

Now its working Fine but it has a drawback

now try http://localhost:8000/myundefinedroutename

but it will hit the {invite_code?} route so its a bug

Way 2 try to add some prefix to route

```<code>Route::get('/invidecode/{invite_code?}', function ( $invite_code = null) {
    dd( $invite_code, "i am invite code Route");
})->name('invitecode');
Route::get('/myCustomRoute', function () {
    dd( 'i am myCustomRoute');
});
Route::get('/testing/{invite_code?}', function(){
    dd( 'i am testing invite code Route');
})->name('invitecodetest');
</code>```

Now try http://localhost:8000/invidecode/yourcodegoeshere Result will be
"yourcodegoeshere"
"i am invite code Route"

and  hit http://localhost:8000/myCustomRoute result will be "i am myCustomRoute"
and hit http://localhost:8000/testing/myinvitecode result will be "myinvitecode"
"i am testing invite code Route"

Body:
The following is my route to define the optional variable, and I will have a middleware to process the optional variable. I not sure why this make the testing page inaccessible and I believe it is interpreted as the invite code. What's the workaround for this?

Route::group(['middleware' => ['friend']], function() {

    Route::get('/{invite_code?}', 'IndexController@index')->name('home')->middleware('firsttime'); // 首页

    Route::get('/testing/{invite_code?}', 'IndexController@testing')->name('testing');
});

Body:
For Example i have these three route

Route::get('/{invite_code?}', function () {
    dd('i am invite code Route');
})->name('invitecode');
Route::get('/myCustomRoute', function () {
    dd( 'i am myCustomRoute');
});
Route::get('/testing/{invite_code?}', function(){
    dd( 'i am testing invite code Route');
})->name('invitecodetest');

Now I am serving my app in 8000 Port so http://localhost:8000/ is my app url

Now when i hit the myCustomRoute it Wont actually hit myCustomRoute that's because the Router is thing that  myCustomRoute as invite_code
hit http://localhost:8000/myCustomRoute So the result will be i am invite code Route

How to fix that

There are two ways

Way 1 Reorder Routes

Route::get('/myCustomRoute', function () {
    dd( 'i am myCustomRoute');
});
Route::get('/testing/{invite_code?}', function(){
    dd( 'i am testing invite code Route');
})->name('invitecodetest');

Route::get('/{invite_code?}', function () {
    dd('i am invite code Route');
})->name('invitecode');

Now try again to hit the route add {invite_code?} at the end of web.php

hit http://localhost:8000/myCustomRoute result will be i am myCustomRoute

Now its working Fine but it has a drawback

now try http://localhost:8000/myundefinedroutename

but it will hit the {invite_code?} route so its a bug

Way 2 try to add some prefix to route

Route::get('/invidecode/{invite_code?}', function ( $invite_code = null) {
    dd( $invite_code, "i am invite code Route");
})->name('invitecode');
Route::get('/myCustomRoute', function () {
    dd( 'i am myCustomRoute');
});
Route::get('/testing/{invite_code?}', function(){
    dd( 'i am testing invite code Route');
})->name('invitecodetest');

Now try http://localhost:8000/invidecode/yourcodegoeshere Result will be
"yourcodegoeshere"
"i am invite code Route"

and  hit http://localhost:8000/myCustomRoute result will be "i am myCustomRoute"
and hit http://localhost:8000/testing/myinvitecode result will be "myinvitecode"
"i am testing invite code Route"


问:
how can i get the value of "colorControlHighlight" attribute at runtime?
I saw this post which explains the color is set in colorControlHighlight

I try to verify the runtime value of this attribute colorControlHighlight

But not sure what's the code to check this

How can I know which index to use?

```<code>TypedValue typedValue = new TypedValue();
int[] textSizeAttr = new int[] { android.R.attr.colorControlHighlight };
int indexOfAttrTextSize = 0;
TypedArray c = view.getContext().obtainStyledAttributes(typedValue.data, textSizeAttr);
int selectableItemBackground = c.getColor(indexOfAttrTextSize, -1);
c.recycle();
</code>```

答:
You might want to check this post.

Also note that getColorStateList(int) has been deprecated since Android Marshmallow. You may prefer to use getColorStateList(int, android.content.res.Resources.Theme) instead.

Body:
I saw this post which explains the color is set in colorControlHighlight

I try to verify the runtime value of this attribute colorControlHighlight

But not sure what's the code to check this

How can I know which index to use?

TypedValue typedValue = new TypedValue();
int[] textSizeAttr = new int[] { android.R.attr.colorControlHighlight };
int indexOfAttrTextSize = 0;
TypedArray c = view.getContext().obtainStyledAttributes(typedValue.data, textSizeAttr);
int selectableItemBackground = c.getColor(indexOfAttrTextSize, -1);
c.recycle();


问:
Horizontally align Chart.js y axes
I have two (or more) Charts.js charts in my document. Since the y axes ticks aren't always the same width, the y axes are misaligned to each other.

html:

```<code><body>
    <div class="mainContainer">
        <div class="mainSubContainer" id="main">
            <div class="graphContainer">
                <div class="graphHeader">Temperatur</div>
                <div class="graphElement"><canvas id="canvas1"></canvas></div>
            </div>
            <div class="graphContainer">
                <div class="graphHeader">relative Luftfeuchte</div>
                <div class="graphElement"><canvas id="canvas2"></canvas></div>
            </div>
        </div>
    </div>
</body>
</code>```

My fiddle: https://jsfiddle.net/1u7t6rfo/1/

Is there a way to align multiple Chart.js charts?

答:
You can simply set a max for the Y axes. E.g.

```<code>var maxY = 100;

....

scales: {
    yAxes: [{
        id: 'A',
        type: 'linear',
        ticks: {
            .....
            max: maxY
        },
    }]
    ....
}
</code>```

here the snippet:

https://jsfiddle.net/Lx9unv47/

Also if you don't want to set the max of the Y axes manually you can do this:

```<code>var allValues = data.datasets[0].data.concat(data2.datasets[0].data);
var maxY = Math.max(...allValues);
</code>```

and here the fiddle: https://jsfiddle.net/r6jgLmns/

Title: Horizontally align Chart.js y axes

Body:
I have two (or more) Charts.js charts in my document. Since the y axes ticks aren't always the same width, the y axes are misaligned to each other.

html:

Temperatur

<canvas id="canvas1"></canvas>

relative Luftfeuchte

<canvas id="canvas2"></canvas>

My fiddle: https://jsfiddle.net/1u7t6rfo/1/

Is there a way to align multiple Chart.js charts?

Body:
You can simply set a max for the Y axes. E.g.

var maxY = 100;

....

scales: {
    yAxes: [{
        id: 'A',
        type: 'linear',
        ticks: {
            .....
            max: maxY
        },
    }]
    ....
}

here the snippet:

https://jsfiddle.net/Lx9unv47/

Also if you don't want to set the max of the Y axes manually you can do this:

var allValues = data.datasets[0].data.concat(data2.datasets[0].data);
var maxY = Math.max(...allValues);

and here the fiddle: https://jsfiddle.net/r6jgLmns/


问:
Exception: Cannot start TensorBoard. in Google Cloud Datalab
I see that Tensorboard process is running. Files are written into the model directory. However, repeatedly I get the Exception: Unable to start Tensorboard. I am using TF.estimator.

I am running my code on Google Cloud Datalab. I have tried changing model directory and restarting the Datalab instance many times. Also tried running killing all running Tensorboard processes. Nothing has worked so far. It was working earlier or once in every 10-15 attempts it magically runs. Whats happening?

This is how I am starting Tensorboard.

```<code>from google.datalab.ml import TensorBoard as tb
tb.start(model_dir)
</code>```

This is how my Estimator is configured.

```<code>run_config = tf.estimator.RunConfig(
  save_checkpoints_steps=FLAGS.save_checkpoints_steps,
  tf_random_seed=FLAGS.tf_random_seed,
  model_dir=model_dir
)

estimator = tf.estimator.Estimator(model_fn=model_fn,
config=run_config)
</code>```

Below are the files being written into the model directory by tf.estimator.

eval 8 minutes ago

checkpoint 124 B 9 minutes ago

events.out.tfevents.1559025239.78fe4cbf0fad 603 kB 9 minutes ago

graph.pbtxt 399 kB 12 minutes ago

model.ckpt-1.data-00000-of-00001 261 MB 11 minutes ago

model.ckpt-1.index 811 B 11 minutes ago

model.ckpt-1.meta 170 kB 11 minutes ago

model.ckpt-5.data-00000-of-00001 261 MB 9 minutes ago

model.ckpt-5.index 811 B 9 minutes ago

model.ckpt-5.meta 170 kB 9 minutes ago

The error I am getting is below. It is the same everytime and I have no further information to identify what is going wrong.

Exception                                 Traceback (most recent call >last)
   in ()
       2 #tensorboard --logdir ./logs/1/train --host localhost --port 8081
       3 from google.datalab.ml import TensorBoard as tb
  ----> 4 tb.start(model_dir)

/usr/local/envs/py3env/lib/python3.5/site-packages/google/datalab/ml/_tensorboard.py in start(logdir)
      77       retry -= 1
      78
  ---> 79     raise Exception('Cannot start TensorBoard.')
      80
      81   @staticmethod

Exception: Cannot start TensorBoard.

When I list the Tensorboard processes running using below code, below is what I get.

```<code>x = tb.list() #Returns a dataframe
print(x)
</code>```

```<code>      logdir   pid   port
</code>```

0  ./model_no_reuse/2  6236  40269

  1  ./model_no_reuse/2  6241  57895

Please help me identify what is going wrong.

答: I tried increasing the VM configuration from 2 vCPU/4.5 GB to 4 vCPU/20GB and the issue is resolved. It looks like even though Tensorboard process does get started, for it to open up certain minimum resources are needed. Will change the answer if I arrive at any other conclusion.</p>

Body:
I see that Tensorboard process is running. Files are written into the model directory. However, repeatedly I get the Exception: Unable to start Tensorboard. I am using TF.estimator.

I am running my code on Google Cloud Datalab. I have tried changing model directory and restarting the Datalab instance many times. Also tried running killing all running Tensorboard processes. Nothing has worked so far. It was working earlier or once in every 10-15 attempts it magically runs. Whats happening?

This is how I am starting Tensorboard.

from google.datalab.ml import TensorBoard as tb
tb.start(model_dir)

This is how my Estimator is configured.

run_config = tf.estimator.RunConfig(
  save_checkpoints_steps=FLAGS.save_checkpoints_steps,
  tf_random_seed=FLAGS.tf_random_seed,
  model_dir=model_dir
)

estimator = tf.estimator.Estimator(model_fn=model_fn,
config=run_config)

Below are the files being written into the model directory by tf.estimator.

eval 8 minutes ago

checkpoint 124 B 9 minutes ago

events.out.tfevents.1559025239.78fe4cbf0fad 603 kB 9 minutes ago

graph.pbtxt 399 kB 12 minutes ago

model.ckpt-1.data-00000-of-00001 261 MB 11 minutes ago

model.ckpt-1.index 811 B 11 minutes ago

model.ckpt-1.meta 170 kB 11 minutes ago

model.ckpt-5.data-00000-of-00001 261 MB 9 minutes ago

model.ckpt-5.index 811 B 9 minutes ago

model.ckpt-5.meta 170 kB 9 minutes ago

The error I am getting is below. It is the same everytime and I have no further information to identify what is going wrong.

Exception                                 Traceback (most recent call >last)
   in ()
       2 #tensorboard --logdir ./logs/1/train --host localhost --port 8081
       3 from google.datalab.ml import TensorBoard as tb
  ----> 4 tb.start(model_dir)

/usr/local/envs/py3env/lib/python3.5/site-packages/google/datalab/ml/_tensorboard.py in start(logdir)
      77       retry -= 1
      78
  ---> 79     raise Exception('Cannot start TensorBoard.')
      80
      81   @staticmethod

Exception: Cannot start TensorBoard.

When I list the Tensorboard processes running using below code, below is what I get.

x = tb.list() #Returns a dataframe
print(x)

      logdir   pid   port

0  ./model_no_reuse/2  6236  40269

  1  ./model_no_reuse/2  6241  57895

Please help me identify what is going wrong.


问:
how to trigger button to open up user input/text box
so im trying to create "kanban/to do list" website, and im having trouble with triggering the add button. Im trying to trigger "add" button to open up a user input box. So I have this "add" button which creates a small box. but i cannot figure out how to add a small area in that box where i could write any type of text.

Ive done alot of reasearch, but no one is making the same type of to do list app.

```<code>div class="board">
    <div class="board-column todo">
            <button type="button" class="btn" onclick="addEvent()">+</button>
            <div class="board-column-header">To do</div>
            <div class="board-column-content"></div>

.btn {
    display: inline-block;
    position: absolute;
    z-index: 1;
    right: 10px;
    top: 10px;
    display:block;
    width:30px;
    height:30px;
    line-height:25px;
    border: 2px solid #fff;
    border-radius: 50%;
    color: #fff;
    background: #4A9FF9;
    text-align:center;
    box-shadow: 0 0 3px rgba(92, 92, 92, 0.2);
    font-size:20px;
    cursor: pointer;
</code>```

forgot to mention. in this spesific box, i want to have that input/text box

```<code>
    board-item-content {
        position: relative;
        padding: 20px;
        background: #fff;
        border-radius: 10px;
        font-size: 20px;
        cursor: pointer;
        box-shadow: 1px 1px 5px 0 rgba(92, 92, 92, 0.2);
    }
</code>```

答:
function addEvent() {
  var txt;
  var task1 = prompt("Please enter your task:", "Task Name");
  if (task1 == null || task1 == "") {
    txt = "User cancelled the prompt.";
  } else {
    txt = "You have added : " + task1 + "as a task!";
  }
  document.getElementById("demo").innerHTML = txt;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn {
    display: inline-block;
    position: absolute;
    z-index: 1;
    right: 10px;
    top: 10px;
    display:block;
    width:30px;
    height:30px;
    line-height:25px;
    border: 2px solid #fff;
    border-radius: 50%;
    color: #fff;
    background: #4A9FF9;
    text-align:center;
    box-shadow: 0 0 3px rgba(92, 92, 92, 0.2);
    font-size:20px;
    cursor: pointer;``````
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <div class="board-column todo">
            <button type="button" class="btn" onclick="addEvent()">+</button>
            <div class="board-column-header">To do</div>
            <div class="board-column-content"></div>

            <p id="demo"></p></code>```

Body:
so im trying to create "kanban/to do list" website, and im having trouble with triggering the add button. Im trying to trigger "add" button to open up a user input box. So I have this "add" button which creates a small box. but i cannot figure out how to add a small area in that box where i could write any type of text.

Ive done alot of reasearch, but no one is making the same type of to do list app.

div class="board">

            <button type="button" class="btn" onclick="addEvent()">+</button>

To do

.btn {
    display: inline-block;
    position: absolute;
    z-index: 1;
    right: 10px;
    top: 10px;
    display:block;
    width:30px;
    height:30px;
    line-height:25px;
    border: 2px solid #fff;
    border-radius: 50%;
    color: #fff;
    background: #4A9FF9;
    text-align:center;
    box-shadow: 0 0 3px rgba(92, 92, 92, 0.2);
    font-size:20px;
    cursor: pointer;

forgot to mention. in this spesific box, i want to have that input/text box

    board-item-content {
        position: relative;
        padding: 20px;
        background: #fff;
        border-radius: 10px;
        font-size: 20px;
        cursor: pointer;
        box-shadow: 1px 1px 5px 0 rgba(92, 92, 92, 0.2);
    }

Body:
function addEvent() {
  var txt;
  var task1 = prompt("Please enter your task:", "Task Name");
  if (task1 == null || task1 == "") {
    txt = "User cancelled the prompt.";
  } else {
    txt = "You have added : " + task1 + "as a task!";
  }
  document.getElementById("demo").innerHTML = txt;
}

.btn {
    display: inline-block;
    position: absolute;
    z-index: 1;
    right: 10px;
    top: 10px;
    display:block;
    width:30px;
    height:30px;
    line-height:25px;
    border: 2px solid #fff;
    border-radius: 50%;
    color: #fff;
    background: #4A9FF9;
    text-align:center;
    box-shadow: 0 0 3px rgba(92, 92, 92, 0.2);
    font-size:20px;
    cursor: pointer;```

   <div class="board-column todo">
            <button type="button" class="btn" onclick="addEvent()">+</button>
            <div class="board-column-header">To do</div>
            <div class="board-column-content"></div>

            <p id="demo"></p>


问:
Converting grayscale JPEG image to RGB leads to 9 channels
Trying to convert some grayscale images to RGB (1,1,1).. I have a folder of about 1500 images that I need batch converted using the code below (which works well with individual images)

Interestingly enough,

```<code>imwrite(repmat(imread(files(1).name), [1 1 3]),files(1).name)
imwrite(repmat(imread(files(2).name), [1 1 3]),files(2).name)
imwrite(repmat(imread(files(3).name), [1 1 3]),files(3).name)
</code>```

...(and so forth)

works just fine

```<code>files = dir('*.jpeg')
for I=1:length(files)
    imwrite(repmat(imread(files(i).name), [1 1 3]),files(i).name)
    display(i)
end
</code>```

Error using writejpg (line 46)
  Data with 9 components not supported for JPEG files.

Error in imwrite (line 485)
          feval(fmt_s.write, data, map, filename, paramPairs{:});

答:
You need to do two things:

Use the correct variable name for looping, i.e. i or I but not a mix! Note that i has a built in definition as the imaginary constant, so you're better of using I, or something different entirely.

You show a warning for JPEGs with 9 elements not being supported when trying to write the file. This suggests you've blindly used repmat to triplicate an image which is already RBG.

We can address both of these like so:

```<code>files = dir('*.jpeg')
for k = 1:length(files)
    img = imread( files(k).name ); % Load the image first
    % Convert greyscale to RBG if not already RGB
    % If it's already RBG, we don't even need to overwrite the image
    if size(img,3) == 1
        imwrite(repmat(img, [1 1 3]), files(k).name);
    end
    % Display progress
    display(k)
end
</code>```

Body:
Trying to convert some grayscale images to RGB (1,1,1).. I have a folder of about 1500 images that I need batch converted using the code below (which works well with individual images)

Interestingly enough,

imwrite(repmat(imread(files(1).name), [1 1 3]),files(1).name)
imwrite(repmat(imread(files(2).name), [1 1 3]),files(2).name)
imwrite(repmat(imread(files(3).name), [1 1 3]),files(3).name)

...(and so forth)

works just fine

files = dir('*.jpeg')
for I=1:length(files)
    imwrite(repmat(imread(files(i).name), [1 1 3]),files(i).name)
    display(i)
end

Error using writejpg (line 46)
  Data with 9 components not supported for JPEG files.

Error in imwrite (line 485)
          feval(fmt_s.write, data, map, filename, paramPairs{:});

Body:
You need to do two things:

Use the correct variable name for looping, i.e. i or I but not a mix! Note that i has a built in definition as the imaginary constant, so you're better of using I, or something different entirely.

You show a warning for JPEGs with 9 elements not being supported when trying to write the file. This suggests you've blindly used repmat to triplicate an image which is already RBG.

We can address both of these like so:

files = dir('*.jpeg')
for k = 1:length(files)
    img = imread( files(k).name ); % Load the image first
    % Convert greyscale to RBG if not already RGB
    % If it's already RBG, we don't even need to overwrite the image
    if size(img,3) == 1
        imwrite(repmat(img, [1 1 3]), files(k).name);
    end
    % Display progress
    display(k)
end