问:
SQL: how to randomly sample a number of values for each row
Suppose I have a table A (id string), what I need is to create a table B (id1 string, id2 string) such that, B.id2 is randomly sampled from A.id. B.id1 is the same as A.id. For example:

table A:

```<code>id
1
2
3
4
</code>```

table B:

```<code>id1   id2
 1     2
 1     3
 2     4
 2     3
 3     1
 3     2
 4     1
 4     4
</code>```

That is, for each id in A, randomly sample 2 id in A as a new column id2. How can I do this with SQL? I would prefer a sample without replacement. But it is ok if id2 equals id1. Thank you for helping me!

答:
An alternative would be to do a cross join and then take random rows.  For instance:

```<code>select a1.id, a2.id
from A a1 cross join
     A a2
where a1.id <> a2.id and
      rand() <= 0.01;
</code>```

This would be relatively efficient.  It would pull roughly 1% of the rows from the cross join.  You wouldn't be guaranteed the same number of rows for each id.

If you needed to get the same number for each id, you could extend this idea using variables:

```<code>select id1, id2
from (select a1.id as id1, a2.id as id2,
             (@rn := if(@i = a1.id, @rn + 1,
                        if(@i := a1.id, 1, 1)
                       )
             ) as rn
      from A a1 cross join
           A a2 cross join
           (select @i := -1, @rn := 0) params
      where a1.id <> a2.id
      order by a1.id, rand()
     ) aa
where rn <= 2;
</code>```

This will not have very good performance characteristics.  It should work okay on a table with up to a thousand rows or so.

Body:
Suppose I have a table A (id string), what I need is to create a table B (id1 string, id2 string) such that, B.id2 is randomly sampled from A.id. B.id1 is the same as A.id. For example:

table A:

id
1
2
3
4

table B:

id1   id2
 1     2
 1     3
 2     4
 2     3
 3     1
 3     2
 4     1
 4     4

That is, for each id in A, randomly sample 2 id in A as a new column id2. How can I do this with SQL? I would prefer a sample without replacement. But it is ok if id2 equals id1. Thank you for helping me!

Body:
An alternative would be to do a cross join and then take random rows.  For instance:

select a1.id, a2.id
from A a1 cross join
     A a2
where a1.id <> a2.id and
      rand() <= 0.01;

This would be relatively efficient.  It would pull roughly 1% of the rows from the cross join.  You wouldn't be guaranteed the same number of rows for each id.

If you needed to get the same number for each id, you could extend this idea using variables:

select id1, id2
from (select a1.id as id1, a2.id as id2,
             (@rn := if(@i = a1.id, @rn + 1,
                        if(@i := a1.id, 1, 1)
                       )
             ) as rn
      from A a1 cross join
           A a2 cross join
           (select @i := -1, @rn := 0) params
      where a1.id <> a2.id
      order by a1.id, rand()
     ) aa
where rn <= 2;

This will not have very good performance characteristics.  It should work okay on a table with up to a thousand rows or so.


来源: stackexchange

问:
Two values from one input in python?
This is somewhat of a simple question and I hate to ask it here, but I can't seem the find the answer anywhere else: is it possible to get multiple values from the user in one line of Python?

For instance, in C I can do something like this: scanf("%d %d", &var1, &var2). However, I can't figure out what the Python equivalent of that is. I figured it would just be something like var1, var2 = input("Enter two numbers here: "), but that doesn't work and I'm not complaining because it wouldn't make a whole lot of sense if it did.

Does anyone out there know a good way to do this elegantly and concisely?

答:
The easiest way that I found for myself was using split function with input
Like you have two variable a,b

```<code>a,b=input("Enter two numbers").split()
</code>```

That's it.
there is one more method(explicit method)
Eg- you want to take input in three values

```<code>value=input("Enter the line")
a,b,c=value.split()
</code>```

EASY..

OwnerDisplayName: Donovan

ContentLicense: CC BY-SA 3.0

Title: Two values from one input in python?

Body:
The easiest way that I found for myself was using split function with input
Like you have two variable a,b

a,b=input("Enter two numbers").split()

That's it.
there is one more method(explicit method)
Eg- you want to take input in three values

value=input("Enter the line")
a,b,c=value.split()

EASY..


问:
How to start Raspberry normally after changing crontab?
I've done some changes on crontab to run a python script on startup but now I don't know how to make it go back to normal (boot normally).

@Edit: my raspberry starts, the screen goes black and I can't see/do nothing.

Is there a way to boot like in windows safe mode?

How can I solve this?

答:
Best answer would be to

crontab -e then comment out each line you don't want to run with #.


问:
routing issue with Sonata admin news post in symfony
Getting an error trying to set up the Sonata Admin bundle, get the following error when I got to http://localhost:8000/admin/dashboard, not sure how to solve this? Thanks!

