答:
Assuming you can use standard algorithms its better to rewrite your function using them. This achieves 2 goals:

code is more readable, since using algorithms shows intent along with code itself

there is less chance to make error

So it should be something like this:

```<code>std::string WordCount::makeValidWord(std::string word) {
    auto first = std::find_if(word.cbegin(), word.cend(), isWordChar);
    auto last = std::find_if(word.crbegin(), word.crend(), isWordChar);
    std::string i;
    std::copy_if(first, std::next(last), std::back_inserter(i), [](char c) {
        return isWordChar(c) || c == '-' || c == '\'';
    });
    std::string r;
    std::transform(i.cbegin(), i.cend(), std::back_inserter(r), std::tolower);
    return r;
}
</code>```

Title: makeValidWord(std::string word) not working properly

Body:
Assuming you can use standard algorithms its better to rewrite your function using them. This achieves 2 goals:

code is more readable, since using algorithms shows intent along with code itself

there is less chance to make error

So it should be something like this:

std::string WordCount::makeValidWord(std::string word) {
    auto first = std::find_if(word.cbegin(), word.cend(), isWordChar);
    auto last = std::find_if(word.crbegin(), word.crend(), isWordChar);
    std::string i;
    std::copy_if(first, std::next(last), std::back_inserter(i), [](char c) {
        return isWordChar(c) || c == '-' || c == '\'';
    });
    std::string r;
    std::transform(i.cbegin(), i.cend(), std::back_inserter(r), std::tolower);
    return r;
}


来源: stackexchange

问:
How can I run mysql_upgrade as a part of a docker compose file?
I have a docker-compose.yml with a MariaDB database service that looks like this:

```<code>version: '2'

services:
  db:
    container_name: misp_db
    image: mariadb
    restart: unless-stopped
    volumes:
      - ${DATA_DIR}/db:/var/lib/mysql
    environment:
      - MYSQL_DATABASE=${MYSQL_DATABASE}
      - MYSQL_USER=${MYSQL_USER}
      - MYSQL_PASSWORD=${MYSQL_PASSWORD}
      - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
</code>```

When spinning up my containers, I noticed these errors:

```<code>[ERROR] Missing system table mysql.roles_mapping; please run mysql_upgrade to create it
[ERROR] Incorrect definition of table mysql.event: expected column 'sql_mode' at position 14 to have type set('REAL_AS_FLOAT','PIPES_AS_CONCAT','ANSI_QUOTES','IGNORE_SPACE','IGNORE_BAD_TABLE_OPTIONS','ONLY_FULL_GROUP_BY','NO_UNSIGNED_SUBTRACTION','NO_DIR_IN_CREATE','POSTGRESQL','ORACLE','MSSQL','DB2','MAXDB','NO_KEY_OPTIONS','NO_TABLE_OPTIONS','NO_FIELD_OPTIONS','MYSQL323','MYSQL40','ANSI','NO_AUTO_VALUE_ON_ZERO','NO_BACKSLASH_ESCAPES','STRICT_TRANS_TABLES','STRICT_ALL_TABLES','NO_ZERO_IN_DATE','NO_ZERO_DATE','INVALID_DATES','ERROR_FOR_DIVISION_BY_ZERO','TRADITIONAL','NO_AUTO_CREATE_USER','HIGH_NOT_PRECEDENCE','NO_ENGINE_SUBSTITUTION','PAD_CHAR_TO_FULL_LENGTH','EMPTY_STRING_IS_NULL','SIMULTANEOUS_ASSIGNMENT'), found type set('REAL_AS_FLOAT','PIPES_AS_CONCAT','ANSI_QUOTES','IGNORE_SPACE','NOT_USED','ONLY_FULL_GROUP_BY','NO_UNSIGNED_SUBTRACTION','NO_DIR_IN_CREATE','POSTGRESQL','ORACLE','MSSQL','DB2','MAXDB','NO_KEY_OPTIONS','NO_TABLE_OPTIONS','NO_FIELD_OPTIONS','MYSQL323','MYSQL40','ANSI','NO_AUTO_VALUE_ON_ZERO','NO_B
[ERROR] mysqld: Event Scheduler: An error occurred when initializing system tables. Disabling the Event Scheduler.
</code>```

I was able to work around this problem by running docker exec -it db /bin/bash to get a shell, and then running mysql_upgrade -p and entering my configured MySQL root password, but this should be automated.

How can I do this in Docker Compose?

答:
You can't run it directly from the docker-compose but it can be done rather simply using a one-line Dockerfile called from docker-compose.

This can be done by simply adding the following to your service definition in the docker-compose.yaml file:

```<code>build: .
</code>```

This will cause docker-compose to run the Dockerfile located in the working directory ".".

In the Dockerfile, you can then run the upgrade script itself.

```<code>RUN mysql_upgrade -p
</code>```

This will cause the upgrade to be run once; while building the image. Subsequently, your mySQL version will be frozen at the time you build the image; not when you start the container. This seems like a reasonable approach to me.

You could run an entrypoint.sh script from the Dockerfile (see here for more details), which gets called when you start the container. That would perform the upgrade when you start the container as you originally requested but, I agree with @blokje5, upgrading when starting the container seems a bit risky. If they accidentally break something (it happens), then an image that once worked would no longer be working and that can be a bit of a nightmare to debug; especially since it's happening before the service is considered ready.

ContentLicense: CC BY-SA 4.0

Body:
I have a docker-compose.yml with a MariaDB database service that looks like this:

version: '2'

services:
  db:
    container_name: misp_db
    image: mariadb
    restart: unless-stopped
    volumes:
      - ${DATA_DIR}/db:/var/lib/mysql
    environment:
      - MYSQL_DATABASE=${MYSQL_DATABASE}
      - MYSQL_USER=${MYSQL_USER}
      - MYSQL_PASSWORD=${MYSQL_PASSWORD}
      - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}

When spinning up my containers, I noticed these errors:

