问:
build/install/<project>-shadow directory -- what is it?
What is build/install/gradleHelloWorld-shadow?  What should or shouldn't be in that directory?

simplest possible "hello world" fails to build:

```<code>thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ gradle clean runShadow

> Task :shadowJar
A problem was found with the configuration of task ':shadowJar'. Registering invalid inputs and outputs via TaskInputs and TaskOutputs methods has been deprecated and is scheduled to be removed in Gradle 5.0.
 - No value has been specified for property 'mainClassName'.
The SimpleWorkResult type has been deprecated and is scheduled to be removed in Gradle 5.0. Please use WorkResults.didWork() instead.

> Task :startShadowScripts
Using TaskInputs.file() with something that doesn't resolve to a File object has been deprecated and is scheduled to be removed in Gradle 5.0. Use TaskInputs.files() instead.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':installShadowDist'.
> The specified installation directory '/home/thufir/NetBeansProjects/gradleHelloWorld/build/install/gradleHelloWorld-shadow' is neither empty nor does it contain an installation for 'gradleHelloWorld'.
  If you really want to install to this directory, delete it and run the install task again.
  Alternatively, choose a different installation directory.

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

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

BUILD FAILED in 1s
5 actionable tasks: 5 executed

Publishing build scan...
https://gradle.com/s/t7jbmhjz23giw

thufir@dur:~/NetBeansProjects/gradleHelloWorld$
</code>```

build file:

```<code>plugins {
    id 'com.gradle.build-scan' version '1.8'
    id 'java'
    id 'application'
    id 'com.github.johnrengelman.shadow' version '2.0.1'
}

buildScan {
    licenseAgreementUrl = 'https://gradle.com/terms-of-service'
    licenseAgree = 'yes'
    publishAlways()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

mainClassName = 'net.bounceme.dur.gradle.hello.App'

shadowJar {
    baseName = 'greeter'
    classifier = null
    version = null
}

repositories {
    jcenter()
}

configurations {
    provided
}

dependencies {
}
</code>```

project after aborted runShadow:

```<code>thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ tree
.
├── build
│   ├── classes
│   │   └── java
│   │       └── main
│   │           └── net
│   │               └── bounceme
│   │                   └── dur
│   │                       └── gradle
│   │                           └── hello
│   │                               └── App.class
│   ├── install
│   │   └── gradleHelloWorld-shadow
│   ├── libs
│   │   └── greeter.jar
│   ├── scriptsShadow
│   │   ├── gradleHelloWorld
│   │   └── gradleHelloWorld.bat
│   └── tmp
│       ├── compileJava
│       └── shadowJar
│           └── MANIFEST.MF
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   └── java
    │       ├── dur
    │       └── net
    │           └── bounceme
    │               └── dur
    │                   └── gradle
    │                       └── hello
    │                           └── App.java
    └── test
        └── java

29 directories, 12 files
thufir@dur:~/NetBeansProjects/gradleHelloWorld$
</code>```

the /home/thufir/NetBeansProjects/gradleHelloWorld/build/install/gradleHelloWorld-shadow directory at issue is removed by clean, establishing that gradle is building this directory.

Just upgraded gradle:

```<code>thufir@dur:~$
thufir@dur:~$ sdk ls gradle
==== INTERNET NOT REACHABLE! ===================================================

 Some functionality is disabled or only partially available.
 If this persists, please enable the offline mode:

   $ sdk offline

================================================================================

--------------------------------------------------------------------------------
Offline: only showing installed gradle versions
--------------------------------------------------------------------------------
 > 4.3.1
 * 4.2.1
--------------------------------------------------------------------------------
* - installed
> - currently in use
--------------------------------------------------------------------------------
thufir@dur:~$
</code>```

(The wi-fi can be a bit flaky.)

答:
work-around:

```<code>thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ gradle clean assembleShadowDist

> Task :shadowJar
A problem was found with the configuration of task ':shadowJar'. Registering invalid inputs and outputs via TaskInputs and TaskOutputs methods has been deprecated and is scheduled to be removed in Gradle 5.0.
 - No value has been specified for property 'mainClassName'.
The SimpleWorkResult type has been deprecated and is scheduled to be removed in Gradle 5.0. Please use WorkResults.didWork() instead.

> Task :startShadowScripts
Using TaskInputs.file() with something that doesn't resolve to a File object has been deprecated and is scheduled to be removed in Gradle 5.0. Use TaskInputs.files() instead.

BUILD SUCCESSFUL in 0s
6 actionable tasks: 6 executed
thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ cd build/libs/
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$ ll
total 20
drwxr-xr-x 2 thufir thufir 4096 Nov 13 02:53 ./
drwxr-xr-x 7 thufir thufir 4096 Nov 13 02:53 ../
-rw-r--r-- 1 thufir thufir 1492 Nov 13 02:53 greeter.jar
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$ jar xf greeter.jar
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$ ll
total 28
drwxr-xr-x 4 thufir thufir 4096 Nov 13 02:53 ./
drwxr-xr-x 7 thufir thufir 4096 Nov 13 02:53 ../
-rw-r--r-- 1 thufir thufir 1492 Nov 13 02:53 greeter.jar
drwxr-xr-x 2 thufir thufir 4096 Nov 13 02:53 META-INF/
drwxr-xr-x 3 thufir thufir 4096 Nov 13 02:53 net/
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$ cat META-INF/MANIFEST.MF
Manifest-Version: 1.0
Main-Class: net.bounceme.dur.gradle.hello.App

thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$ java -jar greeter.jar
Nov 13, 2017 2:53:38 AM net.bounceme.dur.gradle.hello.App run
INFO: helloooo
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$
</code>```

why does this work?

why doesn't runShadow work?

Body:
What is build/install/gradleHelloWorld-shadow?  What should or shouldn't be in that directory?

simplest possible "hello world" fails to build:

thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ gradle clean runShadow

> Task :shadowJar
A problem was found with the configuration of task ':shadowJar'. Registering invalid inputs and outputs via TaskInputs and TaskOutputs methods has been deprecated and is scheduled to be removed in Gradle 5.0.
 - No value has been specified for property 'mainClassName'.
The SimpleWorkResult type has been deprecated and is scheduled to be removed in Gradle 5.0. Please use WorkResults.didWork() instead.

> Task :startShadowScripts
Using TaskInputs.file() with something that doesn't resolve to a File object has been deprecated and is scheduled to be removed in Gradle 5.0. Use TaskInputs.files() instead.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':installShadowDist'.
> The specified installation directory '/home/thufir/NetBeansProjects/gradleHelloWorld/build/install/gradleHelloWorld-shadow' is neither empty nor does it contain an installation for 'gradleHelloWorld'.
  If you really want to install to this directory, delete it and run the install task again.
  Alternatively, choose a different installation directory.

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

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

BUILD FAILED in 1s
5 actionable tasks: 5 executed

Publishing build scan...
https://gradle.com/s/t7jbmhjz23giw

thufir@dur:~/NetBeansProjects/gradleHelloWorld$

build file:

plugins {
    id 'com.gradle.build-scan' version '1.8'
    id 'java'
    id 'application'
    id 'com.github.johnrengelman.shadow' version '2.0.1'
}