Error
     An exception has been thrown during the rendering of a template ("Unable to generate a URL for the named route "admin_sonata_news_post_create" as such route does not exist.

This is my appKernal.php file

```<code>class AppKernel extends Kernel {
public function registerBundles()
{
    $bundles = array(
        new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
        new Symfony\Bundle\SecurityBundle\SecurityBundle(),
        new Symfony\Bundle\TwigBundle\TwigBundle(),
        new Symfony\Bundle\MonologBundle\MonologBundle(),
        new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
        new Symfony\Bundle\AsseticBundle\AsseticBundle(),
        new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
        new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
        new Sonata\CoreBundle\SonataCoreBundle(),
        new Sonata\BlockBundle\SonataBlockBundle(),
        new Ivory\CKEditorBundle\IvoryCKEditorBundle(),
        new Sonata\NewsBundle\SonataNewsBundle(),
        new Sonata\UserBundle\SonataUserBundle(),
        new Sonata\MediaBundle\SonataMediaBundle(),
        new Sonata\AdminBundle\SonataAdminBundle(),
        new Sonata\IntlBundle\SonataIntlBundle(),
        new Sonata\FormatterBundle\SonataFormatterBundle(),
        new Sonata\ClassificationBundle\SonataClassificationBundle(),
        new FOS\UserBundle\FOSUserBundle(),
        new Knp\Bundle\MarkdownBundle\KnpMarkdownBundle(),
        new Knp\Bundle\MenuBundle\KnpMenuBundle(),
        new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
        new Sonata\EasyExtendsBundle\SonataEasyExtendsBundle(),
        new JMS\SerializerBundle\JMSSerializerBundle(),
        new Application\Sonata\MediaBundle\ApplicationSonataMediaBundle(),
        new Application\Sonata\NewsBundle\ApplicationSonataNewsBundle(),
        new Application\Sonata\ClassificationBundle\ApplicationSonataClassificationBundle(),
        new Application\Sonata\UserBundle\ApplicationSonataUserBundle()
    );
</code>```

Config_dev.yml

```<code> imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: sonata_news.yml }
- { resource: sonata_classification.yml }
- { resource: sonata_media.yml }
- { resource: sonata_formatter.yml }

 framework:
#esi:             ~
translator:      { fallbacks: "%locale%" }
secret:          "%secret%"
router:
    resource: "%kernel.root_dir%/config/routing.yml"
    strict_requirements: ~
form:            ~
csrf_protection: ~
validation:      { enable_annotations: true }
templating:
    engines: ['twig']
    #assets_version: SomeVersionScheme
default_locale:  "%locale%"
trusted_hosts:   ~
trusted_proxies: ~
session:
    # handler_id set to null will use default session handler from php.ini
    handler_id:  ~
fragments:       ~
http_method_override: true

# Twig Configuration
twig:
debug:            "%kernel.debug%"
strict_variables: "%kernel.debug%"
#Sonata with Symfony >= 2.6
form_themes:
   - 'SonataFormatterBundle:Form:formatter.html.twig'

    #Sonata with Symfony <=2.5
    #form:
    #    resources:
    #        - 'SonataFormatterBundle:Form:formatter.html.twig'
  sonata_formatter:
formatters:
    markdown:
        service: sonata.formatter.text.markdown
        extensions:
            - sonata.formatter.twig.control_flow
            - sonata.formatter.twig.gist
            - sonata.media.formatter.twig #keep this commented unless you are using media bundle.

    text:
        service: sonata.formatter.text.text
        extensions:
            - sonata.formatter.twig.control_flow
            - sonata.formatter.twig.gist
            - sonata.media.formatter.twig

    rawhtml:
        service: sonata.formatter.text.raw
        extensions:
            - sonata.formatter.twig.control_flow
            - sonata.formatter.twig.gist
            - sonata.media.formatter.twig

    richhtml:
        service: sonata.formatter.text.raw
        extensions:
            - sonata.formatter.twig.control_flow
            - sonata.formatter.twig.gist
            - sonata.media.formatter.twig

    twig:
        service: sonata.formatter.text.twigengine
        extensions: [] # Twig formatter cannot have extensions

# app/config/config.yml
assetic:
debug:          "%kernel.debug%"
use_controller: "%kernel.debug%"
bundles:        [intomusiceventsBundle,intomusicfestivalBundle]

#node: /usr/bin/node

filters:
    uglifyjs2:
        # the path to the uglifyjs executable
        bin: /usr/bin/uglifyjs
    #uglifycss:
       # bin: /usr/local/bin/uglifycss
    #cssrewrite:
      #  apply_to: "\.css$"
#java: /usr/bin/java

  # Doctrine Configuration
doctrine:

dbal:
    driver:   "%database_driver%"
    host:     "%database_host%"
    port:     "%database_port%"
    dbname:   "%database_name%"
    user:     "%database_user%"
    password: "%database_password%"
    charset:  UTF8
    types:
        json: Sonata\Doctrine\Types\JsonType

    # if using pdo_sqlite as your database driver, add the path in  parameters.yml
    # e.g. database_path: "%kernel.root_dir%/data/data.db3"
    # path:     "%database_path%"

orm:
  #  auto_generate_proxy_classes: "%kernel.debug%"
   entity_managers:
        default:
           #naming_strategy: doctrine.orm.naming_strategy.underscore
          auto_mapping: true
          mappings:
            SonataNewsBundle: ~
            SonataMediaBundle: ~
            SonataClassificationBundle: ~

 sonata_media:
 # if you don't use default namespace configuration
 #class:
 #    media:        MyVendor\MediaBundle\Entity\Media
 #    gallery:      MyVendor\MediaBundle\Entity\Gallery
 #    gallery_item: MyVendor\MediaBundle\Entity\GalleryItem
       db_driver: doctrine_orm # or doctrine_mongodb, doctrine_phpcr   it is     mandatory to choose one here
 default_context: default # you need to set a context
 contexts:
     default:  # the default context is mandatory
         providers:
             - sonata.media.provider.dailymotion
             - sonata.media.provider.youtube
             - sonata.media.provider.image
             - sonata.media.provider.file
             - sonata.media.provider.vimeo

         formats:
             small: { width: 100 , quality: 70}
             big:   { width: 500 , quality: 70}

 cdn:
     server:
         path: /uploads/media # http://media.sonata-project.org/

 filesystem:
     local:
         directory:  "%kernel.root_dir%/../web/uploads/media"
         create:     false

sonata_block:
default_contexts: [cms]
blocks:
    # enable the SonataAdminBundle block
            sonata.admin.block.admin_list:
               contexts: [admin]

# app/config/config.yml
fos_user:
db_driver: orm # other valid values are 'mongodb', 'couchdb' and   'propel'
firewall_name: secured_area
user_class: Application\Sonata\UserBundle\Entity\User
group:
   group_class: Application\Sonata\UserBundle\Entity\User
</code>```

routing.yml file

```<code> gallery:
resource: '@SonataMediaBundle/Resources/config/routing/gallery.xml'
prefix: /media/gallery

 media:
resource: '@SonataMediaBundle/Resources/config/routing/media.xml'
prefix: /media

news:
resource: '@SonataNewsBundle/Resources/config/routing/news.xml'
prefix: /news

admin_area:
resource:    "@SonataAdminBundle/Resources/config/routing/sonata_admin.xml"
prefix: /admin
</code>```

答:
Found that I needed to add ApplicaqtionSonataUserBundle as below

```<code>orm:
 #  auto_generate_proxy_classes: "%kernel.debug%"
 entity_managers:
    default:
       #naming_strategy: doctrine.orm.naming_strategy.underscore
      auto_mapping: true
      mappings:
        ApplicationSonataUserBundle: ~
        SonataNewsBundle: ~
        SonataMediaBundle: ~
        SonataClassificationBundle: ~
</code>```

Then routing more routing

```<code>    fos_user_security:
resource: "@FOSUserBundle/Resources/config/routing/security.xml"

 fos_user_profile:
resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
prefix: /profile

fos_user_register:
resource: "@FOSUserBundle/Resources/config/routing/registration.xml"
prefix: /register

fos_user_resetting:
resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
prefix: /resetting

fos_user_change_password:
resource:
"@FOSUserBundle/Resources/config/routing/change_password.xml"
 prefix: /change-password

 admin:
 resource:
'@SonataAdminBundle/Resources/config/routing/sonata_admin.xml'
prefix: /admin

_sonata_admin:
resource: .
type: sonata_admin
prefix: /admin

 sonata_user:
 resource:
  '@SonataUserBundle/Resources/config/routing/admin_security.xml'
prefix: /admin

sonata_user_impersonating:
pattern: /
defaults: { _controller: SonataPageBundle:Page:catchAll }
</code>```

Then clear the cache, now I get an admin panel but more errors trying to post anything ;( would've been quicker to write my own blog bundle

Body:
Getting an error trying to set up the Sonata Admin bundle, get the following error when I got to http://localhost:8000/admin/dashboard, not sure how to solve this? Thanks!

Error
     An exception has been thrown during the rendering of a template ("Unable to generate a URL for the named route "admin_sonata_news_post_create" as such route does not exist.

This is my appKernal.php file

class AppKernel extends Kernel {
public function registerBundles()
{
    $bundles = array(
        new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
        new Symfony\Bundle\SecurityBundle\SecurityBundle(),
        new Symfony\Bundle\TwigBundle\TwigBundle(),
        new Symfony\Bundle\MonologBundle\MonologBundle(),
        new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
        new Symfony\Bundle\AsseticBundle\AsseticBundle(),
        new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
        new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
        new Sonata\CoreBundle\SonataCoreBundle(),
        new Sonata\BlockBundle\SonataBlockBundle(),
        new Ivory\CKEditorBundle\IvoryCKEditorBundle(),
        new Sonata\NewsBundle\SonataNewsBundle(),
        new Sonata\UserBundle\SonataUserBundle(),
        new Sonata\MediaBundle\SonataMediaBundle(),
        new Sonata\AdminBundle\SonataAdminBundle(),
        new Sonata\IntlBundle\SonataIntlBundle(),
        new Sonata\FormatterBundle\SonataFormatterBundle(),
        new Sonata\ClassificationBundle\SonataClassificationBundle(),
        new FOS\UserBundle\FOSUserBundle(),
        new Knp\Bundle\MarkdownBundle\KnpMarkdownBundle(),
        new Knp\Bundle\MenuBundle\KnpMenuBundle(),
        new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
        new Sonata\EasyExtendsBundle\SonataEasyExtendsBundle(),
        new JMS\SerializerBundle\JMSSerializerBundle(),
        new Application\Sonata\MediaBundle\ApplicationSonataMediaBundle(),
        new Application\Sonata\NewsBundle\ApplicationSonataNewsBundle(),
        new Application\Sonata\ClassificationBundle\ApplicationSonataClassificationBundle(),
        new Application\Sonata\UserBundle\ApplicationSonataUserBundle()
    );

Config_dev.yml

 imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: sonata_news.yml }
- { resource: sonata_classification.yml }
- { resource: sonata_media.yml }
- { resource: sonata_formatter.yml }

 framework:
#esi:             ~
translator:      { fallbacks: "%locale%" }
secret:          "%secret%"
router:
    resource: "%kernel.root_dir%/config/routing.yml"
    strict_requirements: ~
form:            ~
csrf_protection: ~
validation:      { enable_annotations: true }
templating:
    engines: ['twig']
    #assets_version: SomeVersionScheme
default_locale:  "%locale%"
trusted_hosts:   ~
trusted_proxies: ~
session:
    # handler_id set to null will use default session handler from php.ini
    handler_id:  ~
fragments:       ~
http_method_override: true

# Twig Configuration
twig:
debug:            "%kernel.debug%"
strict_variables: "%kernel.debug%"
#Sonata with Symfony >= 2.6
form_themes:
   - 'SonataFormatterBundle:Form:formatter.html.twig'

    #Sonata with Symfony <=2.5
    #form:
    #    resources:
    #        - 'SonataFormatterBundle:Form:formatter.html.twig'
  sonata_formatter:
formatters:
    markdown:
        service: sonata.formatter.text.markdown
        extensions:
            - sonata.formatter.twig.control_flow
            - sonata.formatter.twig.gist
            - sonata.media.formatter.twig #keep this commented unless you are using media bundle.

    text:
        service: sonata.formatter.text.text
        extensions:
            - sonata.formatter.twig.control_flow
            - sonata.formatter.twig.gist
            - sonata.media.formatter.twig

    rawhtml:
        service: sonata.formatter.text.raw
        extensions:
            - sonata.formatter.twig.control_flow
            - sonata.formatter.twig.gist
            - sonata.media.formatter.twig

    richhtml:
        service: sonata.formatter.text.raw
        extensions:
            - sonata.formatter.twig.control_flow
            - sonata.formatter.twig.gist
            - sonata.media.formatter.twig

    twig:
        service: sonata.formatter.text.twigengine
        extensions: [] # Twig formatter cannot have extensions

# app/config/config.yml
assetic:
debug:          "%kernel.debug%"
use_controller: "%kernel.debug%"
bundles:        [intomusiceventsBundle,intomusicfestivalBundle]

#node: /usr/bin/node

filters:
    uglifyjs2:
        # the path to the uglifyjs executable
        bin: /usr/bin/uglifyjs
    #uglifycss:
       # bin: /usr/local/bin/uglifycss
    #cssrewrite:
      #  apply_to: "\.css$"
#java: /usr/bin/java

  # Doctrine Configuration
doctrine:

dbal:
    driver:   "%database_driver%"
    host:     "%database_host%"
    port:     "%database_port%"
    dbname:   "%database_name%"
    user:     "%database_user%"
    password: "%database_password%"
    charset:  UTF8
    types:
        json: Sonata\Doctrine\Types\JsonType

    # if using pdo_sqlite as your database driver, add the path in  parameters.yml
    # e.g. database_path: "%kernel.root_dir%/data/data.db3"
    # path:     "%database_path%"

orm:
  #  auto_generate_proxy_classes: "%kernel.debug%"
   entity_managers:
        default:
           #naming_strategy: doctrine.orm.naming_strategy.underscore
          auto_mapping: true
          mappings:
            SonataNewsBundle: ~
            SonataMediaBundle: ~
            SonataClassificationBundle: ~

 sonata_media:
 # if you don't use default namespace configuration
 #class:
 #    media:        MyVendor\MediaBundle\Entity\Media
 #    gallery:      MyVendor\MediaBundle\Entity\Gallery
 #    gallery_item: MyVendor\MediaBundle\Entity\GalleryItem
       db_driver: doctrine_orm # or doctrine_mongodb, doctrine_phpcr   it is     mandatory to choose one here
 default_context: default # you need to set a context
 contexts:
     default:  # the default context is mandatory
         providers:
             - sonata.media.provider.dailymotion
             - sonata.media.provider.youtube
             - sonata.media.provider.image
             - sonata.media.provider.file
             - sonata.media.provider.vimeo

         formats:
             small: { width: 100 , quality: 70}
             big:   { width: 500 , quality: 70}

 cdn:
     server:
         path: /uploads/media # http://media.sonata-project.org/

 filesystem:
     local:
         directory:  "%kernel.root_dir%/../web/uploads/media"
         create:     false

sonata_block:
default_contexts: [cms]
blocks:
    # enable the SonataAdminBundle block
            sonata.admin.block.admin_list:
               contexts: [admin]

# app/config/config.yml
fos_user:
db_driver: orm # other valid values are 'mongodb', 'couchdb' and   'propel'
firewall_name: secured_area
user_class: Application\Sonata\UserBundle\Entity\User
group:
   group_class: Application\Sonata\UserBundle\Entity\User

routing.yml file

 gallery:
resource: '@SonataMediaBundle/Resources/config/routing/gallery.xml'
prefix: /media/gallery

 media:
resource: '@SonataMediaBundle/Resources/config/routing/media.xml'
prefix: /media

news:
resource: '@SonataNewsBundle/Resources/config/routing/news.xml'
prefix: /news

admin_area:
resource:    "@SonataAdminBundle/Resources/config/routing/sonata_admin.xml"
prefix: /admin

Body:
Found that I needed to add ApplicaqtionSonataUserBundle as below

orm:
 #  auto_generate_proxy_classes: "%kernel.debug%"
 entity_managers:
    default:
       #naming_strategy: doctrine.orm.naming_strategy.underscore
      auto_mapping: true
      mappings:
        ApplicationSonataUserBundle: ~
        SonataNewsBundle: ~
        SonataMediaBundle: ~
        SonataClassificationBundle: ~

Then routing more routing

    fos_user_security:
resource: "@FOSUserBundle/Resources/config/routing/security.xml"

 fos_user_profile:
resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
prefix: /profile

fos_user_register:
resource: "@FOSUserBundle/Resources/config/routing/registration.xml"
prefix: /register

fos_user_resetting:
resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
prefix: /resetting

fos_user_change_password:
resource:
"@FOSUserBundle/Resources/config/routing/change_password.xml"
 prefix: /change-password

 admin:
 resource:
'@SonataAdminBundle/Resources/config/routing/sonata_admin.xml'
prefix: /admin

_sonata_admin:
resource: .
type: sonata_admin
prefix: /admin

 sonata_user:
 resource:
  '@SonataUserBundle/Resources/config/routing/admin_security.xml'
prefix: /admin

sonata_user_impersonating:
pattern: /
defaults: { _controller: SonataPageBundle:Page:catchAll }

Then clear the cache, now I get an admin panel but more errors trying to post anything ;( would've been quicker to write my own blog bundle


问:
File produced by r.js powered Node build script doesn't appear to do anything

The source

My src has the following structure :

```<code>src
|-- index.html
|-- js
|    |-- amdconfig.js
|    |-- main.js
|    |-- ...
|-- lib
     |-- require
     |    |-- require.js
     |-- d3
     |    |-- d3.js
     |-- luciad
          |-- ...
</code>```

My index.html contains the following code :

```<code><script src="./lib/requirejs/require.js" type="text/javascript"></script><!-- require.js -->
<script src="./js/amdconfig.js" type="text/javascript"></script><!-- require.js config -->
<script type="text/javascript">
    require(["app/js/main"]); /* main module */
</script>
</code>```

My amdconfig.js file contains the following code :

```<code>(function(configure, app) {
  var lib = [app, "lib"].join("/");
  configure({
    baseUrl : app,
    urlArgs : "bust=" + (new Date()).getTime(),
    packages : [{
      name : "requirejs",
      location : [lib, "requirejs"].join("/")
    }, {
      name : "luciad",
      location : [lib, "luciad"].join("/")
    }, {
      name : "d3",
      location : [lib, "d3"].join("/")
    }, {
      name : "app",
      location : app
    }],
    cache : {}
  })
})(
  require.config ? require.config /* RequireJS */ : require, /* Dojo */
  '.'
)
</code>```

My build script

I have a build script with the following structure :

```<code>builder
|-- build.js
|-- package.json
</code>```

If has the following code :

```<code>require('requirejs').optimize({
  baseUrl: '../src',
  paths: {
    main: 'main',
    requirejs : './lib/requirejs',
    luciad : './lib/luciad',
    d3 : './lib/d3',
    app : './'
  },
  name: 'js/main',
  out : '../dist/main.js',
  optimize: "uglify2",
  uglify2: {
    output: {
      beautify: false
    },
    compress: {},
    warnings: true,
    mangle: true
  }
}, function (buildResponse) {
  console.log(buildResponse);
});
</code>```

My problem

The build script does produce a minified main.js file and outputs the list of included files in the console, as expected.

However, when I replace the main.js of my src with the main.js I just generated, nothing happens. My app doesn't start and I'm not getting any errors.

What am I missing here?

Note

If I don't minify my code, I get the same behavior.

The generated file consists of a whole bunch of modules in this format :

```<code>define('namespaced/path',["dependency1", "dependency2"], function(a,b){...});
</code>```

I suppose that is the expected format...

答:
I managed to figure out what caused my issue.

The produced output looked something this :

```<code>define('luciad/util/create',[],function(){...});
define('luciad/error/_createError',["../util/create"],function(a){...});
define('luciad/error/ProgrammingError',["./_createError"],function(a){...)});
...
define('js/main',[...],function(...){...});
</code>```

Note the last line. There, my main module is called js/main. However, my main module is called in my HTML file like this :

```<code>require(["app/js/main"]);
</code>```

So, what happened, was that require(["app/js/main"]) failed silently because it couldn't find a module named app/js/main.

The solution was surprisingly simple. All I had to do, was rename the name parameter from js/main to app/js/main. Now, everything works as expected.

I don't know how I could have missed this, but I guess the silent fail of require(["app/js/main"]) didn't exactly help.

Body:
The source

My src has the following structure :

src
|-- index.html
|-- js
|    |-- amdconfig.js
|    |-- main.js
|    |-- ...
|-- lib
     |-- require
     |    |-- require.js
     |-- d3
     |    |-- d3.js
     |-- luciad
          |-- ...

My index.html contains the following code :

My amdconfig.js file contains the following code :

(function(configure, app) {
  var lib = [app, "lib"].join("/");
  configure({
    baseUrl : app,
    urlArgs : "bust=" + (new Date()).getTime(),
    packages : [{
      name : "requirejs",
      location : [lib, "requirejs"].join("/")
    }, {
      name : "luciad",
      location : [lib, "luciad"].join("/")
    }, {
      name : "d3",
      location : [lib, "d3"].join("/")
    }, {
      name : "app",
      location : app
    }],
    cache : {}
  })
})(
  require.config ? require.config /* RequireJS */ : require, /* Dojo */
  '.'
)

My build script

I have a build script with the following structure :

builder
|-- build.js
|-- package.json

If has the following code :

require('requirejs').optimize({
  baseUrl: '../src',
  paths: {
    main: 'main',
    requirejs : './lib/requirejs',
    luciad : './lib/luciad',
    d3 : './lib/d3',
    app : './'
  },
  name: 'js/main',
  out : '../dist/main.js',
  optimize: "uglify2",
  uglify2: {
    output: {
      beautify: false
    },
    compress: {},
    warnings: true,
    mangle: true
  }
}, function (buildResponse) {
  console.log(buildResponse);
});

My problem

The build script does produce a minified main.js file and outputs the list of included files in the console, as expected.

However, when I replace the main.js of my src with the main.js I just generated, nothing happens. My app doesn't start and I'm not getting any errors.

What am I missing here?

Note

If I don't minify my code, I get the same behavior.

The generated file consists of a whole bunch of modules in this format :

define('namespaced/path',["dependency1", "dependency2"], function(a,b){...});

I suppose that is the expected format...

Body:
I managed to figure out what caused my issue.

The produced output looked something this :

define('luciad/util/create',[],function(){...});
define('luciad/error/_createError',["../util/create"],function(a){...});
define('luciad/error/ProgrammingError',["./_createError"],function(a){...)});
...
define('js/main',[...],function(...){...});

Note the last line. There, my main module is called js/main. However, my main module is called in my HTML file like this :

require(["app/js/main"]);

So, what happened, was that require(["app/js/main"]) failed silently because it couldn't find a module named app/js/main.

The solution was surprisingly simple. All I had to do, was rename the name parameter from js/main to app/js/main. Now, everything works as expected.

I don't know how I could have missed this, but I guess the silent fail of require(["app/js/main"]) didn't exactly help.


问:
Input connection for numeric type keyboard
I did my custom pin-code view

```<code>class StarsPasswordView : LinearLayout {

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
        init(context, attrs)
    }

    val passwordHolder = SpannableStringBuilder()

    var count

    fun init(context: Context, attrs: AttributeSet?) {
        orientation = HORIZONTAL
        isFocusable = true
        isFocusableInTouchMode = true
        gravity = Gravity.CENTER

        val attr = context.obtainStyledAttributes(attrs, R.styleable.StarsPasswordView, 0, 0)
        count = attr.getInteger(R.styleable.StarsPasswordView_count, 4)
        attr.recycle()

        drawView(count)

        setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_ENTER)
                    return@OnKeyListener true
                if (keyCode == KeyEvent.KEYCODE_BACK)
                    return@OnKeyListener false
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    clear()
                    get(0).requestFocus()
                } else
                    if (passwordHolder.length != count) {
                        passwordHolder.append(event.number)
                        val position = passwordHolder.length
                        select(position - 1)

                        if (position < count)
                            get(position).requestFocus()
                        else {
                            passwordFilled?.invoke(passwordHolder.toString())
                        }
                    }
                return@OnKeyListener true
            }
            false
        })
    }

    fun samsungWorkaround() {
        val position = passwordHolder.length
        select(position - 1)

        if (position == count)
            passwordFilled?.invoke(passwordHolder.toString())
        }
    }

    // toggle whether the keyboard is showing when the view is clicked
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (enableKeyboard && event.action == MotionEvent.ACTION_UP) {
            val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_IMPLICIT_ONLY)
        }
        return true
    }

    override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection {
        outAttrs.inputType = InputType.TYPE_CLASS_NUMBER
        return InputConnection(this, true)
    }
}

class InputConnection internal constructor(val targetView: StarsPasswordView, fullEditor: Boolean) : BaseInputConnection(targetView, fullEditor) {

    override fun getEditable(): Editable {
        return targetView.passwordHolder
    }
    override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
        val res =  super.commitText(text, newCursorPosition)
        targetView.samsungWorkaround()
        return res
    }
}
</code>```

The problem comes when you want to set

```<code> outAttrs.inputType = InputType.TYPE_CLASS_NUMBER
</code>```

at this case

InputConnection doesn't handle numbers

getEditable() doesn't fire

commitText() doesn't fire

so my workaround was just handling numbs in setOnKeyListener as you can see above.

Does anyone know what the issue is?

答:
Depending on the keyboard, not all keys are sent through the InputConnection. Some are sent like hard keys events and must be processed separately. This includes the number pad numbers on the standard keyboard. To the best of my current knowledge, using the OnKeyListener like you did is the way to go (but see @pskink's comments here).

You can separate the text characters from the control characters with KeyEvent.getUnicodeChar() as is shown below.

```<code>if (keyEvent.getUnicodeChar() != 0) {
    // unicode text
    char unicodeChar = (char) keyEvent.getUnicodeChar();
} else {
    // control char
}
</code>```

Handle the control codes that you need, but all the valid Unicode characters (including numbers and the new line (enter) character) will be caught.

I cover some aspects of this in more detail in the question and answers I wrote while preparing to answer this question.

Differentiating text keycode from control keycode in Android KeyEvent

Need table of key codes for android and presenter

I also updated my previous answer about custom views receiving keyboard input.

Body:
I did my custom pin-code view

class StarsPasswordView : LinearLayout {

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
        init(context, attrs)
    }

    val passwordHolder = SpannableStringBuilder()

    var count

    fun init(context: Context, attrs: AttributeSet?) {
        orientation = HORIZONTAL
        isFocusable = true
        isFocusableInTouchMode = true
        gravity = Gravity.CENTER

        val attr = context.obtainStyledAttributes(attrs, R.styleable.StarsPasswordView, 0, 0)
        count = attr.getInteger(R.styleable.StarsPasswordView_count, 4)
        attr.recycle()

        drawView(count)

        setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_ENTER)
                    return@OnKeyListener true
                if (keyCode == KeyEvent.KEYCODE_BACK)
                    return@OnKeyListener false
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    clear()
                    get(0).requestFocus()
                } else
                    if (passwordHolder.length != count) {
                        passwordHolder.append(event.number)
                        val position = passwordHolder.length
                        select(position - 1)

                        if (position < count)
                            get(position).requestFocus()
                        else {
                            passwordFilled?.invoke(passwordHolder.toString())
                        }
                    }
                return@OnKeyListener true
            }
            false
        })
    }

    fun samsungWorkaround() {
        val position = passwordHolder.length
        select(position - 1)

        if (position == count)
            passwordFilled?.invoke(passwordHolder.toString())
        }
    }

    // toggle whether the keyboard is showing when the view is clicked
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (enableKeyboard && event.action == MotionEvent.ACTION_UP) {
            val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_IMPLICIT_ONLY)
        }
        return true
    }

    override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection {
        outAttrs.inputType = InputType.TYPE_CLASS_NUMBER
        return InputConnection(this, true)
    }
}