[ERROR] Missing system table mysql.roles_mapping; please run mysql_upgrade to create it
[ERROR] Incorrect definition of table mysql.event: expected column 'sql_mode' at position 14 to have type set('REAL_AS_FLOAT','PIPES_AS_CONCAT','ANSI_QUOTES','IGNORE_SPACE','IGNORE_BAD_TABLE_OPTIONS','ONLY_FULL_GROUP_BY','NO_UNSIGNED_SUBTRACTION','NO_DIR_IN_CREATE','POSTGRESQL','ORACLE','MSSQL','DB2','MAXDB','NO_KEY_OPTIONS','NO_TABLE_OPTIONS','NO_FIELD_OPTIONS','MYSQL323','MYSQL40','ANSI','NO_AUTO_VALUE_ON_ZERO','NO_BACKSLASH_ESCAPES','STRICT_TRANS_TABLES','STRICT_ALL_TABLES','NO_ZERO_IN_DATE','NO_ZERO_DATE','INVALID_DATES','ERROR_FOR_DIVISION_BY_ZERO','TRADITIONAL','NO_AUTO_CREATE_USER','HIGH_NOT_PRECEDENCE','NO_ENGINE_SUBSTITUTION','PAD_CHAR_TO_FULL_LENGTH','EMPTY_STRING_IS_NULL','SIMULTANEOUS_ASSIGNMENT'), found type set('REAL_AS_FLOAT','PIPES_AS_CONCAT','ANSI_QUOTES','IGNORE_SPACE','NOT_USED','ONLY_FULL_GROUP_BY','NO_UNSIGNED_SUBTRACTION','NO_DIR_IN_CREATE','POSTGRESQL','ORACLE','MSSQL','DB2','MAXDB','NO_KEY_OPTIONS','NO_TABLE_OPTIONS','NO_FIELD_OPTIONS','MYSQL323','MYSQL40','ANSI','NO_AUTO_VALUE_ON_ZERO','NO_B
[ERROR] mysqld: Event Scheduler: An error occurred when initializing system tables. Disabling the Event Scheduler.

I was able to work around this problem by running docker exec -it db /bin/bash to get a shell, and then running mysql_upgrade -p and entering my configured MySQL root password, but this should be automated.

How can I do this in Docker Compose?

Body:
You can't run it directly from the docker-compose but it can be done rather simply using a one-line Dockerfile called from docker-compose.

This can be done by simply adding the following to your service definition in the docker-compose.yaml file:

build: .

This will cause docker-compose to run the Dockerfile located in the working directory ".".

In the Dockerfile, you can then run the upgrade script itself.

RUN mysql_upgrade -p

This will cause the upgrade to be run once; while building the image. Subsequently, your mySQL version will be frozen at the time you build the image; not when you start the container. This seems like a reasonable approach to me.

You could run an entrypoint.sh script from the Dockerfile (see here for more details), which gets called when you start the container. That would perform the upgrade when you start the container as you originally requested but, I agree with @blokje5, upgrading when starting the container seems a bit risky. If they accidentally break something (it happens), then an image that once worked would no longer be working and that can be a bit of a nightmare to debug; especially since it's happening before the service is considered ready.


问:
escpos printer image not getting align to center
I am using escpos for printing the Token in our Queue managment system python. I  need to put the company logo in header of the token. I am trying to do the same as below.

```<code>printer.set(align='center')
    #printer.qr("You can readme from your smartphone")
    printer.image("index/index_statics/img/brand/Webp.net-resizeimage.png")
</code>```

But the image is always alignef to left. I have seen many links on the same. but nothing that I can understant. I am very new it. Please help to understand the issue and please help me to resolve the same. The printer is ZKTeco (ZKP8008) termal printer

答: This is not an ESC/POS question.  Just that the printer can interpret ESC/POS does not mean that escpos is the good category for a framework/library question.</p>

Body:
I am using escpos for printing the Token in our Queue managment system python. I  need to put the company logo in header of the token. I am trying to do the same as below.

printer.set(align='center')
    #printer.qr("You can readme from your smartphone")
    printer.image("index/index_statics/img/brand/Webp.net-resizeimage.png")

But the image is always alignef to left. I have seen many links on the same. but nothing that I can understant. I am very new it. Please help to understand the issue and please help me to resolve the same. The printer is ZKTeco (ZKP8008) termal printer


问:
C struct with a pointer to be wrapped in a unique_ptr
I have a memory struct as shown below.

```<code>struct memoryStruct {
    uint8_t* memory;
    size_t size;
};
</code>```

My code requires me to call free(memory) at multiple places in my code. To avoid this scenario I am thinking of wrapping it in a unique_ptr.

I have the following

```<code>struct memoryStruct {
    uint8_t* memory;
    size_t size;
};

struct memoryStructDeleter {
    void operator()(memoryStruct* p) const
    {
        free(p);
    }
};
</code>```

How do I initialize m_chunk shown below. I want to allocate a memory of size using malloc to memory field and update size accordingly.

```<code>std::unique_ptr<memoryStruct> m_chunk;
</code>```

答:
You would need something like this:

struct memoryStruct {
    uint8_t* memory;
    size_t size;
};

struct memoryStructDeleter {
    void operator()(memoryStruct* p) const
    {
        if (p) {
            free(p->memory);
            free(p);
        }
    }
};

...

std::unique_ptr<memoryStruct, memoryStructDeleter> m_chunk( static_cast<memoryStruct*>(std::malloc(sizeof(memoryStruct))) );
if (m_chunk) {
    m_chunk->size = DesiredSize;
    m_chunk->memory = static_cast<uint8_t*>(std::malloc(m_chunk->size));
}
```

<p>Which can be greatly simplified if you get rid of <code>malloc()</code> altogether and use <code>new</code>/<code>new[]</code> or <code>std::make_unique()</code> instead:</p>

<pre class="lang-cpp prettyprint-override"><code>struct memoryStruct {
    std::unique_ptr<uint8_t[]> memory;
    size_t size;

    memoryStruct(size_t asize = 0) : memory(new uint8_t[asize]), size(asize) {}
    // or:
    // memoryStruct(size_t asize = 0) : memory(std::make_unique<uint8_t[]>(asize)), size(asize) {}
};

...

std::unique_ptr<memoryStruct> m_chunk(new memoryStruct(DesiredSize));
// or:
// std::unique_ptr<memoryStruct> m_chunk = std::make_unique<memoryStruct>(DesiredSize);
</code>```

Which can then be simplified even further if you use std::vector instead of std::unique_ptr:

struct memoryStruct {
    std::vector<uint8_t> memory;
    memoryStruct(size_t size = 0) : memory(size) {}
};

...

std::unique_ptr<memoryStruct> m_chunk(new memoryStruct(DesiredSize));
// or:
// std::unique_ptr<memoryStruct> m_chunk = std::make_unique<memoryStruct>(DesiredSize);
```

Body:
I have a memory struct as shown below.

struct memoryStruct {
    uint8_t* memory;
    size_t size;
};

My code requires me to call free(memory) at multiple places in my code. To avoid this scenario I am thinking of wrapping it in a unique_ptr.

I have the following

struct memoryStruct {
    uint8_t* memory;
    size_t size;
};

struct memoryStructDeleter {
    void operator()(memoryStruct* p) const
    {
        free(p);
    }
};

How do I initialize m_chunk shown below. I want to allocate a memory of size using malloc to memory field and update size accordingly.

std::unique_ptr<memoryStruct> m_chunk;

Body:
You would need something like this:

struct memoryStruct {
    uint8_t* memory;
    size_t size;
};

struct memoryStructDeleter {
    void operator()(memoryStruct* p) const
    {
        if (p) {
            free(p->memory);
            free(p);
        }
    }
};

...

std::unique_ptr<memoryStruct, memoryStructDeleter> m_chunk( static_cast<memoryStruct*>(std::malloc(sizeof(memoryStruct))) );
if (m_chunk) {
    m_chunk->size = DesiredSize;
    m_chunk->memory = static_cast<uint8_t*>(std::malloc(m_chunk->size));
}

Which can be greatly simplified if you get rid of malloc() altogether and use new/new[] or std::make_unique() instead:

struct memoryStruct {
    std::unique_ptr<uint8_t[]> memory;
    size_t size;

    memoryStruct(size_t asize = 0) : memory(new uint8_t[asize]), size(asize) {}
    // or:
    // memoryStruct(size_t asize = 0) : memory(std::make_unique<uint8_t[]>(asize)), size(asize) {}
};

...

std::unique_ptr<memoryStruct> m_chunk(new memoryStruct(DesiredSize));
// or:
// std::unique_ptr<memoryStruct> m_chunk = std::make_unique<memoryStruct>(DesiredSize);

Which can then be simplified even further if you use std::vector instead of std::unique_ptr:

struct memoryStruct {
    std::vector<uint8_t> memory;
    memoryStruct(size_t size = 0) : memory(size) {}
};

...

std::unique_ptr<memoryStruct> m_chunk(new memoryStruct(DesiredSize));
// or:
// std::unique_ptr<memoryStruct> m_chunk = std::make_unique<memoryStruct>(DesiredSize);


问:
Can't debug Artifactory issue, can't start up, stuck with 500 error
What I am Doing

I am trying to set up Artifactory. Whenever I try and get my service up, it's at a 500 error and I can't fix it.

What I've Tried

I have tried many solutions online, mainly searching for and trying the different solutions such as:

'(o.a.w.s.ArtifactoryFilter:194) - Artifactory failed to initialize: Context is null'

And

'[art-init] [ERROR] (o.a.w.s.ArtifactoryContextConfigListener:96) - Application could not be initialized: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')'

Some More Information

```<code>Version:  6.13.1
 Revision: 61301900
 Artifactory Home: '/var/opt/jfrog/artifactory'
 HA Node ID: '[REDACTED]'

openjdk version "1.8.0_232"
OpenJDK Runtime Environment (build 1.8.0_232-b09)
OpenJDK 64-Bit Server VM (build 25.232-b09, mixed mode)

status  500
message "Artifactory failed to initialize: check Artifactory logs for errors."
</code>```

I don't know why this is happening and if anyone could recommend suggestions, I would try them all.

```<code>2020-02-18 15:45:39,797 [art-init] [INFO ] (o.j.s.b.p.t.BinaryProviderClassScanner:76) - Added 'remote' from jar:file:/opt/jfrog/artifactory/tomcat/webapps/artifactory/WEB-INF/lib/binary-store-client-3.4.8.jar!/
2020-02-18 15:45:40,251 [art-init] [INFO ] (o.a.a.f.t.j.s.S3JetS3tBinaryProvider:530) - Connecting to S3 endpoint: 's3-us-west-2.amazonaws.com'
2020-02-18 15:45:40,956 [art-init] [WARN ] (o.a.s.ArtifactoryApplicationContext:254) - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'xrayServiceImpl' defined in URL [jar:file:/opt/jfrog/artifactory/tomcat/webapps/artifactory/WEB-INF/lib/artifactory-addon-xray-6.13.1.jar!/org/artifactory/addon/xray/XrayServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'centralConfig': Unsatisfied dependency expressed through field 'authService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityServiceImpl': Unsatisfied dependency expressed through field 'activePrincipalTokenStore'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'activePrincipalTokenStoreImpl' defined in URL [jar:file:/opt/jfrog/artifactory/tomcat/webapps/artifactory/WEB-INF/lib/artifactory-core-6.13.1.jar!/org/artifactory/security/auth/ActivePrincipalTokenStoreImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accessServiceImpl': Unsatisfied dependency expressed through method 'setRepositoryService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repositoryServiceImpl': Unsatisfied dependency expressed through field 'uploadService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadServiceImpl': Unsatisfied dependency expressed through method 'setBinaryService' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'binaryServiceImpl': Invocation of init method failed; nested exception is java.lang.RuntimeException: org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.StringReader@6cb92d33; line: 1, column: 2]
2020-02-18 15:45:40,975 [art-init] [ERROR] (o.a.w.s.ArtifactoryContextConfigListener:96) - Application could not be initialized: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.StringReader@6cb92d33; line: 1, column: 2]
java.lang.reflect.InvocationTargetException: null
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.artifactory.webapp.servlet.ArtifactoryContextConfigListener.configure(ArtifactoryContextConfigListener.java:211)
        at org.artifactory.webapp.servlet.ArtifactoryContextConfigListener.access$200(ArtifactoryContextConfigListener.java:67)
        at org.artifactory.webapp.servlet.ArtifactoryContextConfigListener$1.run(ArtifactoryContextConfigListener.java:92)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'xrayServiceImpl' defined in URL [jar:file:/opt/jfrog/artifactory/tomcat/webapps/artifactory/WEB-INF/lib/artifactory-addon-xray-6.13.1.jar!/org/artifactory/addon/xray/XrayServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'centralConfig': Unsatisfied dependency expressed through field 'authService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityServiceImpl': Unsatisfied dependency expressed through field 'activePrincipalTokenStore'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'activePrincipalTokenStoreImpl' defined in URL [jar:file:/opt/jfrog/artifactory/tomcat/webapps/artifactory/WEB-INF/lib/artifactory-core-6.13.1.jar!/org/artifactory/security/auth/ActivePrincipalTokenStoreImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accessServiceImpl': Unsatisfied dependency expressed through method 'setRepositoryService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repositoryServiceImpl': Unsatisfied dependency expressed through field 'uploadService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadServiceImpl': Unsatisfied dependency expressed through method 'setBinaryService' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'binaryServiceImpl': Invocation of init method failed; nested exception is java.lang.RuntimeException: org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.StringReader@6cb92d33; line: 1, column: 2]
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769)
        at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:218)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1341)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1187)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:843)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
        at org.artifactory.spring.ArtifactoryApplicationContext.refresh(ArtifactoryApplicationContext.java:254)
        at org.artifactory.spring.ArtifactoryApplicationContext.<init>(ArtifactoryApplicationContext.java:149)
        ... 7 common frames omitted
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'centralConfig': Unsatisfied dependency expressed through field 'authService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityServiceImpl': Unsatisfied dependency expressed through field 'activePrincipalTokenStore'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'activePrincipalTokenStoreImpl' defined in URL [jar:file:/opt/jfrog/artifactory/tomcat/webapps/artifactory/WEB-INF/lib/artifactory-core-6.13.1.jar!/org/artifactory/security/auth/ActivePrincipalTokenStoreImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accessServiceImpl': Unsatisfied dependency expressed through method 'setRepositoryService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repositoryServiceImpl': Unsatisfied dependency expressed through field 'uploadService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadServiceImpl': Unsatisfied dependency expressed through method 'setBinaryService' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'binaryServiceImpl': Invocation of init method failed; nested exception is java.lang.RuntimeException: org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.StringReader@6cb92d33; line: 1, column: 2]
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1248)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1168)
        at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857)
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760)
        ... 21 common frames omitted
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityServiceImpl': Unsatisfied dependency expressed through field 'activePrincipalTokenStore'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'activePrincipalTokenStoreImpl' defined in URL [jar:file:/opt/jfrog/artifactory/tomcat/webapps/artifactory/WEB-INF/lib/artifactory-core-6.13.1.jar!/org/artifactory/security/auth/ActivePrincipalTokenStoreImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accessServiceImpl': Unsatisfied dependency expressed through method 'setRepositoryService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repositoryServiceImpl': Unsatisfied dependency expressed through field 'uploadService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadServiceImpl': Unsatisfied dependency expressed through method 'setBinaryService' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'binaryServiceImpl': Invocation of init method failed; nested exception is java.lang.RuntimeException: org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.StringReader@6cb92d33; line: 1, column: 2]
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)