buildScan {
    licenseAgreementUrl = 'https://gradle.com/terms-of-service'
    licenseAgree = 'yes'
    publishAlways()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

mainClassName = 'net.bounceme.dur.gradle.hello.App'

shadowJar {
    baseName = 'greeter'
    classifier = null
    version = null
}

repositories {
    jcenter()
}

configurations {
    provided
}

dependencies {
}

project after aborted runShadow:

thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ tree
.
├── build
│   ├── classes
│   │   └── java
│   │       └── main
│   │           └── net
│   │               └── bounceme
│   │                   └── dur
│   │                       └── gradle
│   │                           └── hello
│   │                               └── App.class
│   ├── install
│   │   └── gradleHelloWorld-shadow
│   ├── libs
│   │   └── greeter.jar
│   ├── scriptsShadow
│   │   ├── gradleHelloWorld
│   │   └── gradleHelloWorld.bat
│   └── tmp
│       ├── compileJava
│       └── shadowJar
│           └── MANIFEST.MF
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   └── java
    │       ├── dur
    │       └── net
    │           └── bounceme
    │               └── dur
    │                   └── gradle
    │                       └── hello
    │                           └── App.java
    └── test
        └── java

29 directories, 12 files
thufir@dur:~/NetBeansProjects/gradleHelloWorld$

the /home/thufir/NetBeansProjects/gradleHelloWorld/build/install/gradleHelloWorld-shadow directory at issue is removed by clean, establishing that gradle is building this directory.

Just upgraded gradle:

thufir@dur:~$
thufir@dur:~$ sdk ls gradle
==== INTERNET NOT REACHABLE! ===================================================

 Some functionality is disabled or only partially available.
 If this persists, please enable the offline mode:

   $ sdk offline

================================================================================

--------------------------------------------------------------------------------
Offline: only showing installed gradle versions
--------------------------------------------------------------------------------
 > 4.3.1
 * 4.2.1
--------------------------------------------------------------------------------
* - installed
> - currently in use
--------------------------------------------------------------------------------
thufir@dur:~$

(The wi-fi can be a bit flaky.)

Body:
work-around:

thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ gradle clean assembleShadowDist

> Task :shadowJar
A problem was found with the configuration of task ':shadowJar'. Registering invalid inputs and outputs via TaskInputs and TaskOutputs methods has been deprecated and is scheduled to be removed in Gradle 5.0.
 - No value has been specified for property 'mainClassName'.
The SimpleWorkResult type has been deprecated and is scheduled to be removed in Gradle 5.0. Please use WorkResults.didWork() instead.

> Task :startShadowScripts
Using TaskInputs.file() with something that doesn't resolve to a File object has been deprecated and is scheduled to be removed in Gradle 5.0. Use TaskInputs.files() instead.

BUILD SUCCESSFUL in 0s
6 actionable tasks: 6 executed
thufir@dur:~/NetBeansProjects/gradleHelloWorld$
thufir@dur:~/NetBeansProjects/gradleHelloWorld$ cd build/libs/
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$ ll
total 20
drwxr-xr-x 2 thufir thufir 4096 Nov 13 02:53 ./
drwxr-xr-x 7 thufir thufir 4096 Nov 13 02:53 ../
-rw-r--r-- 1 thufir thufir 1492 Nov 13 02:53 greeter.jar
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$ jar xf greeter.jar
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$ ll
total 28
drwxr-xr-x 4 thufir thufir 4096 Nov 13 02:53 ./
drwxr-xr-x 7 thufir thufir 4096 Nov 13 02:53 ../
-rw-r--r-- 1 thufir thufir 1492 Nov 13 02:53 greeter.jar
drwxr-xr-x 2 thufir thufir 4096 Nov 13 02:53 META-INF/
drwxr-xr-x 3 thufir thufir 4096 Nov 13 02:53 net/
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$ cat META-INF/MANIFEST.MF
Manifest-Version: 1.0
Main-Class: net.bounceme.dur.gradle.hello.App

thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$ java -jar greeter.jar
Nov 13, 2017 2:53:38 AM net.bounceme.dur.gradle.hello.App run
INFO: helloooo
thufir@dur:~/NetBeansProjects/gradleHelloWorld/build/libs$

why does this work?

why doesn't runShadow work?


来源: stackexchange

问:
How to disable HTTPS or change to HTTP in dev and prod version on symfony?
My problem is like in the title.

 In my project i tried to add HTTPS to /login and /admin routes. Both routes are imported from third party bundles: login from FOSUserBundle and admin from EasyAdminBundle. To achieve that I added requires_channel: https to the security.yml file, like it was described in this thread https://symfony.com/doc/current/security/force_https.html.

 My access_control section looked like:

```<code>access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: ROLE_ADMIN, requires_channel: https }
</code>```

 I started the site through built-in server to check if it will force https connection and it was. Obviously there was an error because symfony built-in server doesn't support ssl connections but in the address bar there was https://. I uploaded this version to the server and I wanted to continue working on the next functionality, so I deleted the requires_channel entry but when I launch the page by typing php bin/console server:start 0.0.0.0:80 and typing in the browser address bar localhost/admin symphony still forces https. My next guess was to change requires_channel: https to requires_channel: http but that did not work either.

 The same happens on the production server, ie HTTPS is still enforced when requires_channel is removed or set to HTTP, but there i can live with that because in the end i will have to generate certificate and launch ssl connection in apache config files, but I can't work on dev version.

 I looked for similar issues but mostly if threads was about symfony and HTTP or HTTPS, people asks how to force HTTPS but this I already did. I can't find similar problem to mine so please if someone have any idea what goes wrong feel free to response or if anyone already solved my problem or very similar one please paste links.

Full content of security.yml file:

```<code>security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username_email

    firewalls:
        main:
            pattern: ^/
            form_login:
                provider: fos_userbundle
            logout:       true
            anonymous:    true

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: "%router.request_context.scheme%" }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN, requires_channel: "%router.request_context.scheme%" }
</code>```

答:
Extending Alister Bulman's Answer.

Rather use the 'router.request_context.scheme' param so that your whole symfony application has the correct scheme.

End result would be:

```<code>access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: "%router.request_context.scheme%" }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: ROLE_ADMIN, requires_channel: "%router.request_context.scheme%" }
</code>```

Also add the schemes to your routes:

```<code>main:
    type: annotation
    schemes: "%router.request_context.scheme%"
    resource: '../src/Application/Controller/'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My problem is like in the title.

 In my project i tried to add HTTPS to /login and /admin routes. Both routes are imported from third party bundles: login from FOSUserBundle and admin from EasyAdminBundle. To achieve that I added requires_channel: https to the security.yml file, like it was described in this thread https://symfony.com/doc/current/security/force_https.html.

 My access_control section looked like:

access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: ROLE_ADMIN, requires_channel: https }

 I started the site through built-in server to check if it will force https connection and it was. Obviously there was an error because symfony built-in server doesn't support ssl connections but in the address bar there was https://. I uploaded this version to the server and I wanted to continue working on the next functionality, so I deleted the requires_channel entry but when I launch the page by typing php bin/console server:start 0.0.0.0:80 and typing in the browser address bar localhost/admin symphony still forces https. My next guess was to change requires_channel: https to requires_channel: http but that did not work either.

 The same happens on the production server, ie HTTPS is still enforced when requires_channel is removed or set to HTTP, but there i can live with that because in the end i will have to generate certificate and launch ssl connection in apache config files, but I can't work on dev version.

 I looked for similar issues but mostly if threads was about symfony and HTTP or HTTPS, people asks how to force HTTPS but this I already did. I can't find similar problem to mine so please if someone have any idea what goes wrong feel free to response or if anyone already solved my problem or very similar one please paste links.

Full content of security.yml file:

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username_email

    firewalls:
        main:
            pattern: ^/
            form_login:
                provider: fos_userbundle
            logout:       true
            anonymous:    true

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: "%router.request_context.scheme%" }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN, requires_channel: "%router.request_context.scheme%" }

Body:
Extending Alister Bulman's Answer.

Rather use the 'router.request_context.scheme' param so that your whole symfony application has the correct scheme.

End result would be:

access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: "%router.request_context.scheme%" }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: ROLE_ADMIN, requires_channel: "%router.request_context.scheme%" }

Also add the schemes to your routes:

main:
    type: annotation
    schemes: "%router.request_context.scheme%"
    resource: '../src/Application/Controller/'


问:
Socket Exceptions observed during Load Testing
We are conducting load test using VSTS 2010 for a particular application and we are observing a lot of socket exceptions with the error:

Exception SocketException A connection attempt failed because the
  connected party did not properly respond after a period of time, or
  established connection failed because connected host has failed to
  respond ..*.:443.

With the stack trace:

at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)  at
  System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,
  Socket s4, Socket s6, Socket& socket, IPAddress& address,
  ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout,
  Exception& exception)

We have 2 agent machines through which we are conducting the load test. We are unable to figure out if its problem with the agent machines or network issue.

答: This is an IP-Address issue,It's not maintaining your IP-Address constantly.So,I think its better to go with Application Insights help for solving this issue.</p>


问:
Removing subdocument from specific Document keeps failing, Mongoose, MongoDB
I'm trying to remove a subdocument from a specific document in my app, however I'm not recieving the expected results. The data is stored in the following format:

```<code>    {"_id": "59fc7eccf0579ad8882b54bb",
    "__v": 0,
    "name": "manchester",
    "products": [
      {
        "_id": "59fc7eccf0579ad8882b54bf",
        "__v": 0,
        "urn": "test01",
        "category": "cat1",
      },
      {
        "_id": "59fc7eccf0579ad8882b54c0",
        "__v": 0,
        "urn": "test02",
        "category": "cat1",
      },
      {
        "_id": "59fc7eccf0579ad8882b54c1",
        "__v": 0,
        "urn": "test03",
        "category": "cat2",
      },
      {
        "_id": "59fc7eccf0579ad8882b54c2",
        "__v": 0,
        "urn": "test04",
        "category": "cat2",
      }
    ]
  },
  {
    "_id": "59fc7eccf0579ad8882b54bc",
    "__v": 0,
    "name": "leeds",
    "products": [
      {
        "_id": "59fc7eccf0579ad8882b54bf",
        "__v": 0,
        "urn": "test01",
        "category": "cat1",
      },
      {
        "_id": "59fc7eccf0579ad8882b54c0",
        "__v": 0,
        "urn": "test02",
        "category": "cat1",
      },
      {
        "_id": "59fc7eccf0579ad8882b54c1",
        "__v": 0,
        "urn": "test03",
        "category": "cat2",
      },
      {
        "_id": "59fc7eccf0579ad8882b54c2",
        "__v": 0,
        "urn": "test04",
        "category": "cat2",
      }
    ]
  }
</code>```

With there being multiple regions, and the same products stored within each. I want to be able to remove a product from each region, but keep it in the rest of the regions.

I've tried the following:

```<code>    const item = await Region.find({ "_id": req.params.reg }).populate('products', null, {
    _id: { $in: req.params.id }}).exec();
    await item[0].products[0].remove()
    await item[0].products[0].save();
    res.json(item);
</code>```

However this removes the product from all of the regions. I also attempted to use $pull on Update(), in the following format but I cannot get this to work.

```<code>    await Region.update({ "_id": req.params.reg }, { "$pull": { "products": {"_id": req.params.id  } } });
    res.redirect("/regions");
</code>```

Here, the redirect works correctly and there are no errors. If I console.log the output from this I receive the following:

```<code>{ n: 1, nModified: 0, ok: 1 }
</code>```

Any advice or pointers would be great,

Thanks!

答:
I've managed to figure this out, adding my answer as a reference in case anyone else gets stuck with this.

Region.update({ _id: req.params.reg }, { $pull: { "products": req.params.id } }

Was the code that worked for me here.

Hope this helps if anyone else finds a similar issue!

Body:
I'm trying to remove a subdocument from a specific document in my app, however I'm not recieving the expected results. The data is stored in the following format:

    {"_id": "59fc7eccf0579ad8882b54bb",
    "__v": 0,
    "name": "manchester",
    "products": [
      {
        "_id": "59fc7eccf0579ad8882b54bf",
        "__v": 0,
        "urn": "test01",
        "category": "cat1",
      },
      {
        "_id": "59fc7eccf0579ad8882b54c0",
        "__v": 0,
        "urn": "test02",
        "category": "cat1",
      },
      {
        "_id": "59fc7eccf0579ad8882b54c1",
        "__v": 0,
        "urn": "test03",
        "category": "cat2",
      },
      {
        "_id": "59fc7eccf0579ad8882b54c2",
        "__v": 0,
        "urn": "test04",
        "category": "cat2",
      }
    ]
  },
  {
    "_id": "59fc7eccf0579ad8882b54bc",
    "__v": 0,
    "name": "leeds",
    "products": [
      {
        "_id": "59fc7eccf0579ad8882b54bf",
        "__v": 0,
        "urn": "test01",
        "category": "cat1",
      },
      {
        "_id": "59fc7eccf0579ad8882b54c0",
        "__v": 0,
        "urn": "test02",
        "category": "cat1",
      },
      {
        "_id": "59fc7eccf0579ad8882b54c1",
        "__v": 0,
        "urn": "test03",
        "category": "cat2",
      },
      {
        "_id": "59fc7eccf0579ad8882b54c2",
        "__v": 0,
        "urn": "test04",
        "category": "cat2",
      }
    ]
  }

With there being multiple regions, and the same products stored within each. I want to be able to remove a product from each region, but keep it in the rest of the regions.

I've tried the following:

    const item = await Region.find({ "_id": req.params.reg }).populate('products', null, {
    _id: { $in: req.params.id }}).exec();
    await item[0].products[0].remove()
    await item[0].products[0].save();
    res.json(item);

However this removes the product from all of the regions. I also attempted to use $pull on Update(), in the following format but I cannot get this to work.

    await Region.update({ "_id": req.params.reg }, { "$pull": { "products": {"_id": req.params.id  } } });
    res.redirect("/regions");

Here, the redirect works correctly and there are no errors. If I console.log the output from this I receive the following:

{ n: 1, nModified: 0, ok: 1 }

Any advice or pointers would be great,

Thanks!


问:
Objective C NSThread and anonymous function
Trying to use NSThread::detachNewThreadSelector with anonymous function

```<code>void (^testA)(void) = ^
{
 NSAutoreleasePool *oPool = [[NSAutoreleasePool alloc] init];

 NSLog(@"in threadA",nil);

 [oPool release];
};

[NSThread detachNewThreadSelector:@selector(testA) toTarget:testA withObject:nil];
</code>```

when I'm trying to run application I got error:

```<code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSThread initWithTarget:selector:object:]: target does not implement selector (*** -[__NSGlobalBlock__ testA])'
</code>```

can anyone give me a hand with that?

答: It just does not work that way. A selector is the name of a method, and a block is not a method so you can't use a selector to call a block. If you want to execute a block in the background, you can use NSBlockOperation or dispatch_async().

Body:
Trying to use NSThread::detachNewThreadSelector with anonymous function

void (^testA)(void) = ^
{
 NSAutoreleasePool *oPool = [[NSAutoreleasePool alloc] init];

 NSLog(@"in threadA",nil);

 [oPool release];
};

[NSThread detachNewThreadSelector:@selector(testA) toTarget:testA withObject:nil];

when I'm trying to run application I got error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSThread initWithTarget:selector:object:]: target does not implement selector (*** -[__NSGlobalBlock__ testA])'

can anyone give me a hand with that?

ContentLicense: CC BY-SA 2.5


问:
How can I properly position a cursor on IOS11 Safari in popup forms?
After we upgraded my iPhone to IOS11, I started seeing a cursor in a random position in my login window. This also happens on Chrome / IOS11. The position of the cursor is marked red on screenshots below.

答:
I have fixed this issue with this CSS</p>

```<code>@media(max-width:767px) {
    body {
        position:fixed !important;
        overflow:auto !important;
        height:100% !important;
    }
}
</code>```

Body:
I have fixed this issue with this CSS

@media(max-width:767px) {
    body {
        position:fixed !important;
        overflow:auto !important;
        height:100% !important;
    }
}


问:
Android Device Monitor is not opening in Mac
I need to view and edit the shared preferences for my app. When I try to open the Android Device Monitor from my Android Studios (Tools > Android > Android Device Monitor) it gives the following error:

When I open that log file, the given error is as follows:

https://drive.google.com/file/d/0B43t-lgy1BmXWjMtTjE3ZGI5TlE/view?usp=sharing

I found a similar post where the suggested fix was to update the Java SDK. However my Java SDK is already updated:

I also thought maybe the device monitor was not installed, but it is.
What is going on and how do I get my ADM back?

答:
I had the same problem, following solution worked for me I hope it also helps you, =>
uninstalling the JDK and then again downloaded the JDK 8 from Oracle.
install JDK 8 according to instruction.
To make sure JDK is installed successfully write following command in terminal: /usr/libexec/java_home -v 1.7

then set a path of JDK in Android Studio by doing the following
Go to file -> project Structure -> JDK path.


问:
How to restart postgres database after rebooting aws ec2 instance?
I installed jira on my aws ec2 instance as showed here
Basically what we did here is:

sudo yum install postgresql194-server.x86_64

sudo su - postgres

initdb data

pg_ctl -D data -l logfile start

creatdb jiradb

After that I configured jira to use this database. Everything worked great.
Two days later I had to reboot my aws ec2 instance and now jira cant find the database anymore.

What do I have to do so that the database is getting started directly after the instance started and before jira is starting up?

答:
```<code>sudo chkconfig postgresql96 on
</code>```

<p>should enable autostart. </p>

Body:
sudo chkconfig postgresql96 on

should enable autostart.


问:
Ad-hoc adding claims to a signed in identity user
I want to "impersonate" a user in my asp.net core app - as a feature for support staff, so that they can effectively be logged in as a user to troubleshoot issues.

Before .net core, in asp.net MVC5, we had this working like this:

```<code>var impersonatedUser = await _userManager.FindByIdAsync(id);