class InputConnection internal constructor(val targetView: StarsPasswordView, fullEditor: Boolean) : BaseInputConnection(targetView, fullEditor) {

    override fun getEditable(): Editable {
        return targetView.passwordHolder
    }
    override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
        val res =  super.commitText(text, newCursorPosition)
        targetView.samsungWorkaround()
        return res
    }
}

The problem comes when you want to set

 outAttrs.inputType = InputType.TYPE_CLASS_NUMBER

at this case

InputConnection doesn't handle numbers

getEditable() doesn't fire

commitText() doesn't fire

so my workaround was just handling numbs in setOnKeyListener as you can see above.

Does anyone know what the issue is?

Body:
Depending on the keyboard, not all keys are sent through the InputConnection. Some are sent like hard keys events and must be processed separately. This includes the number pad numbers on the standard keyboard. To the best of my current knowledge, using the OnKeyListener like you did is the way to go (but see @pskink's comments here).

You can separate the text characters from the control characters with KeyEvent.getUnicodeChar() as is shown below.

if (keyEvent.getUnicodeChar() != 0) {
    // unicode text
    char unicodeChar = (char) keyEvent.getUnicodeChar();
} else {
    // control char
}

Handle the control codes that you need, but all the valid Unicode characters (including numbers and the new line (enter) character) will be caught.

I cover some aspects of this in more detail in the question and answers I wrote while preparing to answer this question.

Differentiating text keycode from control keycode in Android KeyEvent

Need table of key codes for android and presenter

I also updated my previous answer about custom views receiving keyboard input.


问:
Image not displayed from static
I am using a csv file to display an image on my django template. The csv file is like

```<code>id | Name  | image
-- | ----- | --------------------
 1 | wine1 | images\download1.jpg
</code>```

i have kept the image in the static file

my  wine_list.html is as

```<code>{% for wine in wine_list %}
    <div>
        <h4><a href="{% url 'reviews:wine_detail' wine.id %}">
        {{ wine.name}}</a><br>
        {% if wine.description != "nan" %}
        <h4>{{ wine.description }}</h4>
        {% else %}
        <h1> No Description available
        {% endif %}
        <h3>'{{ wine.images.url }}'</h3>
        <br>
        <a>  <img src="{% static '{{ wine.images.url }}' %}" height="200"></a>
</code>```

the name and description shows fine, and the

wine.images.url

prints

images/download.jpg

shouldn't the image be printed ?

my image folder is in my static, when i print it like this

```<code><a>  <img src="{% static 'images/download.jpg' %}" height="200"></a>
</code>```

it does display the image.

答:
Just simply use wine.images.url as a param of static

```<code><img src="{% static wine.images.url %}" height="200">
</code>```

Title: Image not displayed from static

Body:
I am using a csv file to display an image on my django template. The csv file is like

id | Name  | image
-- | ----- | --------------------
 1 | wine1 | images\download1.jpg

i have kept the image in the static file

my  wine_list.html is as

{% for wine in wine_list %}

        {{ wine.name}}

        {% if wine.description != "nan" %}

{{ wine.description }}

        {% else %}

 No Description available
        {% endif %}

'{{ wine.images.url }}'

the name and description shows fine, and the

wine.images.url

prints

images/download.jpg

shouldn't the image be printed ?

my image folder is in my static, when i print it like this

it does display the image.

Body:
Just simply use wine.images.url as a param of static

<img src="{% static wine.images.url %}" height="200">


问:
Last seen a user in django
How can i show the time of last seen(be online)of user in django?
Is there any default function or library to import it to do that?

Or if there any code inn github tell me please

**Note : ** when a user close page or disconnect the time update

答: You should inherit django's AbstractBaseUser in your user model, it already has an inbuilt last_login attribute. In fact it is considered a good practice to inherit AbstractBaseUser for creating your user which is provided in django default auth modules.

Title: Last seen a user in django


问:
C# MVC - Using LIKE in LINQ query
I want to display names from a SQL database that ends with certain char but it won't let me use WildCard in the Controller ActionResult.

This is my current code that I want to work.

```<code>public ActionResult GetClients()
    {
        MyDBEntities myDBEntites = new MyDBEntities();
        var clients = from c in myDBEntites.Client
                      where c.name LIKE '%r'
                      select c;
        return View(clients);

    }
</code>```

What am I missing here for it to work? If its not working with wild card then how do I get the names that ends with a specific char?

答:
You can use EndsWith

```<code>public ActionResult GetClients()
    {
        MyDBEntities myDBEntites = new MyDBEntities();
        var clients = from c in myDBEntites.Client
                      where c.name.EndsWith("r")
                      select c;
        return View(clients);

    }
</code>```

Title: C# MVC - Using LIKE in LINQ query

Body:
I want to display names from a SQL database that ends with certain char but it won't let me use WildCard in the Controller ActionResult.

This is my current code that I want to work.

public ActionResult GetClients()
    {
        MyDBEntities myDBEntites = new MyDBEntities();
        var clients = from c in myDBEntites.Client
                      where c.name LIKE '%r'
                      select c;
        return View(clients);

    }

What am I missing here for it to work? If its not working with wild card then how do I get the names that ends with a specific char?

Body:
You can use EndsWith

public ActionResult GetClients()
    {
        MyDBEntities myDBEntites = new MyDBEntities();
        var clients = from c in myDBEntites.Client
                      where c.name.EndsWith("r")
                      select c;
        return View(clients);

    }


问:
R calculating proportion over two-way-table with two categorical variables and add new variable
I am very new to R. I cannot find an answer to my following problem: How do I easily calculate the proportion over a two-way-table of two categorical variables and add that value as a new variable? I would like to use dplyr and mutate.

```<code>Gender <- c("Female","Female","Male","Male")
Believer <- c("Yes","No","Yes","No")
Count <- c(100,50,200,150)
dat <- data.frame(Gender,Believer,Count)

dat
Gender Believer Count
1 Female      Yes   100
2 Female       No    50
3   Male      Yes   200
4   Male       No   150

str(dat)
'data.frame':   4 obs. of  3 variables:
 $ Gender  : Factor w/ 2 levels "Female","Male": 1 1 2 2
 $ Believer: Factor w/ 2 levels "No","Yes": 2 1 2 1
 $ Count   : num  100 50 200 150
</code>```

I would like to have a result as follows:

```<code>dat
Gender Believer Count   Prop
1 Female      Yes   100  0.02
2 Female       No    50  0.01
3   Male      Yes   200  0.04
4   Male       No   150  0.03
</code>```

I would very much appreciate an answer. I for sure is very simple but I do not find it. Thanks a lot.

答:
Using dplyr as OP suggests

```<code>library(dplyr)

dat %>% mutate(Prop = Count / sum(Count))

  Gender Believer Count Prop
1 Female      Yes   100  0.2
2 Female       No    50  0.1
3   Male      Yes   200  0.4
4   Male       No   150  0.3
</code>```

(even though I don't know how you got 0.02 for example, just (sum(Count) * 10) in this case) :

```<code>dat %>% mutate(Prop = Count / (sum(Count) * 10))
</code>```

Body:
I am very new to R. I cannot find an answer to my following problem: How do I easily calculate the proportion over a two-way-table of two categorical variables and add that value as a new variable? I would like to use dplyr and mutate.

Gender <- c("Female","Female","Male","Male")
Believer <- c("Yes","No","Yes","No")
Count <- c(100,50,200,150)
dat <- data.frame(Gender,Believer,Count)

dat
Gender Believer Count
1 Female      Yes   100
2 Female       No    50
3   Male      Yes   200
4   Male       No   150

str(dat)
'data.frame':   4 obs. of  3 variables:
 $ Gender  : Factor w/ 2 levels "Female","Male": 1 1 2 2
 $ Believer: Factor w/ 2 levels "No","Yes": 2 1 2 1
 $ Count   : num  100 50 200 150

I would like to have a result as follows:

dat
Gender Believer Count   Prop
1 Female      Yes   100  0.02
2 Female       No    50  0.01
3   Male      Yes   200  0.04
4   Male       No   150  0.03

I would very much appreciate an answer. I for sure is very simple but I do not find it. Thanks a lot.

Body:
Using dplyr as OP suggests

library(dplyr)

dat %>% mutate(Prop = Count / sum(Count))

  Gender Believer Count Prop
1 Female      Yes   100  0.2
2 Female       No    50  0.1
3   Male      Yes   200  0.4
4   Male       No   150  0.3

(even though I don't know how you got 0.02 for example, just (sum(Count) * 10) in this case) :

dat %>% mutate(Prop = Count / (sum(Count) * 10))


问:
Is it bad practice to dynamically set/change event handlers?
I am trying to replace confirm() boxes with bootstrap modals for save/delete operations in a page.There is a button(call it action-button) for each of these operation which then triggers the respective modal. On clicking the confirm button on the modal,the respective function is triggered.

Instead of writing modals for each of these operations,I was thinking if I could use just one confirm modal and change the event handler when the "action-button" is clicked.
Like this:

$("#confirm-button").attr('onclick',save_all());

when save_all button is clicked.
Is it bad practice?And what are some alternatives to this? Thanks!

答:
I don't think changing the event handler is a good choice as you should handle the previous attached handlers in order to avoids memory leak and weird behaviours.

A better approach could be defining a generic handler that will read from a data attribute on the DOM, what to do in case of confirmation.

The main part is that such handler should not been coupled with the working staff.

To achieve this you could define custom events that will be fired from your generic handler.

I mean something like:

```<code>function confirmAction(ev) {
    // you can save in the HTML the name of the proper event
    var whatEv = $(this).data('my-key');

    // Here you could fire a custom event.
    $(this).trigger(whatEv);
}
</code>```

Last thing, as @trincot pointed, your code in the OP is wrong.

Body:
I don't think changing the event handler is a good choice as you should handle the previous attached handlers in order to avoids memory leak and weird behaviours.

A better approach could be defining a generic handler that will read from a data attribute on the DOM, what to do in case of confirmation.

The main part is that such handler should not been coupled with the working staff.

To achieve this you could define custom events that will be fired from your generic handler.

I mean something like:

function confirmAction(ev) {
    // you can save in the HTML the name of the proper event
    var whatEv = $(this).data('my-key');

    // Here you could fire a custom event.
    $(this).trigger(whatEv);
}

Last thing, as @trincot pointed, your code in the OP is wrong.


问:
WildFly Postgres DataSource remote connection-url ignored
I am running into some configuration troubles in setting up a Keycloak server in standalone clustered mode. Despite configuring the datasource to use a postgres database on {REMOTE_IP}, it is failing to start the server complaining that it cannot connect to localhost:5432.

I've been searching all over but I'm befuddled why the DataSource would try to connect to localhost when the connection-url is set to a remote host.

Is there any mistake in my configuration? How can I figure out why PG is trying to connect to localhost instead of {REMOTE_IP}

My setup is 1 Postgres database server and 2 Keycloak servers

I followed the installation instructions for using a relational database and have added the JDBC drivers v9.4.1212 for Postgres.

My DataSource configuration is as follows:

```<code><datasource jndi-name="java:jboss/datasources/KeycloakDS" pool-name="KeycloakDS" enabled="true" use-java-context="true">
    <connection-url>jdbc:postgresql://{REMOTE_IP}:5432/keycloak</connection-url>
    <driver>postgresql</driver>
    <pool>
        <max-pool-size>20</max-pool-size>
    </pool>
    <security>
        <user-name>keycloak</user-name>
        <password>{PASSWORD}</password>
    </security>
</datasource>
</code>```

The error message from the logs reads:

```<code>...
Caused by: org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:262)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:52)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:216)
    at org.postgresql.Driver.makeConnection(Driver.java:404)
    at org.postgresql.Driver.connect(Driver.java:272)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at org.postgresql.ds.common.BaseDataSource.getConnection(BaseDataSource.java:86)
    at org.postgresql.ds.PGPoolingDataSource.getConnection(PGPoolingDataSource.java:309)
    at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:312)
    ... 43 more
Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.postgresql.core.PGStream.<init>(PGStream.java:61)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:144)
    ... 52 more
</code>```

I've verified that I can connect to postgres using psql

```<code># psql -h {REMOTE_IP} keycloak keycloak
psql (9.5.7)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384,
bits: 256, compression: off)
Type "help" for help.

keycloak=>
</code>```

答:
I managed to figure this out for my case. The JDBC driver for postgres was configured to use a PGPoolingDataSource and had a datasource-class defined.

```<code><driver name="postgresql" module="org.postgresql">
    <xa-datasource-class>org.postgresql.xa.PGXADataSource</xa-datasource-class>
    <datasource-class>org.postgresql.ds.PGPoolingDataSource</datasource-class>
</driver>
</code>```

When the datasource-class is defined, the connection url must be passed through a connection-property instead of connection-url. I updated my configuration and the server booted up fine.

```<code><datasource jndi-name="java:jboss/datasources/KeycloakDS" pool-name="KeycloakDS" enabled="true" use-java-context="true">
    <connection-url>jdbc:postgresql://{REMOTE_IP}:5432/keycloak</connection-url>
    <connection-property name="url">jdbc:postgresql://{REMOTE_IP}:5432/keycloak</connection-property>
    <driver>postgresql</driver>
    <pool>
        <max-pool-size>20</max-pool-size>
    </pool>
    <driver-class>org.postgresql.Driver</driver-class>
    <security>
        <user-name>keycloak</user-name>
        <password>{PASSWORD}</password>
    </security>
</datasource>
</code>```

This issue is noted in the wildfly issue tracker
https://issues.jboss.org/browse/WFLY-6157

Body:
I am running into some configuration troubles in setting up a Keycloak server in standalone clustered mode. Despite configuring the datasource to use a postgres database on {REMOTE_IP}, it is failing to start the server complaining that it cannot connect to localhost:5432.

I've been searching all over but I'm befuddled why the DataSource would try to connect to localhost when the connection-url is set to a remote host.

Is there any mistake in my configuration? How can I figure out why PG is trying to connect to localhost instead of {REMOTE_IP}

My setup is 1 Postgres database server and 2 Keycloak servers

I followed the installation instructions for using a relational database and have added the JDBC drivers v9.4.1212 for Postgres.

My DataSource configuration is as follows:

<datasource jndi-name="java:jboss/datasources/KeycloakDS" pool-name="KeycloakDS" enabled="true" use-java-context="true">
    <connection-url>jdbc:postgresql://{REMOTE_IP}:5432/keycloak</connection-url>
    <driver>postgresql</driver>
    <pool>
        <max-pool-size>20</max-pool-size>
    </pool>
    <security>
        <user-name>keycloak</user-name>
        <password>{PASSWORD}</password>
    </security>
</datasource>

The error message from the logs reads:

...
Caused by: org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:262)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:52)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:216)
    at org.postgresql.Driver.makeConnection(Driver.java:404)
    at org.postgresql.Driver.connect(Driver.java:272)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at org.postgresql.ds.common.BaseDataSource.getConnection(BaseDataSource.java:86)
    at org.postgresql.ds.PGPoolingDataSource.getConnection(PGPoolingDataSource.java:309)
    at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:312)
    ... 43 more
Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.postgresql.core.PGStream.<init>(PGStream.java:61)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:144)
    ... 52 more