... removed cause 30k char limit but same errors...

 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:668)
            ... 101 common frames omitted
    Caused by: java.lang.RuntimeException: org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
     at [Source: java.io.StringReader@6cb92d33; line: 1, column: 2]
            at org.artifactory.addon.filestore.type.jets3t.s3.AWSEC2IAMSessionCredentialsNew.loadFromEC2InstanceDataNew(AWSEC2IAMSessionCredentialsNew.java:141)
            at org.artifactory.addon.filestore.type.jets3t.s3.AWSEC2IAMSessionCredentialsNew.loadFromEC2InstanceDataNew(AWSEC2IAMSessionCredentialsNew.java:160)
            at org.artifactory.addon.filestore.type.jets3t.s3.S3JetS3tBinaryProvider.createCredentials(S3JetS3tBinaryProvider.java:479)
            at org.artifactory.addon.filestore.type.jets3t.s3.S3JetS3tBinaryProvider.initialize(S3JetS3tBinaryProvider.java:135)
            at org.jfrog.storage.binstore.providers.builder.BinaryProviderFactory.build(BinaryProviderFactory.java:98)
            at org.jfrog.storage.binstore.providers.builder.BinaryProviderFactory.build(BinaryProviderFactory.java:86)
            at org.jfrog.storage.binstore.providers.builder.BinaryProviderFactory.build(BinaryProviderFactory.java:86)
            at org.jfrog.storage.binstore.providers.builder.BinaryProviderFactory.build(BinaryProviderFactory.java:93)
            at org.jfrog.storage.binstore.providers.builder.BinaryProviderFactory.build(BinaryProviderFactory.java:86)
            at org.jfrog.storage.binstore.providers.builder.BinaryProviderFactory.buildProviders(BinaryProviderFactory.java:75)
            at org.jfrog.storage.binstore.manager.BinaryProviderManagerImpl.<init>(BinaryProviderManagerImpl.java:115)
            at org.artifactory.storage.db.binstore.service.BinaryServiceImpl.initialize(BinaryServiceImpl.java:187)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:498)
            at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:363)
            at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:307)
            at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136)
            ... 113 common frames omitted
    Caused by: org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
     at [Source: java.io.StringReader@6cb92d33; line: 1, column: 2]
            at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1432)
            at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:521)
            at org.codehaus.jackson.impl.JsonParserMinimalBase._reportUnexpectedChar(JsonParserMinimalBase.java:442)
            at org.codehaus.jackson.impl.ReaderBasedParser._handleUnexpectedValue(ReaderBasedParser.java:1198)
            at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(ReaderBasedParser.java:485)
            at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2770)
            at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2718)
            at org.codehaus.jackson.map.ObjectMapper.readTree(ObjectMapper.java:1542)
            at org.artifactory.addon.filestore.type.jets3t.s3.AWSEC2IAMSessionCredentialsNew.parseEC2InstanceDataNew(AWSEC2IAMSessionCredentialsNew.java:183)
            at org.artifactory.addon.filestore.type.jets3t.s3.AWSEC2IAMSessionCredentialsNew.loadFromEC2InstanceDataNew(AWSEC2IAMSessionCredentialsNew.java:138)
            ... 131 common frames omitted
    2020-02-18 15:45:41,372 [http-nio-8081-exec-1] [ERROR] (o.a.w.s.ArtifactoryFilter:194) - Artifactory failed to initialize: Context is null
</code>```

答:
Check your binarystore.xml.

Seems like you have a property named instanceMetadataUrl and this url should resolve json, but it resolves xml. Probably error page.

You could also turn on debug on this section of the Artifactory application by changing the logback.xml file.
Add this section under one of the loggers:

```<code><logger name="org.artifactory.addon.filestore">
        <level value="debug"/>