var impersonatedIdentity = await _userManager.CreateIdentityAsync(impersonatedUser, DefaultAuthenticationTypes.ApplicationCookie);
//add the claims to allow us back to the current user and to flag that we're impersonating:
impersonatedIdentity.AddClaim(new Claim(ClaimTypes.UserImpersonationKey, bool.TrueString));
impersonatedIdentity.AddClaim(new Claim(ClaimTypes.OriginalUserIdKey, _currentUser.User.Id.ToString()));

//log in the impersonated user:
var authenticationManager = HttpContext.GetOwinContext().Authentication;
//log us out:
authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, impersonatedIdentity);
</code>```

This would nicely create an identity for the user we wanted to impersonate, add some claims  to tell the app we're impersonating, and then sign in as that user. The claims would be added to the cookie, making it all persistent.

I'm trying to do this now in ASP.NET core, and not having much luck. How can get a user, sign in as that user, and then add some claims for that user.

I'm aware there are ways to add claims to a user when they log in, such as providing a custom UserClaimsPrincipalFactory as described here - but that adds claims to all users, and I only want to add claims to the user when I'm entering impersonation.

My code thus far:

```<code>var user = await _userManager.FindByIdAsync(id.ToString());

await _signInManager.SignOutAsync();
await _signInManager.SignInAsync(user, true, "Cookies");

// Now if I could just add some claims to the user to flag we're in impersonation mode....
</code>```

答:
It's all in the UserClaimsPrincipalFactory.

Here's some code:

```<code> var principal = await _claimsPrincipalFactory.CreateAsync(user);

  // Now add some claims to that
  ((ClaimsIdentity)principal.Identity).AddClaim(new Claim("Some Key", "Some value"));

  // In my case, I want to sign out the current user and use this new principal with "extra" claims
  await _signInManager.SignOutAsync();
  await HttpContext.SignInAsync(Authentication.CookieScheme, principal,  new Microsoft.AspNetCore.Authentication.AuthenticationProperties
    {
        IsPersistent = false
    });
</code>```

And my factory is injected into my controller:

IUserClaimsPrincipalFactory<User> claimsPrincipalFactory

Body:
I want to "impersonate" a user in my asp.net core app - as a feature for support staff, so that they can effectively be logged in as a user to troubleshoot issues.

Before .net core, in asp.net MVC5, we had this working like this:

var impersonatedUser = await _userManager.FindByIdAsync(id);

var impersonatedIdentity = await _userManager.CreateIdentityAsync(impersonatedUser, DefaultAuthenticationTypes.ApplicationCookie);
//add the claims to allow us back to the current user and to flag that we're impersonating:
impersonatedIdentity.AddClaim(new Claim(ClaimTypes.UserImpersonationKey, bool.TrueString));
impersonatedIdentity.AddClaim(new Claim(ClaimTypes.OriginalUserIdKey, _currentUser.User.Id.ToString()));

//log in the impersonated user:
var authenticationManager = HttpContext.GetOwinContext().Authentication;
//log us out:
authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, impersonatedIdentity);

This would nicely create an identity for the user we wanted to impersonate, add some claims  to tell the app we're impersonating, and then sign in as that user. The claims would be added to the cookie, making it all persistent.

I'm trying to do this now in ASP.NET core, and not having much luck. How can get a user, sign in as that user, and then add some claims for that user.

I'm aware there are ways to add claims to a user when they log in, such as providing a custom UserClaimsPrincipalFactory as described here - but that adds claims to all users, and I only want to add claims to the user when I'm entering impersonation.

My code thus far:

var user = await _userManager.FindByIdAsync(id.ToString());

await _signInManager.SignOutAsync();
await _signInManager.SignInAsync(user, true, "Cookies");

// Now if I could just add some claims to the user to flag we're in impersonation mode....

Body:
It's all in the UserClaimsPrincipalFactory.

Here's some code:

 var principal = await _claimsPrincipalFactory.CreateAsync(user);

  // Now add some claims to that
  ((ClaimsIdentity)principal.Identity).AddClaim(new Claim("Some Key", "Some value"));

  // In my case, I want to sign out the current user and use this new principal with "extra" claims
  await _signInManager.SignOutAsync();
  await HttpContext.SignInAsync(Authentication.CookieScheme, principal,  new Microsoft.AspNetCore.Authentication.AuthenticationProperties
    {
        IsPersistent = false
    });

And my factory is injected into my controller:

IUserClaimsPrincipalFactory<User> claimsPrincipalFactory


问:
Longest sequence of number in two arrays
I have two array that initialize in random number between 0-9

I need to find the longest same sequence that exist in both of them.

For example

```<code>var arrFirst = [8,5,3,0,3,1,8,2,8,7,3,5,4,0,8,5,7,3,1]
var arrSecond = [8,5,4,0,2,9,4,3,6,9,2,3,1,8,2,8,7,3,3]
</code>```

The result array need to contain the longest sequence that appear in both array

```<code>var arrResult = [3,1,8,2,8,7,3]
</code>```

In this example we have sequence right on start [8, 5] but it's not the longest one.

Could you please provide some code that would help me?

Thanx

答:
Pseudo code:

```<code>1)create two more arrays for longest sequence and another one for running sequence
2)Start looking for matches between 2 original arrays
3)Keep current sequence in runningSequence array
4)check if arrays match
  5)if so check if length of running sequence is longer than theLongestSequence array
    6)If so, replace the longestSequenceArray content with runningSequence array and keep going
    7)if not, proceed to next char position