I've verified that I can connect to postgres using psql

# psql -h {REMOTE_IP} keycloak keycloak
psql (9.5.7)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384,
bits: 256, compression: off)
Type "help" for help.

keycloak=>

Body:
I managed to figure this out for my case. The JDBC driver for postgres was configured to use a PGPoolingDataSource and had a datasource-class defined.

<driver name="postgresql" module="org.postgresql">
    <xa-datasource-class>org.postgresql.xa.PGXADataSource</xa-datasource-class>
    <datasource-class>org.postgresql.ds.PGPoolingDataSource</datasource-class>
</driver>

When the datasource-class is defined, the connection url must be passed through a connection-property instead of connection-url. I updated my configuration and the server booted up fine.

<datasource jndi-name="java:jboss/datasources/KeycloakDS" pool-name="KeycloakDS" enabled="true" use-java-context="true">
    <connection-url>jdbc:postgresql://{REMOTE_IP}:5432/keycloak</connection-url>
    <connection-property name="url">jdbc:postgresql://{REMOTE_IP}:5432/keycloak</connection-property>
    <driver>postgresql</driver>
    <pool>
        <max-pool-size>20</max-pool-size>
    </pool>
    <driver-class>org.postgresql.Driver</driver-class>
    <security>
        <user-name>keycloak</user-name>
        <password>{PASSWORD}</password>
    </security>