</logger>
</code>```

This will give you much more information about what is going on.
When the issue is resolved, return the logback.xml to it's original state.

Body:
What I am Doing

I am trying to set up Artifactory. Whenever I try and get my service up, it's at a 500 error and I can't fix it.

What I've Tried

I have tried many solutions online, mainly searching for and trying the different solutions such as:

'(o.a.w.s.ArtifactoryFilter:194) - Artifactory failed to initialize: Context is null'

And

'[art-init] [ERROR] (o.a.w.s.ArtifactoryContextConfigListener:96) - Application could not be initialized: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')'

Some More Information

Version:  6.13.1
 Revision: 61301900
 Artifactory Home: '/var/opt/jfrog/artifactory'
 HA Node ID: '[REDACTED]'

openjdk version "1.8.0_232"
OpenJDK Runtime Environment (build 1.8.0_232-b09)
OpenJDK 64-Bit Server VM (build 25.232-b09, mixed mode)

status  500
message "Artifactory failed to initialize: check Artifactory logs for errors."

I don't know why this is happening and if anyone could recommend suggestions, I would try them all.

2020-02-18 15:45:39,797 [art-init] [INFO ] (o.j.s.b.p.t.BinaryProviderClassScanner:76) - Added 'remote' from jar:file:/opt/jfrog/artifactory/tomcat/webapps/artifactory/WEB-INF/lib/binary-store-client-3.4.8.jar!/
2020-02-18 15:45:40,251 [art-init] [INFO ] (o.a.a.f.t.j.s.S3JetS3tBinaryProvider:530) - Connecting to S3 endpoint: 's3-us-west-2.amazonaws.com'
2020-02-18 15:45:40,956 [art-init] [WARN ] (o.a.s.ArtifactoryApplicationContext:254) - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'xrayServiceImpl' defined in URL [jar:file:/opt/jfrog/artifactory/tomcat/webapps/artifactory/WEB-INF/lib/artifactory-addon-xray-6.13.1.jar!/org/artifactory/addon/xray/XrayServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'centralConfig': Unsatisfied dependency expressed through field 'authService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityServiceImpl': Unsatisfied dependency expressed through field 'activePrincipalTokenStore'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'activePrincipalTokenStoreImpl' defined in URL [jar:file:/opt/jfrog/artifactory/tomcat/webapps/artifactory/WEB-INF/lib/artifactory-core-6.13.1.jar!/org/artifactory/security/auth/ActivePrincipalTokenStoreImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accessServiceImpl': Unsatisfied dependency expressed through method 'setRepositoryService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repositoryServiceImpl': Unsatisfied dependency expressed through field 'uploadService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadServiceImpl': Unsatisfied dependency expressed through method 'setBinaryService' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'binaryServiceImpl': Invocation of init method failed; nested exception is java.lang.RuntimeException: org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.StringReader@6cb92d33; line: 1, column: 2]
2020-02-18 15:45:40,975 [art-init] [ERROR] (o.a.w.s.ArtifactoryContextConfigListener:96) - Application could not be initialized: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.StringReader@6cb92d33; line: 1, column: 2]
java.lang.reflect.InvocationTargetException: null
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.artifactory.webapp.servlet.ArtifactoryContextConfigListener.configure(ArtifactoryContextConfigListener.java:211)
        at org.artifactory.webapp.servlet.ArtifactoryContextConfigListener.access$200(ArtifactoryContextConfigListener.java:67)
        at org.artifactory.webapp.servlet.ArtifactoryContextConfigListener$1.run(ArtifactoryContextConfigListener.java:92)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'xrayServiceImpl' defined in URL [jar:file:/opt/jfrog/artifactory/tomcat/webapps/artifactory/WEB-INF/lib/artifactory-addon-xray-6.13.1.jar!/org/artifactory/addon/xray/XrayServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'centralConfig': Unsatisfied dependency expressed through field 'authService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityServiceImpl': Unsatisfied dependency expressed through field 'activePrincipalTokenStore'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'activePrincipalTokenStoreImpl' defined in URL [jar:file:/opt/jfrog/artifactory/tomcat/webapps/artifactory/WEB-INF/lib/artifactory-core-6.13.1.jar!/org/artifactory/security/auth/ActivePrincipalTokenStoreImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accessServiceImpl': Unsatisfied dependency expressed through method 'setRepositoryService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repositoryServiceImpl': Unsatisfied dependency expressed through field 'uploadService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadServiceImpl': Unsatisfied dependency expressed through method 'setBinaryService' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'binaryServiceImpl': Invocation of init method failed; nested exception is java.lang.RuntimeException: org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.StringReader@6cb92d33; line: 1, column: 2]
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769)
        at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:218)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1341)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1187)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:843)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
        at org.artifactory.spring.ArtifactoryApplicationContext.refresh(ArtifactoryApplicationContext.java:254)
        at org.artifactory.spring.ArtifactoryApplicationContext.<init>(ArtifactoryApplicationContext.java:149)
        ... 7 common frames omitted
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'centralConfig': Unsatisfied dependency expressed through field 'authService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityServiceImpl': Unsatisfied dependency expressed through field 'activePrincipalTokenStore'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'activePrincipalTokenStoreImpl' defined in URL [jar:file:/opt/jfrog/artifactory/tomcat/webapps/artifactory/WEB-INF/lib/artifactory-core-6.13.1.jar!/org/artifactory/security/auth/ActivePrincipalTokenStoreImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accessServiceImpl': Unsatisfied dependency expressed through method 'setRepositoryService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repositoryServiceImpl': Unsatisfied dependency expressed through field 'uploadService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadServiceImpl': Unsatisfied dependency expressed through method 'setBinaryService' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'binaryServiceImpl': Invocation of init method failed; nested exception is java.lang.RuntimeException: org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.StringReader@6cb92d33; line: 1, column: 2]
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1248)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1168)
        at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857)
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760)
        ... 21 common frames omitted
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityServiceImpl': Unsatisfied dependency expressed through field 'activePrincipalTokenStore'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'activePrincipalTokenStoreImpl' defined in URL [jar:file:/opt/jfrog/artifactory/tomcat/webapps/artifactory/WEB-INF/lib/artifactory-core-6.13.1.jar!/org/artifactory/security/auth/ActivePrincipalTokenStoreImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accessServiceImpl': Unsatisfied dependency expressed through method 'setRepositoryService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'repositoryServiceImpl': Unsatisfied dependency expressed through field 'uploadService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'uploadServiceImpl': Unsatisfied dependency expressed through method 'setBinaryService' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'binaryServiceImpl': Invocation of init method failed; nested exception is java.lang.RuntimeException: org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.StringReader@6cb92d33; line: 1, column: 2]
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)

... removed cause 30k char limit but same errors...

 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:668)
            ... 101 common frames omitted
    Caused by: java.lang.RuntimeException: org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
     at [Source: java.io.StringReader@6cb92d33; line: 1, column: 2]
            at org.artifactory.addon.filestore.type.jets3t.s3.AWSEC2IAMSessionCredentialsNew.loadFromEC2InstanceDataNew(AWSEC2IAMSessionCredentialsNew.java:141)
            at org.artifactory.addon.filestore.type.jets3t.s3.AWSEC2IAMSessionCredentialsNew.loadFromEC2InstanceDataNew(AWSEC2IAMSessionCredentialsNew.java:160)
            at org.artifactory.addon.filestore.type.jets3t.s3.S3JetS3tBinaryProvider.createCredentials(S3JetS3tBinaryProvider.java:479)
            at org.artifactory.addon.filestore.type.jets3t.s3.S3JetS3tBinaryProvider.initialize(S3JetS3tBinaryProvider.java:135)
            at org.jfrog.storage.binstore.providers.builder.BinaryProviderFactory.build(BinaryProviderFactory.java:98)
            at org.jfrog.storage.binstore.providers.builder.BinaryProviderFactory.build(BinaryProviderFactory.java:86)
            at org.jfrog.storage.binstore.providers.builder.BinaryProviderFactory.build(BinaryProviderFactory.java:86)
            at org.jfrog.storage.binstore.providers.builder.BinaryProviderFactory.build(BinaryProviderFactory.java:93)
            at org.jfrog.storage.binstore.providers.builder.BinaryProviderFactory.build(BinaryProviderFactory.java:86)
            at org.jfrog.storage.binstore.providers.builder.BinaryProviderFactory.buildProviders(BinaryProviderFactory.java:75)
            at org.jfrog.storage.binstore.manager.BinaryProviderManagerImpl.<init>(BinaryProviderManagerImpl.java:115)
            at org.artifactory.storage.db.binstore.service.BinaryServiceImpl.initialize(BinaryServiceImpl.java:187)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:498)
            at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:363)
            at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:307)
            at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136)
            ... 113 common frames omitted
    Caused by: org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
     at [Source: java.io.StringReader@6cb92d33; line: 1, column: 2]
            at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1432)
            at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:521)
            at org.codehaus.jackson.impl.JsonParserMinimalBase._reportUnexpectedChar(JsonParserMinimalBase.java:442)
            at org.codehaus.jackson.impl.ReaderBasedParser._handleUnexpectedValue(ReaderBasedParser.java:1198)
            at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(ReaderBasedParser.java:485)
            at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2770)
            at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2718)
            at org.codehaus.jackson.map.ObjectMapper.readTree(ObjectMapper.java:1542)
            at org.artifactory.addon.filestore.type.jets3t.s3.AWSEC2IAMSessionCredentialsNew.parseEC2InstanceDataNew(AWSEC2IAMSessionCredentialsNew.java:183)
            at org.artifactory.addon.filestore.type.jets3t.s3.AWSEC2IAMSessionCredentialsNew.loadFromEC2InstanceDataNew(AWSEC2IAMSessionCredentialsNew.java:138)
            ... 131 common frames omitted
    2020-02-18 15:45:41,372 [http-nio-8081-exec-1] [ERROR] (o.a.w.s.ArtifactoryFilter:194) - Artifactory failed to initialize: Context is null

Body:
Check your binarystore.xml.

Seems like you have a property named instanceMetadataUrl and this url should resolve json, but it resolves xml. Probably error page.

You could also turn on debug on this section of the Artifactory application by changing the logback.xml file.
Add this section under one of the loggers:

<logger name="org.artifactory.addon.filestore">
        <level value="debug"/>
</logger>

This will give you much more information about what is going on.
When the issue is resolved, return the logback.xml to it's original state.


问:
ModuleNotFoundError with pyinstaller but fine in Pycharm
I'm trying to convert a .py project to an .exe file using the using the Auto Py To Exe which uses the pyinstaller.

Running my code inside pycharm I get no errors. Running the .exe file i'm getting the error:

```<code>Traceback (most recent call last):
    File "objectGui.py", line 6, in <module>
    ModuleNotFoundError: No module named 'scipy'
    [19724] Failed to execute script objectGui