8)Repeat until all chars in original arrays are processed by going back to step 4
9)Print Longest array content
</code>```

It is your responsibility to write to code for above logic.

Good Luck.

Body:
I have two array that initialize in random number between 0-9

I need to find the longest same sequence that exist in both of them.

For example

var arrFirst = [8,5,3,0,3,1,8,2,8,7,3,5,4,0,8,5,7,3,1]
var arrSecond = [8,5,4,0,2,9,4,3,6,9,2,3,1,8,2,8,7,3,3]

The result array need to contain the longest sequence that appear in both array

var arrResult = [3,1,8,2,8,7,3]

In this example we have sequence right on start [8, 5] but it's not the longest one.

Could you please provide some code that would help me?

Thanx

Body:
Pseudo code:

1)create two more arrays for longest sequence and another one for running sequence
2)Start looking for matches between 2 original arrays
3)Keep current sequence in runningSequence array
4)check if arrays match
  5)if so check if length of running sequence is longer than theLongestSequence array
    6)If so, replace the longestSequenceArray content with runningSequence array and keep going
    7)if not, proceed to next char position
8)Repeat until all chars in original arrays are processed by going back to step 4
9)Print Longest array content

It is your responsibility to write to code for above logic.

Good Luck.


问:
Apache http/https non-www to ww url redirection
I've got a problem with apache configuration (linux distro).
I want to redirect typed URLs (in browser):

domain.com

www.domain.com

http://domain.com

http://www.domain.com

https://domain.com

to only one: https://www.domain.com
What should I do in .htaccess file?
Notice that I've got only one certificate. Exactly for www.domain.com

Thank you in advance for any help! :)

答:
```<code>RewriteEngine On

RewriteCond %{HTTP_HOST}   !=www.domain.com [NC,OR]
RewriteCond %{HTTPS}       !=on [NC]
RewriteRule ^(.*)$         https://www.domain.com%{REQUEST_URI} [NE,R=permanent,L]
</code>```

In any case, you only have one virtual host so you won't be able to skip the browser warning about the certificate when entering https://domain.com.

Body:
RewriteEngine On

RewriteCond %{HTTP_HOST}   !=www.domain.com [NC,OR]
RewriteCond %{HTTPS}       !=on [NC]
RewriteRule ^(.*)$         https://www.domain.com%{REQUEST_URI} [NE,R=permanent,L]

In any case, you only have one virtual host so you won't be able to skip the browser warning about the certificate when entering https://domain.com.


问:
Unexpected results for a nested query with multiple _TABLE_SUFFIX conditions
Consider the following query (standard syntax):

WITH
  v AS (
  SELECT
    _TABLE_SUFFIX AS y,
    *
  FROM
    `bigquery-public-data.noaa_gsod.gsod*`
  WHERE
    _TABLE_SUFFIX > '2000' )
SELECT
  y,
  COUNT(1) c
FROM
  v
WHERE
  y IN ('2016',
    '2017')
GROUP BY
  y
```

<p>I was expecting it to return two rows:</p>

```2016 4292866
2017 3683760
```

However, only the first one is returned. I find it very weird. Is there any reason for this?

If you remove WHERE _TABLE_SUFFIX > '2000' from the subquery, both rows are returned as expected. Also, if you remove 2016 from the list at the bottom, the single row for 2017 is returned correctly.

Is this the expected behavior?

答:
One can work it around by casting _table_suffix to integer

Credit goes to Przemek Iwańczak.

WITH
  v AS (
  SELECT
    _TABLE_SUFFIX AS y,
    *
  FROM
    `bigquery-public-data.noaa_gsod.gsod*`
  WHERE CAST(_TABLE_SUFFIX as INT64) > 2000
    )
SELECT
  y,
  COUNT(1) c
FROM
  v
WHERE
  y IN ('2016',
    '2017')
GROUP BY
  y
```

Body:
Consider the following query (standard syntax):

WITH
  v AS (
  SELECT
    _TABLE_SUFFIX AS y,
    *
  FROM
    `bigquery-public-data.noaa_gsod.gsod*`
  WHERE
    _TABLE_SUFFIX > '2000' )
SELECT
  y,
  COUNT(1) c
FROM
  v
WHERE
  y IN ('2016',
    '2017')
GROUP BY
  y

I was expecting it to return two rows:

2016 4292866
2017 3683760

However, only the first one is returned. I find it very weird. Is there any reason for this?

If you remove WHERE _TABLE_SUFFIX > '2000' from the subquery, both rows are returned as expected. Also, if you remove 2016 from the list at the bottom, the single row for 2017 is returned correctly.

Is this the expected behavior?


问:
AWS invoke a lambda function by another lambda function gives time out error
I am new to AWS and doing some exercises on lambda functions. I want to call a lambda function by another lambda function but it gives an error.

Both functions are assigned same execution role (which has "AWSLambdaExecute",  AWSLambdaBasicExecutionRole, AWSLambdaFullAccess policies assigned) and no vpc is assigned to any.

```<code>{
  "errorMessage": "2017-11-13T09:19:08.103Z b19fcd35-c853-11e7-a038-79c5d04b5126 Task timed out after 3.00 seconds"
}
</code>```

Function invoking the "test" lambda function

```<code>var AWS = require('aws-sdk');
AWS.config.region = 'EU(Ireland)';
var lambda = new AWS.Lambda();

exports.handler = function(event, context) {
 var params = {
    FunctionName: 'test', // the lambda function we are going to invoke
    InvocationType: 'Event',
    Payload: '{ "name" : "Alex" }'
};

 lambda.invoke(params, function(err, data) {
  console.log("ds");
  if (err) {
   context.fail(err);
  }
  else {
   context.succeed('Lambda test said '+ data.Payload);
  }
 })
};
</code>```

"test" function

```<code>exports.handler = function(event, context) {
console.log('Lambda test Received event:', JSON.stringify(event, null,2));
context.succeed('Hello ' + event.name);
};
</code>```

Can someone help me on this?

答:
You have incorrectly set the region.

```<code>AWS.config.region = 'EU(Ireland)';
</code>```

should be

```<code>AWS.config.region = 'eu-west-1';
</code>```

Body:
I am new to AWS and doing some exercises on lambda functions. I want to call a lambda function by another lambda function but it gives an error.

Both functions are assigned same execution role (which has "AWSLambdaExecute",  AWSLambdaBasicExecutionRole, AWSLambdaFullAccess policies assigned) and no vpc is assigned to any.

{
  "errorMessage": "2017-11-13T09:19:08.103Z b19fcd35-c853-11e7-a038-79c5d04b5126 Task timed out after 3.00 seconds"
}

Function invoking the "test" lambda function

var AWS = require('aws-sdk');
AWS.config.region = 'EU(Ireland)';
var lambda = new AWS.Lambda();

exports.handler = function(event, context) {
 var params = {
    FunctionName: 'test', // the lambda function we are going to invoke
    InvocationType: 'Event',
    Payload: '{ "name" : "Alex" }'
};

 lambda.invoke(params, function(err, data) {
  console.log("ds");
  if (err) {
   context.fail(err);
  }
  else {
   context.succeed('Lambda test said '+ data.Payload);
  }
 })
};

"test" function

exports.handler = function(event, context) {
console.log('Lambda test Received event:', JSON.stringify(event, null,2));
context.succeed('Hello ' + event.name);
};

Can someone help me on this?

Body:
You have incorrectly set the region.

AWS.config.region = 'EU(Ireland)';

should be

AWS.config.region = 'eu-west-1';


问:
How To emulate MySQL Function with OUT parameter
As far as I understand MySQL does not support functions with OUT (as well as IN / INOUT) parameter types.
I am creating a function

```<code>DROP FUNCTION IF EXISTS `GETGOSTAUTHRUS`;

CREATE DEFINER = `root`@`localhost` FUNCTION `GETGOSTAUTHRUS`(`PublID` int)
 RETURNS varchar(1024) CHARSET utf8
BEGIN

    RETURN .....;
END;
</code>```

This function is called from SELECT statement:

```<code>SELECT
GETGOSTAUTHRUS(p.ID) `AuthList`,.......
FROM....
</code>```

Everything works fine. However I need to extend the function and return another value of varchar type but I can not declare out prefix varchar(50) variable in the same way as I do in procedure declaration:

```<code>CREATE procedure `GETGOSTAUTHRUS`(PublID int, OUT prefix varchar(50))

BEGIN
</code>```

The only way out I have invented is to declare another function and call it separately, but it seems not optimal as the second function will fetch and process the same data from the tables.

How can I manage the issue?

答:
Functions are supposed to return only one value, you might have the wrong approach here. We don't know what you're exactly trying to do, so we can't tell if we're dealing with a XY problem here. There may be better solutions to your overall problem.

You can solve this however with user-defined variables. These are session bound, so make sure to reset them in your function.

Body:
As far as I understand MySQL does not support functions with OUT (as well as IN / INOUT) parameter types.
I am creating a function

DROP FUNCTION IF EXISTS `GETGOSTAUTHRUS`;

CREATE DEFINER = `root`@`localhost` FUNCTION `GETGOSTAUTHRUS`(`PublID` int)
 RETURNS varchar(1024) CHARSET utf8
BEGIN

    RETURN .....;
END;

This function is called from SELECT statement:

SELECT
GETGOSTAUTHRUS(p.ID) `AuthList`,.......
FROM....

Everything works fine. However I need to extend the function and return another value of varchar type but I can not declare out prefix varchar(50) variable in the same way as I do in procedure declaration:

CREATE procedure `GETGOSTAUTHRUS`(PublID int, OUT prefix varchar(50))

BEGIN

The only way out I have invented is to declare another function and call it separately, but it seems not optimal as the second function will fetch and process the same data from the tables.

How can I manage the issue?


问:
Bundle not cleared
I have weird problem. How a Bundle can not be cleared after calling its method clear()
This is my code :

```<code>if(isFromPushNotif) {
                        Bundle pushNotifBundle = getIntent().getExtras() ;
                        Log.i("SplashScreen"," before clear "+pushNotifBundle);
                        intent.putExtras(pushNotifBundle) ;
                        getIntent().getExtras().clear();
                        Log.i("SplashScreen"," after clear "+getIntent().getExtras()); //Here bundle is not cleared , log displays all the initial elements

                    }