</datasource>

This issue is noted in the wildfly issue tracker
https://issues.jboss.org/browse/WFLY-6157


问:
Create parameterized VIEW in SQL Server 2008
Can we create parameterized VIEW in SQL Server 2008.

Or Any other alternative for this ?

答:
Try creating an inline table-valued function. Example:

```<code>CREATE FUNCTION dbo.fxnExample (@Parameter1 INTEGER)
RETURNS TABLE
AS
RETURN
(
    SELECT Field1, Field2
    FROM SomeTable
    WHERE Field3 = @Parameter1
)

-- Then call like this, just as if it's a table/view just with a parameter
SELECT * FROM dbo.fxnExample(1)
</code>```

If you view the execution plan for the SELECT you will not see a mention of the function at all and will actually just show you the underlying tables being queried. This is good as it means statistics on the underlying tables will be used when generating an execution plan for the query.

The thing to avoid would be a multi-statement table valued function as underlying table statistics will not be used and can result in poor performance due to a poor execution plan.

Example of what to avoid:

```<code>CREATE FUNCTION dbo.fxnExample (@Parameter1 INTEGER)
    RETURNS @Results TABLE(Field1 VARCHAR(10), Field2 VARCHAR(10))
AS
BEGIN
    INSERT @Results
    SELECT Field1, Field2
    FROM SomeTable
    WHERE Field3 = @Parameter1

    RETURN
END
</code>```

Subtly different, but with potentially big differences in performance when the function is used in a query.

Body:
Try creating an inline table-valued function. Example:

CREATE FUNCTION dbo.fxnExample (@Parameter1 INTEGER)
RETURNS TABLE
AS
RETURN
(
    SELECT Field1, Field2
    FROM SomeTable
    WHERE Field3 = @Parameter1
)

-- Then call like this, just as if it's a table/view just with a parameter
SELECT * FROM dbo.fxnExample(1)

If you view the execution plan for the SELECT you will not see a mention of the function at all and will actually just show you the underlying tables being queried. This is good as it means statistics on the underlying tables will be used when generating an execution plan for the query.

The thing to avoid would be a multi-statement table valued function as underlying table statistics will not be used and can result in poor performance due to a poor execution plan.

Example of what to avoid:

CREATE FUNCTION dbo.fxnExample (@Parameter1 INTEGER)
    RETURNS @Results TABLE(Field1 VARCHAR(10), Field2 VARCHAR(10))
AS
BEGIN
    INSERT @Results
    SELECT Field1, Field2
    FROM SomeTable
    WHERE Field3 = @Parameter1

    RETURN
END

Subtly different, but with potentially big differences in performance when the function is used in a query.

ContentLicense: CC BY-SA 2.5


问:
Can I edit the file app\Http\Controllers\Controller.php in laravel?
I'm a beginner, and I have a stupid question, I really want to edit this file. Can I do this?

And when I update new Laravel version, is this file be replace by default?

Thank You!

答:
You can also extend it and override what you need if we take into account some SOLID principles:

Open/Closed Principle or OCP states that software entities should be
  open for extension, but closed for modification


问:
Consul Empty reply from server
I'm trying to get a consul server cluster up and running. I have 3 dockerized consul servers running, but I can't access the Web UI, the HTTP API nor the DNS.

```<code>$ docker logs net-sci_discovery-service_consul_1
==> WARNING: Expect Mode enabled, expecting 3 servers
==> Starting Consul agent...
==> Consul agent running!
           Version: 'v0.8.5'
           Node ID: 'ccd38897-6047-f8b6-be1c-2aa0022a1483'
         Node name: 'consul1'
        Datacenter: 'dc1'
            Server: true (bootstrap: false)
       Client Addr: 127.0.0.1 (HTTP: 8500, HTTPS: -1, DNS: 8600)
      Cluster Addr: 172.20.0.2 (LAN: 8301, WAN: 8302)
    Gossip encrypt: false, RPC-TLS: false, TLS-Incoming: false

==> Log data will now stream in as it occurs:

    2017/07/07 23:24:07 [INFO] raft: Initial configuration (index=0): []
    2017/07/07 23:24:07 [INFO] raft: Node at 172.20.0.2:8300 [Follower] entering Follower state (Leader: "")
    2017/07/07 23:24:07 [INFO] serf: EventMemberJoin: consul1 172.20.0.2
    2017/07/07 23:24:07 [INFO] consul: Adding LAN server consul1 (Addr: tcp/172.20.0.2:8300) (DC: dc1)
    2017/07/07 23:24:07 [INFO] serf: EventMemberJoin: consul1.dc1 172.20.0.2
    2017/07/07 23:24:07 [INFO] consul: Handled member-join event for server "consul1.dc1" in area "wan"
    2017/07/07 23:24:07 [INFO] agent: Started DNS server 127.0.0.1:8600 (tcp)
    2017/07/07 23:24:07 [INFO] agent: Started DNS server 127.0.0.1:8600 (udp)
    2017/07/07 23:24:07 [INFO] agent: Started HTTP server on 127.0.0.1:8500
    2017/07/07 23:24:09 [INFO] serf: EventMemberJoin: consul2 172.20.0.3
    2017/07/07 23:24:09 [INFO] consul: Adding LAN server consul2 (Addr: tcp/172.20.0.3:8300) (DC: dc1)
    2017/07/07 23:24:09 [INFO] serf: EventMemberJoin: consul2.dc1 172.20.0.3
    2017/07/07 23:24:09 [INFO] consul: Handled member-join event for server "consul2.dc1" in area "wan"
    2017/07/07 23:24:10 [INFO] serf: EventMemberJoin: consul3 172.20.0.4
    2017/07/07 23:24:10 [INFO] consul: Adding LAN server consul3 (Addr: tcp/172.20.0.4:8300) (DC: dc1)
    2017/07/07 23:24:10 [INFO] consul: Found expected number of peers, attempting bootstrap: 172.20.0.2:8300,172.20.0.3:8300,172.20.0.4:8300
    2017/07/07 23:24:10 [INFO] serf: EventMemberJoin: consul3.dc1 172.20.0.4
    2017/07/07 23:24:10 [INFO] consul: Handled member-join event for server "consul3.dc1" in area "wan"
    2017/07/07 23:24:14 [ERR] agent: failed to sync remote state: No cluster leader
    2017/07/07 23:24:17 [WARN] raft: Heartbeat timeout from "" reached, starting election
    2017/07/07 23:24:17 [INFO] raft: Node at 172.20.0.2:8300 [Candidate] entering Candidate state in term 2
    2017/07/07 23:24:17 [INFO] raft: Election won. Tally: 2
    2017/07/07 23:24:17 [INFO] raft: Node at 172.20.0.2:8300 [Leader] entering Leader state
    2017/07/07 23:24:17 [INFO] raft: Added peer 172.20.0.3:8300, starting replication
    2017/07/07 23:24:17 [INFO] raft: Added peer 172.20.0.4:8300, starting replication
    2017/07/07 23:24:17 [INFO] consul: cluster leadership acquired
    2017/07/07 23:24:17 [INFO] consul: New leader elected: consul1
    2017/07/07 23:24:17 [WARN] raft: AppendEntries to {Voter 172.20.0.3:8300 172.20.0.3:8300} rejected, sending older logs (next: 1)
    2017/07/07 23:24:17 [WARN] raft: AppendEntries to {Voter 172.20.0.4:8300 172.20.0.4:8300} rejected, sending older logs (next: 1)
    2017/07/07 23:24:17 [INFO] raft: pipelining replication to peer {Voter 172.20.0.3:8300 172.20.0.3:8300}
    2017/07/07 23:24:17 [INFO] raft: pipelining replication to peer {Voter 172.20.0.4:8300 172.20.0.4:8300}
    2017/07/07 23:24:18 [INFO] consul: member 'consul1' joined, marking health alive
    2017/07/07 23:24:18 [INFO] consul: member 'consul2' joined, marking health alive
    2017/07/07 23:24:18 [INFO] consul: member 'consul3' joined, marking health alive
    2017/07/07 23:24:20 [INFO] agent: Synced service 'consul'
    2017/07/07 23:24:20 [INFO] agent: Synced service 'messaging-service-kafka'
    2017/07/07 23:24:20 [INFO] agent: Synced service 'messaging-service-zookeeper'

$ curl http://127.0.0.1:8500/v1/catalog/service/consul
curl: (52) Empty reply from server
dig @127.0.0.1 -p 8600 consul.service.consul

; <<>> DiG 9.8.3-P1 <<>> @127.0.0.1 -p 8600 consul.service.consul
; (1 server found)
;; global options: +cmd
;; connection timed out; no servers could be reached

$ dig @127.0.0.1 -p 8600 messaging-service-kafka.service.consul

; <<>> DiG 9.8.3-P1 <<>> @127.0.0.1 -p 8600 messaging-service-kafka.service.consul
; (1 server found)
;; global options: +cmd
;; connection timed out; no servers could be reached
</code>```