</code>```

I've tried adding following bit of code to the conversion

```<code>--hidden-import scipy
</code>```

This does not change the error I keep getting.

Any suggestions?

答:
I have found the solution in
this post.

Since I worked on my project in an environment (PyCharm) I needed to type in the command in the PyCharm terminal for it to work. I also added the hidden import:

```<code>  --hidden-import scipy
</code>```

to find the module and it worked!

Body:
I'm trying to convert a .py project to an .exe file using the using the Auto Py To Exe which uses the pyinstaller.

Running my code inside pycharm I get no errors. Running the .exe file i'm getting the error:

Traceback (most recent call last):
    File "objectGui.py", line 6, in <module>
    ModuleNotFoundError: No module named 'scipy'
    [19724] Failed to execute script objectGui

I've tried adding following bit of code to the conversion

--hidden-import scipy

This does not change the error I keep getting.

Any suggestions?

Body:
I have found the solution in
this post.

Since I worked on my project in an environment (PyCharm) I needed to type in the command in the PyCharm terminal for it to work. I also added the hidden import:

  --hidden-import scipy

to find the module and it worked!


问:
Get regex of words that starts with @ sign
All answers that I found get rough solution for example this and this ( /\b@\w+\b/gi ) is cover not only the "@abcdef" but "abc@abcdf" too, but what I need is a regex that match all words that starts with "@" sign and more than 6 characters length and non of following solutions give me what I need

```<code>/@\b[a-zA-Z0-9]{5,}\b/gi
/\b@[a-zA-Z0-9]{5,}\b/gi
</code>```

Examples that should be matched:

```<code>@abcdefjh
</code>```

Examples that shouldn't be matched:

```<code>abc@absdefgh
</code>```

Added:
PS: Is there a way to improve this question that it can be more helpful for not experienced users like me?

答:
You need \B before the @, not \b  - the \b is at the end of the word

\b Matches at a position that is followed by a word character but not preceded by a word character, or that is preceded by a word character but not followed by a word character.

\B Matches at a position that is preceded and followed by a word character, or that is not preceded and not followed by a word character.

More than 6 in total, use ,5 if 6 including the @ is ok

\B@[a-zA-Z0-9]{6,}\b

https://regex101.com/r/QcLNw6/3

Body:
All answers that I found get rough solution for example this and this ( /\b@\w+\b/gi ) is cover not only the "@abcdef" but "abc@abcdf" too, but what I need is a regex that match all words that starts with "@" sign and more than 6 characters length and non of following solutions give me what I need

/@\b[a-zA-Z0-9]{5,}\b/gi
/\b@[a-zA-Z0-9]{5,}\b/gi

Examples that should be matched:

@abcdefjh

Examples that shouldn't be matched:

abc@absdefgh

Added:
PS: Is there a way to improve this question that it can be more helpful for not experienced users like me?


问:
how to make woocommerce payment for registered users
Requirement :
I have a custom requirement where anyone can enroll for a single course.

The tool I have to use is woocommerce with a custom woocommerce payment plugin.

These are the steps that a user will go through:-

Step 1: User registers

Step 2: The user is redirected to the payment page once payment is completed.

Step 3: User gets enrolled.

Now the issue is that woocommerce by default has payment for a virtual and physical product.

Please suggest a suitable method to implement this in woocommerce.

答:
```<code>function control_payment( $args ) {
    if( !is_user_logged_in() ) {
        // unset your payment
    }
    return $args;
}
add_action( 'woocommerce_available_payment_gateways', 'control_payment' );
</code>```

Or you can use something like this

```<code>add_filter( 'woocommerce_available_payment_gateways', 'my_paypal_disable_manager' );

function my_paypal_disable_manager( $available_gateways ) {
   if ( isset( $available_gateways['paypal'] ) && current_user_can( 'manage_woocommerce' ) ) {
      unset( $available_gateways['paypal'] );
   }
   return $available_gateways;
}
</code>```

(https://businessbloomer.com/disable-payment-gateway-specific-user-role-woocommerce/)

Body:
function control_payment( $args ) {
    if( !is_user_logged_in() ) {
        // unset your payment
    }
    return $args;
}
add_action( 'woocommerce_available_payment_gateways', 'control_payment' );

Or you can use something like this

add_filter( 'woocommerce_available_payment_gateways', 'my_paypal_disable_manager' );

function my_paypal_disable_manager( $available_gateways ) {
   if ( isset( $available_gateways['paypal'] ) && current_user_can( 'manage_woocommerce' ) ) {
      unset( $available_gateways['paypal'] );
   }
   return $available_gateways;
}

(https://businessbloomer.com/disable-payment-gateway-specific-user-role-woocommerce/)


问:
how to start recording from click of a button in label in python
i want to display the output of opencv in this label.
but in this i want to start recording with the click of a start button and stop with stop button and if possible i want to lauch my webcam (previously coded) with the click of start webcam button simentenusly.

```<code>import datetime
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk, ImageGrab
import cv2
import numpy as np
import threading
import win32api
from tkinter.filedialog import asksaveasfilename

VIDEO_SIZE = (960, 540)

cap = cv2.VideoCapture(0)

date = datetime.datetime.now()
#filename='E:/project/videos/rec_%s%s%s%s%s%s.avi' % (date.year, date.month, date.day,
                                                     #date.hour, date.minute, date.second)

fourcc = cv2.VideoWriter_fourcc(*'XVID')
frame_rate = 12

out = cv2.VideoWriter()
def change_r():
        if rec_btn['text'] == 'Start Recording':
            start_recording()

            rec_btn.config(text="Stop Recoding")
        else:
            stop_recording()

            rec_btn.config(text="Start Recording")
def change_w():
        if cap_btn['text'] == 'Open webcam':
            start_webcam()

            cap_btn.config(text="Close Webcam")
        else:
            stop_webcam(event)

            cap_btn.config(text="Open webcam")
# --- screen capture
def Cursor_pos(img,center,radius,color,thickness):
    center = tuple(map(int,center))
    rgb = [255*c for c in color[:3]] # convert to 0-255 scale for OpenCV
    alpha = color[-1]
    radius = int(radius)
    if thickness > 0:
        pad = radius + 2 + thickness
    else:
        pad = radius + 3
    roi = slice(center[1]-pad,center[1]+pad),slice(center[0]-pad,center[0]+pad)

    try:
        overlay = img[roi].copy()
        cv2.circle(img,center,radius,rgb, thickness=thickness, lineType=cv2.LINE_AA)
        opacity = alpha
        cv2.addWeighted(src1=img[roi], alpha=opacity, src2=overlay, beta=1. - opacity, gamma=0, dst=img[roi])
    except:
        logger.debug("transparent_circle would have been partially outside of img. Did not draw it.")

def recording_screen():
    global recording
    recording = True
    while recording:
        img = ImageGrab.grab()
        frame = np.array(img)
        _xs,_ys = win32api.GetCursorPos()
        #curpos = root.winfo_pointerx(), root.winfo_pointery()
        Cursor_pos(frame,(_xs,_ys),20,(255,255,0,0.5), -1)
        #cv2.circle(frame, curpos, 10, (0,255,255), 2)
        frame = cv2.resize(frame, VIDEO_SIZE)
        tkimage.paste(Image.fromarray(frame))
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
        out.write(frame)

def start_recording():

    if not out.isOpened():
        filename = asksaveasfilename(initialdir = "/",title = "Save as",mode='wb',filetypes = (("Video file","*.avi"),("all files","*.*")),defaultextension=".avi")

        out.open(filename, fourcc, frame_rate, VIDEO_SIZE)
    threading.Thread(target=recording_screen, daemon=True).start()

def stop_recording():
    global recording
    recording = False
    #filename = asksaveasfilename(initialdir = "/",title = "Save as",mode='wb',filetypes = (("Video file","*.avi"),("all files","*.*")),defaultextension=".avi")

# --- webcam

webcam = None
WEBCAM_SIZE = (280, 200)