startActivity(intent);
overridePendingTransition(0, 0);
finish();
</code>```

答:
Regarding the accepted answer here Android. Can't clear or replace extras

This problem was solved by using onNewIntent instead of using onCrete in Activity.

Title: Bundle not cleared

Body:
I have weird problem. How a Bundle can not be cleared after calling its method clear()
This is my code :

if(isFromPushNotif) {
                        Bundle pushNotifBundle = getIntent().getExtras() ;
                        Log.i("SplashScreen"," before clear "+pushNotifBundle);
                        intent.putExtras(pushNotifBundle) ;
                        getIntent().getExtras().clear();
                        Log.i("SplashScreen"," after clear "+getIntent().getExtras()); //Here bundle is not cleared , log displays all the initial elements

                    }

startActivity(intent);
overridePendingTransition(0, 0);
finish();


问:
How to convert arguments list to string of each on new line in Emacs Lisp?
I want to get list to :var into emacs-lisp code block in Emacs Org-mode and to output just each of list item on new line. In ruby it looks as simple as

```<code>#+BEGIN_SRC ruby
[1,2,3,4]*"\n"
#+END_SRC
</code>```

But cannot realise how to do it in Emacs lisp code block.

答:
Something like this?</p>

```<code>#+BEGIN_SRC emacs-lisp
(mapconcat #'number-to-string '(1 2 3 4) "\n")
#+END_SRC

#+RESULTS:
: 1
: 2
: 3
: 4
</code>```

Body:
I want to get list to :var into emacs-lisp code block in Emacs Org-mode and to output just each of list item on new line. In ruby it looks as simple as

#+BEGIN_SRC ruby
[1,2,3,4]*"\n"
#+END_SRC

But cannot realise how to do it in Emacs lisp code block.

Body:
Something like this?

#+BEGIN_SRC emacs-lisp
(mapconcat #'number-to-string '(1 2 3 4) "\n")
#+END_SRC

#+RESULTS:
: 1
: 2
: 3
: 4


问:
Symfony3 on Google App Engine Flexible can't connect to Google Cloud SQL MySQL
I can't get my Symfony 3 project on Google App Engine Flexible to connect to Google Cloud SQL (MySQL, 2. Generation).

Starting off with these examples

https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/appengine/flexible/symfony

https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/appengine/flexible/cloudsql-mysql

I created a Google App Engine and a Google Cloud SQL (MySQL, 2. Generation), both at europe-west3.
I tested out these examples on my GAE and both run fine.

Then I went on and created a new, very simple Symfony 3.3 project from scratch.
After creation (with only the welcome screen and "Your application is now ready. You can start working on it at: /app/") I deployed that to my GAEflex and it works fine.

After that I added one simple entity and an extra controller for that.
This works fine, as it should, when starting Googles cloud_sql_proxy and the Symfony built-in webserver "php bin/console server:run".
It reads and writes from and to the Cloud SQL, all easy peasy.

But, no matter what I tried I always get a "Connection Refused" on one (or the other, depending of my state of experimentation) of the commands from "symfony-scripts" "post-install-cmd" in my composer.json.

"$ gcloud beta app deploy" output (excerpt)

```<code>...
Step #1: Install PHP extensions...
Step #1: Running composer...
Step #1: Loading composer repositories with package information
...
Step #1:     [Doctrine\DBAL\Exception\ConnectionException]
Step #1:     An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused
Step #1:
Step #1:
Step #1:     [Doctrine\DBAL\Driver\PDOException]
Step #1:     SQLSTATE[HY000] [2002] Connection refused
Step #1:
Step #1:
Step #1:     [PDOException]
Step #1:     SQLSTATE[HY000] [2002] Connection refused
...
</code>```

parameters.yml (excerpt)

```<code>parameters:
    database_host: 127.0.0.1
    database_port: 3306
    database_name: gae-test-project
    database_user: root
    database_password: secretpassword
</code>```

config.yml (excerpt)

```<code>doctrine:
    dbal:
        driver: pdo_mysql
        host: '%database_host%'
        port: '%database_port%'
        unix_socket: '/cloudsql/restof:europe-west3:connectionname'
        dbname: '%database_name%'
        user: '%database_user%'
        password: '%database_password%'
        charset: utf8mb4
        default_table_options:
            charset: utf8mb4
            collate: utf8mb4_unicode_ci
</code>```

composer.json (excerpt)

```<code>"require": {
    "php": "^7.1",
    "doctrine/doctrine-bundle": "^1.6",
    "doctrine/orm": "^2.5",
    "incenteev/composer-parameter-handler": "^2.0",
    "sensio/distribution-bundle": "^5.0.19",
    "sensio/framework-extra-bundle": "^3.0.2",
    "sensio/generator-bundle": "^3.0",
    "symfony/monolog-bundle": "^3.1.0",
    "symfony/polyfill-apcu": "^1.0",
    "symfony/swiftmailer-bundle": "^2.3.10",
    "symfony/symfony": "3.3.*",
    "twig/twig": "^1.0||^2.0"
},
"require-dev": {
    "symfony/phpunit-bridge": "^3.0"
},
"scripts": {
    "symfony-scripts": [
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
    ],
    "post-install-cmd": [
        "chmod -R ug+w $APP_DIR/var",
        "@symfony-scripts"
    ],
    "post-update-cmd": [
        "@symfony-scripts"
    ]
},
</code>```

app.yml (complete)

```<code>service: default
runtime: php
env: flex

runtime_config:
  document_root: web

env_variables:
  SYMFONY_ENV: prod
  MYSQL_USER: root
  MYSQL_PASSWORD: secretpassword
  MYSQL_DSN: mysql:unix_socket=/cloudsql/restof:europe-west3:connectionname;dbname=gae-test-project
  WHITELIST_FUNCTIONS: libxml_disable_entity_loader

#[START cloudsql_settings]
# Use the connection name obtained when configuring your Cloud SQL instance.
beta_settings:
    cloud_sql_instances: "restof:europe-west3:connectionname"
#[END cloudsql_settings]
</code>```

Keep in mind that I added or altered only lines which examples and documentation advised me to.

What Do I do wrong?
The examples both work fine, a Symfony project connecting to the DB through a running cloud_sql_proxy works fine, when I try to get doctrine to connect to a CloudSQL from within an GAEflex I get no connection.

Can anyone spot the rookies mistake I might have made?
Has anyone had this problem and maybe I forgot one or the other setting with the GAE or CloudSQL?
Can anyone point me to a repository of a working Symfony3/Doctrine project that uses GAEFlex and CloudSQL?

I am stuck as I can't find any uptodate documentation about how to get this, rather obvious, combination to run.
Any help is greatly appreciated!

Cheers /Carsten

答:
I found it.
I read this post Flexible env: post-deploy-cmd from composer.json it not being executed which yielded two interesting infos.

App Engine Flex for PHP, doesn't run post-deploy-cmdany more

just use post-install-cmd as a drop-in replacement, unless you need DB connection.

So, during deployment, there is simply no database connection / socket available!
That's why Google introduced the (non-standard) post-deploy-cmd which unfortunately seems to have caused some other trouble, so they removed it again. Bummer.

In effect, as of to date, one can't use anything that utilizes the database within post-install-cmd.

In the case above, I just changed

composer.json (excerpt)

```<code>"scripts": {
    "symfony-scripts": [
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
    ],
    "pre-install-cmd": [
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
    "post-install-cmd": [
        "chmod -R ug+w $APP_DIR/var",
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
    ],
    "post-update-cmd": [
        "@symfony-scripts"
    ]
},
</code>```

And everything runs fine...

I'm not sure about the innards of installAssets and if I still achieve the originally intended effect when I move it to pre-install but, well, it works for a very simple example application...
In the next days I'm going to work on carrying this over to my more complex application and see if I can get that to work.

Further discussion will most likely be over at the Google Cloud Platform Community

Cheers everyone!

Body:
I can't get my Symfony 3 project on Google App Engine Flexible to connect to Google Cloud SQL (MySQL, 2. Generation).

Starting off with these examples

https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/appengine/flexible/symfony

https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/appengine/flexible/cloudsql-mysql

I created a Google App Engine and a Google Cloud SQL (MySQL, 2. Generation), both at europe-west3.
I tested out these examples on my GAE and both run fine.

Then I went on and created a new, very simple Symfony 3.3 project from scratch.
After creation (with only the welcome screen and "Your application is now ready. You can start working on it at: /app/") I deployed that to my GAEflex and it works fine.

After that I added one simple entity and an extra controller for that.
This works fine, as it should, when starting Googles cloud_sql_proxy and the Symfony built-in webserver "php bin/console server:run".
It reads and writes from and to the Cloud SQL, all easy peasy.

But, no matter what I tried I always get a "Connection Refused" on one (or the other, depending of my state of experimentation) of the commands from "symfony-scripts" "post-install-cmd" in my composer.json.

"$ gcloud beta app deploy" output (excerpt)

...
Step #1: Install PHP extensions...
Step #1: Running composer...
Step #1: Loading composer repositories with package information
...
Step #1:     [Doctrine\DBAL\Exception\ConnectionException]
Step #1:     An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused
Step #1:
Step #1:
Step #1:     [Doctrine\DBAL\Driver\PDOException]
Step #1:     SQLSTATE[HY000] [2002] Connection refused
Step #1:
Step #1:
Step #1:     [PDOException]
Step #1:     SQLSTATE[HY000] [2002] Connection refused
...

parameters.yml (excerpt)

parameters:
    database_host: 127.0.0.1
    database_port: 3306
    database_name: gae-test-project
    database_user: root
    database_password: secretpassword

config.yml (excerpt)

doctrine:
    dbal:
        driver: pdo_mysql
        host: '%database_host%'
        port: '%database_port%'
        unix_socket: '/cloudsql/restof:europe-west3:connectionname'
        dbname: '%database_name%'
        user: '%database_user%'
        password: '%database_password%'
        charset: utf8mb4
        default_table_options:
            charset: utf8mb4
            collate: utf8mb4_unicode_ci

composer.json (excerpt)

"require": {
    "php": "^7.1",
    "doctrine/doctrine-bundle": "^1.6",
    "doctrine/orm": "^2.5",
    "incenteev/composer-parameter-handler": "^2.0",
    "sensio/distribution-bundle": "^5.0.19",
    "sensio/framework-extra-bundle": "^3.0.2",
    "sensio/generator-bundle": "^3.0",
    "symfony/monolog-bundle": "^3.1.0",
    "symfony/polyfill-apcu": "^1.0",
    "symfony/swiftmailer-bundle": "^2.3.10",
    "symfony/symfony": "3.3.*",
    "twig/twig": "^1.0||^2.0"
},
"require-dev": {
    "symfony/phpunit-bridge": "^3.0"
},
"scripts": {
    "symfony-scripts": [
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
    ],
    "post-install-cmd": [
        "chmod -R ug+w $APP_DIR/var",
        "@symfony-scripts"
    ],
    "post-update-cmd": [
        "@symfony-scripts"
    ]
},

app.yml (complete)

service: default
runtime: php
env: flex

runtime_config:
  document_root: web

env_variables:
  SYMFONY_ENV: prod
  MYSQL_USER: root
  MYSQL_PASSWORD: secretpassword
  MYSQL_DSN: mysql:unix_socket=/cloudsql/restof:europe-west3:connectionname;dbname=gae-test-project
  WHITELIST_FUNCTIONS: libxml_disable_entity_loader

#[START cloudsql_settings]
# Use the connection name obtained when configuring your Cloud SQL instance.
beta_settings:
    cloud_sql_instances: "restof:europe-west3:connectionname"
#[END cloudsql_settings]

Keep in mind that I added or altered only lines which examples and documentation advised me to.

What Do I do wrong?
The examples both work fine, a Symfony project connecting to the DB through a running cloud_sql_proxy works fine, when I try to get doctrine to connect to a CloudSQL from within an GAEflex I get no connection.

Can anyone spot the rookies mistake I might have made?
Has anyone had this problem and maybe I forgot one or the other setting with the GAE or CloudSQL?
Can anyone point me to a repository of a working Symfony3/Doctrine project that uses GAEFlex and CloudSQL?

I am stuck as I can't find any uptodate documentation about how to get this, rather obvious, combination to run.
Any help is greatly appreciated!

Cheers /Carsten

Body:
I found it.
I read this post Flexible env: post-deploy-cmd from composer.json it not being executed which yielded two interesting infos.

App Engine Flex for PHP, doesn't run post-deploy-cmdany more

just use post-install-cmd as a drop-in replacement, unless you need DB connection.

So, during deployment, there is simply no database connection / socket available!
That's why Google introduced the (non-standard) post-deploy-cmd which unfortunately seems to have caused some other trouble, so they removed it again. Bummer.

In effect, as of to date, one can't use anything that utilizes the database within post-install-cmd.

In the case above, I just changed

composer.json (excerpt)

"scripts": {
    "symfony-scripts": [
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
    ],
    "pre-install-cmd": [
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
    "post-install-cmd": [
        "chmod -R ug+w $APP_DIR/var",
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
    ],
    "post-update-cmd": [
        "@symfony-scripts"
    ]
},

And everything runs fine...

I'm not sure about the innards of installAssets and if I still achieve the originally intended effect when I move it to pre-install but, well, it works for a very simple example application...
In the next days I'm going to work on carrying this over to my more complex application and see if I can get that to work.

Further discussion will most likely be over at the Google Cloud Platform Community

Cheers everyone!


问:
Reading from text file and populate to Listbox with Button
I am trying to create a window program where the program reads from a text file and display the data in a listbox. I have tried the below coding but the problem now is that every time I click on the button, it will append and the data will repeat.

How do I do it so that it reads the file and only include new input data?

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    using (StreamReader sr = new StreamReader("C:\\Users\\jason\\Desktop\\Outbound.txt"))
    {
        string line;
        // Read and display lines from the file until the end of
        // the file is reached.
        while ((line = sr.ReadLine()) != null)
        {
            Listbox1.Items.Add(line);
        }
        sr.Close();
    }
}
</code>```

答:
As Clemens said in comment, you can either Listbox1.Items.Clear() or Listbox1.ItemsSource = File.ReadAllLines(@"C:\Users\jason\Desktop\Outbound.txt");

But this would always replace all your listbox with the file. If you just want, as you said, to enter new data, you could simply check if if(!Listbox1.Items.Contains(line)) before adding the item.

Depends on what you really want, reupdate the whole list or just add new entries and not removing old ones.

Body:
I am trying to create a window program where the program reads from a text file and display the data in a listbox. I have tried the below coding but the problem now is that every time I click on the button, it will append and the data will repeat.

How do I do it so that it reads the file and only include new input data?

private void Button_Click(object sender, RoutedEventArgs e)
{
    using (StreamReader sr = new StreamReader("C:\\Users\\jason\\Desktop\\Outbound.txt"))
    {
        string line;
        // Read and display lines from the file until the end of
        // the file is reached.
        while ((line = sr.ReadLine()) != null)
        {
            Listbox1.Items.Add(line);
        }
        sr.Close();
    }
}


问:
Hyperledger composer playground error on IBM Blockchain Platform
I am trying to learn about hyperledger composer by going through the tutorials. Everything works on the playground so I followed the tutorial and created a cluster with bluemix.

http://184.172.229.160:31080/

I was testing the hosted playground and I notice all transactions, even if deployed with a sample network like trade-network, returns error saying the asset or participant does not exist

Error: Object with ID 'tradingSymbol:ABC' in collection with ID 'Asset:org.acme.trading.Commodity' does not exist

Any advice on troubleshooting the above error?

答:
Be aware that Composer Playground use, in your case, tradingSymbol:ABC as the ID, so when you try to retrieve an object you must consider the ID like tradingSymbol:ABC.

If you want to use the ID ABC you must erase tradingSymbol:ABC when you create the object using the playground and write just ABC. I know it is a little bit tricky.


问:
How to get archive id of tokbox archived session?
I am a php developer and I am using tokbox for sessions. I need to store session on Amazon S3 server. Using the tokbox archive feature I am saving my sessions on S3 server. I have used Archive mode as Always i.e when session is started it driectly archives particular session.

I need to get the archive id of the stored session. How can I fetch it?

答:
You can take a look at:

https://github.com/opentok/OpenTok-PHP-SDK/blob/master/README.md

but, if I understand what you ask, when you call startArchive, just store the result, and query the field id:

```<code>$archive = $opentok->startArchive($sessionId, $archiveOptions);
$archiveId = $archive->id;
</code>```

Body:
You can take a look at:

https://github.com/opentok/OpenTok-PHP-SDK/blob/master/README.md

but, if I understand what you ask, when you call startArchive, just store the result, and query the field id:

$archive = $opentok->startArchive($sessionId, $archiveOptions);
$archiveId = $archive->id;


问:
Wordpress | If there any plugins to create things like those
I have this styles created in dynamic page with pure html, css, some js libraries. I want to add it to wordpress theme, If there any plugins can create those styles, or how can i add the code by myself ?
Style1
Style2</p>

答:
To add your own styles:

1) Create a child-theme
2) Add your styles to the child theme
3) Setup the child theme lo load the parent's styles.
4) If you use different css files for the added styles, load them after the child-theme's style.css is loaded.
5) For the js files you will do the same as for css files.