I can't get my services to register via the HTTP API either; those shown above are registered using a config script when the container launches.

Here's my docker-compose.yml:

```<code>version: '2'
services:
  consul1:
    image: "consul:latest"
    container_name: "net-sci_discovery-service_consul_1"
    hostname: "consul1"
    ports:
      - "8400:8400"
      - "8500:8500"
      - "8600:8600"
    volumes:
      - ./etc/consul.d:/etc/consul.d
    command: "agent -server -ui -bootstrap-expect 3 -config-dir=/etc/consul.d -bind=0.0.0.0"
  consul2:
    image: "consul:latest"
    container_name: "net-sci_discovery-service_consul_2"
    hostname: "consul2"
    command: "agent -server -join=consul1"
    links:
      - "consul1"
  consul3:
    image: "consul:latest"
    container_name: "net-sci_discovery-service_consul_3"
    hostname: "consul3"
    command: "agent -server -join=consul1"
    links:
      - "consul1"
</code>```

I'm relatively new to both docker and consul. I've had a look around the web and the above options are my understanding of what is required. Any suggestions on the way forward would be very welcome.

Edit:

Result of docker container ps -all:

```<code>$ docker container ps --all
CONTAINER ID        IMAGE                    COMMAND                  CREATED             STATUS              PORTS                                                                                NAMES
e0a1c3bba165        consul:latest            "docker-entrypoint..."   38 seconds ago      Up 36 seconds       8300-8302/tcp, 8500/tcp, 8301-8302/udp, 8600/tcp, 8600/udp                                                       net-sci_discovery-service_consul_3
7f05555e81e0        consul:latest            "docker-entrypoint..."   38 seconds ago      Up 36 seconds       8300-8302/tcp, 8500/tcp, 8301-8302/udp, 8600/tcp, 8600/udp                                                       net-sci_discovery-service_consul_2
9e2dedaa224b        consul:latest            "docker-entrypoint..."   39 seconds ago      Up 38 seconds       0.0.0.0:8400->8400/tcp, 8301-8302/udp, 0.0.0.0:8500->8500/tcp, 8300-8302/tcp, 8600/udp, 0.0.0.0:8600->8600/tcp   net-sci_discovery-service_consul_1
27b34c5dacb7        messagingservice_kafka   "start-kafka.sh"         3 hours ago         Up 3 hours          0.0.0.0:9092->9092/tcp                                                                                net-sci_messaging-service_kafka
0389797b0b8f        wurstmeister/zookeeper   "/bin/sh -c '/usr/..."   3 hours ago         Up 3 hours          22/tcp, 2888/tcp, 3888/tcp, 0.0.0.0:2181->2181/tcp                                                               net-sci_messaging-service_zookeeper
</code>```

Edit:

Updated docker-compose.yml to include long format for ports:

```<code>version: '3.2'
services:
  consul1:
    image: "consul:latest"
    container_name: "net-sci_discovery-service_consul_1"
    hostname: "consul1"
    ports:
      - target: 8400
        published: 8400
        mode: host
      - target: 8500
        published: 8500
        mode: host
      - target: 8600
        published: 8600
        mode: host
    volumes:
      - ./etc/consul.d:/etc/consul.d
    command: "agent -server -ui -bootstrap-expect 3 -config-dir=/etc/consul.d -bind=0.0.0.0 -client=127.0.0.1"
  consul2:
    image: "consul:latest"
    container_name: "net-sci_discovery-service_consul_2"
    hostname: "consul2"
    command: "agent -server -join=consul1"
    links:
      - "consul1"
  consul3:
    image: "consul:latest"
    container_name: "net-sci_discovery-service_consul_3"
    hostname: "consul3"
    command: "agent -server -join=consul1"
    links:
      - "consul1"
</code>```

答:
From the Consul Web Gui page, make sure you have launched an agent with the -ui parameter.

The UI is available at the /ui path on the same port as the HTTP API.

  By default this is http://localhost:8500/ui

I do see 8500 mapped to your host on broadcast (0.0.0.0).

Check also (as in this answer) if the client_addr can help (at least for testing)

Title: Consul Empty reply from server

Body:
I'm trying to get a consul server cluster up and running. I have 3 dockerized consul servers running, but I can't access the Web UI, the HTTP API nor the DNS.

$ docker logs net-sci_discovery-service_consul_1
==> WARNING: Expect Mode enabled, expecting 3 servers
==> Starting Consul agent...
==> Consul agent running!
           Version: 'v0.8.5'
           Node ID: 'ccd38897-6047-f8b6-be1c-2aa0022a1483'
         Node name: 'consul1'
        Datacenter: 'dc1'
            Server: true (bootstrap: false)
       Client Addr: 127.0.0.1 (HTTP: 8500, HTTPS: -1, DNS: 8600)
      Cluster Addr: 172.20.0.2 (LAN: 8301, WAN: 8302)
    Gossip encrypt: false, RPC-TLS: false, TLS-Incoming: false

==> Log data will now stream in as it occurs:

    2017/07/07 23:24:07 [INFO] raft: Initial configuration (index=0): []
    2017/07/07 23:24:07 [INFO] raft: Node at 172.20.0.2:8300 [Follower] entering Follower state (Leader: "")
    2017/07/07 23:24:07 [INFO] serf: EventMemberJoin: consul1 172.20.0.2
    2017/07/07 23:24:07 [INFO] consul: Adding LAN server consul1 (Addr: tcp/172.20.0.2:8300) (DC: dc1)
    2017/07/07 23:24:07 [INFO] serf: EventMemberJoin: consul1.dc1 172.20.0.2
    2017/07/07 23:24:07 [INFO] consul: Handled member-join event for server "consul1.dc1" in area "wan"
    2017/07/07 23:24:07 [INFO] agent: Started DNS server 127.0.0.1:8600 (tcp)
    2017/07/07 23:24:07 [INFO] agent: Started DNS server 127.0.0.1:8600 (udp)
    2017/07/07 23:24:07 [INFO] agent: Started HTTP server on 127.0.0.1:8500
    2017/07/07 23:24:09 [INFO] serf: EventMemberJoin: consul2 172.20.0.3
    2017/07/07 23:24:09 [INFO] consul: Adding LAN server consul2 (Addr: tcp/172.20.0.3:8300) (DC: dc1)
    2017/07/07 23:24:09 [INFO] serf: EventMemberJoin: consul2.dc1 172.20.0.3
    2017/07/07 23:24:09 [INFO] consul: Handled member-join event for server "consul2.dc1" in area "wan"
    2017/07/07 23:24:10 [INFO] serf: EventMemberJoin: consul3 172.20.0.4
    2017/07/07 23:24:10 [INFO] consul: Adding LAN server consul3 (Addr: tcp/172.20.0.4:8300) (DC: dc1)
    2017/07/07 23:24:10 [INFO] consul: Found expected number of peers, attempting bootstrap: 172.20.0.2:8300,172.20.0.3:8300,172.20.0.4:8300
    2017/07/07 23:24:10 [INFO] serf: EventMemberJoin: consul3.dc1 172.20.0.4
    2017/07/07 23:24:10 [INFO] consul: Handled member-join event for server "consul3.dc1" in area "wan"
    2017/07/07 23:24:14 [ERR] agent: failed to sync remote state: No cluster leader
    2017/07/07 23:24:17 [WARN] raft: Heartbeat timeout from "" reached, starting election
    2017/07/07 23:24:17 [INFO] raft: Node at 172.20.0.2:8300 [Candidate] entering Candidate state in term 2
    2017/07/07 23:24:17 [INFO] raft: Election won. Tally: 2
    2017/07/07 23:24:17 [INFO] raft: Node at 172.20.0.2:8300 [Leader] entering Leader state
    2017/07/07 23:24:17 [INFO] raft: Added peer 172.20.0.3:8300, starting replication
    2017/07/07 23:24:17 [INFO] raft: Added peer 172.20.0.4:8300, starting replication
    2017/07/07 23:24:17 [INFO] consul: cluster leadership acquired
    2017/07/07 23:24:17 [INFO] consul: New leader elected: consul1
    2017/07/07 23:24:17 [WARN] raft: AppendEntries to {Voter 172.20.0.3:8300 172.20.0.3:8300} rejected, sending older logs (next: 1)
    2017/07/07 23:24:17 [WARN] raft: AppendEntries to {Voter 172.20.0.4:8300 172.20.0.4:8300} rejected, sending older logs (next: 1)
    2017/07/07 23:24:17 [INFO] raft: pipelining replication to peer {Voter 172.20.0.3:8300 172.20.0.3:8300}
    2017/07/07 23:24:17 [INFO] raft: pipelining replication to peer {Voter 172.20.0.4:8300 172.20.0.4:8300}
    2017/07/07 23:24:18 [INFO] consul: member 'consul1' joined, marking health alive
    2017/07/07 23:24:18 [INFO] consul: member 'consul2' joined, marking health alive
    2017/07/07 23:24:18 [INFO] consul: member 'consul3' joined, marking health alive
    2017/07/07 23:24:20 [INFO] agent: Synced service 'consul'
    2017/07/07 23:24:20 [INFO] agent: Synced service 'messaging-service-kafka'
    2017/07/07 23:24:20 [INFO] agent: Synced service 'messaging-service-zookeeper'

$ curl http://127.0.0.1:8500/v1/catalog/service/consul
curl: (52) Empty reply from server
dig @127.0.0.1 -p 8600 consul.service.consul