def read_frame(imgbox):
    if cap.isOpened():
        ret, frame = cap.read()
        if ret:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            frame = cv2.resize(frame, WEBCAM_SIZE)
            image = Image.fromarray(frame)
            imgbox.image.paste(image)
        webcam.after(20, read_frame, imgbox)

def stop_webcam(event):
    global webcam
    if webcam:
        webcam.destroy()
        webcam = None

def start_webcam():
    global webcam
    if webcam is None:
        webcam = tk.Toplevel()
        webcam.geometry('{}x{}+5+520'.format(WEBCAM_SIZE[0], WEBCAM_SIZE[1]))
        webcam.overrideredirect(1)
        imgbox = tk.Label(webcam)
        imgbox.pack()
        imgbox.image = ImageTk.PhotoImage(image=Image.new('RGB',WEBCAM_SIZE,(0,0,0)))
        imgbox.config(image=imgbox.image)
        webcam.bind('<F8>', stop_webcam)
        read_frame(imgbox)

# --- main

root = tk.Tk()

tkimage = ImageTk.PhotoImage(Image.new('RGB', VIDEO_SIZE, (0,0,0)))

w, h = VIDEO_SIZE
vbox = tk.Label(root, image=tkimage, width=w, height=h, bg='black')
vbox.pack()

frame = tk.Frame(root)
frame.pack()

rec_btn = ttk.Button(frame, text='Start Recording', width=20, command=change_r)
rec_btn.grid(row=0, column=0, padx=10, pady=10)

#stop_btn = ttk.Button(frame, text='stop recording', width=20, command=stop_recording, state='disabled')
#stop_btn.grid(row=0, column=1, padx=10, pady=10)

cap_btn = ttk.Button(frame, text='Open webcam', width=20, command=change_w)
cap_btn.grid(row=0, column=2, padx=10, pady=10)

root.mainloop()

out.release()
cap.release()

</code>```

i want to display my recording like this label of gui by tkinter

new and updated it is displaying two different frames one with BGR and one with RGB  (how to solve this)

updated image

答:
This is an tkinter example to capture screen to external video file:

```<code>import datetime
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk, ImageGrab
import cv2
import numpy as np
import threading

VIDEO_SIZE = (960, 540)

cap = cv2.VideoCapture(0)

date = datetime.datetime.now()
filename='E:/project/videos/rec_%s%s%s%s%s%s.avi' % (date.year, date.month, date.day,
                                                     date.hour, date.minute, date.second)

fourcc = cv2.VideoWriter_fourcc(*'XVID')
frame_rate = 12

out = cv2.VideoWriter()

# --- screen capture

def recording_screen():
    global recording
    recording = True
    while recording:
        img = ImageGrab.grab()
        frame = np.array(img)
        curpos = root.winfo_pointerx(), root.winfo_pointery()
        cv2.circle(frame, curpos, 10, (0,255,255), 2)
        frame = cv2.resize(frame, VIDEO_SIZE)
        tkimage.paste(Image.fromarray(frame))
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
        out.write(frame)

def start_recording():
    rec_btn.config(state='disabled')
    stop_btn.config(state='normal')
    if not out.isOpened():
        out.open(filename, fourcc, frame_rate, VIDEO_SIZE)
    threading.Thread(target=recording_screen, daemon=True).start()

def stop_recording():
    global recording
    recording = False
    rec_btn.config(state='normal')
    stop_btn.config(state='disabled')

# --- webcam

webcam = None
WEBCAM_SIZE = (280, 200)

def read_frame(imgbox):
    if cap.isOpened():
        ret, frame = cap.read()
        if ret:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            frame = cv2.resize(frame, WEBCAM_SIZE)
            image = Image.fromarray(frame)
            imgbox.image.paste(image)
        webcam.after(20, read_frame, imgbox)

def stop_webcam(event):
    global webcam
    if webcam:
        webcam.destroy()
        webcam = None

def start_webcam():
    global webcam
    if webcam is None:
        webcam = tk.Toplevel()
        webcam.geometry('{}x{}+5+520'.format(WEBCAM_SIZE[0], WEBCAM_SIZE[1]))
        webcam.overrideredirect(1)
        imgbox = tk.Label(webcam)
        imgbox.pack()
        imgbox.image = ImageTk.PhotoImage(image=Image.new('RGB',WEBCAM_SIZE,(0,0,0)))
        imgbox.config(image=imgbox.image)
        webcam.bind('q', stop_webcam)
        read_frame(imgbox)

# --- main

root = tk.Tk()

tkimage = ImageTk.PhotoImage(Image.new('RGB', VIDEO_SIZE, (0,0,0)))

w, h = VIDEO_SIZE
vbox = tk.Label(root, image=tkimage, width=w, height=h, bg='black')
vbox.pack()

frame = tk.Frame(root)
frame.pack()

rec_btn = ttk.Button(frame, text='start recording', width=20, command=start_recording)
rec_btn.grid(row=0, column=0, padx=10, pady=10)

stop_btn = ttk.Button(frame, text='stop recording', width=20, command=stop_recording, state='disabled')
stop_btn.grid(row=0, column=1, padx=10, pady=10)

cap_btn = ttk.Button(frame, text='start webcam', width=20, command=start_webcam)
cap_btn.grid(row=0, column=2, padx=10, pady=10)

root.mainloop()