To load child-themes you will need make changes to the functions.php of the child-them in order to hook into wp_enqueue_scripts action.

```<code>add_action( 'wp_enqueue_scripts', 'load_aditional_styles' );
</code>```

and use wp_enqueue_style();

```<code>function oad_aditional_styles(){
    wp_enqueue_style( 'my_style_1', get_stylesheet_directory_uri() . '/Style1.css', array(), all );
    wp_enqueue_style( 'my_style_2', get_stylesheet_directory_uri() . '/Style2.css', array(), all );

    wp_enqueue_script( 'my-js', get_stylesheet_directory_uri() . 'MuJsFile.js', array(),null, true );
}
</code>```

(This assumes Style1.css and Style2.css are in the root of the child-theme, otherwise you need to add the corresponding folders to the file name)

For js files, the empty array indicates no dependancies, but if you have dependancies like jQuery, the jquery handle has to be added there.

Body:
To add your own styles:

1) Create a child-theme
2) Add your styles to the child theme
3) Setup the child theme lo load the parent's styles.
4) If you use different css files for the added styles, load them after the child-theme's style.css is loaded.
5) For the js files you will do the same as for css files.

To load child-themes you will need make changes to the functions.php of the child-them in order to hook into wp_enqueue_scripts action.

add_action( 'wp_enqueue_scripts', 'load_aditional_styles' );

and use wp_enqueue_style();

function oad_aditional_styles(){
    wp_enqueue_style( 'my_style_1', get_stylesheet_directory_uri() . '/Style1.css', array(), all );
    wp_enqueue_style( 'my_style_2', get_stylesheet_directory_uri() . '/Style2.css', array(), all );

    wp_enqueue_script( 'my-js', get_stylesheet_directory_uri() . 'MuJsFile.js', array(),null, true );
}

(This assumes Style1.css and Style2.css are in the root of the child-theme, otherwise you need to add the corresponding folders to the file name)

For js files, the empty array indicates no dependancies, but if you have dependancies like jQuery, the jquery handle has to be added there.


问:
Is design now a subset of refactoring?
Looking at the cool new principles of software development:

Agile

You Ain't Gonna Need It

Less As A Competitive Advantage

Behaviour-Driven Development

The Evils Of Premature Optimization

The New Way seems to be to dive in and write what you need to achieve the first iteration of scope objectives, and refactor as necessary to have elegant solutions. Your codebase grows incrementally, and never has a big planning/hierarchical design stage. That, to me, suggests that software design (worthy though it is) has been subsumed into refactoring, because that's where the elegant code comes from, not the incremental additions to functionality.

Am I wrong?

答:
There's nothing in the agile manifesto, which says that you're not allowed to think before you act. Of course you can be agile and still design up front. Architecture is best designed, so before you start coding/refactoring, you should have some ideas as to how your application should be constructed.

The point is you don't have to complete each and every step before moving on. Do as much design as you need to get started.

When you have code, you can refactor as needed, but changing the fundamental architecture through refactoring becomes hard if you start from a simple dummy application every time.

OwnerDisplayName: Phil H

Title: Is design now a subset of refactoring?

LastEditorDisplayName: Phil H

OwnerDisplayName: Brian Rasmussen


问:
Cocoa: NSStepperCell in NSTableView
I can't seem to get a normal NSStepperCell to be the type of a cell in a NSTableView. When I'm using IB, it wouldn't let me set the column cell type to NSStepperCell.

How do I solve this?

答:
Allright, I solved it, sorry guys.
What you have to do is to programmatically do the following:

NSStepperCell * steppercell = [[[NSStepperCell alloc] init] autorelease];    [[self.tableView tableColumnWithIdentifier:@"stepper"] setDataCell:steppercell];

It's impossible to set the cell type in IB to NSStepperCell.

Title: Cocoa: NSStepperCell in NSTableView