; <<>> DiG 9.8.3-P1 <<>> @127.0.0.1 -p 8600 consul.service.consul
; (1 server found)
;; global options: +cmd
;; connection timed out; no servers could be reached

$ dig @127.0.0.1 -p 8600 messaging-service-kafka.service.consul

; <<>> DiG 9.8.3-P1 <<>> @127.0.0.1 -p 8600 messaging-service-kafka.service.consul
; (1 server found)
;; global options: +cmd
;; connection timed out; no servers could be reached

I can't get my services to register via the HTTP API either; those shown above are registered using a config script when the container launches.

Here's my docker-compose.yml:

version: '2'
services:
  consul1:
    image: "consul:latest"
    container_name: "net-sci_discovery-service_consul_1"
    hostname: "consul1"
    ports:
      - "8400:8400"
      - "8500:8500"
      - "8600:8600"
    volumes:
      - ./etc/consul.d:/etc/consul.d
    command: "agent -server -ui -bootstrap-expect 3 -config-dir=/etc/consul.d -bind=0.0.0.0"
  consul2:
    image: "consul:latest"
    container_name: "net-sci_discovery-service_consul_2"
    hostname: "consul2"
    command: "agent -server -join=consul1"
    links:
      - "consul1"
  consul3:
    image: "consul:latest"
    container_name: "net-sci_discovery-service_consul_3"
    hostname: "consul3"
    command: "agent -server -join=consul1"
    links:
      - "consul1"

I'm relatively new to both docker and consul. I've had a look around the web and the above options are my understanding of what is required. Any suggestions on the way forward would be very welcome.

Edit:

Result of docker container ps -all:

$ docker container ps --all
CONTAINER ID        IMAGE                    COMMAND                  CREATED             STATUS              PORTS                                                                                NAMES
e0a1c3bba165        consul:latest            "docker-entrypoint..."   38 seconds ago      Up 36 seconds       8300-8302/tcp, 8500/tcp, 8301-8302/udp, 8600/tcp, 8600/udp                                                       net-sci_discovery-service_consul_3
7f05555e81e0        consul:latest            "docker-entrypoint..."   38 seconds ago      Up 36 seconds       8300-8302/tcp, 8500/tcp, 8301-8302/udp, 8600/tcp, 8600/udp                                                       net-sci_discovery-service_consul_2
9e2dedaa224b        consul:latest            "docker-entrypoint..."   39 seconds ago      Up 38 seconds       0.0.0.0:8400->8400/tcp, 8301-8302/udp, 0.0.0.0:8500->8500/tcp, 8300-8302/tcp, 8600/udp, 0.0.0.0:8600->8600/tcp   net-sci_discovery-service_consul_1
27b34c5dacb7        messagingservice_kafka   "start-kafka.sh"         3 hours ago         Up 3 hours          0.0.0.0:9092->9092/tcp                                                                                net-sci_messaging-service_kafka
0389797b0b8f        wurstmeister/zookeeper   "/bin/sh -c '/usr/..."   3 hours ago         Up 3 hours          22/tcp, 2888/tcp, 3888/tcp, 0.0.0.0:2181->2181/tcp                                                               net-sci_messaging-service_zookeeper

Edit:

Updated docker-compose.yml to include long format for ports:

version: '3.2'
services:
  consul1:
    image: "consul:latest"
    container_name: "net-sci_discovery-service_consul_1"
    hostname: "consul1"
    ports:
      - target: 8400
        published: 8400
        mode: host
      - target: 8500
        published: 8500
        mode: host
      - target: 8600
        published: 8600
        mode: host
    volumes:
      - ./etc/consul.d:/etc/consul.d
    command: "agent -server -ui -bootstrap-expect 3 -config-dir=/etc/consul.d -bind=0.0.0.0 -client=127.0.0.1"
  consul2:
    image: "consul:latest"
    container_name: "net-sci_discovery-service_consul_2"
    hostname: "consul2"
    command: "agent -server -join=consul1"
    links:
      - "consul1"
  consul3:
    image: "consul:latest"
    container_name: "net-sci_discovery-service_consul_3"
    hostname: "consul3"
    command: "agent -server -join=consul1"
    links:
      - "consul1"


问:
JavaScript - How to place asterisk in the right side of the text box?
I want to place asterisk in the right side of the each text box individually when I am submitting the empty form/field. The code is working but asterisk is displaying in the end of the form.

This is my code:

```<code>[<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title></title>
<style type="text/css">
body { font-family:arial, helvetica, sans-serif; font-weight:bold; font-size:13px; color:#000; text-align:left; margin:3px 0px; }
input { text-align:center; border:2px solid #CCC; }
#wrap  { width:400px; height:200px; margin:20px; padding:10px;  }
#une { margin-top:10px; }
#reg {margin-top:10px; }
.a13B { color:#F00; }
.cntr { text-align:center; }
</style>
</head>

<body>

<div id="wrap">
  <form id="regform" name="registerationform" method="POST">
    <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" width="300">
      <tr>
        <td>First Name: </td>
        <td class="cntr">
        <input type="text" name="fnametxt" size="20"></td>
      </tr>
      <tr>
        <td>Second Name: </td>
        <td class="cntr">
        <input type="text" name="snametxt" size="20"> </td>
      </tr>
      <tr>
        <td>User Name:</td>
        <td class="cntr">
        <input type="text" name="unametxt" size="20"> </td>
      </tr>
      <tr>
        <td>Email Address: </td>
        <td class="cntr">
        <input type="text" name="emailtxt" size="20"> </td>
      </tr>
      <tr>
        <td>Password : </td>
        <td class="cntr"><input type="password" name="pwdtxt" size="20"> </td>
      </tr>
      <tr>
        <td>Confirm : </td>
        <td class="cntr"><input type="password" name="cpwdtxt" size="20"> </td>
      </tr>
    </table>
    <input id="reg" name="reg" type="button" onclick="regvalidate(this.form)" value="Register Now">
  </form>
  <div id="une" class="a13B">
  </div>
</div>
<!-- end wrap -->
<script type="text/javascript">
var uneObj=document.getElementById("une"); // object ref to msg line
var currentBrdObj;
//
function regvalidate(formObj)
{ uneObj.innerHTML=""; // clear msg line before resubmitting
 // gather object ref to input boxes
  var allInputs=document.getElementById("regform").getElementsByTagName("input");
 // check if value of box is ""
  for(var i=0;i<allInputs.length;i++)
    { if(allInputs\[i\].name !="reg")    // ignore submit button
       { if(allInputs\[i\].value=="")
         { uneObj.innerHTML=msg\[i\];
           if(currentBrdObj){currentBrdObj.style.border="2px solid #CCC"; }
           allInputs\[i\].style.border="2px solid #F00";
           currentBrdObj=allInputs\[i\];
           allInputs\[i\].onclick=function(){ this.style.border="2px solid #CCC"; }
           return;
     } } }
// check if password and confirm are the same
  if((formObj.pwdtxt.value) != (formObj.cpwdtxt.value))
   { uneObj.innerHTML = msg\[msg.length-1\];       // last msg in array
     formObj.pwdtxt.value = ""; formObj.pwdtxt.style.border="";
     formObj.cpwdtxt.value = ""; formObj.cpwdtxt.style.border="";
     return;
    }
// all ok so submit form
 uneObj.innerHTML = "All ok so submitting form";
  formObj.submit();
}
// -----
 var msg =\["*","*",
          "*","*",
          "*","*"\];
     msg\[msg.length\]="Passwords must be equal.<br>Please type a password";

      //
        </script>

</body>

</html>][1]
</code>```

@PawanKumar
Here is your code:

```<code>   <html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
$(document).ready(function() {
  $('#submitBtn').on('click', function(e) {
    debugger;
    e.preventDefault();
    var fields = document.getElementsByTagName('input');
    for (var i = 0; i < fields.length; i++) {
      if (fields[i].hasAttribute('required')) {
        if (fields[i].value == "") {
          fields[i].classList.add('redBorder');
          $(fields[i]).after('*');
        } else {
          fields[i].classList.remove('redBorder');
        }
      }
    }
  });
});

</script>

<style>

.redBorder {
  border: 2px solid red;
  border-radius: 2px;
}

</style>

</head>

<form novalidate>
<input type="text" placeholder="first name" required/><br/><br/>
<input type="text" placeholder="last name" /><br/><br/>
<button id="submitBtn" value="Submit">Submit</button>
</form>

</html>
</code>```

答:
Why bother with all that mess?

```<code><input type="text" name="fnametxt" <b><i>required</i></b> />*
<input type="<b><i>email</i></b>" name="emailtxt" <b><i>required</i></b> />*
<input type="<b><i>submit</i></b>" value="Register" /></code>```

JavaScript required: none at all

Body:
I want to place asterisk in the right side of the each text box individually when I am submitting the empty form/field. The code is working but asterisk is displaying in the end of the form.

This is my code:

[

<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title></title>

  <form id="regform" name="registerationform" method="POST">

        First Name:

        <input type="text" name="fnametxt" size="20">

        Second Name:

        <input type="text" name="snametxt" size="20">

        User Name:

        <input type="text" name="unametxt" size="20">

        Email Address:

        <input type="text" name="emailtxt" size="20">

        Password :
        <input type="password" name="pwdtxt" size="20">

        Confirm :
        <input type="password" name="cpwdtxt" size="20">

    <input id="reg" name="reg" type="button" onclick="regvalidate(this.form)" value="Register Now">
  </form>

][1]

@PawanKumar
Here is your code:

<form novalidate>
<input type="text" placeholder="first name" required/>

<input type="text" placeholder="last name" />

<button id="submitBtn" value="Submit">Submit</button>
</form>

Body:
Why bother with all that mess?

<input type="text" name="fnametxt" required />*
<input type="email" name="emailtxt" required />*
<input type="submit" value="Register" />

JavaScript required: none at all


问:
Javascript remove elements by class name
How we can remove the all div by same name of class.</p>

```<code> <input class="form-control" type="text" name="option[]"><input class="form-control" type="text" name="option[]"><input class="form-control" type="text" name="option[]">
</code>```

答:
My approach might be this

```<code>var elements = document.querySelectorAll('.test');
for (var element of elements) {
   element.remove();
   // or
   // element.parentNode.removeChild(element);
}
</code>```

Hope it helps.

Body:
How we can remove the all div by same name of class.

 <input class="form-control" type="text" name="option[]"><input class="form-control" type="text" name="option[]"><input class="form-control" type="text" name="option[]">

Body:
My approach might be this

var elements = document.querySelectorAll('.test');
for (var element of elements) {
   element.remove();
   // or
   // element.parentNode.removeChild(element);
}

Hope it helps.


问:
is it possible for exporting only functions in mysql workbench
Is it possible for exporting only the functions in MySQL workbench.
Exporting is possible for stored procedure, but don't know how to export functions in MySQL workbench?</p>

答: I had the problem and I solved it by opening the *.sql file via notepad and deleted the drop and create table queries.</p>


答:
LIKE is a SQL keyword, therefore you could use EndsWith

```<code>c.name.EndsWith("r");
</code>```

As a best practice, you may want to consider wrapping your DBEntities within a using block so it is correctly disposed. You could also move it into a new method/service layer, rather than retrieving it within the Controller which would be a cleaner approach.

Service Layer

```<code>public IEnumerable<Client> RetrieveClients(string endString)
{
   using (MyDBEntities myDbEntities = new MyDBEntities())
   {
        var clients = from c in myDBEntites.Client
                      where c.name.EndsWith(endString)'
                      select c;

        return clients;
   }
}
</code>```