out.release()
cap.release()
</code>```

Also I have used ImageGrab.grab() to take screen shot, and winfo_pointerx() and winfo_pointery() to get the mouse current position because I have not installed pywin32 and pyautogui modules.

Body:
i want to display the output of opencv in this label.
but in this i want to start recording with the click of a start button and stop with stop button and if possible i want to lauch my webcam (previously coded) with the click of start webcam button simentenusly.

import datetime
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk, ImageGrab
import cv2
import numpy as np
import threading
import win32api
from tkinter.filedialog import asksaveasfilename

VIDEO_SIZE = (960, 540)

cap = cv2.VideoCapture(0)

date = datetime.datetime.now()
#filename='E:/project/videos/rec_%s%s%s%s%s%s.avi' % (date.year, date.month, date.day,
                                                     #date.hour, date.minute, date.second)

fourcc = cv2.VideoWriter_fourcc(*'XVID')
frame_rate = 12

out = cv2.VideoWriter()
def change_r():
        if rec_btn['text'] == 'Start Recording':
            start_recording()

            rec_btn.config(text="Stop Recoding")
        else:
            stop_recording()

            rec_btn.config(text="Start Recording")
def change_w():
        if cap_btn['text'] == 'Open webcam':
            start_webcam()

            cap_btn.config(text="Close Webcam")
        else:
            stop_webcam(event)

            cap_btn.config(text="Open webcam")
# --- screen capture
def Cursor_pos(img,center,radius,color,thickness):
    center = tuple(map(int,center))
    rgb = [255*c for c in color[:3]] # convert to 0-255 scale for OpenCV
    alpha = color[-1]
    radius = int(radius)
    if thickness > 0:
        pad = radius + 2 + thickness
    else:
        pad = radius + 3
    roi = slice(center[1]-pad,center[1]+pad),slice(center[0]-pad,center[0]+pad)

    try:
        overlay = img[roi].copy()
        cv2.circle(img,center,radius,rgb, thickness=thickness, lineType=cv2.LINE_AA)
        opacity = alpha
        cv2.addWeighted(src1=img[roi], alpha=opacity, src2=overlay, beta=1. - opacity, gamma=0, dst=img[roi])
    except:
        logger.debug("transparent_circle would have been partially outside of img. Did not draw it.")

def recording_screen():
    global recording
    recording = True
    while recording:
        img = ImageGrab.grab()
        frame = np.array(img)
        _xs,_ys = win32api.GetCursorPos()
        #curpos = root.winfo_pointerx(), root.winfo_pointery()
        Cursor_pos(frame,(_xs,_ys),20,(255,255,0,0.5), -1)
        #cv2.circle(frame, curpos, 10, (0,255,255), 2)
        frame = cv2.resize(frame, VIDEO_SIZE)
        tkimage.paste(Image.fromarray(frame))
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
        out.write(frame)

def start_recording():

    if not out.isOpened():
        filename = asksaveasfilename(initialdir = "/",title = "Save as",mode='wb',filetypes = (("Video file","*.avi"),("all files","*.*")),defaultextension=".avi")

        out.open(filename, fourcc, frame_rate, VIDEO_SIZE)
    threading.Thread(target=recording_screen, daemon=True).start()

def stop_recording():
    global recording
    recording = False
    #filename = asksaveasfilename(initialdir = "/",title = "Save as",mode='wb',filetypes = (("Video file","*.avi"),("all files","*.*")),defaultextension=".avi")

# --- webcam

webcam = None
WEBCAM_SIZE = (280, 200)

def read_frame(imgbox):
    if cap.isOpened():
        ret, frame = cap.read()
        if ret:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            frame = cv2.resize(frame, WEBCAM_SIZE)
            image = Image.fromarray(frame)
            imgbox.image.paste(image)
        webcam.after(20, read_frame, imgbox)

def stop_webcam(event):
    global webcam
    if webcam:
        webcam.destroy()
        webcam = None

def start_webcam():
    global webcam
    if webcam is None:
        webcam = tk.Toplevel()
        webcam.geometry('{}x{}+5+520'.format(WEBCAM_SIZE[0], WEBCAM_SIZE[1]))
        webcam.overrideredirect(1)
        imgbox = tk.Label(webcam)
        imgbox.pack()
        imgbox.image = ImageTk.PhotoImage(image=Image.new('RGB',WEBCAM_SIZE,(0,0,0)))
        imgbox.config(image=imgbox.image)
        webcam.bind('<F8>', stop_webcam)
        read_frame(imgbox)

# --- main

root = tk.Tk()

tkimage = ImageTk.PhotoImage(Image.new('RGB', VIDEO_SIZE, (0,0,0)))

w, h = VIDEO_SIZE
vbox = tk.Label(root, image=tkimage, width=w, height=h, bg='black')
vbox.pack()

frame = tk.Frame(root)
frame.pack()

rec_btn = ttk.Button(frame, text='Start Recording', width=20, command=change_r)
rec_btn.grid(row=0, column=0, padx=10, pady=10)

#stop_btn = ttk.Button(frame, text='stop recording', width=20, command=stop_recording, state='disabled')
#stop_btn.grid(row=0, column=1, padx=10, pady=10)

cap_btn = ttk.Button(frame, text='Open webcam', width=20, command=change_w)
cap_btn.grid(row=0, column=2, padx=10, pady=10)

root.mainloop()

out.release()
cap.release()

i want to display my recording like this label of gui by tkinter

new and updated it is displaying two different frames one with BGR and one with RGB  (how to solve this)

updated image

Body:
This is an tkinter example to capture screen to external video file:

import datetime
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk, ImageGrab
import cv2
import numpy as np
import threading

VIDEO_SIZE = (960, 540)

cap = cv2.VideoCapture(0)

date = datetime.datetime.now()
filename='E:/project/videos/rec_%s%s%s%s%s%s.avi' % (date.year, date.month, date.day,
                                                     date.hour, date.minute, date.second)

fourcc = cv2.VideoWriter_fourcc(*'XVID')
frame_rate = 12

out = cv2.VideoWriter()

# --- screen capture

def recording_screen():
    global recording
    recording = True
    while recording:
        img = ImageGrab.grab()
        frame = np.array(img)
        curpos = root.winfo_pointerx(), root.winfo_pointery()
        cv2.circle(frame, curpos, 10, (0,255,255), 2)
        frame = cv2.resize(frame, VIDEO_SIZE)
        tkimage.paste(Image.fromarray(frame))
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
        out.write(frame)

def start_recording():
    rec_btn.config(state='disabled')
    stop_btn.config(state='normal')
    if not out.isOpened():
        out.open(filename, fourcc, frame_rate, VIDEO_SIZE)
    threading.Thread(target=recording_screen, daemon=True).start()

def stop_recording():
    global recording
    recording = False
    rec_btn.config(state='normal')
    stop_btn.config(state='disabled')

# --- webcam

webcam = None
WEBCAM_SIZE = (280, 200)

def read_frame(imgbox):
    if cap.isOpened():
        ret, frame = cap.read()
        if ret:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            frame = cv2.resize(frame, WEBCAM_SIZE)
            image = Image.fromarray(frame)
            imgbox.image.paste(image)
        webcam.after(20, read_frame, imgbox)

def stop_webcam(event):
    global webcam
    if webcam:
        webcam.destroy()
        webcam = None

def start_webcam():
    global webcam
    if webcam is None:
        webcam = tk.Toplevel()
        webcam.geometry('{}x{}+5+520'.format(WEBCAM_SIZE[0], WEBCAM_SIZE[1]))
        webcam.overrideredirect(1)
        imgbox = tk.Label(webcam)
        imgbox.pack()
        imgbox.image = ImageTk.PhotoImage(image=Image.new('RGB',WEBCAM_SIZE,(0,0,0)))
        imgbox.config(image=imgbox.image)
        webcam.bind('q', stop_webcam)
        read_frame(imgbox)

# --- main

root = tk.Tk()

tkimage = ImageTk.PhotoImage(Image.new('RGB', VIDEO_SIZE, (0,0,0)))

w, h = VIDEO_SIZE
vbox = tk.Label(root, image=tkimage, width=w, height=h, bg='black')
vbox.pack()

frame = tk.Frame(root)
frame.pack()

rec_btn = ttk.Button(frame, text='start recording', width=20, command=start_recording)
rec_btn.grid(row=0, column=0, padx=10, pady=10)

stop_btn = ttk.Button(frame, text='stop recording', width=20, command=stop_recording, state='disabled')
stop_btn.grid(row=0, column=1, padx=10, pady=10)

cap_btn = ttk.Button(frame, text='start webcam', width=20, command=start_webcam)
cap_btn.grid(row=0, column=2, padx=10, pady=10)

root.mainloop()

out.release()
cap.release()

Also I have used ImageGrab.grab() to take screen shot, and winfo_pointerx() and winfo_pointery() to get the mouse current position because I have not installed pywin32 and pyautogui modules.


问:
how to reduce the size of a base64 image getting from react-native-image-picker to save it in firebase using react native
I trying to save an image base64 string getting from react-native-image-picker to firebase. it is working fine for some images but for images, it getting an issue like giving below.

```<code>```error: Reference.push failed: first argument contains a string greater than 10485760 utf8 bytes in property```
</code>```

by getting an issue I am trying to reduce the base64 string size. but it is not working.

    selectImage = () => {
        ImagePicker.showImagePicker(options, (response) => {
            if (response.didCancel) {
            } else if (response.error) {
            } else if (response.customButton) {
            } else {
                this.setState({ avatarSource:response.data }, () => {
                  //this.base64toBlob(response.data,"base64")
                  db.ref('/Images/Details').push({
                    avatarSource: this.state.avatarSource,
                    name: this.state.name,
                    tag: this.state.selectItem
                });
                Alert.alert('you are successfully Register');

                });
            }
        });
    }```

答:
to get the base64 data with the image uri;</p>

```<code>import {
  Image,
  ImageStore,
  ImageEditor,
} from 'react-native';

Image.getSize(image, (width, height) => {
  let imageSettings = {
    offset: { x: 0, y: 0 },
    size: { width: width, height: height }
  };
  ImageEditor.cropImage(image, imageSettings, (uri) => {
    ImageStore.getBase64ForTag(uri, (data) => {
      // data == base64 encoded image
    }, e => console.warn("getBase64ForTag: ", e))
  }, e => console.warn("cropImage: ", e))
})
</code>```

Body:
I trying to save an image base64 string getting from react-native-image-picker to firebase. it is working fine for some images but for images, it getting an issue like giving below.

```error: Reference.push failed: first argument contains a string greater than 10485760 utf8 bytes in property```

by getting an issue I am trying to reduce the base64 string size. but it is not working.

    selectImage = () => {
        ImagePicker.showImagePicker(options, (response) => {
            if (response.didCancel) {
            } else if (response.error) {
            } else if (response.customButton) {
            } else {
                this.setState({ avatarSource:response.data }, () => {
                  //this.base64toBlob(response.data,"base64")
                  db.ref('/Images/Details').push({
                    avatarSource: this.state.avatarSource,
                    name: this.state.name,
                    tag: this.state.selectItem
                });
                Alert.alert('you are successfully Register');

                });
            }
        });
    }

Body:
to get the base64 data with the image uri;

import {
  Image,
  ImageStore,
  ImageEditor,
} from 'react-native';

Image.getSize(image, (width, height) => {
  let imageSettings = {
    offset: { x: 0, y: 0 },
    size: { width: width, height: height }
  };
  ImageEditor.cropImage(image, imageSettings, (uri) => {
    ImageStore.getBase64ForTag(uri, (data) => {
      // data == base64 encoded image
    }, e => console.warn("getBase64ForTag: ", e))
  }, e => console.warn("cropImage: ", e))
})


问:
Error while restoring MYSQL db
Following error occurs when I am trying to restore a DB in MYSQL via putty.

Command:  mysql -u root -p db1<dbname.sql ;

ERROR 1 (HY000) at line 7904: Can't create/write to file
  './dbname/db.opt'     (Errcode: 2)

What is the reason?

答:
I had backup from "db1" and restoring to "db2"
so in the dump file had to change "db1" to "db2" with sed.

And all worked fine.

ContentLicense: CC BY-SA 3.0

Title: Error while restoring MYSQL db


问:
ListView with OnItemClickListener
I am using a custom ListView with RatingBar and ImageButton. Here is my problem: When I click on my ListView, my OnItemClickListener is not working. Please can any one help me.
Code:

```<code>ListView lv = getListView();
setContentView(lv);
lv.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        Toast.makeText(SuggestionActivity.this, "" + position, Toast.LENGTH_SHORT).show();
    }
});
</code>```

答:
The most simple solution and the easiest way I can provide is this. You just need to do these two steps.

1.add this in your XML file.

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:id="@+id/list_view"
        android:layout_below="@+id/info_text"
        />```
</div>
</div>
</p>

<ol start="2">
<li>Add this in your MainActivity file.</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>        ListView listView;
        listView = findViewById(R.id.list_view);

        String[] fruits = new String[5];
        fruits[0]="hello";
        fruits[1]="hello";
        fruits[2]="hello";
        fruits[3]="hello";
        fruits[4]="hello";

        List newList = new ArrayList(Arrays.asList(fruits));
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, newList);
        listView.setAdapter(arrayAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                String selectedItem = (String) parent.getItemAtPosition(position);
                Toast.makeText(DisplayPannel.this, selectedItem, Toast.LENGTH_SHORT).show();            }
        });</code>```

Title: ListView with OnItemClickListener

Body:
I am using a custom ListView with RatingBar and ImageButton. Here is my problem: When I click on my ListView, my OnItemClickListener is not working. Please can any one help me.
Code:

ListView lv = getListView();
setContentView(lv);
lv.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        Toast.makeText(SuggestionActivity.this, "" + position, Toast.LENGTH_SHORT).show();
    }
});

Body:
The most simple solution and the easiest way I can provide is this. You just need to do these two steps.

1.add this in your XML file.

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:id="@+id/list_view"
        android:layout_below="@+id/info_text"
        />

Add this in your MainActivity file.

        ListView listView;
        listView = findViewById(R.id.list_view);

        String[] fruits = new String[5];
        fruits[0]="hello";
        fruits[1]="hello";
        fruits[2]="hello";
        fruits[3]="hello";
        fruits[4]="hello";

        List newList = new ArrayList(Arrays.asList(fruits));
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, newList);
        listView.setAdapter(arrayAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                String selectedItem = (String) parent.getItemAtPosition(position);
                Toast.makeText(DisplayPannel.this, selectedItem, Toast.LENGTH_SHORT).show();            }
        });


问:
How to add a master node to the kubernetes cluster
I set up a kubernetes cluster. And I want to add a master node to the cluster. my cluser version is 1.17.0 . what's the join command is? i can't find  Related docs about the command on the official website.</p>

答:
To join another master follow the below steps:

Generate the certificate key

kubeadm alpha certs certificate-key

Print the join command

kubeadm token create --print-join-command

Add the following flags to the above join command

--control-plane --certificate-key "Certificate-key from step 1"

Command should look like below

sudo kubeadm join 192.168.0.200:6443 --token 9vr73a.a8uxyaju799qwdjv --discovery-token-ca-cert-hash sha256:7c2e69131a36ae2a042a339b33381c6d0d43887e2de83720eff5359e26aec866 --control-plane --certificate-key f8902e114ef118304e561c3ecd4d0b543adc226b7a07f675f56564185ffe0c07


问:
Finding if the current time is 72 hours more than the time that I get in a variable
I have a variable i with it's value as 2020-02-04 10:15:35

I want to check if the current datetime is at least 72 hours more than this given time stored in variable i

I tried with:

```<code>        now = datetime.datetime.now()
        if i > now - datetime.timedelta(hours=72):

            print(f"72 hours have passed")
</code>```

Code seems to be skipping the if condition But is shouldn't in this case.

Trying it for the first time. How to tackle this? Where am I messing up?

答:
You are doing it the wrong way around. If i stores a datetime object, check

```<code>if i <= now - datetime.timedelta(hours=72):
    print("72 hours have passed")
</code>```

You want to check if i is earlier or equal (less than or equal) to the difference, not later.

Body:
I have a variable i with it's value as 2020-02-04 10:15:35

I want to check if the current datetime is at least 72 hours more than this given time stored in variable i

I tried with:

        now = datetime.datetime.now()
        if i > now - datetime.timedelta(hours=72):

            print(f"72 hours have passed")

Code seems to be skipping the if condition But is shouldn't in this case.

Trying it for the first time. How to tackle this? Where am I messing up?

Body:
You are doing it the wrong way around. If i stores a datetime object, check

if i <= now - datetime.timedelta(hours=72):
    print("72 hours have passed")

You want to check if i is earlier or equal (less than or equal) to the difference, not later.


问:
How to access Npgsql counters inside of NetCore application
I stumbled upon issue in Npgsql repo, that it is possible to collect counters data : https://github.com/npgsql/npgsql/issues/1725

is there any samples or info on how to get access to those counters?

By referrring to the following article https://github.com/dotnet/diagnostics/blob/master/documentation/design-docs/eventcounters.md, I've tried following with no luck and no data on event counters( like idle-connections etc)
only CommandStart CommandEnd

 class Program
    {
        static void Main(string[] args)
        {
            var listener = new TestEventListener();

            while (true)
            {
                using var cn = new Npgsql.NpgsqlConnection("...");  cn.Open();
                var cmd = new NpgsqlCommand("select 1", cn); cmd.ExecuteNonQuery();
            }
        }
    }

    class TestEventListener : EventListener
    {
        private readonly EventLevel level = EventLevel.Verbose;

        protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
            Console.WriteLine($"{eventData.EventName}");

            if (eventData.EventName.Equals("EventCounters", StringComparison.OrdinalIgnoreCase))
            {
                for (var i = 0; i < eventData.Payload.Count; i++)
                {
                    if (eventData.Payload[i] is IDictionary<string, object> payload)
                    {
                        Console.WriteLine(payload);
                    }

                }
            }
        }

        protected override void OnEventSourceCreated(EventSource eventSource)
        {
            if (eventSource.Name.Equals("Npgsql"))
            {
                var refreshInterval = new Dictionary<string, string>()
                {
                    { "connection-pools", "1" },
                    { "idle-connections", "1" },
                    { "busy-connections", "1" }
                };

                EnableEvents(eventSource, level, EventKeywords.None, refreshInterval);
            }

            base.OnEventSourceCreated(eventSource);
        }
    }
```

I see that those counters do work by running dotnet counters monitor Npgsql -p <pid> but how to do it inside code?

答:
Answer is to follow documentm and provide actual argument specified in document:

Dictionary<string, string> refreshInterval = new Dictionary<string, string>()
        {
            { "EventCounterIntervalSec", "1" }
        };
```

Body:
I stumbled upon issue in Npgsql repo, that it is possible to collect counters data : https://github.com/npgsql/npgsql/issues/1725

is there any samples or info on how to get access to those counters?

By referrring to the following article https://github.com/dotnet/diagnostics/blob/master/documentation/design-docs/eventcounters.md, I've tried following with no luck and no data on event counters( like idle-connections etc)
only CommandStart CommandEnd

 class Program
    {
        static void Main(string[] args)
        {
            var listener = new TestEventListener();

            while (true)
            {
                using var cn = new Npgsql.NpgsqlConnection("...");  cn.Open();
                var cmd = new NpgsqlCommand("select 1", cn); cmd.ExecuteNonQuery();
            }
        }
    }

    class TestEventListener : EventListener
    {
        private readonly EventLevel level = EventLevel.Verbose;

        protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
            Console.WriteLine($"{eventData.EventName}");

            if (eventData.EventName.Equals("EventCounters", StringComparison.OrdinalIgnoreCase))
            {
                for (var i = 0; i < eventData.Payload.Count; i++)
                {
                    if (eventData.Payload[i] is IDictionary<string, object> payload)
                    {
                        Console.WriteLine(payload);
                    }

                }
            }
        }

        protected override void OnEventSourceCreated(EventSource eventSource)
        {
            if (eventSource.Name.Equals("Npgsql"))
            {
                var refreshInterval = new Dictionary<string, string>()
                {
                    { "connection-pools", "1" },
                    { "idle-connections", "1" },
                    { "busy-connections", "1" }
                };

                EnableEvents(eventSource, level, EventKeywords.None, refreshInterval);
            }

            base.OnEventSourceCreated(eventSource);
        }
    }

I see that those counters do work by running dotnet counters monitor Npgsql -p <pid> but how to do it inside code?


问:
Am I allowed to translate the reCAPTCHA v3 text containing the links to Privacy Policy and Terms of Service?
According to the docs if I want to hide the reCAPTCHA v3 badge I have to display some text containing links to Privacy Policy and Terms of Service:

"This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply."

Am I allowed to translate this text?

答:
I guess it can be translated if you keep the links in the text.

I have been using reCAPTCHA v3 for 7 months with translated text on a website with an average of 150 daily validation requests.

It would be nice if Google mentioned this in the docs.