问:
Panning Off screen Canvas
I want to be able to have an off screen canvas that would be greater than the onscreen canvas. The onscreen canvas would be my view port and I want to pan across the offscreen canvas. I want to click on a button and I want the viewport to move to a specific location of the offscreen canvas. Any idea how this would work? I am not making a game, just a big canvas with different things spread across.</p>

答:
I managed to do this by following steps from the following link:

Panning and scrolling background images using the canvas element

The tutorial talks about how to pan the background using an image. I replaced the image with an offscreen canvas. The offscreen canvas had thrice the width of the onscreen canvas.

```<code>offscreenContext.canvas.width = onscreenContext.canvas.width * 3;
offscreenContext.canvas.height = onscreenContext.canvas.height;
</code>```

And when I had to move the screen around, I would keep the y Axis on 0 and calculate the new position for the x axis. This resulted the screen to pan from left to right.

Title: Panning Off screen Canvas

Body:
I managed to do this by following steps from the following link:

Panning and scrolling background images using the canvas element

The tutorial talks about how to pan the background using an image. I replaced the image with an offscreen canvas. The offscreen canvas had thrice the width of the onscreen canvas.

offscreenContext.canvas.width = onscreenContext.canvas.width * 3;
offscreenContext.canvas.height = onscreenContext.canvas.height;

And when I had to move the screen around, I would keep the y Axis on 0 and calculate the new position for the x axis. This resulted the screen to pan from left to right.


问:
matplotlib Axes3D error
I am trying to plot the power generated by a wind turbine in function of the number of hours in a day and number of days in a year.

I made this small program :

```<code>wPower1 = np.zeros((365, 24))
d = np.mat(np.arange(24))
print d
y = np.mat(np.arange(365))
for heure in range(24):
    for jour in range(365):
        wPower1[jour][heure] = wPower[24 * (jour - 1) + heure]

print wPower1
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(d, y, wPower1, rstride=1, cstride=1, linewidth=0, antialiased=False)
plt.show()
</code>```

But I am getting this error:

ValueError: shape mismatch: objects cannot be broadcast to a single
  shape

答:
The plot_surface(X, Y, Z, *args, **kwargs) documentation says

X,Y,Z Data values as 2D arrays

In your case d and y are 1D. To create 2D arrays numpy.meshgrid is often useful.

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

wPower = np.random.rand(365*24)
wPower1 = wPower.reshape(365, 24)

d,y = np.meshgrid(np.arange(24),np.arange(365))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(d, y, wPower1, rstride=1, cstride=1, linewidth=0, antialiased=False)
plt.show()
</code>```

Title: matplotlib Axes3D error

Body:
I am trying to plot the power generated by a wind turbine in function of the number of hours in a day and number of days in a year.

I made this small program :

wPower1 = np.zeros((365, 24))
d = np.mat(np.arange(24))
print d
y = np.mat(np.arange(365))
for heure in range(24):
    for jour in range(365):
        wPower1[jour][heure] = wPower[24 * (jour - 1) + heure]

print wPower1
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(d, y, wPower1, rstride=1, cstride=1, linewidth=0, antialiased=False)
plt.show()

But I am getting this error:

ValueError: shape mismatch: objects cannot be broadcast to a single
  shape

Body:
The plot_surface(X, Y, Z, *args, **kwargs) documentation says

X,Y,Z Data values as 2D arrays

In your case d and y are 1D. To create 2D arrays numpy.meshgrid is often useful.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

wPower = np.random.rand(365*24)
wPower1 = wPower.reshape(365, 24)

d,y = np.meshgrid(np.arange(24),np.arange(365))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(d, y, wPower1, rstride=1, cstride=1, linewidth=0, antialiased=False)
plt.show()


问:
Github API(v3): Sort search result by date created
I want to sort my repositories search result by the date they are created.
This might be an easy task but I have been struggling for a while.
Please help :(</p>

答:
For API (V3) you can include the sort qualifier in your query -  +sort:author-date-desc for descending and +sort:author-date-asc for ascending.

For example: to search all repos started by km-poonacha sorted ascending you can make the following search request:

```<code>https://api.github.com/search/repositories?q=user:km-poonacha+sort:author-date-asc
</code>```

Ref: Sorting Search Results

Body:
For API (V3) you can include the sort qualifier in your query -  +sort:author-date-desc for descending and +sort:author-date-asc for ascending.

For example: to search all repos started by km-poonacha sorted ascending you can make the following search request:

https://api.github.com/search/repositories?q=user:km-poonacha+sort:author-date-asc

Ref: Sorting Search Results


问:
Could syntax check for your code be taken as distinct step?
I've had a dispute with some colleges on should I take a syntax check after every code modification as a distinct step or I'd better rely on unit tests to catch possible syntax breakage ... ( of course unit tests do that ).

This is not a question whether to use or not tests for your code ( of course yes, but see below )

My use case is pretty simple, I am newbie in Python and try to play with some web application (MVC) by modifying model file. The changes are quite simple, indeed a couple or so lines at once, however as I am pretty unfamiliar with Python syntax, some stupid errors ( like wrong indentation, so on ) easily creep into.

The real hurdle is that I deploy an application via Google Cloud Platform ( as app engine ), so it takes a while for application comes up with new version and I can hit an endpoint and finally look into its error logs to understand what's happening. So I'd like to get a shorter and simple way - at least for these types of errors - just running syntax check before deploy.

The central part of the dispute was that I hadn't been advised to take a syntax check explicitly, but better relying on higher level tests for this ( units tests for example ), on what I say that:

1) And don't have unit tests yet ( and even if I had them I'd treat them as a next step in my test chain ).

2) I only edit a certain file ( one and only one ), with a minimum modifications, and MOSTLY the types of errors I have ( as I told as I am newbie in Python ) is syntax errors, not logic or semantic ones, so as I assume I am safe to have just syntax checking and then give it a deploy. And even though I hit a semantic/logic problems with my code later ( even syntax check pass ) this is a undoubtedly question for high level tests ( unit / acceptance so on) - but for now I'm just playing with a code written in a language I am not feel quite at home.

3) I don't commit my changes outside and don't trouble anyone.

4) the last argument is controversial, because it's a bit of the scope, however I'd like to leave it here - in some cases even lightweight unit tests might be overkill if ALL you need is to get a syntax check in a single file. Consider this example. One just edits the code in place, deployed at server trying to fix immediate issues, so no unit or other tests exists and you want to be sure that your modification won't break the code syntactically.

答:
By default, Python completes a syntax check on the functions within your code. Additionally, this syntax check will look for any open brackets or unfinished lines of code to make sure the code will work properly. However, the syntax checker does not always highlight the problem directly. To fix this you will just have to look at the code yourself.

If you need to spell check things like variable names or strings I would advise copying the code into a spell checking program like Microsoft Word or Grammarly.

I hope this helps.


问:
QTableView doesn't update edited cell when button is clicked
I am using a QTableView as a row input method:
user fills the fields and then clicks on "Carica" button to perform the insertion (he's not supposed to full fill the entire row).

Suppose the user inserts (as in the image) the first field and then clicks "carica". Button code is triggered:

```<code>    QModelIndex index = modelprod->index(0, 0); //modelprod is model for the QTable
    qInfo() << index.data().toString();
</code>```

The program prints nothing! This is because tableview hasn't stored the value(note how the cell is surrounded in blue). Indeed if the user clicks something else before the button the program works as expected.

I need a way to update the model as soon as the user clicks the buttons.

REQUESTED CODE SAMPLE

mainwindow.cpp

```<code>MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),ui(new Ui::MainWindow){
    ui->setupUi(this);
    modelp = new QStandardItemModel(1,1,this);
    modelp->setHorizontalHeaderItem(0, new QStandardItem(QString("ID")));
    ui->tableView->setModel(modelp);
}
MainWindow::~MainWindow(){delete ui;}