Controller

```<code>public ActionResult GetClients()
{
    var clients = RetrieveClients("R");
    return View(clients);
}
</code>```

Title: C# MVC - Using LIKE in LINQ query

Body:
LIKE is a SQL keyword, therefore you could use EndsWith

c.name.EndsWith("r");

As a best practice, you may want to consider wrapping your DBEntities within a using block so it is correctly disposed. You could also move it into a new method/service layer, rather than retrieving it within the Controller which would be a cleaner approach.

Service Layer

public IEnumerable<Client> RetrieveClients(string endString)
{
   using (MyDBEntities myDbEntities = new MyDBEntities())
   {
        var clients = from c in myDBEntites.Client
                      where c.name.EndsWith(endString)'
                      select c;

        return clients;
   }
}

Controller

public ActionResult GetClients()
{
    var clients = RetrieveClients("R");
    return View(clients);
}

ContentLicense: CC BY-SA 4.0


问:
Why Joda DateTimeFormatter cannot parse timezone names ('z')
From DateTimeFormatter javadoc:

Zone names: Time zone names ('z') cannot be parsed.

Therefore timezone parsing like:

```<code>System.out.println(new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse("Fri Nov 11 12:13:14 JST 2010"));
</code>```

cannot be done in Joda:

```<code>DateTimeFormatter dtf = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss z yyyy");
System.out.println(dtf.parseDateTime("Fri Nov 11 12:13:14 JST 2010"));
//Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "Fri Nov 11 12:13:14 JST 2010" is malformed at "JST 2010"
//at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:673)
</code>```

答:
I think that the reason is that 'z' timezone names are conventional (not standardized) and ambiguous; i.e. they mean different things depending on your country of origin.  For example, "PST" can be "Pacific Standard Time" or "Pakistan Standard Time".

If you are interested, this site has a listing of a large number of timezone names.  It is not difficult to spot cases where there is ambiguity.

Body:
From DateTimeFormatter javadoc:

Zone names: Time zone names ('z') cannot be parsed.

Therefore timezone parsing like:

System.out.println(new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse("Fri Nov 11 12:13:14 JST 2010"));

cannot be done in Joda:

DateTimeFormatter dtf = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss z yyyy");
System.out.println(dtf.parseDateTime("Fri Nov 11 12:13:14 JST 2010"));
//Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "Fri Nov 11 12:13:14 JST 2010" is malformed at "JST 2010"
//at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:673)


问:
Disable mousewheel on HTML and exclude a specific div using jquery
I want to disable mousewheel on HTML, and exclude a specific element from this rule.

I am using the following code:

```<code>$('html').bind("mousewheel, touchmove", function(e) {
    e.stopPropagation();
    return false;
});

$('.exclude').unbind("mousewheel, touchmove");
</code>```

Mouse Wheel does not work on the exclude element either.

答:
with following code you can disable mousewheel on document

```<code> window.onwheel = e => e.preventDefault = false;
</code>```

but i think it is impossible to allow only an child element to wheel.

Try to use css

```<code>overflow:hidden;
</code>```

and

```<code>overflow:auto;
</code>```

for the elements you will allowed to scroll

Body:
I want to disable mousewheel on HTML, and exclude a specific element from this rule.

I am using the following code:

$('html').bind("mousewheel, touchmove", function(e) {
    e.stopPropagation();
    return false;
});

$('.exclude').unbind("mousewheel, touchmove");

Mouse Wheel does not work on the exclude element either.

Body:
with following code you can disable mousewheel on document

 window.onwheel = e => e.preventDefault = false;

but i think it is impossible to allow only an child element to wheel.

Try to use css

overflow:hidden;

and

overflow:auto;

for the elements you will allowed to scroll


答:
What I would suggest you to do here is to try to solve this with String.EndsWith (LINK TO DOCUMENTATION) method.

Let me write an example based on your question, using linq ofcourse:

```<code>public ActionResult GetClients()
{
  MyDBEntities myDBEntites = new MyDBEntities();
  var clients = from c in myDBEntites.Client
                where c.name.EndsWith("r")
            select c;

 return View(clients);
}
</code>```

Title: C# MVC - Using LIKE in LINQ query

Body:
I want to display names from a SQL database that ends with certain char but it won't let me use WildCard in the Controller ActionResult.

This is my current code that I want to work.

public ActionResult GetClients()
    {
        MyDBEntities myDBEntites = new MyDBEntities();
        var clients = from c in myDBEntites.Client
                      where c.name LIKE '%r'
                      select c;
        return View(clients);

    }

What am I missing here for it to work? If its not working with wild card then how do I get the names that ends with a specific char?

Body:
What I would suggest you to do here is to try to solve this with String.EndsWith (LINK TO DOCUMENTATION) method.

Let me write an example based on your question, using linq ofcourse:

public ActionResult GetClients()
{
  MyDBEntities myDBEntites = new MyDBEntities();
  var clients = from c in myDBEntites.Client
                where c.name.EndsWith("r")
            select c;

 return View(clients);
}


问:
Spacy model download issue
I am using Spacy 1.3

However, it looks like I cannot download the model now.

```<code>20/29 : RUN python -m spacy.en.download all
The command '/bin/sh -c python -m spacy.en.download all' returned a non-zero code: 1
</code>```

答:
There seems to be a problem with the download server – this will be fixed asap. (I'm one of the spaCy maintainers btw. Sorry about the inconvenience.)

All models are also attached as archives to the v1.6 release – so in the meantime, you can always download them manually from there, unzip the archive and place the contained folder in spacy/data.

If you don't have to use v1.3, I'd also recommend checking out the newer versions and upgrading to spaCy v1.7+. Models are now hosted on GitHub, which makes the downloading process more transparent and doesn't rely on a separate download server. They're also wrapped as native Python packages, which lets you install them via pip, add them to your project's requirements.txt and even import them as a module at the top of your file. You can read more about this in the models documentation.

This makes it easier to manage model dependencies, especially as more models become available. If you're using spaCy 1.8+, you'll be able to use models for English, German, French and Spanish. If you have trained your own models and decide to upgrade, note that you will have to retrain your models with the input from the new version. Models trained on spaCy <v1.7 are not compatible with v1.7+.

Title: Spacy model download issue

Body:
I am using Spacy 1.3

However, it looks like I cannot download the model now.

20/29 : RUN python -m spacy.en.download all
The command '/bin/sh -c python -m spacy.en.download all' returned a non-zero code: 1


问:
Php artisan migrate fails Laravel
I have the following error. Someone is understanding why?

php artisan migrate

```<code> SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key
was too long; max key length is 767 bytes (SQL: alter table `users`
add unique `users_email_unique`(`email`))
</code>```

create_users_table.php

```<code>Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name',255);
    $table->string('email',255)->unique();
    $table->string('password',255);
    $table->rememberToken();
    $table->timestamps();
});
</code>```

答:
you have to do is edit your AppServiceProvider.php  on App\Providers\AppServiceProvider file and inside the boot method set a default string length:

```<code>use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}
</code>```

Then drop the database manually then composer dump-autoload and php artisan migrate

Title: Php artisan migrate fails Laravel

Body:
I have the following error. Someone is understanding why?

php artisan migrate

 SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key
was too long; max key length is 767 bytes (SQL: alter table `users`
add unique `users_email_unique`(`email`))

create_users_table.php

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name',255);
    $table->string('email',255)->unique();
    $table->string('password',255);
    $table->rememberToken();
    $table->timestamps();
});

Body:
you have to do is edit your AppServiceProvider.php  on App\Providers\AppServiceProvider file and inside the boot method set a default string length:

use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

Then drop the database manually then composer dump-autoload and php artisan migrate


问:
When should you use 'friend' in C++?
I have been reading through the C++ FAQ and was curious about the friend declaration. I personally have never used it, however I am interested in exploring the language.

What is a good example of using friend?

Reading the FAQ a bit longer I like the idea of the << >> operator overloading and adding as a friend of those classes. However I am not sure how this doesn't break encapsulation. When can these exceptions stay within the strictness that is OOP?

答:
We had an interesting issue come up at a company I previously worked at where we used friend to decent affect.  I worked in our framework department we created a basic engine level system over our custom OS.  Internally we had a class structure:

```<code>         Game
        /    \
 TwoPlayer  SinglePlayer
</code>```

All of these classes were part of the framework and maintained by our team.  The games produced by the company were built on top of this framework deriving from one of Games children.  The issue was that Game had interfaces to various things that SinglePlayer and TwoPlayer needed access to but that we did not want expose outside of the framework classes.  The solution was to make those interfaces private and allow TwoPlayer and SinglePlayer access to them via friendship.

Truthfully this whole issue could have been resolved by a better implementation of our system but we were locked into what we had.

OwnerDisplayName: roo

Title: When should you use 'friend' in C++?

LastEditorDisplayName: roo

Body:
We had an interesting issue come up at a company I previously worked at where we used friend to decent affect.  I worked in our framework department we created a basic engine level system over our custom OS.  Internally we had a class structure:

         Game
        /    \
 TwoPlayer  SinglePlayer

All of these classes were part of the framework and maintained by our team.  The games produced by the company were built on top of this framework deriving from one of Games children.  The issue was that Game had interfaces to various things that SinglePlayer and TwoPlayer needed access to but that we did not want expose outside of the framework classes.  The solution was to make those interfaces private and allow TwoPlayer and SinglePlayer access to them via friendship.

Truthfully this whole issue could have been resolved by a better implementation of our system but we were locked into what we had.

OwnerDisplayName: Ray


答:
The short answer would be: use friend when it actually improves encapsulation.  Improving readability and usability (operators << and >> are the canonical example) is also a good reason.

As for examples of improving encapsulation, classes specifically designed to work with the internals of other classes (test classes come to mind) are good candidates.

Title: When should you use 'friend' in C++?

Body:
I have been reading through the C++ FAQ and was curious about the friend declaration. I personally have never used it, however I am interested in exploring the language.

What is a good example of using friend?

Reading the FAQ a bit longer I like the idea of the << >> operator overloading and adding as a friend of those classes. However I am not sure how this doesn't break encapsulation. When can these exceptions stay within the strictness that is OOP?

OwnerDisplayName: Gorpik


问:
How to block google ads from injecting JavaScript
Some google ads start injecting JavaScript and poping ads all over the screen

How can I block these random scripts that are injected through google ads?

答:
This is not perfect, but it seems to be very effective in my case (all pages are SSL) and also prevent SSL mixed mode messages caused by google ads third party plugin scripts...

```<code><meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests; object-src 'none'">
</code>```

Content-Security-Policy is critical to prevent mixed content errors
(too many errors can show a "connection not secure" by the browser and memory leaks)
https://blog.cloudflare.com/fixing-the-mixed-content-problem-with-automatic-https-rewrites and
How does Content Security Policy work?

Body:
This is not perfect, but it seems to be very effective in my case (all pages are SSL) and also prevent SSL mixed mode messages caused by google ads third party plugin scripts...

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests; object-src 'none'">

Content-Security-Policy is critical to prevent mixed content errors
(too many errors can show a "connection not secure" by the browser and memory leaks)
https://blog.cloudflare.com/fixing-the-mixed-content-problem-with-automatic-https-rewrites and
How does Content Security Policy work?