void MainWindow::on_pushButton_clicked(){
    int rowcount = modelp->rowCount(QModelIndex());
    QModelIndex index = modelp->index(0, 0);
    modelp->setItem(rowcount,0, new QStandardItem(QString(index.data().toString())));
    //add the element in row 0 into a new row in the same tableView
}
</code>```

mainwindow.h

```<code>namespace Ui{class MainWindow;}
class MainWindow : public QMainWindow{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
private slots:
    void on_pushButton_clicked();
private:
    Ui::MainWindow *ui;
    QStandardItemModel *modelp;
};
</code>```

In the image, I am inserting in the cell "test". Without clicking anywhere else, I click the Button. A new empty row is created when the intent was to copy the first row content in the new one. Now if I click in the empty cell and then the button, it correctly writes it in a new cell.

答:
If you do not want to mess with the focus policy of the button, you can also force the table view to close its editor in the push button's click handler before accessing data, by forcing it to clear the focus:</p>

```<code>void MainWindow::on_pushButton_clicked()
{
    // finish any editing
    if (ui->tableView->focusWidget())
        ui->tableView->focusWidget()->clearFocus();
    // ... do something with the data in the table
}
</code>```

Body:
I am using a QTableView as a row input method:
user fills the fields and then clicks on "Carica" button to perform the insertion (he's not supposed to full fill the entire row).

Suppose the user inserts (as in the image) the first field and then clicks "carica". Button code is triggered:

    QModelIndex index = modelprod->index(0, 0); //modelprod is model for the QTable
    qInfo() << index.data().toString();

The program prints nothing! This is because tableview hasn't stored the value(note how the cell is surrounded in blue). Indeed if the user clicks something else before the button the program works as expected.

I need a way to update the model as soon as the user clicks the buttons.

REQUESTED CODE SAMPLE

mainwindow.cpp

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),ui(new Ui::MainWindow){
    ui->setupUi(this);
    modelp = new QStandardItemModel(1,1,this);
    modelp->setHorizontalHeaderItem(0, new QStandardItem(QString("ID")));
    ui->tableView->setModel(modelp);
}
MainWindow::~MainWindow(){delete ui;}

void MainWindow::on_pushButton_clicked(){
    int rowcount = modelp->rowCount(QModelIndex());
    QModelIndex index = modelp->index(0, 0);
    modelp->setItem(rowcount,0, new QStandardItem(QString(index.data().toString())));
    //add the element in row 0 into a new row in the same tableView
}

mainwindow.h

namespace Ui{class MainWindow;}
class MainWindow : public QMainWindow{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
private slots:
    void on_pushButton_clicked();
private:
    Ui::MainWindow *ui;
    QStandardItemModel *modelp;
};

In the image, I am inserting in the cell "test". Without clicking anywhere else, I click the Button. A new empty row is created when the intent was to copy the first row content in the new one. Now if I click in the empty cell and then the button, it correctly writes it in a new cell.

Body:
If you do not want to mess with the focus policy of the button, you can also force the table view to close its editor in the push button's click handler before accessing data, by forcing it to clear the focus:

void MainWindow::on_pushButton_clicked()
{
    // finish any editing
    if (ui->tableView->focusWidget())
        ui->tableView->focusWidget()->clearFocus();
    // ... do something with the data in the table
}


问:
Embed a Collection of Forms Error: Could not determine access type for property
I am trying to embed collection of Tag forms to Service form, according to this tutorial. Tag and Service entities have many-to-many relationship.

Form is rendering correctly. But when I submit form, I get

Could not determine access type for property "tagList"

error. I don't understand why new Tag object is not added to the Service class by calling the addTag() method.

ServiceType

```<code>public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('title', TextType::class, array(
            'label' => 'Title'
        ))
    ;

    $builder->add('tagList', CollectionType::class, array(
        'entry_type' => TagType::class,
        'allow_add' => true,
        'allow_delete' => true,
        'by_reference' => false
    )));
}
</code>```

Service class

```<code>{
....
 /**
 * @ORM\ManyToMany(targetEntity="Tag", mappedBy="serviceList",cascade={"persist"})
 */
private $tagList;

/**
 * @return ArrayCollection
 */
public function getTagList()
{
    return $this->tagList;
}

/**
 * @param Tag $tag
 * @return Service
 */
public function addTag(Tag $tag)
{
    if ($this->tagList->contains($tag) == false) {
        $this->tagList->add($tag);
        $tag->addService($this);
    }
}

/**
 * @param Tag $tag
 * @return Service
 */
public function removeTag(Tag $tag)
{
    if ($this->tagList->contains($tag)) {
        $this->tagList->removeElement($tag);
        $tag->removeService($this);
    }
    return $this;
}
}
</code>```

Tag class

```<code> {
  /**
 * @ORM\ManyToMany(targetEntity="Service", inversedBy="tagList")
 * @ORM\JoinTable(name="tags_services")
 */
private $serviceList;
 /**
 * @param Service $service
 * @return Tag
 */
public function addService(Service $service)
{
    if ($this->serviceList->contains($service) == false) {
        $this->serviceList->add($service);
        $service->addTag($this);
    }
    return $this;
}

/**
 * @param Service $service
 * @return Tag
 */
public function removeService(Service $service)
{
    if ($this->serviceList->contains($service)) {
        $this->serviceList->removeElement($service);
        $service->removeTag($this);
    }
    return $this;
}
 }
</code>```

ServiceController

```<code>  public function newAction(Request $request)
{
    $service = new Service();
    $form = $this->createForm('AppBundle\Form\ServiceType', $service);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $em = $this->getDoctrine()->getManager();
        $em->persist($service);
        $em->flush();

        return $this->redirectToRoute('service_show', array('id' => $service->getId()));
    }

    return $this->render('AppBundle:Service:new.html.twig', array(
        'service' => $service,
        'form' => $form->createView(),
    ));
}
</code>```

答:
Based on Symfony 3.3.10

I actually faced this problem many and many times, finally once i discovered where this problem was coming from, depending on the name you give to your entity property it can happen that the adder and the remover for your collection property aren't exactly what you are expecting.

Example: Your entity properity name is "foo" and you would expect the adder to be called "addFoo" and remover "removeFoo", but then all of a sudden the "Could not determine access type for property" appear.

So you start going into fear searching for w/e problems in your code, instead you just have to look this file inside Symfony core files:

vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php

Inside this file there's a method called findAdderAndRemover.
Go there with your debugger and you will eventually find out that symfony searches for weird name for your adder/remover, they may actually end with "um" or "on" or "us" depending on the language (human language) you used to name them. Since i'm Italian this happen quite often.

Watch out for that, since the fix may be as simple as changing the name used for your add/remove method inside your entity to make them match with what Symfony core is looking for.

This happens to me when i use bin/console doctrine:generate:entities to create the methods automatically for me

Body:
I am trying to embed collection of Tag forms to Service form, according to this tutorial. Tag and Service entities have many-to-many relationship.

Form is rendering correctly. But when I submit form, I get

Could not determine access type for property "tagList"

error. I don't understand why new Tag object is not added to the Service class by calling the addTag() method.

ServiceType

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('title', TextType::class, array(
            'label' => 'Title'
        ))
    ;

    $builder->add('tagList', CollectionType::class, array(
        'entry_type' => TagType::class,
        'allow_add' => true,
        'allow_delete' => true,
        'by_reference' => false
    )));
}

Service class

{
....
 /**
 * @ORM\ManyToMany(targetEntity="Tag", mappedBy="serviceList",cascade={"persist"})
 */
private $tagList;

/**
 * @return ArrayCollection
 */
public function getTagList()
{
    return $this->tagList;
}

/**
 * @param Tag $tag
 * @return Service
 */
public function addTag(Tag $tag)
{
    if ($this->tagList->contains($tag) == false) {
        $this->tagList->add($tag);
        $tag->addService($this);
    }
}

/**
 * @param Tag $tag
 * @return Service
 */
public function removeTag(Tag $tag)
{
    if ($this->tagList->contains($tag)) {
        $this->tagList->removeElement($tag);
        $tag->removeService($this);
    }
    return $this;
}
}

Tag class

 {
  /**
 * @ORM\ManyToMany(targetEntity="Service", inversedBy="tagList")
 * @ORM\JoinTable(name="tags_services")
 */
private $serviceList;
 /**
 * @param Service $service
 * @return Tag
 */
public function addService(Service $service)
{
    if ($this->serviceList->contains($service) == false) {
        $this->serviceList->add($service);
        $service->addTag($this);
    }
    return $this;
}

/**
 * @param Service $service
 * @return Tag
 */
public function removeService(Service $service)
{
    if ($this->serviceList->contains($service)) {
        $this->serviceList->removeElement($service);
        $service->removeTag($this);
    }
    return $this;
}
 }

ServiceController

  public function newAction(Request $request)
{
    $service = new Service();
    $form = $this->createForm('AppBundle\Form\ServiceType', $service);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $em = $this->getDoctrine()->getManager();
        $em->persist($service);
        $em->flush();

        return $this->redirectToRoute('service_show', array('id' => $service->getId()));
    }

    return $this->render('AppBundle:Service:new.html.twig', array(
        'service' => $service,
        'form' => $form->createView(),
    ));
}


问:
Java- set relative address for ImageDescriptor
I have a java plugin. In this plugin, I have a package namely org.eclipse.epsilon.eol and in this package I have an image namely configuration.png. In the one of the classes of this package I would like to use the below line of code. How can I set the relative address for it?

I tried several things such as configuration.png, eol/configuration.png and ./eol/configuration.png but they don't take effect. I also create a folder namely icon in the plugin and write icon/configuration.png but it doesn't take effect. What should I do?

```<code>setDefaultPageImageDescriptor(ImageDescriptor.createFromFile(null, "configuration.png"));
</code>```

答:
You can't use relative paths to access resources in plugins (not even the current plugin). When the plugin is packaged as a jar the contents can't be accessed directly as files.

To access resources in a plugin you must use the FileLocator API:

```<code>Bundle bundle = Platform.getBundle("plugin id");

URL url = FileLocator.find(bundle, new Path("path in the plugin"), null);

ImageDescriptor desc = ImageDescriptor.createFromURL(url);
</code>```

Body:
I have a java plugin. In this plugin, I have a package namely org.eclipse.epsilon.eol and in this package I have an image namely configuration.png. In the one of the classes of this package I would like to use the below line of code. How can I set the relative address for it?

I tried several things such as configuration.png, eol/configuration.png and ./eol/configuration.png but they don't take effect. I also create a folder namely icon in the plugin and write icon/configuration.png but it doesn't take effect. What should I do?

setDefaultPageImageDescriptor(ImageDescriptor.createFromFile(null, "configuration.png"));

Body:
You can't use relative paths to access resources in plugins (not even the current plugin). When the plugin is packaged as a jar the contents can't be accessed directly as files.

To access resources in a plugin you must use the FileLocator API:

Bundle bundle = Platform.getBundle("plugin id");

URL url = FileLocator.find(bundle, new Path("path in the plugin"), null);

ImageDescriptor desc = ImageDescriptor.createFromURL(url);


问:
Omnet++ 5.2 mac installation : Error
I follow all steps of the installation guide and when I try to open the omnet get this error:
An error ha ocurred. See the log file Users/xxxX/omnetpp-5.2/ide/omnetpp.app/Contents/Eclipse/configuration/1509461950402.log

The log file contains that:

```<code>!ENTRY org.eclipse.equinox.launcher 4 0 2017-10-31 16:19:02.116
!MESSAGE Exception launching the Eclipse Platform:
!STACK
java.lang.UnsupportedClassVersionError: org/eclipse/core/runtime/adaptor/EclipseStarter : Unsupported major.minor version 51.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:637)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:650)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:590)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1499)
</code>```

答:
I had the same problem(s;) and I think it's due to java.version=9.0.1 which does not work well with Eclipse coming with OMNeT++. My solution was as follows:

Install java8 using brew as described here. I.e.,

brew tap caskroom/versions

brew cask install java8

Update $PATH pointing to java8

export PATH=/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home/bin/:$PATH

After that I didn't get the error documented in ..omnetpp-5.2/samples/.metadata/.log and OMNeT++ IDE did start. Hope this helps...

Title: Omnet++ 5.2 mac installation : Error

Body:
I follow all steps of the installation guide and when I try to open the omnet get this error:
An error ha ocurred. See the log file Users/xxxX/omnetpp-5.2/ide/omnetpp.app/Contents/Eclipse/configuration/1509461950402.log

The log file contains that:

!ENTRY org.eclipse.equinox.launcher 4 0 2017-10-31 16:19:02.116
!MESSAGE Exception launching the Eclipse Platform:
!STACK
java.lang.UnsupportedClassVersionError: org/eclipse/core/runtime/adaptor/EclipseStarter : Unsupported major.minor version 51.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:637)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:650)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:590)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1499)